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: select Responses or Messages per Qoder and Pi route (#46)
澄潭edea6b8ace93
diff --git a/apps/desktop/src-tauri/src/agent_session.rs b/apps/desktop/src-tauri/src/agent_session.rsindex f8dde1f7..26a3d264 100644--- a/apps/desktop/src-tauri/src/agent_session.rs+++ b/apps/desktop/src-tauri/src/agent_session.rs@@ -203,7 +203,10 @@ impl AgentConfirmation {let effect = &self.preview.model_effect;let details = match &self.input.spec.model {AgentFacetIntent::Configure {- settings: AgentModelSelectionV2::QoderAdditional { allowed_plan_ids },+ settings:+ AgentModelSelectionV2::QoderAdditional {+ allowed_plan_ids, ..+ },} => {let routes = allowed_plan_ids.iter()diff --git a/apps/desktop/src/features/AgentProtocolChoice.tsx b/apps/desktop/src/features/AgentProtocolChoice.tsxnew file mode 100644index 00000000..d41459ce--- /dev/null+++ b/apps/desktop/src/features/AgentProtocolChoice.tsx@@ -0,0 +1,26 @@+import React from 'react';+import './agent-protocol-choice.css';+export type AgentProtocol = 'responses' | 'messages';+export type ProtocolAdvice = { supported: AgentProtocol[]; native: AgentProtocol[] };+const label = (protocol: AgentProtocol) => protocol === 'responses' ? 'Responses' : 'Messages';++/** Advice never mutates the saved choice or issues a model request. */+export function AgentProtocolChoice({ value, advice, language, name, onChange }: {+ value: AgentProtocol; advice?: ProtocolAdvice; language: 'zh' | 'en'; name: string;+ onChange: (protocol: AgentProtocol) => void;+}) {+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;+ const recommended = advice?.native[0];+ return <div className="agent-protocol-choice" data-plan-protocol={name}>+ <label className="agent-protocol-choice__field"><span>{text('接入协议', 'Connection protocol')}</span>+ <select className="select" aria-label={`${name} · ${text('接入协议', 'Connection protocol')}`} value={value} onChange={event => onChange(event.target.value as AgentProtocol)}>+ {(['responses', 'messages'] as const).map(protocol => <option key={protocol} value={protocol} disabled={advice !== undefined && !advice.supported.includes(protocol)}>{label(protocol)}</option>)}+ </select>+ </label>+ <p className="field-help">{recommended+ ? text(`推荐 ${label(recommended)}:全部候选及回退模型均原生支持,可避免协议转换的额外开销与兼容风险。`, `Recommended: ${label(recommended)}. All candidates, including fallbacks, support it natively, avoiding protocol conversion overhead and compatibility risks.`)+ : advice ? text('当前模型组合没有共同的原生协议,可能需要协议转换。', 'The current models share no native protocol; conversion may be required.')+ : text('协议推荐需要候选模型的能力信息。', 'Protocol recommendations require candidate capability information.')}</p>+ {advice && !advice.native.includes(value) && advice.supported.includes(value) && <p className="field-help">{text('所选协议可用,但部分候选模型需要转换。', 'The selected protocol is supported, but some candidates require conversion.')}</p>}+ </div>;+}diff --git a/apps/desktop/src/features/agent-protocol-choice.css b/apps/desktop/src/features/agent-protocol-choice.cssnew file mode 100644index 00000000..cebe5dd5--- /dev/null+++ b/apps/desktop/src/features/agent-protocol-choice.css@@ -0,0 +1,19 @@+.agent-protocol-choice {+ display: grid;+ align-content: start;+ gap: 8px;+ min-width: 0;+}++.agent-protocol-choice__field {+ display: grid;+ gap: 6px;+ min-width: 0;+ color: var(--text-soft);+ font-size: calc(12px * var(--hr-text-scale));+ font-weight: 620;+}++.agent-protocol-choice__field > span { line-height: 1.5; }+.agent-protocol-choice__field > .select { font: inherit; }+.agent-protocol-choice > .field-help { margin: 0; line-height: 1.6; }diff --git a/apps/desktop/src/features/agents/AdditionalModelEditor.tsx b/apps/desktop/src/features/agents/AdditionalModelEditor.tsxindex f49ddfab..e39f871e 100644--- a/apps/desktop/src/features/agents/AdditionalModelEditor.tsx+++ b/apps/desktop/src/features/agents/AdditionalModelEditor.tsx@@ -1,4 +1,6 @@import React from 'react';+import './additional-model-editor.css';+import { AgentProtocolChoice } from '../AgentProtocolChoice';import { UiIcon } from '../../ui';import { agentDisplayName } from './ecosystems';import type { AgentModelEditorProps } from './AgentModelEditor';@@ -14,21 +16,23 @@ export function AdditionalModelEditor({ agent, values, plans, language, disabled? 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}>+ return <div className="additional-model-editor" 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">+ <fieldset disabled={disabled} className="additional-model-editor__plans"><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>)}+ {enabledPlans.map(plan => <div className="additional-model-editor__plan" data-selected={values.allowedPlanIds.includes(plan.agent_plan_id)} key={plan.agent_plan_id} data-agent-plan-id={plan.agent_plan_id}>+ <label className="check-row"><input type="checkbox" checked={values.allowedPlanIds.includes(plan.agent_plan_id)} onChange={() => toggle(plan.agent_plan_id)} /><span>{plan.desired.display_name}</span></label>+ {values.allowedPlanIds.includes(plan.agent_plan_id) && <AgentProtocolChoice name={plan.desired.display_name} language={language} value={values.planProtocols?.[plan.agent_plan_id] ?? 'responses'} advice={plan.protocol_advice} onChange={protocol => { onChange(current => ({ ...current, planProtocols: { ...current.planProtocols, [plan.agent_plan_id]: protocol } })); onEdited(); }} />}+ </div>)}{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>+ <div className="additional-model-editor__help"><p className="field-help" data-agent-activation>{text(`保存后重新启动 ${name},通过 /model 明确选用已添加的 HiRoute 路由。未选择时继续使用原来的模型。`, `Restart ${name} after saving, then explicitly select an added HiRoute route with /model. Otherwise it keeps using your previous model.`)}</p><p className="field-help">{text(`在 HiRoute 中调整或移除这些路由。如果已将某条路由设为 ${name} 默认模型,移除前请先在 ${name} 中切换到其他模型。`, `Adjust or remove these routes in HiRoute. If one is now your ${name} default, switch to another model in ${name} before removing it.`)}</p>+ </div>{invalid && <span className="oc-inline-error">{text(`至少选择一条已启用路由,并取消不可用的选择。`, `Select at least one enabled route and remove unavailable selections.`)}</span>}{!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/additional-model-editor.css b/apps/desktop/src/features/agents/additional-model-editor.cssnew file mode 100644index 00000000..3741ce0f--- /dev/null+++ b/apps/desktop/src/features/agents/additional-model-editor.css@@ -0,0 +1,19 @@+.additional-model-editor {+ display: grid;+ align-content: start;+ gap: 18px;+ min-width: 0;+}++.additional-model-editor > p { margin: 0; font-size: calc(13px * var(--hr-text-scale)); line-height: 1.6; }+.additional-model-editor__plans { display: grid; gap: 8px; }+.additional-model-editor__plans > legend { padding: 0; margin-bottom: 10px; }+.additional-model-editor__plan { min-width: 0; border: 1px solid var(--border); border-radius: 10px; background: var(--bg-soft); }+.additional-model-editor__plan[data-selected='true'] { border-color: var(--accent); }+.additional-model-editor__plan > .check-row { margin: 0; padding: 10px 12px; border: 0; border-radius: 9px; background: transparent; cursor: pointer; align-items: center; }+.additional-model-editor__plan > .check-row > input { margin: 0; }+.additional-model-editor__plan > .check-row > span { margin: 0; color: var(--text); overflow-wrap: anywhere; }+.additional-model-editor__plan[data-selected='true'] > .check-row { background: var(--accent-soft); border-radius: 9px 9px 0 0; }+.additional-model-editor__plan > .agent-protocol-choice { padding: 12px; border-top: 1px solid var(--border); }+.additional-model-editor__help { display: grid; gap: 6px; }+.additional-model-editor__help > p { margin: 0; line-height: 1.6; }diff --git a/apps/desktop/src/features/agents/editor-state.ts b/apps/desktop/src/features/agents/editor-state.tsindex 534f319d..816fd397 100644--- a/apps/desktop/src/features/agents/editor-state.ts+++ b/apps/desktop/src/features/agents/editor-state.ts@@ -13,6 +13,7 @@ export type AgentEditorValues = {fixedModels: AgentFixedModel[];nativeModelMode: CodexNativeModelMode;allowedPlanIds: string[];+ planProtocols: Record<string, 'responses' | 'messages'>;defaultChoice: AgentDefaultChoice;claudePresets: AgentClaudePresetMappings;triggerMode: AgentCollaborationTriggerMode;@@ -22,6 +23,7 @@ export const EMPTY_EDITOR_VALUES: AgentEditorValues = {fixedModels: [],nativeModelMode: 'hiroute_only',allowedPlanIds: [],+ planProtocols: {},defaultChoice: { kind: 'preserve_native' },claudePresets: {opus: { kind: 'preserve_native' },@@ -82,6 +84,7 @@ export function agentEditorSeed(known: facet === 'model'? known && agentSupportsModelRouting(agent.agent_id) && (initial || Boolean(currentModel && agentModelSelectionMatches(agent.agent_id, currentModel))): known,+ planProtocols: qoder?.plan_protocols ?? {},fixedModels: currentModel && 'fixed_models' in currentModel ? currentModel.fixed_models : [],nativeModelMode: codex?.native_model_mode ?? 'hiroute_only',allowedPlanIds: codex?.allowed_plan_ids ?? qoder?.allowed_plan_idsdiff --git a/apps/desktop/src/features/agents/settings-request.ts b/apps/desktop/src/features/agents/settings-request.tsindex 85f2f76d..c8cb0169 100644--- a/apps/desktop/src/features/agents/settings-request.ts+++ b/apps/desktop/src/features/agents/settings-request.ts@@ -39,10 +39,10 @@ export function agentSettingsSpec(agent: Agent, facet: AgentFacet, restore: bool};break;case 'pi':- settings = { mode: 'pi_additional', allowed_plan_ids: values.allowedPlanIds };+ settings = { mode: 'pi_additional', allowed_plan_ids: values.allowedPlanIds, plan_protocols: Object.fromEntries(values.allowedPlanIds.map(id => [id, values.planProtocols?.[id] ?? 'responses'])) };break;case 'qoder':- settings = { mode: 'qoder_additional', allowed_plan_ids: values.allowedPlanIds };+ settings = { mode: 'qoder_additional', allowed_plan_ids: values.allowedPlanIds, plan_protocols: Object.fromEntries(values.allowedPlanIds.map(id => [id, values.planProtocols?.[id] ?? 'responses'])) };break;default: throw new Error('AGENT_INPUT_INVALID');}diff --git a/apps/desktop/src/features/agents/types.ts b/apps/desktop/src/features/agents/types.tsindex 6208bade..68f2b813 100644--- a/apps/desktop/src/features/agents/types.ts+++ b/apps/desktop/src/features/agents/types.ts@@ -83,9 +83,10 @@ export type ClaudeModelSelection = {};export type QoderModelSelection = {mode: 'qoder_additional';+ plan_protocols?: Record<string, 'responses' | 'messages'>;allowed_plan_ids: string[];};-export type PiModelSelection = { mode: 'pi_additional'; allowed_plan_ids: string[] };+export type PiModelSelection = { mode: 'pi_additional'; plan_protocols?: Record<string, 'responses' | 'messages'>; allowed_plan_ids: string[] };export type AgentModelSelection = CodexModelSelection | ClaudeModelSelection | QoderModelSelection | PiModelSelection;export type AgentSurfaceResult = {surface: AgentModelSurface;diff --git a/apps/desktop/src/occami/styles/components.css b/apps/desktop/src/occami/styles/components.cssindex f36d6ef9..faf182f8 100644--- a/apps/desktop/src/occami/styles/components.css+++ b/apps/desktop/src/occami/styles/components.css@@ -374,6 +374,7 @@.modal.xwide { width: min(1080px, calc(100vw - 44px)); }.modal-head {+ flex-shrink: 0;display: flex;align-items: flex-start;justify-content: space-between;@@ -387,6 +388,7 @@.modal-head p { margin: 5px 0 0; color: var(--text-muted); font-size:calc(13px * var(--hr-text-scale)); }.modal-body { min-height: 0; overflow: auto; padding: 20px 22px; }.modal-foot {+ flex-shrink: 0;display: flex;align-items: center;justify-content: flex-end;diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsxindex 3b9f3fe0..c2821212 100644--- a/apps/desktop/src/plan-editor.tsx+++ b/apps/desktop/src/plan-editor.tsx@@ -1,3 +1,4 @@+import { AgentProtocolChoice, type ProtocolAdvice } from './features/AgentProtocolChoice';import { contextWindowError, type ContextWindowBounds } from './plan-context-window';import { DEFAULT_REQUEST_TIMEOUT_MS, requestTimeoutError } from './plan-request-timeout';import { ProviderIcon } from './ui/ProviderIcon';@@ -29,10 +30,10 @@ export type PlanEditorMemory = { restClassifier?: Extract<SmartClassifier, { kintype Smart = { economy: Selection[]; primary: Selection[]; primary_fallback: boolean; reselect_on_user_message: boolean; classifier: SmartClassifier; complex_keywords: string[] };type Free = { candidates: Selection[]; primary: Selection[]; primary_fallback: boolean };export type Editor = { schema: string; display_name: string; purpose: string; custom_alias?: string; mode: Mode; candidates: Selection[]; smart: Smart; free: Free; delegation_enabled: boolean; work?: Work; requirements: Record<string, unknown>; limits: { context_window_tokens?: number; maximum_attempts: number; request_timeout_ms: number; attempt_timeout_ms: number } };-export type Plan = { agent_plan_id: string; desired: { display_name: string; purpose: string; mode: Mode; strategy: { mode: string; candidates?: Selection[] } & Partial<Smart & Free>; delegation_enabled: boolean; work?: Work; requirements: Record<string, unknown>; limits: Editor['limits'] }; head: { head_revision: number; status: string }; agent_plan_revision: number; model_alias: string; publication: { revision: number; digest: string }; execution: string };+export type Plan = { protocol_advice?: ProtocolAdvice; agent_plan_id: string; desired: { display_name: string; purpose: string; mode: Mode; strategy: { mode: string; candidates?: Selection[] } & Partial<Smart & Free>; delegation_enabled: boolean; work?: Work; requirements: Record<string, unknown>; limits: Editor['limits'] }; head: { head_revision: number; status: string }; agent_plan_revision: number; model_alias: string; publication: { revision: number; digest: string }; execution: string };export type Draft = { draft_id: string; plan_id?: string; base_head_revision?: number; revision: number; editor: Editor };type Native = NativeReasoning;-type Candidate = { binding_id: string; model_configuration_id: string; display_name: string; reasoning: Native; billing_class: string; routable: boolean; ingress_protocols: string[] };+type Candidate = { binding_id: string; model_configuration_id: string; display_name: string; reasoning: Native; billing_class: string; routable: boolean; ingress_protocols: string[]; native_ingress_protocols?: string[] };type CodexCapabilityLimit = { kind: 'context_window' | 'image_input'; binding_ids: string[] };type CodexCapabilityIssue = { kind: 'plan_compilation' | 'invalid_compiled_plan' | 'responses_protocol' | 'request_capabilities' | 'instruction_roles' | 'context_input' | 'context_output' | 'context_total' | 'reasoning_profile' | 'context_window'; binding_id?: string };type CodexCapabilities = { state: 'available'; context_window: number; input_modalities: ('text' | 'image')[]; reasoning: 'route_configuration'; limitations: CodexCapabilityLimit[]; fixed_limits: ('parallel_tool_calls_disabled')[] }@@ -49,6 +50,18 @@ export type PlanEditorHandle = {cancel(): void;};+function workerProtocolAdvice(editor: Editor, options: Options | null): ProtocolAdvice | undefined {+ if (!options) return undefined;+ const selections = editor.mode === 'fixed_model' ? editor.candidates+ : editor.mode === 'smart_saving' ? [...editor.smart.economy, ...editor.smart.primary]+ : [...editor.free.candidates, ...(editor.free.primary_fallback ? editor.free.primary : [])];+ const candidates = selections.map(s => options.candidates.find(c => c.binding_id === s.binding_id));+ if (!candidates.length || candidates.some(c => !c)) return undefined;+ const protocols = ['responses', 'messages'] as const;+ return { supported: protocols.filter(p => candidates.every(c => c!.ingress_protocols.includes(p))),+ native: protocols.filter(p => candidates.every(c => c!.native_ingress_protocols?.includes(p))) };+}+function defaultReasoning(native: Native | undefined, preferred: 'low' | 'high' = 'high'): Selection['reasoning'] {if (!native || native.kind === 'fixed' || native.kind === 'budget') return undefined;if (native.kind === 'toggle') return { kind: 'toggle', enabled: preferred === 'high' };@@ -484,8 +497,9 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr['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' : 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} />}+ ] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => { if (editor.work?.harness !== value) update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } }); }}><BrandIcon kind={value === 'codex_cli' ? 'codex' : value === 'claude_code' ? 'claude-code' : value === 'pi' ? 'pi' : 'qoder'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}+ {editor.work && (editor.work.harness === 'pi' || editor.work.harness === 'qoder_cli') && <AgentProtocolChoice name={editor.display_name || text('任务路由', 'Task route')} language={language} value={editor.work.protocol} advice={workerProtocolAdvice(editor, options)} onChange={protocol => update({ work: { ...editor.work!, protocol } })} />}+{editor.work && <WorkerDependencies key={editor.work.harness} harness={editor.work.harness} language={language} active={active && moreSettingsOpen} onOperation={onOperation} />}</div>}</section></Disclosure></section>diff --git a/apps/desktop/tests/README.md b/apps/desktop/tests/README.mdindex abcb2154..047c72c5 100644--- a/apps/desktop/tests/README.md+++ b/apps/desktop/tests/README.md@@ -25,6 +25,10 @@ proves native authorization, persistence, process cleanup or real model calls.| Return to routing or configure a classifier | `desktop.routing.reactivation-models`, `desktop.routing.classifier-protocol` | An existing editor refreshes saved model names; quality uses active models; selection, curl copy and native-save outcomes are visible. || Inspect a model or open its documentation | `desktop.models.documentation-retains-input`; [model-to-route scenario](v3/browser/model-to-route-scenarios.mjs) | Local readiness does not claim inference success; browser failure retains form input; web anchors retain their default action; route creation uses the selected model. |+Task-route save scenarios also cover Pi and Qoder executor reselection: an explicit+Messages choice survives clicking the selected executor and reaches the saved draft.+They reuse the real Plan editor and existing IPC trace, without launching a native Agent.+The focused Agent fixture explicitly spans the application grid and keeps its evidencenote outside the page viewport. Layout assertions must observe usable component width;a DOM element that exists outside a valid viewport does not establish readability.diff --git a/apps/desktop/tests/agent-settings-request.test.mjs b/apps/desktop/tests/agent-settings-request.test.mjsindex 5a7137fe..1856272e 100644--- a/apps/desktop/tests/agent-settings-request.test.mjs+++ b/apps/desktop/tests/agent-settings-request.test.mjs@@ -124,7 +124,7 @@ for (const ecosystem of ['qoder', 'pi']) test(`${ecosystem} adds only selected rconst configure = wire(agentSettingsSpec(capable, 'model', false, draft));assert.deepEqual(configure, {schema_version: { major: 2, minor: 0 }, context_id: `context/${ecosystem}`,- model: { intent: 'configure', settings: { mode: `${ecosystem}_additional`, allowed_plan_ids: ['route/b', 'route/a'] } },+ model: { intent: 'configure', settings: { mode: `${ecosystem}_additional`, allowed_plan_ids: ['route/b', 'route/a'], plan_protocols: { 'route/b': 'responses', 'route/a': 'responses' } } },collaboration: { intent: 'keep' },});const saved = { ...capable, settings: {@@ -200,3 +200,11 @@ test('editing model routes retains distinct Codex authorization and Claude preseassert.equal(agentModelFormInvalid(codex, draft.values, ['route/a', 'route/b']), true, 'an unproven independent fixed source must block Save');assert.equal(agentModelFormInvalid(claude, { ...EMPTY_EDITOR_VALUES, fixedModels: [fixed] }, []), false, 'an existing Claude fixed model can survive without a preset route');});++for (const ecosystem of ['qoder', 'pi']) test(`${ecosystem} saves each selected plan protocol and excludes deselected plans`, () => {+ const capable = { ...qoder, agent_id: `agent_${ecosystem}_default`, context_id: `context/${ecosystem}`, settings: { state: 'not_configured' } };+ const values = { ...draft.values, planProtocols: { 'route/a': 'messages', 'route/b': 'responses', 'removed': 'messages' } };+ const result = agentSettingsSpec(capable, 'model', false, { ...draft, values });+ assert.deepEqual(result.model.settings.plan_protocols, { 'route/b': 'responses', 'route/a': 'messages' });+ assert.deepEqual(result.collaboration, { intent: 'keep' });+});diff --git a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjsindex b41e0d19..8d14b1e5 100644--- a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs@@ -142,6 +142,27 @@ const scenarios = [button('更换或高级设置').click(); await tick();assert(document.querySelector('#worker-qoder_cli-cli')?.value === request.cli_path, 'Switching away lost the Qoder installation');}),+ ...[['pi', 'Pi'], ['qoder_cli', 'Qoder CLI']].map(([harness, title]) =>+ scenario(`routing.protocol.${harness.replace("_cli", "")}-reselection`, ['route-save'], `${title} retains an explicit protocol when reselected and saved`, async () => {+ const executor = () => [...document.querySelectorAll('.v3-executor')].find(node => node.querySelector('strong')?.textContent === title);+ executor().click();+ await until(() => document.querySelector('[data-plan-protocol] select'), `${title} protocol choice`);+ const select = document.querySelector('[data-plan-protocol] select');+ assert(!select.querySelector('option[value="messages"]').disabled, 'The fixture must offer Messages');+ select.value = 'messages';+ select.dispatchEvent(new Event('change', { bubbles: true }));+ await tick();+ executor().click();+ await tick();+ assert(select.value === 'messages', `${title} reselection reset the explicit Messages choice`);+ trace().commands.length = 0;+ await until(() => !button('保存草稿')?.disabled, 'protocol draft save');+ button('保存草稿').click();+ await until(() => calls('preview_plan_editor') === 1, 'protocol draft submission');+ const saved = trace().requests.filter(item => item.command === 'preview_plan_editor').at(-1).payload.input.editor;+ assert(saved.work.harness === harness && saved.work.protocol === 'messages', 'The saved task route lost its explicit protocol');+ await until(() => !document.querySelector('.plan-editor > fieldset')?.disabled, 'editor released after save');+ })),scenario('routing.save.unobserved-editable', ['route-save'], 'an unobserved route save does not lock the editor or the route list', async () => {trace().commands.length = 0;const name = document.querySelector('.plan-identity-fields input');diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjsindex 626cd2bb..439cf1f7 100644--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs@@ -33,6 +33,8 @@ export const routingWorkerRequired = ['routing.capabilities.candidate-vs-fixed','worker.installation.replace','worker.installation.latest-edit','qoder.installation.single-cli',+ 'routing.protocol.pi-reselection',+ 'routing.protocol.qoder-reselection','routing.save.unobserved-editable','routing.publish.qoder-budget-conflict'];@@ -40,7 +42,7 @@ export const focusedRequirements = {'claude-collaboration': ['claude.collaboration.check-before-save', 'claude.collaboration.retry-preserves-edit', 'claude.collaboration.obsolete-blocker'],'worker-replacement': ['worker.installation.replace', 'worker.installation.latest-edit'],'qoder': ['qoder.collaboration.enable-without-model', 'qoder.collaboration.retry-and-restore', 'qoder.routing.additional-plans', 'qoder.routing.adjust-and-restore', 'agent.configuration.shared-interactions', 'qoder.routing.resume-pending', 'qoder.installation.single-cli', 'routing.publish.qoder-budget-conflict', 'desktop.routing.qoder-budget-checkpoint'],- 'route-save': ['routing.save.unobserved-editable', 'routing.publish.qoder-budget-conflict'],+ 'route-save': ['routing.protocol.pi-reselection', 'routing.protocol.qoder-reselection', 'routing.save.unobserved-editable', 'routing.publish.qoder-budget-conflict'],};export const productShellRequired = [diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.jsonindex 0386c7b4..d9f1a33a 100644--- a/contracts/compatibility-support.v1.json+++ b/contracts/compatibility-support.v1.json@@ -248,6 +248,7 @@"hiroute.pi-local-cli/v1","hiroute.pi-native-resources/v1","hiroute.pi-native-restore/v1",+ "hiroute.pi-native-restore/v2","hiroute.pi-sdk-capability/v1","hiroute.pi-worker-failure/v1","hiroute.plan-authoring/v2",@@ -279,6 +280,7 @@"hiroute.qoder-additional-model/v1","hiroute.qoder-borrowed-context-collaboration/v1","hiroute.qoder-native-restore/v1",+ "hiroute.qoder-native-restore/v2","hiroute.rating-snapshot/v2","hiroute.registered-compute-discovery-fact/v1","hiroute.release-facts-compiler-input/v2",@@ -884,6 +886,50 @@"hiroute.daemon-upgrade-progress/v1"],"legacy_support": []+ },+ {+ "subject": "pi_native_provider_restore",+ "audited_prefixes": [+ "hiroute.pi-native-restore"+ ],+ "current_contracts": [+ "hiroute.pi-native-restore/v2"+ ],+ "legacy_support": [+ {+ "contract": "hiroute.pi-native-restore/v1",+ "mode": "recovery_read_only",+ "owner": "integrations/additional_native",+ "reason": "Restore original single-provider encrypted records without adopting user nodes; new writes own one provider per plan.",+ "removal_condition": "Remove only after all supported single-provider Operations have been restored or explicitly migrated with verified ownership.",+ "allowed_paths": [+ "crates/integrations/src/agents/additional_native.rs",+ "crates/integrations/src/agents/qoder_native_tests.rs"+ ]+ }+ ]+ },+ {+ "subject": "qoder_native_provider_restore",+ "audited_prefixes": [+ "hiroute.qoder-native-restore"+ ],+ "current_contracts": [+ "hiroute.qoder-native-restore/v2"+ ],+ "legacy_support": [+ {+ "contract": "hiroute.qoder-native-restore/v1",+ "mode": "recovery_read_only",+ "owner": "integrations/additional_native",+ "reason": "Restore original single-provider encrypted records without adopting user nodes; new writes own one provider per plan.",+ "removal_condition": "Remove only after all supported single-provider Operations have been restored or explicitly migrated with verified ownership.",+ "allowed_paths": [+ "crates/integrations/src/agents/additional_native.rs",+ "crates/integrations/src/agents/qoder_native_tests.rs"+ ]+ }+ ]}],"forbidden_contracts": [@@ -1097,6 +1143,21 @@"crates/local-storage/src/migrations/agent_surface_checks_v25.rs","crates/local-storage/src/migrations/agent_surface_checks_v25_tests.rs"]+ },+ {+ "contract": "hiroute.agent-model-grant/v3",+ "field": "route_protocols and corresponding plan_protocols / AdditionalAgentModel protocol omissions",+ "mode": "recovery_read_only",+ "owner": "domain/agents",+ "reason": "Existing grants and Operations keep their single sealed protocol; omitted additional-model fields retain Responses and original digest bytes. New UI writes explicit per-plan selections, mixed grants seal exact overrides.",+ "removal_condition": "Retire only with an explicit migration for retained grant and Operation identities.",+ "allowed_paths": [+ "crates/domain/src/agents/model_grant.rs",+ "crates/domain/src/agents/settings.rs",+ "crates/domain/src/agents/additional_model.rs",+ "crates/domain/src/publication/snapshot.rs",+ "crates/gateway/src/publication/schema.rs"+ ]}]}diff --git a/crates/application-api/src/agent_settings.rs b/crates/application-api/src/agent_settings.rsindex 8932f0fe..54d7cb63 100644--- a/crates/application-api/src/agent_settings.rs+++ b/crates/application-api/src/agent_settings.rs@@ -384,6 +384,7 @@ mod tests {fn qoder_model_verification_cannot_inherit_another_clients_success() {let mut value = status();value.current_selection = Some(AgentModelSelectionV2::QoderAdditional {+ plan_protocols: Default::default(),allowed_plan_ids: [AgentPlanId::parse("plan/test").unwrap()].into(),});assert!(!value.derive_model_verified(value.applied_revision));diff --git a/crates/application-api/src/client_access.rs b/crates/application-api/src/client_access.rsindex 757a2bb5..5fe1935d 100644--- a/crates/application-api/src/client_access.rs+++ b/crates/application-api/src/client_access.rs@@ -47,6 +47,7 @@ pub struct ClientServiceStatusV1 {#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(deny_unknown_fields)]pub struct AgentPlanStatusV2 {+ pub protocol_advice: hiroute_domain::AgentProtocolAdviceV1,pub agent_plan_id: AgentPlanId,pub desired: AgentPlanAuthoringV2,pub head: PlanHeadV1,diff --git a/crates/application-api/src/plan_authoring.rs b/crates/application-api/src/plan_authoring.rsindex 40f00557..9eb4ea9d 100644--- a/crates/application-api/src/plan_authoring.rs+++ b/crates/application-api/src/plan_authoring.rs@@ -168,6 +168,7 @@ pub struct PlanCandidateOptionV1 {pub billing_class: BillingClass,pub routable: bool,pub ingress_protocols: Vec<UpstreamProtocol>,+ pub native_ingress_protocols: Vec<UpstreamProtocol>,}#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]diff --git a/crates/application/src/agent_connection/additional_model_journal.rs b/crates/application/src/agent_connection/additional_model_journal.rsindex 9c70079d..8546bb2f 100644--- a/crates/application/src/agent_connection/additional_model_journal.rs+++ b/crates/application/src/agent_connection/additional_model_journal.rs@@ -1,10 +1,10 @@//! Non-secret additive Qoder model effects, bound to one settings Operation.use hiroute_domain::{AdditionalAgentModelV1, AgentConnectionControlIntentV1, AgentConnectionEffectRoleV1,- AgentConnectionTransactionKindV1, AgentFacetIntent, AgentIngressProtocolV1, AgentKindV1,- AgentModelGrantV2, AgentModelRouteV2, AgentModelSelectionV2, AgentOperationRead,- AgentSettingsSpecV2, CanonicalDigest, ExternalEffectIntentV1, OperationId,- OperationValidationError, PortError, PortErrorCode, PortResult,+ AgentConnectionTransactionKindV1, AgentFacetIntent, AgentKindV1, AgentModelGrantV2,+ AgentModelRouteV2, AgentModelSelectionV2, AgentOperationRead, AgentSettingsSpecV2,+ CanonicalDigest, ExternalEffectIntentV1, OperationId, OperationValidationError, PortError,+ PortErrorCode, PortResult,};use serde::{Deserialize, Serialize};@@ -190,8 +190,12 @@ pub fn settings_additional_model_file_for_operation((AgentFacetIntent::Configure {settings:- AgentModelSelectionV2::QoderAdditional { allowed_plan_ids }- | AgentModelSelectionV2::PiAdditional { allowed_plan_ids },+ AgentModelSelectionV2::QoderAdditional {+ allowed_plan_ids, ..+ }+ | AgentModelSelectionV2::PiAdditional {+ allowed_plan_ids, ..+ },},AdditionalModelFileAction::Configure {previous_operation,@@ -214,10 +218,10 @@ pub fn settings_additional_model_file_for_operation(return Err(invalid());};let scope = mutation.desired_scope().ok_or_else(invalid)?;- if scope.model_grant() != &grant || grant.protocol != AgentIngressProtocolV1::Responses+ if scope.model_grant() != &grant|| previous_operation.as_ref() == Some(operation.operation_id())|| models.len() != grant.routes.len() || models.len() != allowed_plan_ids.len()- || !models.iter().all(|model| matches!(grant.routes.get(&model.alias), Some(AgentModelRouteV2::Plan { plan_id, alias, .. }) if allowed_plan_ids.contains(plan_id) && alias.as_str() == model.alias))+ || !models.iter().all(|model| matches!(grant.routes.get(&model.alias), Some(AgentModelRouteV2::Plan { plan_id, alias, .. }) if allowed_plan_ids.contains(plan_id) && alias.as_str() == model.alias && grant.protocol_for(&model.alias) == model.protocol)){ return Err(invalid()); }}(diff --git a/crates/application/src/client_access/editor_options.rs b/crates/application/src/client_access/editor_options.rsindex 80d06137..d76d0df5 100644--- a/crates/application/src/client_access/editor_options.rs+++ b/crates/application/src/client_access/editor_options.rs@@ -111,6 +111,12 @@ pub(super) fn dispatch(reasoning: fact.reasoning.clone(),billing_class: fact.binding.billing_class,routable: fact.is_routable(),+ native_ingress_protocols: fact+ .protocol_profiles+ .iter()+ .filter(|p| p.ingress_protocol == p.capability.upstream_protocol)+ .map(|p| p.ingress_protocol)+ .collect(),ingress_protocols: fact.protocol_profiles.iter()diff --git a/crates/daemon/src/control/runtime/agent_live_check_qoder.rs b/crates/daemon/src/control/runtime/agent_live_check_qoder.rsindex e90c4592..ad4f7ab5 100644--- a/crates/daemon/src/control/runtime/agent_live_check_qoder.rs+++ b/crates/daemon/src/control/runtime/agent_live_check_qoder.rs@@ -46,11 +46,13 @@ impl LocalControlAdapter {.mode(0o600).open(&output_path).map_err(|_| unavailable())?;- let native_model = format!(- "{}/{}",- hiroute_application::agent_connection::additional_model_provider_id(context_id),- model- );+ let native_model = self+ .scanner+ .qoder_saved_plan_selector(+ &hiroute_application::agent_connection::additional_model_provider_id(context_id),+ model,+ )+ .map_err(|_| unavailable())?;let mut command = Command::new(executable);command.arg("--cwd")diff --git a/crates/daemon/src/control/runtime/client_access.rs b/crates/daemon/src/control/runtime/client_access.rsindex 14f4fb9d..fd2df7ed 100644--- a/crates/daemon/src/control/runtime/client_access.rs+++ b/crates/daemon/src/control/runtime/client_access.rs@@ -170,6 +170,7 @@ impl ClientAccessPort for LocalControlAdapter {.map_err(|_| ControlReadError::Corrupt)?;let desired = version.configuration;plans.push(AgentPlanStatusV2 {+ protocol_advice: hiroute_domain::agent_protocol_advice(&compiled.body.materialized),agent_plan_id: compiled.agent_plan_id().clone(),desired,head: head.clone(),diff --git a/crates/daemon/src/control/runtime/native_additional_model.rs b/crates/daemon/src/control/runtime/native_additional_model.rsindex 19c4308b..c2bd8102 100644--- a/crates/daemon/src/control/runtime/native_additional_model.rs+++ b/crates/daemon/src/control/runtime/native_additional_model.rs@@ -4,10 +4,10 @@ use hiroute_application::agent_connection::{AdditionalModelFileAction, additional_model_kind, settings_additional_model_file_for_operation,};use hiroute_domain::{- AdditionalAgentModelV1, AgentAccessGrantRefV1, AgentIngressProtocolV1, AgentKindV1,- AgentModelGrantV2, AgentModelRouteV2, ControlRepositoryPort, ExternalEffectIntentV1,- GatewayPublicationV1, OperationState, OperationStepKind, OperationV1, OwnedEffectV1, PortError,- PortErrorCode, PortResult, SecretStorePort, WorkspaceId, is_agent_access_grant_effect,+ AdditionalAgentModelV1, AgentAccessGrantRefV1, 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_additional_model(intent: &ExternalEffectIntentV1) -> bool {@@ -71,6 +71,7 @@ pub(super) fn additional_models_for_grant(.map_err(|_| conflict("qoder.models.budget"))?;Ok(AdditionalAgentModelV1 {alias: name.clone(),+ protocol: grant.protocol_for(name),context_window_tokens: budget.context_window_tokens,max_output_tokens: budget.max_output_tokens,})@@ -136,7 +137,6 @@ impl LocalControlAdapter {.ok_or_else(|| conflict("qoder.settings.scope"))?;if mutation.owner_scope() != operation.workspace_id.as_str()|| scope.connection_id() != format!("agent-connection/{}", payload.context_id)- || scope.protocol() != AgentIngressProtocolV1::Responses{return Err(conflict("qoder.settings.grant.binding"));}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 f7590353..70f5aba0 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@@ -173,8 +173,13 @@ 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::additional_model_provider_id(&fixture.context);+ let provider = configured["providers"]+ .as_object()+ .unwrap()+ .keys()+ .find(|id| id.starts_with("hiroute-main-"))+ .unwrap()+ .clone();assert_eq!(configured["providers"][&provider]["baseUrl"],"http://127.0.0.1:5837/_hiroute/qoder/v1"@@ -252,6 +257,13 @@ fn qoder_restore_rejects_native_default_reference_then_preserves_unrelated_edits.unwrap();let mut native: serde_json::Value =serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();+ let provider = native["providers"]+ .as_object()+ .unwrap()+ .keys()+ .find(|id| id.starts_with(&provider))+ .unwrap()+ .clone();native["model"]["name"] = json!(format!("{provider}/{alias}"));native["unknown"]["new_user_value"] = json!(9);private_file(@@ -289,7 +301,13 @@ fn qoder_restore_rejects_native_default_reference_then_preserves_unrelated_edits);let restored: serde_json::Value =serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();- assert!(restored["providers"].get(&provider).is_none());+ assert!(+ !restored["providers"]+ .as_object()+ .unwrap()+ .keys()+ .any(|id| id.starts_with(&provider))+ );assert_eq!(restored["unknown"]["new_user_value"], 9);assert_eq!(restored["model"]["name"], "native/default");}@@ -702,5 +720,11 @@ fn qoder_managed_bearer_permission_drift_revokes_live_eligibility_but_allows_resassert_eq!(restored["model"]["name"], "native/default");let provider =hiroute_application::agent_connection::additional_model_provider_id(&fixture.context);- assert!(restored["providers"].get(&provider).is_none());+ assert!(+ !restored["providers"]+ .as_object()+ .unwrap()+ .keys()+ .any(|id| id.starts_with(&provider))+ );}diff --git a/crates/daemon/src/control/runtime/settings_facts/additional_model.rs b/crates/daemon/src/control/runtime/settings_facts/additional_model.rsindex d4750ce2..b1f7b313 100644--- a/crates/daemon/src/control/runtime/settings_facts/additional_model.rs+++ b/crates/daemon/src/control/runtime/settings_facts/additional_model.rs@@ -191,11 +191,12 @@ impl LocalControlAdapter {);restore = Some((operation.operation_id.clone(), reference.clone()));}+ let protocol = AgentIngressProtocolV1::Responses;let qoder_model_conflict;let models = match &spec.model {AgentFacetIntent::Configure { settings } => {let grant = hiroute_domain::AgentModelGrantV2::derive(- AgentIngressProtocolV1::Responses,+ protocol,settings,&active,&BTreeMap::new(),@@ -296,7 +297,7 @@ impl LocalControlAdapter {input.facts.dependency_digest = dependency_digest;input.facts.model = Some(SettingsModelFacts {common: SettingsModelCommonFacts {- ingress: AgentIngressProtocolV1::Responses,+ ingress: protocol,available_surfaces: [if kind == hiroute_domain::AgentKindV1::Pi {AgentModelSurfaceV2::PiCli} else {diff --git a/crates/daemon/src/delegation/executor.rs b/crates/daemon/src/delegation/executor.rsindex 9eb5704d..76547fe2 100644--- a/crates/daemon/src/delegation/executor.rs+++ b/crates/daemon/src/delegation/executor.rs@@ -59,6 +59,7 @@ const MAX_INPUT_BYTES: usize = 256 * 1024;/// model credential is move-only and must be consumed by the profile renderer; it is never put/// in a task record, process argument, or diagnostic value.pub struct WorkerProfileInput {+ pub protocol: hiroute_domain::AgentIngressProtocolV1,pub task: DelegationTaskV1,pub run: DelegationRunV1,/// The already-verified frozen task version; native metadata must follow this version.@@ -405,6 +406,7 @@ impl DelegationRunExecutor {.clone();let profile_workspace_path = workspace_path.clone();let profile = match profiles.build(WorkerProfileInput {+ protocol: work.protocol,task: task.clone(),run: run.clone(),compiled_plan: version.compiled.clone(),diff --git a/crates/daemon/src/delegation/installation.rs b/crates/daemon/src/delegation/installation.rsindex 3fa78474..bddac9d9 100644--- a/crates/daemon/src/delegation/installation.rs+++ b/crates/daemon/src/delegation/installation.rs@@ -502,6 +502,7 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {.transpose().map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;CandidateWorkerProfile::build(ProfileInput {+ protocol: input.protocol,context_window_tokens: if let Some(budget) = qoder_budget {Some(budget.context_window_tokens)} else if installation.harness == WorkerHarnessV1::ClaudeCode {diff --git a/crates/daemon/src/delegation/installation/installation_probe.rs b/crates/daemon/src/delegation/installation/installation_probe.rsindex bd8f7b4f..5c744d2b 100644--- a/crates/daemon/src/delegation/installation/installation_probe.rs+++ b/crates/daemon/src/delegation/installation/installation_probe.rs@@ -297,6 +297,7 @@ fn build_profile(};let catalog = (worker == WorkerHarnessV1::CodexCli).then(|| test_codex_catalog(PROBE_MODEL));CandidateWorkerProfile::build(ProfileInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,context_window_tokens: None,max_output_tokens: None,harness: worker,diff --git a/crates/daemon/src/delegation/lifecycle/tests.rs b/crates/daemon/src/delegation/lifecycle/tests.rsindex c83b5fdc..5b6701d3 100644--- a/crates/daemon/src/delegation/lifecycle/tests.rs+++ b/crates/daemon/src/delegation/lifecycle/tests.rs@@ -233,6 +233,7 @@ fn inputs_in_context(let catalog =borrowed_root.map(|_| crate::delegation::profile::test_codex_catalog("fixed-alias"));let profile = CandidateWorkerProfile::build(ProfileInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,context_window_tokens: None,max_output_tokens: None,harness: WorkerHarnessV1::CodexCli,diff --git a/crates/daemon/src/delegation/profile/mod.rs b/crates/daemon/src/delegation/profile/mod.rsindex b7029c02..a322c220 100644--- a/crates/daemon/src/delegation/profile/mod.rs+++ b/crates/daemon/src/delegation/profile/mod.rs@@ -29,6 +29,7 @@ pub use materials::{};pub struct ProfileInput<'a> {+ pub protocol: hiroute_domain::AgentIngressProtocolV1,pub context_window_tokens: Option<u64>,/// Qoder's frozen catalogue output upper bound; other Harness renderers are unchanged.pub max_output_tokens: Option<u64>,diff --git a/crates/daemon/src/delegation/profile/pi.rs b/crates/daemon/src/delegation/profile/pi.rsindex 90f2fb79..d7011395 100644--- a/crates/daemon/src/delegation/profile/pi.rs+++ b/crates/daemon/src/delegation/profile/pi.rs@@ -32,7 +32,11 @@ pub(super) fn render(],..Default::default()};- let route = json!({"minimumNode":hiroute_integrations::PI_NODE_MINIMUM,"provider":provider,"endpoint":format!("http://{}/v1",input.gateway),+ let gateway_v1_base = format!("http://{}/v1", input.gateway);+ let (api, endpoint) =+ hiroute_integrations::agents::pi_native_provider_api(input.protocol, &gateway_v1_base)+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;+ let route = json!({"api":api,"minimumNode":hiroute_integrations::PI_NODE_MINIMUM,"provider":provider,"endpoint":endpoint,"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 [diff --git a/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs b/crates/daemon/src/delegation/profile/pi_worker_bridge.mjsindex 236ce19a..b918eeff 100644--- a/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs+++ b/crates/daemon/src/delegation/profile/pi_worker_bridge.mjs@@ -233,6 +233,7 @@ function ownedFile(path, root) {try {const route = JSON.parse(process.env.HIROUTE_PI_ROUTE);+ if (!["openai-responses", "anthropic-messages"].includes(route.api)) throw new Error();const nodeVersion = process.versions.node.split(".").map(Number);if (nodeVersion.some((part, index) =>@@ -284,7 +285,8 @@ try {},});runtime.registerProvider(route.provider, {- api: "openai-responses",+ api: route.api,+ headers: route.api === "anthropic-messages" ? { Authorization: `Bearer ${token}` } : {},baseUrl: route.endpoint,models: [route.model],});@@ -292,7 +294,7 @@ try {const model = runtime.getModels(route.provider).find((item) => item.id === route.model.id);if (!model ||- model.api !== "openai-responses" ||+ model.api !== route.api ||model.baseUrl !== route.endpoint ||model.contextWindow !== route.model.contextWindow ||model.maxTokens !== route.model.maxTokensdiff --git a/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs b/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjsindex 08fda934..7ac4f4d7 100644--- a/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs+++ b/crates/daemon/src/delegation/profile/pi_worker_bridge.test.mjs@@ -35,7 +35,7 @@ export class SettingsManager {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}));}+ registerProvider(provider, value) {if(process.env.FIXTURE_API) {receipt('api:'+value.api);receipt('managed-authorization:'+String(value.headers?.Authorization==='Bearer '+secret));}this.models=value.models.map(model=>({...model,provider,api:value.api,baseUrl:value.baseUrl}));}setRuntimeApiKey() {}getModels() {return this.models;}}@@ -109,6 +109,7 @@ function fixture(t, env = {}) {HIROUTE_PI_SESSION_ROOT: root,HIROUTE_RUN_TOKEN: "fixture-private-token-do-not-emit",HIROUTE_PI_ROUTE: JSON.stringify({+ api: env.FIXTURE_API || "openai-responses",minimumNode: [22, 19],provider: "managed",endpoint: "http://127.0.0.1:1/v1",@@ -371,3 +372,12 @@ for (const [replacement, target] of [assert.deepEqual(f.events(), []);});}++for (const api of ["openai-responses", "anthropic-messages"]) {+ test(`frozen ${api} route reaches SDK with protocol-specific managed authorization`, async (t) => {+ const f = fixture(t, { FIXTURE_API: api });+ assert.equal((await f.ready()).result.sessionId, "fixture-session");+ assert.ok(f.events().includes("api:" + api));+ assert.ok(f.events().includes("managed-authorization:" + String(api === "anthropic-messages")));+ });+}diff --git a/crates/daemon/src/delegation/profile/qoder.rs b/crates/daemon/src/delegation/profile/qoder.rsindex da41f053..9bfee8bc 100644--- a/crates/daemon/src/delegation/profile/qoder.rs+++ b/crates/daemon/src/delegation/profile/qoder.rs@@ -21,6 +21,7 @@ pub(super) fn render(let provider_id = format!("hiroute-worker-{task_key}");let endpoint = format!("http://{}/v1", input.gateway);let route = render_qoder_transient_route(QoderTransientRouteInput {+ protocol: input.protocol,provider_id: &provider_id,endpoint: &endpoint,alias: input.alias,diff --git a/crates/daemon/src/delegation/profile/tests.rs b/crates/daemon/src/delegation/profile/tests.rsindex 1efb8fe9..4fbeb2d6 100644--- a/crates/daemon/src/delegation/profile/tests.rs+++ b/crates/daemon/src/delegation/profile/tests.rs@@ -199,6 +199,7 @@ fn try_request_in_context(revoked: false,};CandidateWorkerProfile::build(ProfileInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,context_window_tokens: Some(272_000),max_output_tokens: (harness == WorkerHarnessV1::QoderCli).then_some(4096),harness,diff --git a/crates/daemon/tests/local_worker_support/mod.rs b/crates/daemon/tests/local_worker_support/mod.rsindex 4a30ad41..f58118e5 100644--- a/crates/daemon/tests/local_worker_support/mod.rs+++ b/crates/daemon/tests/local_worker_support/mod.rs@@ -50,6 +50,7 @@ pub fn request(root: &Path, cwd: &Path, nonce: &str, mode: &str) -> WorkerLaunch.unwrap();let builder_root = cwd.join(format!("build-{nonce}"));let mut profile = CandidateWorkerProfile::build(ProfileInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,context_window_tokens: None,max_output_tokens: None,harness: WorkerHarnessV1::CodexCli,diff --git a/crates/daemon/tests/support/additional_model_fixture.py b/crates/daemon/tests/support/additional_model_fixture.pyindex e9206069..857d7c8b 100644--- a/crates/daemon/tests/support/additional_model_fixture.py+++ b/crates/daemon/tests/support/additional_model_fixture.py@@ -80,9 +80,9 @@ class OwnedModelSettings:self.baseline['hirouteAcceptance'] = {'unknown': ['preserve', secrets.token_hex(8)]}self.write(self.baseline)- def install_conflicting_auth(self, provider):+ def install_conflicting_auth(self, providers):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_owned = json.dumps({provider:{"type":"api_key","key":"saved-key-must-not-override-route"} for provider in providers}).encode()self.auth_path.write_bytes(self.auth_owned)self.auth_path.chmod(0o600)@@ -97,7 +97,9 @@ class OwnedModelSettings:def assert_preserved(self, provider_id, selected_default=None):actual = self.read()- actual.get('providers', {}).pop(provider_id, None)+ for name in list(actual.get('providers', {})):+ if name == provider_id or name.startswith(provider_id + '-'):+ actual['providers'].pop(name)expected = deepcopy(self.baseline)if selected_default is not None:if self.harness == 'qoder':@@ -230,4 +232,18 @@ def read_persisted_route(product, binary, selector, source, oracle, label):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'}+ from native_context_boundaries import source_events+ observed_protocol = source_events(source)[-1]['protocol']+ if hasattr(source, 'expected_protocol'):+ assert observed_protocol == source.expected_protocol, 'native route did not use its chosen upstream protocol'+ return {'label': label, 'model': source.model, 'provider': selector.split('/', 1)[0],+ 'protocol': observed_protocol, 'native_session_id': native_session_id, 'state': 'green'}+++def persisted_plan_provider(settings, namespace, alias):+ """Select the native entry by its declared route, never by list ordering."""+ matches = [name for name, provider in settings.read().get('providers', {}).items()+ if (name == namespace or name.startswith(namespace + '-'))+ and any(model.get('id', model.get('model')) == alias for model in provider.get('models', []))]+ assert len(matches) == 1, 'persisted route must have exactly one provider'+ return matches[0]diff --git a/crates/daemon/tests/support/additional_model_product.py b/crates/daemon/tests/support/additional_model_product.pyindex aedefb1a..d8386f28 100644--- a/crates/daemon/tests/support/additional_model_product.py+++ b/crates/daemon/tests/support/additional_model_product.py@@ -22,13 +22,14 @@ from publication_process import plan_changefrom publication_product import Product, encodedfrom collaboration_product import apply_collaboration, check_collaboration as _check_collaboration, restore_skillfrom additional_model_fixture import (CASES, OwnedModelSettings, PersistedRouteOracle,- read_persisted_route, select_model_context)+ read_persisted_route, select_model_context, persisted_plan_provider)import qoder_native_contextHARNESS = "qoder"AGENT = "agent_qoder_default"MODE = "qoder_additional"TAIL = "/_hiroute/qoder/v1"+PLAN_PROTOCOLS = {}def check_collaboration(product, key):return _check_collaboration(product, key, agent=AGENT)@@ -36,7 +37,7 @@ def check_collaboration(product, key):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}})+ {'intent': 'configure', 'settings': {'mode': MODE, 'allowed_plan_ids': plans, 'plan_protocols': {p: PLAN_PROTOCOLS.get(p, 'responses') for p in plans}}})return {'schema_version': {'major': 2, 'minor': 0}, 'context_id': context, 'model': model,'collaboration': {'intent': 'keep'},'access_token': {'intent': 'regenerate' if regenerate else 'keep'}}@@ -48,7 +49,7 @@ def apply_models(product, spec, key):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)+ variant=HARNESS + '-model-' + str(index), context_tokens=100000, protocol='responses' if index == 0 else 'messages')product.editor = {'schema': 'hiroute.plan-editor/v2', 'display_name': 'Additional ' + HARNESS + ' route ' + str(index),'purpose': 'Read a persisted additional model route', 'mode': 'fixed_model',@@ -63,17 +64,21 @@ def publish_source_plan(product, source, 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']+ PLAN_PROTOCOLS[product.plan_id] = 'responses' if index == 0 else 'messages'+ source.expected_protocol = PLAN_PROTOCOLS[product.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)}, \+ assert status['current_selection'] == {'mode': MODE, 'allowed_plan_ids': sorted(plans), 'plan_protocols': {p: PLAN_PROTOCOLS.get(p, 'responses') for p in plans}}, \'model selection changed the selected Plan set'def assert_saved_aliases(settings, provider, aliases):- models = settings.read()['providers'][provider]['models']+ models = [model for name, value in settings.read()['providers'].items() if name == provider or name.startswith(provider + '-') for model in value['models']]+ for alias in aliases:+ assert len(settings.read()['providers'][persisted_plan_provider(settings, provider, alias)]['models']) == 1assert 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'@@ -97,24 +102,27 @@ def live_check(product, context, aliases, oracles):'Live verification must actually request each selected persisted route once'-def reject_gateway_request(product, token, alias, sources, expected_statuses):+def reject_gateway_request(product, token, alias, protocol, sources, expected_codes):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}),+ body = ({'model': alias, 'input': 'Untrusted removed route', 'max_output_tokens': 16, 'stream': True}+ if protocol == 'responses' else {'model': alias, 'messages': [{'role':'user','content':'Untrusted removed route'}],+ 'max_tokens':16, 'stream':True})+ client.request('POST', TAIL + '/' + protocol, body=encoded(body),headers={'Content-Type': 'application/json', **({'X-HiRoute-Token':token} if HARNESS == 'pi'else {'Authorization':'Bearer ' + token})})response = client.getresponse()- response.read()- assert response.status in expected_statuses, f'obsolete authority or removed alias rejection: {response.status}'+ error = json.loads(response.read())+ assert response.status in (401, 403, 404, 422) and error.get('code') in expected_codes, \+ f'obsolete authority or removed alias rejection: {response.status} {error.get("code")}'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']+ selected = persisted_plan_provider(settings, provider, plans[0]['alias']) + '/' + plans[0]['alias']settings.select_default(settings.native_default, selected)try:status = settings_status(product, context)@@ -148,6 +156,7 @@ def restore_models(product, context):def run(repository, candidate):global HARNESS, AGENT, MODE, TAIL+ PLAN_PROTOCOLS.clear()HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS', 'qoder')assert HARNESS in ('qoder', 'pi')AGENT = 'agent_' + HARNESS + '_default'@@ -201,13 +210,13 @@ def run(repository, candidate):settings.assert_preserved(provider)settings.add_user_edit(provider)if HARNESS == 'pi':- settings.install_conflicting_auth(provider)+ settings.install_conflicting_auth([persisted_plan_provider(settings, provider, plan['alias']) for plan in plans])for index, plan in enumerate(plans):- report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plan['alias'],+ report['native_reads'].append(read_persisted_route(product, binary, persisted_plan_provider(settings, provider, plan['alias']) + '/' + 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'],+ report['native_reads'].append(read_persisted_route(product, binary, persisted_plan_provider(settings, provider, plans[0]['alias']) + '/' + plans[0]['alias'],sources[0], oracles[0], 'after-daemon-restart'))if HARNESS == 'qoder':live_check(product, context, [plan['alias'] for plan in plans], oracles)@@ -219,8 +228,8 @@ def run(repository, candidate):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'],+ reject_gateway_request(product, old_token, plans[0]['alias'], PLAN_PROTOCOLS[plans[0]['plan_id']], sources, ('GATEWAY_GRANT_UNAUTHORIZED',))+ report['native_reads'].append(read_persisted_route(product, binary, persisted_plan_provider(settings, provider, plans[1]['alias']) + '/' + plans[1]['alias'],sources[1], oracles[1], 'after-token-rotation'))settings.assert_preserved(provider)report['cases'].append({'id': CASES[1], 'state': 'green'})@@ -238,7 +247,7 @@ def run(repository, candidate):restore_skill(product, context, collaboration['restore_point_ref'], before_skill, skill)skill_active = Falseassert_configured(settings_status(product, context), plan_ids)- report['native_reads'].append(read_persisted_route(product, binary, provider + '/' + plans[0]['alias'],+ report['native_reads'].append(read_persisted_route(product, binary, persisted_plan_provider(settings, provider, plans[0]['alias']) + '/' + 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.@@ -252,8 +261,9 @@ def run(repository, candidate):_, 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'],+ reject_gateway_request(product, product.bearer(product.agent_connection), plans[1]['alias'], PLAN_PROTOCOLS[plans[1]['plan_id']], sources,+ ('AGENT_MODEL_NOT_GRANTED', 'AGENT_PLAN_NOT_AVAILABLE', 'AGENT_PROTOCOL_UNSUPPORTED'))+ report['native_reads'].append(read_persisted_route(product, binary, persisted_plan_provider(settings, provider, plans[0]['alias']) + '/' + plans[0]['alias'],sources[0], oracles[0], 'after-route-adjustment'))restore_models(product, context)model_active = Falsediff --git a/crates/daemon/tests/support/native_context_fixture.py b/crates/daemon/tests/support/native_context_fixture.pyindex 9d37f3ed..f2f5d792 100644--- a/crates/daemon/tests/support/native_context_fixture.py+++ b/crates/daemon/tests/support/native_context_fixture.py@@ -96,13 +96,13 @@ def assert_preserved(fixture):def tool_results(body, harness):"""Only correlated tool-result records count, never arbitrary prompt substrings."""- if harness in ('codex', 'qoder', 'pi'):+ if 'messages' not in body: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'} \if isinstance(source, list) else {}return {block.get('tool_use_id'): block.get('content', '')- for message in body.get('messages', [])+ for message in body.get('messages', []) if message.get('role') == 'user'for block in (message.get('content', []) if isinstance(message.get('content'), list) else [])if isinstance(block, dict) and block.get('type') == 'tool_result'and block.get('is_error') is not True}@@ -111,7 +111,7 @@ def tool_results(body, harness):def qoder_skill_expansions(body, directory):"""Read exact native Skill user-message expansions, never a path substring."""expected_header = 'Base directory for this skill: ' + str(directory)- for item in body.get('input', []):+ for item in body.get('messages', body.get('input', [])):if not isinstance(item, dict) or item.get('role') != 'user':continuecontent = item.get('content', [])@@ -130,13 +130,13 @@ def native_text(value):return '\n'.join(native_text(item) for item in value)if isinstance(value, dict):return '\n'.join(native_text(item) for key, item in value.items()- if key in ('text', 'content', 'input', 'instructions', 'output'))+ if key in ('text', 'content', 'input', 'instructions', 'output', 'messages', 'system'))return ''def is_native_compaction(body):"""Pinned Qoder 1.1.65 request signature, independent of request order."""- items = body.get('input', [])+ items = body.get('messages', body.get('input', []))last = native_text(items[-1]) if isinstance(items, list) and items else native_text(items)return 'detailed summary' in last.lower() and 'summarization' in last.lower()@@ -145,7 +145,8 @@ def decision(fixture, body):"""Small deterministic model: require native discovery, then real tools, then history."""harness = fixture['harness']if harness == 'qoder' and 'expected_max_output_tokens' in fixture:- assert body.get('max_output_tokens') == fixture['expected_max_output_tokens'], \+ budget_field = 'max_tokens' if 'messages' in body else 'max_output_tokens'+ assert body.get(budget_field) == fixture['expected_max_output_tokens'], \'Qoder request did not carry the frozen source output budget'assert harness != 'qoder' or not is_native_compaction(body), \'unexpected Qoder compaction in the ordinary Skill journey; check the native context budget'diff --git a/crates/daemon/tests/support/native_context_product.py b/crates/daemon/tests/support/native_context_product.pyindex 31e90116..ea631d03 100644--- a/crates/daemon/tests/support/native_context_product.py+++ b/crates/daemon/tests/support/native_context_product.py@@ -24,9 +24,9 @@ import qoder_native_contextimport pi_native_context-def save_context_source(product, upstream, variant='', context_tokens=None):+def save_context_source(product, upstream, variant='', context_tokens=None, protocol=None):"""Declare a source budget supported by the selected native client contract."""- protocol = product.worker_work['protocol']+ protocol = protocol or product.worker_work['protocol']return save_native_source(product, upstream, token=upstream.token, protocol=protocol,upstream_model_id=upstream.model, variant=variant,context_tokens=context_tokens if context_tokens is not None else@@ -67,7 +67,8 @@ def prepare_product(product, harness, context_tokens=None):native = Path(product.env[roots[harness]])product.worker_work = {'harness': {'codex': 'codex_cli', 'claude': 'claude_code','qoder': 'qoder_cli', 'pi': 'pi'}[harness],- 'protocol': 'messages' if harness == 'claude' else 'responses'}+ 'protocol': 'messages' if harness == 'claude' else (os.environ.get('HIROUTE_PRODUCT_AGENT_PROTOCOL', 'responses') if harness in ('pi', 'qoder') else 'responses')}+ assert product.worker_work['protocol'] in ('responses', 'messages')fixture['source_context_tokens'] = (context_tokens if context_tokens is not Noneelse native_context_budget(product))upstream = NativeContextUpstream(product.root)@@ -126,10 +127,14 @@ def publish_replacement_route(product, fixture):upstream.model = 'gpt-5.5'upstream.token = 'synthetic-replacement-native-context-source-token'try:- saved = save_context_source(product, upstream, variant='native-context-replacement')+ replacement_work = dict(product.worker_work)+ if fixture['harness'] in ('qoder', 'pi'):+ replacement_work['protocol'] = 'messages' if replacement_work['protocol'] == 'responses' else 'responses'+ upstream.plan_protocol = replacement_work['protocol']+ saved = save_context_source(product, upstream, variant='native-context-replacement', protocol=upstream.plan_protocol)change = plan_change(product, 'update', display_name='Published replacement Worker route',candidates=[{'binding_id': saved['binding_id']}],- delegation_enabled=True, work=product.worker_work)+ delegation_enabled=True, work=replacement_work)preview = product.preview('routing preview', {'change': change})product.apply('routing apply', 'ApplyAgentPlanChange', preview,{'change': change}, 'native-plan-update')@@ -139,13 +144,15 @@ def publish_replacement_route(product, fixture):raise-def assert_frozen_route(original_events, before, replacement):+def assert_frozen_route(original_events, before, replacement, protocol=None):"""Require actual requests to the old route and no requests to the new route."""requests = original_events[before:]assert requests and all(event['state'] == 'green' for event in requests), \'Continue did not use the original source'assert any(event.get('continued') is True for event in requests), \'original source did not receive the resumed native history'+ if protocol is not None:+ assert all(event.get('protocol') == protocol for event in requests), 'Continue changed the frozen protocol'replacement_log = replacement.controls / 'native-context-events.jsonl'assert not replacement_log.exists() or not replacement_log.read_text().strip(), \'existing task used the newly published route'@@ -293,7 +300,9 @@ def run(repository, candidate):if restart:assert current_history == history, 'Continue changed native session or transcript'assert ready['plan_revision'] == report['frozen_plan_revision']- assert_frozen_route(events(product), before_requests, replacement)+ assert_frozen_route(events(product), before_requests, replacement, product.worker_work['protocol'])+ report['frozen_protocol'] = product.worker_work['protocol']+ report['current_plan_protocol'] = replacement.plan_protocolreport['continued_after_route_replacement'] = Trueelse:# The oracle required the first run's real tool history. Both turnsdiff --git a/crates/daemon/tests/support/pi_discovery_product.py b/crates/daemon/tests/support/pi_discovery_product.pyindex 34d54aec..42cbf3f9 100644--- a/crates/daemon/tests/support/pi_discovery_product.py+++ b/crates/daemon/tests/support/pi_discovery_product.py@@ -19,6 +19,8 @@ from publication_process import plan_changefrom agent_product_support import apply_settings, expose_native_installationfrom additional_model_fixture import PersistedRouteOracle, read_persisted_route+NATIVE_PREFIX = '\ufeff// Native effective endpoint differs from provider default\n'+CASES = ('agent.sources.effective-static-import', 'agent.sources.changed-source-rejected','agent.sources.imported-route-usable')@@ -48,7 +50,11 @@ def use_imported_route(product, binary, source, saved):oracle = PersistedRouteOracle(source.model)source.reply = oracle.replytry:- selector = configured['model_effect']['provider_id'] + '/' + plan['model_alias']+ namespace = configured['model_effect']['provider_id']+ providers = json.loads((Path(product.env['PI_CODING_AGENT_DIR']) / 'models.json').read_text().removeprefix(NATIVE_PREFIX))['providers']+ ids = [name for name, provider in providers.items() if name.startswith(namespace + '-') and any(m.get('id') == plan['model_alias'] for m in provider.get('models', []))]+ assert len(ids) == 1+ selector = ids[0] + '/' + 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']}@@ -93,7 +99,7 @@ def run(repository, candidate):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' ++ write_new(config / 'models.json', NATIVE_PREFIX +json.dumps({'providers':{'native-source':provider}}))write_new(config / 'auth.json', json.dumps({'native-source':{'type':'api_key','key':'${IMPORT_KEY}','env':{'IMPORT_KEY':source.token}}}))diff --git a/crates/domain/src/agents/additional_model.rs b/crates/domain/src/agents/additional_model.rsindex 172f3a6d..85834c0e 100644--- a/crates/domain/src/agents/additional_model.rs+++ b/crates/domain/src/agents/additional_model.rs@@ -63,6 +63,8 @@ pub fn validate_qoder_output_budget(tokens: u64) -> Result<(), QoderBudgetError>#[serde(deny_unknown_fields)]pub struct AdditionalAgentModelV1 {pub alias: String,+ #[serde(default = "responses_protocol", skip_serializing_if = "is_responses")]+ pub protocol: crate::AgentIngressProtocolV1,pub context_window_tokens: u64,pub max_output_tokens: u64,}@@ -90,3 +92,24 @@ impl AdditionalAgentModelV1 {Ok(())}}++pub fn responses_protocol() -> crate::AgentIngressProtocolV1 {+ crate::AgentIngressProtocolV1::Responses+}+fn is_responses(protocol: &crate::AgentIngressProtocolV1) -> bool {+ *protocol == responses_protocol()+}++/// Stable per-plan native identity. Alias changes already require a new plan identity.+pub fn additional_model_provider_for(+ provider: &str,+ _models: &[AdditionalAgentModelV1],+ model: &AdditionalAgentModelV1,+) -> String {+ additional_model_plan_provider_id(provider, &model.alias)+}++pub fn additional_model_plan_provider_id(provider: &str, alias: &str) -> String {+ let digest = crate::CanonicalDigest::of_bytes(alias.as_bytes());+ format!("{provider}-{}", &digest.as_str()[7..39])+}diff --git a/crates/domain/src/agents/model_grant.rs b/crates/domain/src/agents/model_grant.rsindex 688ccf07..1617bfb8 100644--- a/crates/domain/src/agents/model_grant.rs+++ b/crates/domain/src/agents/model_grant.rs@@ -63,6 +63,8 @@ impl ModelRequestRouteV2 {pub struct AgentModelGrantV2 {pub protocol: AgentIngressProtocolV1,pub routes: BTreeMap<String, AgentModelRouteV2>,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub route_protocols: BTreeMap<String, AgentIngressProtocolV1>,pub digest: CanonicalDigest,}@@ -88,7 +90,18 @@ impl AgentModelGrantV2 {) {return Err(AgentConnectionError::InvalidGrant);}- let mut routes = Self::plan_routes(protocol, selection.allowed_plan_ids(), publication)?;+ let mut routes = BTreeMap::new();+ let mut route_protocols = BTreeMap::new();+ for id in selection.allowed_plan_ids() {+ let selected = selection.plan_protocol(&id, protocol);+ let plan_routes = Self::plan_routes(selected, [id].into(), publication)?;+ for name in plan_routes.keys() {+ if selected != protocol {+ route_protocols.insert(name.clone(), selected);+ }+ }+ routes.extend(plan_routes);+ }for fixed in selection.fixed_models() {let binding = fixed_bindings.get(&fixed.client_model_id)@@ -107,7 +120,7 @@ impl AgentModelGrantV2 {return Err(AgentConnectionError::InvalidGrant);}}- Self::seal(protocol, routes)+ Self::seal_routes(protocol, routes, route_protocols)}pub fn from_plan_ids(@@ -169,8 +182,16 @@ impl AgentModelGrantV2 {}pub fn seal(+ protocol: AgentIngressProtocolV1,+ routes: BTreeMap<String, AgentModelRouteV2>,+ ) -> Result<Self, AgentConnectionError> {+ Self::seal_routes(protocol, routes, BTreeMap::new())+ }++ pub fn seal_routes(protocol: AgentIngressProtocolV1,mut routes: BTreeMap<String, AgentModelRouteV2>,+ route_protocols: BTreeMap<String, AgentIngressProtocolV1>,) -> Result<Self, AgentConnectionError> {for route in routes.values_mut() {if let AgentModelRouteV2::Fixed { binding, .. } = route {@@ -179,19 +200,43 @@ impl AgentModelGrantV2 {.map_err(|_| AgentConnectionError::InvalidGrant)?;}}- let digest = CanonicalDigest::of(&("hiroute.agent-model-grant/v3", protocol, &routes))- .map_err(|_| AgentConnectionError::Encoding)?;+ let digest = Self::route_digest(protocol, &routes, &route_protocols)?;let grant = Self {protocol,routes,+ route_protocols,digest,};grant.validate()?;Ok(grant)}+ pub fn protocol_for(&self, name: &str) -> AgentIngressProtocolV1 {+ self.route_protocols+ .get(name)+ .copied()+ .unwrap_or(self.protocol)+ }+ fn route_digest(+ protocol: AgentIngressProtocolV1,+ routes: &BTreeMap<String, AgentModelRouteV2>,+ protocols: &BTreeMap<String, AgentIngressProtocolV1>,+ ) -> Result<CanonicalDigest, AgentConnectionError> {+ if protocols.is_empty() {+ CanonicalDigest::of(&("hiroute.agent-model-grant/v3", protocol, routes))+ } else {+ CanonicalDigest::of(&("hiroute.agent-model-grant/v3", protocol, routes, protocols))+ }+ .map_err(|_| AgentConnectionError::Encoding)+ }+pub fn validate(&self) -> Result<(), AgentConnectionError> {- if self.routes.is_empty() {+ if self.routes.is_empty()+ || self.route_protocols.iter().any(|(name, protocol)| {+ *protocol == self.protocol+ || !matches!(self.routes.get(name), Some(AgentModelRouteV2::Plan { .. }))+ })+ {return Err(AgentConnectionError::InvalidGrant);}let ingress = match self.protocol {@@ -235,10 +280,7 @@ impl AgentModelGrantV2 {}}}- if CanonicalDigest::of(&("hiroute.agent-model-grant/v3", self.protocol, &self.routes))- .map_err(|_| AgentConnectionError::Encoding)?- != self.digest- {+ if Self::route_digest(self.protocol, &self.routes, &self.route_protocols)? != self.digest {return Err(AgentConnectionError::DigestMismatch);}Ok(())@@ -272,7 +314,10 @@ impl AgentModelGrantV2 {AgentModelRouteV2::Fixed { .. } => None,}).collect::<std::collections::BTreeSet<_>>();- if plans != selection.allowed_plan_ids()+ if self.routes.iter().any(|(name, route)| match route {+ AgentModelRouteV2::Plan { plan_id, .. } => self.protocol_for(name) != selection.plan_protocol(plan_id, self.protocol),+ _ => false,+ }) || plans != selection.allowed_plan_ids()|| self.routes.len() != plans.len() + selection.fixed_models().len()|| selection.fixed_models().iter().any(|fixed| {!matches!(self.routes.get(&fixed.client_model_id),@@ -390,6 +435,7 @@ mod tests {#[test]fn qoder_additional_routes_authorize_only_selected_plans_without_native_defaults() {let selection = AgentModelSelectionV2::QoderAdditional {+ plan_protocols: Default::default(),allowed_plan_ids: [AgentPlanId::parse("plan/example").unwrap()].into(),};let grant = grant();@@ -397,6 +443,7 @@ mod tests {assert!(grant.codex_default_override(&selection).is_err());assert!(selection.fixed_models().is_empty());let other = AgentModelSelectionV2::QoderAdditional {+ plan_protocols: Default::default(),allowed_plan_ids: [AgentPlanId::parse("plan/other").unwrap()].into(),};assert!(grant.validate_selection(&other).is_err());@@ -405,6 +452,7 @@ mod tests {assert!(wrong_protocol.validate_selection(&selection).is_err());assert!(AgentModelSelectionV2::QoderAdditional {+ plan_protocols: Default::default(),allowed_plan_ids: Default::default(),}.validate()@@ -419,6 +467,42 @@ mod tests {}}+ #[test]+ fn explicit_plan_protocol_is_sealed_and_cannot_expand_other_clients() {+ let base = grant();+ let id = AgentPlanId::parse("plan/example").unwrap();+ let selected = AgentModelSelectionV2::PiAdditional {+ allowed_plan_ids: [id.clone()].into(),+ plan_protocols: [(id.clone(), AgentIngressProtocolV1::Messages)].into(),+ };+ assert!(base.validate_selection(&selected).is_err());+ let messages = AgentModelGrantV2::seal_routes(+ base.protocol,+ base.routes.clone(),+ [("hiroute-example".into(), AgentIngressProtocolV1::Messages)].into(),+ )+ .unwrap();+ assert_ne!(messages.digest, base.digest);+ assert!(messages.validate_selection(&selected).is_ok());+ assert_eq!(+ messages.protocol_for("hiroute-example"),+ AgentIngressProtocolV1::Messages+ );+ let legacy = AgentModelSelectionV2::PiAdditional {+ allowed_plan_ids: [id].into(),+ plan_protocols: BTreeMap::new(),+ };+ assert!(messages.validate_selection(&legacy).is_err());+ assert!(+ AgentModelGrantV2::seal_routes(+ base.protocol,+ base.routes,+ [("ungranted".into(), AgentIngressProtocolV1::Messages)].into()+ )+ .is_err()+ );+ }+#[test]fn claude_presets_keep_absence_and_native_values_without_a_default() {use crate::{diff --git a/crates/domain/src/agents/settings.rs b/crates/domain/src/agents/settings.rsindex 41e7627a..216ff96a 100644--- a/crates/domain/src/agents/settings.rs+++ b/crates/domain/src/agents/settings.rs@@ -1,7 +1,7 @@//! Independent main-Agent settings. An omitted facet means keep, never implicit revocation.use crate::{AgentPlanId, SchemaVersion};use serde::{Deserialize, Serialize};-use std::collections::BTreeSet;+use std::collections::{BTreeMap, BTreeSet};pub const AGENT_SETTINGS_SCHEMA_V2: SchemaVersion = SchemaVersion::new(2, 0);@@ -28,9 +28,13 @@ pub enum AgentModelSelectionV2 {},PiAdditional {allowed_plan_ids: BTreeSet<AgentPlanId>,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ plan_protocols: BTreeMap<AgentPlanId, crate::AgentIngressProtocolV1>,},QoderAdditional {allowed_plan_ids: BTreeSet<AgentPlanId>,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ plan_protocols: BTreeMap<AgentPlanId, crate::AgentIngressProtocolV1>,},ClaudeLauncher {surfaces: BTreeSet<AgentModelSurfaceV2>,@@ -95,6 +99,20 @@ pub struct AgentClaudePresetValuesV2 {}impl AgentModelSelectionV2 {+ pub fn plan_protocol(+ &self,+ id: &AgentPlanId,+ fallback: crate::AgentIngressProtocolV1,+ ) -> crate::AgentIngressProtocolV1 {+ match self {+ Self::QoderAdditional { plan_protocols, .. }+ | Self::PiAdditional { plan_protocols, .. } => {+ plan_protocols.get(id).copied().unwrap_or(fallback)+ }+ _ => fallback,+ }+ }+pub fn fixed_models(&self) -> &[AgentFixedModelSelectionV2] {match self {Self::CodexDefault { fixed_models, .. } | Self::ClaudeLauncher { fixed_models, .. } => {@@ -109,8 +127,12 @@ impl AgentModelSelectionV2 {Self::CodexDefault {allowed_plan_ids, ..}- | Self::QoderAdditional { allowed_plan_ids }- | Self::PiAdditional { 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, ..} => [@@ -159,7 +181,12 @@ impl AgentModelSelectionV2 {AgentModelDefaultSelectionV2::Plan { plan_id } if plans.contains(plan_id) => {}_ => return Err(invalid),},- Self::QoderAdditional { .. } | Self::PiAdditional { .. } => {}+ Self::QoderAdditional { plan_protocols, .. }+ | Self::PiAdditional { plan_protocols, .. } => {+ if plan_protocols.keys().any(|id| !plans.contains(id)) {+ return Err(crate::AgentConnectionError::InvalidGrant);+ }+ }Self::ClaudeLauncher { surfaces, .. } => {if *surfaces != BTreeSet::from([AgentModelSurfaceV2::ClaudeCli]) {return Err(invalid);diff --git a/crates/domain/src/publication/plan_state.rs b/crates/domain/src/publication/plan_state.rsindex 25666725..556c633d 100644--- a/crates/domain/src/publication/plan_state.rs+++ b/crates/domain/src/publication/plan_state.rs@@ -176,9 +176,14 @@ impl GatewayPublicationV1 {});if !routes.is_empty() {let mut projected = grant.clone();- projected.model_grant =- crate::AgentModelGrantV2::seal(grant.model_grant.protocol, routes)- .map_err(|_| PublicationError::InvalidGrant)?;+ let mut protocols = grant.model_grant.route_protocols.clone();+ protocols.retain(|name, _| routes.contains_key(name));+ projected.model_grant = crate::AgentModelGrantV2::seal_routes(+ grant.model_grant.protocol,+ routes,+ protocols,+ )+ .map_err(|_| PublicationError::InvalidGrant)?;enabled.push(projected);}}diff --git a/crates/domain/src/publication/projection.rs b/crates/domain/src/publication/projection.rsindex e2e4cdd6..b154aa83 100644--- a/crates/domain/src/publication/projection.rs+++ b/crates/domain/src/publication/projection.rs@@ -80,8 +80,12 @@ pub(super) fn rebind_current_grant_routes(return Err(PublicationError::InvalidGrant);}}- let model_grant = crate::AgentModelGrantV2::seal(grant.model_grant.protocol, routes)- .map_err(|_| PublicationError::InvalidGrant)?;+ let model_grant = crate::AgentModelGrantV2::seal_routes(+ grant.model_grant.protocol,+ routes,+ grant.model_grant.route_protocols,+ )+ .map_err(|_| PublicationError::InvalidGrant)?;Ok(GatewayExecutableGrantV2 {grant_id: grant.grant_id,generation: grant.generation,@@ -148,7 +152,7 @@ pub(super) fn materialize_aliases(let protocols = grants.iter().filter(|grant| grant.permits_plan(plan.model_alias()))- .map(|grant| grant.model_grant.protocol)+ .map(|grant| grant.model_grant.protocol_for(plan.model_alias().as_str())).collect::<BTreeSet<_>>().into_iter().collect::<Vec<_>>();diff --git a/crates/domain/src/publication/snapshot.rs b/crates/domain/src/publication/snapshot.rsindex 4c341966..09ee72f2 100644--- a/crates/domain/src/publication/snapshot.rs+++ b/crates/domain/src/publication/snapshot.rs@@ -25,6 +25,8 @@ pub struct GatewayProjectedGrantV2 {pub generation: u64,pub bearer_token_sha256: CanonicalDigest,pub protocol: AgentIngressProtocolV1,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub route_protocols: BTreeMap<String, AgentIngressProtocolV1>,pub routes: BTreeMap<String, GatewayModelRouteV2>,}@@ -46,6 +48,12 @@ pub(super) fn project_grants(.routes.into_iter().map(|(name, route)| {+ let route_protocol = grant+ .model_grant+ .route_protocols+ .get(&name)+ .copied()+ .unwrap_or(protocol);let route = match route {crate::AgentModelRouteV2::Plan {plan_id,@@ -64,7 +72,7 @@ pub(super) fn project_grants(&& semantic_digest != plan.body.materialized_route_digest)|| !aliases.iter().any(|projected| {projected.served_model_id == alias- && projected.protocols.contains(&protocol)+ && projected.protocols.contains(&route_protocol)}){return Err(PublicationError::InvalidGrant);@@ -117,6 +125,7 @@ pub(super) fn project_grants(generation: grant.generation,bearer_token_sha256: grant.bearer_token_sha256,protocol,+ route_protocols: grant.model_grant.route_protocols,routes,})})diff --git a/crates/domain/src/routing/mod.rs b/crates/domain/src/routing/mod.rsindex 621dfb2b..14e4fbe1 100644--- a/crates/domain/src/routing/mod.rs+++ b/crates/domain/src/routing/mod.rs@@ -10,6 +10,8 @@ mod classifier;mod context_window;mod gateway_execution;mod materialized;+mod native_protocol;+pub use native_protocol::{AgentProtocolAdviceV1, agent_protocol_advice};mod stored;mod stored_capability;pub use stored::*;diff --git a/crates/domain/src/routing/native_protocol.rs b/crates/domain/src/routing/native_protocol.rsnew file mode 100644index 00000000..ee4ca304--- /dev/null+++ b/crates/domain/src/routing/native_protocol.rs@@ -0,0 +1,93 @@+//! Advice only: selecting a protocol remains an explicit user decision.+use crate::{AgentIngressProtocolV1, MaterializedAgentPlanV1, UpstreamProtocol};+use serde::{Deserialize, Serialize};++#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct AgentProtocolAdviceV1 {+ pub supported: Vec<AgentIngressProtocolV1>,+ pub native: Vec<AgentIngressProtocolV1>,+}++pub fn agent_protocol_advice(plan: &MaterializedAgentPlanV1) -> AgentProtocolAdviceV1 {+ let candidates = plan+ .attempt_owned+ .groups+ .iter()+ .flat_map(|g| &g.candidates)+ .collect::<Vec<_>>();+ let mut advice = AgentProtocolAdviceV1::default();+ if candidates.is_empty() {+ return advice;+ }+ for (ingress, upstream) in [+ (+ AgentIngressProtocolV1::Responses,+ UpstreamProtocol::Responses,+ ),+ (AgentIngressProtocolV1::Messages, UpstreamProtocol::Messages),+ ] {+ if candidates.iter().all(|c| {+ c.protocol_profiles+ .iter()+ .any(|p| p.ingress_protocol == upstream)+ }) {+ advice.supported.push(ingress);+ }+ if candidates.iter().all(|c| {+ c.protocol_profiles.iter().any(|p| {+ p.ingress_protocol == upstream && p.capability.upstream_protocol == upstream+ })+ }) {+ advice.native.push(ingress);+ }+ }+ advice+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn recommendation_requires_every_candidate_and_fallback_to_be_native() {+ let publication: crate::GatewayPublicationV1 = serde_json::from_slice(include_bytes!(+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"+ ))+ .unwrap();+ let mut plan = publication.plans[0].body.materialized.clone();+ for c in plan+ .attempt_owned+ .groups+ .iter_mut()+ .flat_map(|g| &mut g.candidates)+ {+ c.protocol_profiles+ .retain(|p| p.ingress_protocol == UpstreamProtocol::Responses);+ for p in &mut c.protocol_profiles {+ p.capability.upstream_protocol = UpstreamProtocol::Responses;+ }+ }+ assert_eq!(+ agent_protocol_advice(&plan).native,+ vec![AgentIngressProtocolV1::Responses]+ );+ let mut fallback = plan.attempt_owned.groups[0].clone();+ for c in &mut fallback.candidates {+ for p in &mut c.protocol_profiles {+ p.capability.upstream_protocol = UpstreamProtocol::Messages;+ }+ }+ plan.attempt_owned.groups.push(fallback);+ let advice = agent_protocol_advice(&plan);+ assert_eq!(advice.supported, vec![AgentIngressProtocolV1::Responses]);+ assert!(+ advice.native.is_empty(),+ "conversion support is not native support"+ );+ plan.attempt_owned.groups.clear();+ assert_eq!(+ agent_protocol_advice(&plan),+ AgentProtocolAdviceV1::default()+ );+ }+}diff --git a/crates/gateway/benches/gateway_product_paths.rs b/crates/gateway/benches/gateway_product_paths.rsindex 65488c77..31aec80c 100644--- a/crates/gateway/benches/gateway_product_paths.rs+++ b/crates/gateway/benches/gateway_product_paths.rs@@ -508,6 +508,7 @@ impl Fixture {)],}],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "gateway-benchmark-grant".into(),generation: 1,bearer_token_sha256: token_sha256(TOKEN),diff --git a/crates/gateway/src/adapters/ingress.rs b/crates/gateway/src/adapters/ingress.rsindex c9cb4430..0eb2ec6f 100644--- a/crates/gateway/src/adapters/ingress.rs+++ b/crates/gateway/src/adapters/ingress.rs@@ -917,9 +917,20 @@ fn decode_messages_tools(ensure_keys(context,object,- &["name", "description", "input_schema", "strict"],+ &[+ "name",+ "description",+ "input_schema",+ "strict",+ "eager_input_streaming",+ "cache_control",+ ],"messages Tool",)?;+ // Known delivery/cache hints do not grant another tool or execution target.+ // Native projection preserves them; conversion keeps the canonical function.+ optional_bool(object, "eager_input_streaming")?;+ validate_messages_cache_control(context, object.get("cache_control"))?;Ok(CanonicalTool {kind: ToolKindV1::Function,name: required_string(object, "name")?,diff --git a/crates/gateway/src/adapters/tests/payload_tolerance.rs b/crates/gateway/src/adapters/tests/payload_tolerance.rsindex ca618d48..abd0594e 100644--- a/crates/gateway/src/adapters/tests/payload_tolerance.rs+++ b/crates/gateway/src/adapters/tests/payload_tolerance.rs@@ -404,3 +404,47 @@ fn messages_stop_sequence_is_completion_metadata_not_a_decode_failure() {assert!(response.response.completed);assert!(!response.response.blocks.is_empty());}++#[test]+fn native_messages_tool_delivery_hints_survive_without_authorizing_unknown_tools() {+ let body = json!({"model":"alias","max_tokens":1024,"stream":true,+ "messages":[{"role":"user","content":"read the fixture"}],+ "tools":[{"name":"read","description":"Read a local fixture",+ "input_schema":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]},+ "eager_input_streaming":true,"cache_control":{"type":"ephemeral"}}]});+ let request = decode_ingress_request(IngressProtocol::Messages, &body).unwrap();+ assert_eq!(request.tools.len(), 1);+ assert_eq!(request.tools[0].kind, ToolKindV1::Function);+ let profile = exact_state_profile(IngressProtocol::Messages, IngressProtocol::Messages);+ let projected = project_candidate_request(&request, &profile).unwrap();+ assert_eq!(projected.body["tools"], body["tools"]);+ let converted = project_candidate_request(+ &request,+ &exact_state_profile(IngressProtocol::Messages, IngressProtocol::Responses),+ )+ .unwrap();+ assert_eq!(converted.body["tools"][0]["name"], "read");+ assert_eq!(+ converted.body["tools"][0]["parameters"],+ body["tools"][0]["input_schema"]+ );+ assert!(+ converted.body["tools"][0]+ .get("eager_input_streaming")+ .is_none()+ );+ for (key, value) in [+ ("eager_input_streaming", json!("true")),+ ("endpoint", json!("http://untrusted.invalid")),+ ("mcp_servers", json!([])),+ ("defer_loading", json!(true)),+ ("type", json!("computer_20250124")),+ ] {+ let mut invalid = body.clone();+ invalid["tools"][0][key] = value;+ assert!(+ decode_ingress_request(IngressProtocol::Messages, &invalid).is_err(),+ "{key}"+ );+ }+}diff --git a/crates/gateway/src/core_runtime.rs b/crates/gateway/src/core_runtime.rsindex f3e39c58..b1ff849d 100644--- a/crates/gateway/src/core_runtime.rs+++ b/crates/gateway/src/core_runtime.rs@@ -1390,7 +1390,7 @@ fn inbound_authorization<'a>() -> Option<std::borrow::Cow<'a, str>> {if path.strip_prefix(hiroute_domain::QODER_MODEL_BASE_PATH)- .is_some_and(|resource| matches!(resource, "/responses" | "/models"))+ .is_some_and(|resource| matches!(resource, "/responses" | "/messages" | "/models")){// This explicit native entry consumes only local model-grant credentials.// Normal publication authentication still rejects unissued/native account@@ -1413,7 +1413,7 @@ fn inbound_authorization<'a>(return Some(std::borrow::Cow::Borrowed(authorization));}if headers.contains_key("x-hiroute-token") {- if !matches!(path, "/v1/responses" | "/v1/models")+ if !matches!(path, "/v1/responses" | "/v1/messages" | "/v1/models")|| headers.get_all("x-hiroute-token").iter().count() != 1{return None;diff --git a/crates/gateway/src/core_runtime/inbound_auth_tests.rs b/crates/gateway/src/core_runtime/inbound_auth_tests.rsindex 5495ffaf..d893df98 100644--- a/crates/gateway/src/core_runtime/inbound_auth_tests.rs+++ b/crates/gateway/src/core_runtime/inbound_auth_tests.rs@@ -3,13 +3,18 @@ use super::*;#[test]fn qoder_model_entry_is_explicit_and_never_adopts_worker_or_mixed_credentials() {let path = format!("{}/responses", hiroute_domain::QODER_MODEL_BASE_PATH);+ let messages = format!("{}/messages", hiroute_domain::QODER_MODEL_BASE_PATH);+ assert_eq!(+ IngressProtocol::from_path(&messages),+ Some(IngressProtocol::Messages)+ );let catalog = format!("{}/models", hiroute_domain::QODER_MODEL_BASE_PATH);assert_eq!(IngressProtocol::from_path(&path),Some(IngressProtocol::Responses));let mut headers = HeaderMap::new();- for target in [&path, &catalog] {+ for target in [&path, &messages, &catalog] {headers.insert(AUTHORIZATION,HeaderValue::from_static("Bearer local-model-grant"),@@ -70,7 +75,7 @@ fn x_api_key_never_authenticates_and_bearer_wins_when_both_are_present() {}#[test]-fn codex_requires_independent_grant_without_native_bearer_fallback() {+fn model_entry_uses_independent_grant_without_native_bearer_fallback() {let mut headers = HeaderMap::new();headers.insert(AUTHORIZATION,@@ -82,7 +87,10 @@ fn codex_requires_independent_grant_without_native_bearer_fallback() {inbound_authorization("/v1/responses", &headers).as_deref(),Some("Bearer model-grant"));- assert!(inbound_authorization("/v1/messages", &headers).is_none());+ assert_eq!(+ inbound_authorization("/v1/messages", &headers).as_deref(),+ Some("Bearer model-grant")+ );headers.insert("x-hiroute-token", HeaderValue::from_static(""));assert!(inbound_authorization("/v1/responses", &headers).is_none());}diff --git a/crates/gateway/src/dispatch/authority.rs b/crates/gateway/src/dispatch/authority.rsindex 36cc26a1..31fb7913 100644--- a/crates/gateway/src/dispatch/authority.rs+++ b/crates/gateway/src/dispatch/authority.rs@@ -95,7 +95,11 @@ impl GatewayRequestAuthority {.ok_or(DispatchError::Unauthorized)?;(publication, grant, None)};- if grant.protocol != protocol {+ if !grant+ .routes+ .keys()+ .any(|name| grant.protocol_for(name) == protocol)+ {return Err(DispatchError::AgentPlanProtocolUnsupported);}let has_protocol_alias = grant.routes.values().any(|route| match route {@@ -169,6 +173,9 @@ impl AuthenticatedRequest {.routes.get(served_model_id).ok_or(DispatchError::AgentModelNotGranted)?;+ if self.grant.protocol_for(served_model_id) != self.protocol {+ return Err(DispatchError::AgentPlanProtocolUnsupported);+ }let (execution, provenance, plan_display_name) = match route {CompiledGrantRoute::Plan { alias } => {let alias = selfdiff --git a/crates/gateway/src/dispatch/run.rs b/crates/gateway/src/dispatch/run.rsindex b34c85a7..427efb5a 100644--- a/crates/gateway/src/dispatch/run.rs+++ b/crates/gateway/src/dispatch/run.rs@@ -227,6 +227,7 @@ impl VerifiedRunRequestAuthority {.authenticate(authorization).ok_or(RunRequestAuthorityError::Denied)?;if grant.protocol != protocol+ || !grant.route_protocols.is_empty()|| grant.routes.len() != 1|| !matches!(grant.routes.get(self.publication.model_alias()),Some(crate::server::publication::CompiledGrantRoute::Plan { alias })@@ -364,6 +365,7 @@ mod tests {candidates: vec![exact_test_candidate(1, IngressProtocol::Responses, None)],}],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "delegation-run/run-one".into(),generation: 1,bearer_token_sha256: token_sha256(TOKEN),diff --git a/crates/gateway/src/dispatch/tests.rs b/crates/gateway/src/dispatch/tests.rsindex f986fb6f..65c385e5 100644--- a/crates/gateway/src/dispatch/tests.rs+++ b/crates/gateway/src/dispatch/tests.rs@@ -121,6 +121,7 @@ fn runtime(},],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "grant".into(),generation: 1,bearer_token_sha256: token_sha256("token"),@@ -279,6 +280,7 @@ fn selector_budget_is_independent_of_extreme_agent_plan_budgets() {"renderer",aliases,vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "budget-grant".into(),generation: 1,bearer_token_sha256: token_sha256("budget-token"),diff --git a/crates/gateway/src/observation.rs b/crates/gateway/src/observation.rsindex 6c6fad5b..3afebb46 100644--- a/crates/gateway/src/observation.rs+++ b/crates/gateway/src/observation.rs@@ -104,7 +104,7 @@ pub enum NativeAgentObservationIdentityV1 {CodexSession {session_id: String,},- /// Qoder 1.1.65 sends its native session UUID in the Responses `session-id` header.+ /// Qoder native session UUID from the supported API client `session-id` header.QoderSession {session_id: String,},@@ -169,7 +169,11 @@ pub fn derive_native_agent_observation_session_id(("codex_session", vec![session_id.as_str()])}NativeAgentObservationIdentityV1::QoderSession { session_id } => {- if trust.ingress_protocol != hiroute_domain::IngressProtocolV1::Responses {+ if !matches!(+ trust.ingress_protocol,+ hiroute_domain::IngressProtocolV1::Responses+ | hiroute_domain::IngressProtocolV1::Messages+ ) {return Err(NativeAgentObservationSessionError::UnsupportedIngress);}// The existing wire producer already accepts this header independently of clientdiff --git a/crates/gateway/src/observation/tests.rs b/crates/gateway/src/observation/tests.rsindex 20a40e98..d3669346 100644--- a/crates/gateway/src/observation/tests.rs+++ b/crates/gateway/src/observation/tests.rs@@ -100,8 +100,27 @@ fn native_agent_session_derivation_reuses_the_producer_identity_formula() {session,derive_native_agent_observation_session_id(&workspace, &key, &other_grant, &qoder).unwrap());+ let mut messages_trust = trust.clone();+ messages_trust.ingress_protocol = hiroute_domain::IngressProtocolV1::Messages;+ let messages_session =+ derive_native_agent_observation_session_id(&workspace, &key, &messages_trust, &qoder)+ .unwrap();+ assert_ne!(+ session, messages_session,+ "protocol remains part of the trusted session identity"+ );+ assert_eq!(+ messages_session,+ derive_native_agent_observation_session_id(+ &workspace,+ &key,+ &messages_trust,+ &header_session+ )+ .unwrap()+ );let mut wrong_protocol = trust;- wrong_protocol.ingress_protocol = hiroute_domain::IngressProtocolV1::Messages;+ wrong_protocol.ingress_protocol = hiroute_domain::IngressProtocolV1::ChatCompletions;assert!(derive_native_agent_observation_session_id(&workspace, &key, &wrong_protocol, &qoder).is_err()diff --git a/crates/gateway/src/publication/catalog.rs b/crates/gateway/src/publication/catalog.rsindex f0eb4541..7b38f6e0 100644--- a/crates/gateway/src/publication/catalog.rs+++ b/crates/gateway/src/publication/catalog.rs@@ -55,7 +55,11 @@ fn render(let Some(alias) = publication.aliases.get(alias) else {continue;};- if !alias.execution.protocols.contains(&grant.protocol) {+ if !alias+ .execution+ .protocols+ .contains(&grant.protocol_for(name))+ {continue;}(@@ -72,7 +76,7 @@ fn render(owned_by: "hiroute",purpose,agent_plan_revision: revision,- protocols: vec![grant.protocol],+ protocols: vec![grant.protocol_for(name)],});}let document = CatalogDocument {diff --git a/crates/gateway/src/publication/compiler.rs b/crates/gateway/src/publication/compiler.rsindex f094851b..fb172a1d 100644--- a/crates/gateway/src/publication/compiler.rs+++ b/crates/gateway/src/publication/compiler.rs@@ -74,8 +74,17 @@ pub(crate) struct CompiledGrant {pub generation: u64,pub bearer_token_sha256: Arc<str>,pub protocol: IngressProtocol,+ pub route_protocols: std::collections::BTreeMap<String, IngressProtocol>,pub routes: BTreeMap<Arc<str>, CompiledGrantRoute>,}+impl CompiledGrant {+ pub(crate) fn protocol_for(&self, name: &str) -> IngressProtocol {+ self.route_protocols+ .get(name)+ .copied()+ .unwrap_or(self.protocol)+ }+}#[derive(Clone, Debug)]pub(crate) enum CompiledGrantRoute {@@ -978,6 +987,7 @@ fn compile_grant(grant: &GrantV1, revision: u64) -> Result<CompiledGrant, Publicgeneration: grant.generation,bearer_token_sha256: grant.bearer_token_sha256.clone().into(),protocol: grant.protocol,+ route_protocols: grant.route_protocols.clone(),routes,})}diff --git a/crates/gateway/src/publication/run.rs b/crates/gateway/src/publication/run.rsindex df7d4c92..26a4e0ae 100644--- a/crates/gateway/src/publication/run.rs+++ b/crates/gateway/src/publication/run.rs@@ -51,6 +51,7 @@ impl RunPublicationHandle {|| alias.protocols.len() != 1|| alias.protocols[0] != protocol|| grant.protocol != protocol+ || !grant.route_protocols.is_empty()|| grant.routes.len() != 1|| !matches!(grant.routes.get(model_alias), Some(super::schema::ModelRouteV2::Plan { alias, .. }) if alias == model_alias)|| grant.bearer_token_sha256 != token_fingerprint.as_str()diff --git a/crates/gateway/src/publication/schema.rs b/crates/gateway/src/publication/schema.rsindex 480612a4..b627aa59 100644--- a/crates/gateway/src/publication/schema.rs+++ b/crates/gateway/src/publication/schema.rs@@ -241,8 +241,18 @@ pub struct GrantV1 {pub generation: u64,pub bearer_token_sha256: String,pub protocol: IngressProtocol,+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]+ pub route_protocols: std::collections::BTreeMap<String, IngressProtocol>,pub routes: std::collections::BTreeMap<String, ModelRouteV2>,}+impl GrantV1 {+ pub(crate) fn protocol_for(&self, name: &str) -> IngressProtocol {+ self.route_protocols+ .get(name)+ .copied()+ .unwrap_or(self.protocol)+ }+}#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]@@ -549,6 +559,14 @@ impl GatewayPublicationSnapshotV3 {|| !is_sha256(&grant.bearer_token_sha256)|| !token_verifiers.insert(grant.bearer_token_sha256.as_str())|| grant.routes.is_empty()+ || grant.route_protocols.iter().any(|(name, protocol)| {+ *protocol == grant.protocol+ || !matches!(grant.routes.get(name), Some(ModelRouteV2::Plan { .. }))+ || !matches!(+ protocol,+ IngressProtocol::Responses | IngressProtocol::Messages+ )+ }){return Err(PublicationSchemaError::InvalidGrant(grant.grant_id.clone()));}@@ -567,7 +585,7 @@ impl GatewayPublicationSnapshotV3 {&& self.aliases.iter().any(|target| {target.served_model_id == *alias&& target.agent_plan_revision == *revision- && target.protocols.contains(&grant.protocol)+ && target.protocols.contains(&grant.protocol_for(name))&& target.routing.as_ref()diff --git a/crates/gateway/src/publication/tests.rs b/crates/gateway/src/publication/tests.rsindex f27e9dd7..d811e295 100644--- a/crates/gateway/src/publication/tests.rs+++ b/crates/gateway/src/publication/tests.rs@@ -136,6 +136,7 @@ pub(super) fn snapshot(revision: u64, renderer: &str) -> GatewayPublicationSnaps],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "grant-alpha".into(),generation: 1,bearer_token_sha256: token_sha256("token-alpha"),@@ -143,6 +144,7 @@ pub(super) fn snapshot(revision: u64, renderer: &str) -> GatewayPublicationSnapsroutes: [test_plan_route("alpha", 10)].into(),},GrantV1 {+ route_protocols: Default::default(),grant_id: "grant-beta".into(),generation: 1,bearer_token_sha256: token_sha256("token-beta"),@@ -199,6 +201,7 @@ fn rest_classifier_snapshot() -> GatewayPublicationSnapshotV3 {candidates: vec![candidate(1), candidate(2)],}],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "grant".into(),generation: 1,bearer_token_sha256: token_sha256("token"),@@ -907,6 +910,7 @@ fn fixed_grants_isolate_same_name_and_revocation_without_hidden_plans() {.map(|id| {let binding = candidate(id);GrantV1 {+ route_protocols: Default::default(),grant_id: format!("fixed-{id}"),generation: 1,bearer_token_sha256: token_sha256(&format!("fixed-token-{id}")),diff --git a/crates/gateway/src/publication/tests/grant_projection.rs b/crates/gateway/src/publication/tests/grant_projection.rsindex 5263f468..e0fc86d7 100644--- a/crates/gateway/src/publication/tests/grant_projection.rs+++ b/crates/gateway/src/publication/tests/grant_projection.rs@@ -158,3 +158,93 @@ fn restored_plan_can_serve_codex_and_claude_without_a_new_plan_revision() {assert!(protocols.contains(&IngressProtocol::Responses));assert!(protocols.contains(&IngressProtocol::Messages));}++#[test]+fn mixed_plan_grant_authorizes_only_each_selected_protocol_after_restart() {+ let product: hiroute_domain::GatewayPublicationV1 = serde_json::from_slice(include_bytes!(+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"+ ))+ .unwrap();+ let mut snapshot: GatewayPublicationSnapshotV3 =+ serde_json::from_value(serde_json::to_value(product.gateway_snapshot().unwrap()).unwrap())+ .unwrap();+ let messages = snapshot+ .aliases+ .iter()+ .find(|alias| {+ alias.candidates.iter().all(|c| {+ c.protocol_profiles+ .iter()+ .any(|p| p.ingress_protocol == hiroute_domain::UpstreamProtocol::Messages)+ })+ })+ .unwrap()+ .served_model_id+ .clone();+ let responses = snapshot+ .aliases+ .iter()+ .find(|alias| {+ alias.served_model_id != messages+ && alias.protocols.contains(&IngressProtocol::Responses)+ })+ .unwrap()+ .served_model_id+ .clone();+ let routes = [&messages, &responses]+ .into_iter()+ .map(|name| {+ (+ name.clone(),+ snapshot+ .grants+ .iter()+ .find_map(|g| g.routes.get(name))+ .unwrap()+ .clone(),+ )+ })+ .collect();+ let alias = snapshot+ .aliases+ .iter_mut()+ .find(|a| a.served_model_id == messages)+ .unwrap();+ if !alias.protocols.contains(&IngressProtocol::Messages) {+ alias.protocols.push(IngressProtocol::Messages);+ }+ snapshot.grants = vec![GrantV1 {+ grant_id: "mixed-plan-protocols".into(),+ generation: 1,+ bearer_token_sha256: token_sha256("mixed-protocol-token"),+ protocol: IngressProtocol::Responses,+ routes,+ route_protocols: [(messages.clone(), IngressProtocol::Messages)].into(),+ }];+ let directory = TestDirectory::new();+ let path = directory.path().join("mixed.json");+ let installer = GatewayPublicationInstaller::open(&path).unwrap();+ publish(&installer, reseal(snapshot));+ drop(installer);+ let installer = std::sync::Arc::new(GatewayPublicationInstaller::open(&path).unwrap());+ let authority = crate::server::dispatch::GatewayRequestAuthority::new(installer);+ for (protocol, allowed, forbidden) in [+ (IngressProtocol::Messages, &messages, &responses),+ (IngressProtocol::Responses, &responses, &messages),+ ] {+ assert!(+ authority+ .begin(protocol, Some("Bearer mixed-protocol-token"))+ .unwrap()+ .authorize_alias(allowed, std::time::Instant::now())+ .is_ok()+ );+ assert!(+ authority+ .begin(protocol, Some("Bearer mixed-protocol-token"))+ .unwrap()+ .authorize_alias(forbidden, std::time::Instant::now())+ .is_err()+ );+ }+}diff --git a/crates/gateway/src/publication/trust.rs b/crates/gateway/src/publication/trust.rsindex 2aa5c1c6..360a31a1 100644--- a/crates/gateway/src/publication/trust.rs+++ b/crates/gateway/src/publication/trust.rs@@ -53,7 +53,7 @@ impl GatewayPublicationSnapshotV3 {None,),};- let ingress_protocol = match grant.protocol {+ let ingress_protocol = match grant.protocol_for(served_model_id) {IngressProtocol::Responses => IngressProtocolV1::Responses,IngressProtocol::Messages => IngressProtocolV1::Messages,IngressProtocol::ChatCompletions => IngressProtocolV1::ChatCompletions,diff --git a/crates/gateway/src/request_plan/mod.rs b/crates/gateway/src/request_plan/mod.rsindex 41ea37b6..e424d12f 100644--- a/crates/gateway/src/request_plan/mod.rs+++ b/crates/gateway/src/request_plan/mod.rs@@ -23,8 +23,12 @@ pub enum IngressProtocol {impl IngressProtocol {pub fn from_path(path: &str) -> Option<Self> {- if path.strip_prefix(hiroute_domain::QODER_MODEL_BASE_PATH) == Some("/responses") {- return Some(Self::Responses);+ if let Some(resource) = path.strip_prefix(hiroute_domain::QODER_MODEL_BASE_PATH) {+ return match resource {+ "/responses" => Some(Self::Responses),+ "/messages" => Some(Self::Messages),+ _ => None,+ };}match path {"/v1/responses" => Some(Self::Responses),diff --git a/crates/gateway/src/test_control/fixture.rs b/crates/gateway/src/test_control/fixture.rsindex 7bf22530..9e1288f0 100644--- a/crates/gateway/src/test_control/fixture.rs+++ b/crates/gateway/src/test_control/fixture.rs@@ -99,6 +99,7 @@ pub fn sealed_native_candidate(.iter().enumerate().map(|(index, (protocol, _))| GrantV1 {+ route_protocols: Default::default(),grant_id: format!("fixture-validation-{index}"),generation: 1,bearer_token_sha256: token_sha256(&format!("fixture-validation-{index}")),diff --git a/crates/integrations/src/agents/additional_native.rs b/crates/integrations/src/agents/additional_native.rsindex f883a292..5027305b 100644--- a/crates/integrations/src/agents/additional_native.rs+++ b/crates/integrations/src/agents/additional_native.rs@@ -25,7 +25,10 @@ pub(super) fn parse_native_jsonc(bytes: &[u8]) -> Result<Value, QoderNativeErrorpub(super) struct Restore {schema: String,provider_id: String,- provider_digest: CanonicalDigest,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ provider_digest: Option<CanonicalDigest>,+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]+ providers: std::collections::BTreeMap<String, CanonicalDigest>,rendered_digest: CanonicalDigest,original_exists: bool,#[serde(skip)]@@ -113,6 +116,10 @@ pub(super) fn validate_configuration() -> Result<(), QoderNativeError> {validate_declaration(kind, provider_id, endpoint, models)?;let document = document(current)?;+ let desired: BTreeSet<_> = models+ .iter()+ .map(|m| hiroute_domain::additional_model_provider_for(provider_id, models, m))+ .collect();if let Some(previous) = previous {if previous.kind()? != kind|| previous.provider_id != provider_id@@ -122,11 +129,24 @@ pub(super) fn validate_configuration(}let retain = models.iter()- .map(|model| format!("{provider_id}/{}", model.alias))+ .map(|m| {+ format!(+ "{}/{}",+ hiroute_domain::additional_model_provider_for(provider_id, models, m),+ m.alias+ )+ }).collect();- default_not_removed(&document, provider_id, &retain)?;- } else if owned(&document, provider_id)?.is_some() {- return Err(qoder_error("provider already exists"));+ for id in previous.owned_providers().keys() {+ default_not_removed(&document, id, &retain)?;+ }+ }+ for id in desired {+ if owned(&document, &id)?.is_some()+ && !previous.is_some_and(|p| p.owned_providers().contains_key(&id))+ {+ return Err(qoder_error("provider already exists"));+ }}Ok(())}@@ -171,48 +191,46 @@ pub(super) fn configure(};let credential =std::str::from_utf8(material.expose()).map_err(|_| qoder_error("local grant encoding"))?;- 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)+ let mut groups = std::collections::BTreeMap::<String, Vec<AdditionalAgentModelV1>>::new();+ for model in models {+ groups+ .entry(hiroute_domain::additional_model_provider_for(+ provider_id,+ models,+ model,+ ))+ .or_default()+ .push(model.clone());+ }+ let mut bytes = base.as_deref().map_or_else(+ || Zeroizing::new(b"{}".to_vec()),+ |b| Zeroizing::new(b.to_vec()),+ );+ let mut digests = std::collections::BTreeMap::new();+ for (id, models) in groups {+ let provider = render_provider(kind, endpoint, credential, &models)?;+ digests.insert(id.clone(), digest(&provider)?);+ let document = document(Some(&bytes))?;+ bytes = if let Some(providers) = document.object(&document.root, "providers")? {+ document.edit(&providers, &id, Some(&provider))?} else {- 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})+ document.edit(+ &document.root,+ "providers",+ Some(&serde_json::json!({(id):provider})),+ )?};- 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))?- } else {- document.edit(- &document.root,- "providers",- Some(&serde_json::json!({(provider_id):provider})),- )?- };+ }let restore = Restore {schema: if kind == AgentKindV1::Pi {- "hiroute.pi-native-restore/v1"+ "hiroute.pi-native-restore/v2"} else {- "hiroute.qoder-native-restore/v1"+ "hiroute.qoder-native-restore/v2"}.into(),provider_id: provider_id.into(),- provider_digest: digest(&provider)?,+ provider_digest: None,+ providers: digests,rendered_digest: CanonicalDigest::of_bytes(&bytes),original_exists: base.is_some(),original: base.map_or_else(Vec::new, |bytes| bytes.to_vec()),@@ -220,11 +238,54 @@ pub(super) fn configure(Ok(Edit { bytes, restore })}+fn render_provider(+ kind: AgentKindV1,+ endpoint: &str,+ credential: &str,+ models: &[AdditionalAgentModelV1],+) -> Result<Value, QoderNativeError> {+ let protocol = models+ .first()+ .ok_or_else(|| qoder_error("additional models"))?+ .protocol;+ Ok(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, protocol)+ } 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.+ let (api, base_url) = super::pi_native_provider_api(protocol, endpoint)+ .map_err(|_| qoder_error("Pi native endpoint"))?;+ serde_json::json!({"api":api,"baseUrl":base_url,"apiKey":credential,+ "headers":{"X-HiRoute-Token":credential},"models":models})+ })+}+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),+ "hiroute.qoder-native-restore/v1" | "hiroute.qoder-native-restore/v2" => {+ Ok(AgentKindV1::Qoder)+ }+ "hiroute.pi-native-restore/v1" | "hiroute.pi-native-restore/v2" => Ok(AgentKindV1::Pi),_ => Err(qoder_error("restore schema")),}}@@ -270,24 +331,53 @@ impl Restore {{return Err(qoder_error("restore schema"));}- CanonicalDigest::parse(record.provider_digest.as_str())- .map_err(|_| qoder_error("restore digest"))?;+ let legacy = record.schema.ends_with("/v1");+ if legacy != record.provider_digest.is_some()+ || (legacy && !record.providers.is_empty())+ || (!legacy && (record.providers.is_empty() || record.providers.len() > 256))+ {+ return Err(qoder_error("restore schema"));+ }CanonicalDigest::parse(record.rendered_digest.as_str()).map_err(|_| qoder_error("restore digest"))?;let original = document(record.original_exists.then_some(record.original.as_slice()))?;- if owned(&original, &record.provider_id)?.is_some() {- return Err(qoder_error("restore ownership"));+ for (id, digest) in record.owned_providers() {+ if !legacy+ && id+ .strip_prefix(&format!("{}-", record.provider_id))+ .is_none_or(|suffix| {+ suffix.len() != 32+ || !suffix+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))+ })+ {+ return Err(qoder_error("restore ownership"));+ }+ CanonicalDigest::parse(digest.as_str()).map_err(|_| qoder_error("restore digest"))?;+ if owned(&original, &id)?.is_some() {+ return Err(qoder_error("restore ownership"));+ }}Ok(record)}+ fn owned_providers(&self) -> std::collections::BTreeMap<String, CanonicalDigest> {+ if let Some(digest) = &self.provider_digest {+ [(self.provider_id.clone(), digest.clone())].into()+ } else {+ self.providers.clone()+ }+ }+pub fn applied(&self, current: Option<&[u8]>) -> Result<bool, QoderNativeError> {let document = document(current)?;- Ok(owned(&document, &self.provider_id)?- .map(digest)- .transpose()?- .as_ref()- == Some(&self.provider_digest))+ for (id, expected) in self.owned_providers() {+ if owned(&document, &id)?.map(digest).transpose()?.as_ref() != Some(&expected) {+ return Ok(false);+ }+ }+ Ok(true)}pub fn validate_restoration(&self, current: Option<&[u8]>) -> Result<(), QoderNativeError> {@@ -308,7 +398,9 @@ impl Restore {) -> Result<Option<Zeroizing<Vec<u8>>>, QoderNativeError> {let document = document(current)?;if check_default {- default_not_removed(&document, &self.provider_id, &BTreeSet::new())?;+ for id in self.owned_providers().keys() {+ default_not_removed(&document, id, &BTreeSet::new())?;+ }}if current.is_none() && !self.original_exists {return Ok(None);@@ -321,12 +413,20 @@ impl Restore {.original_exists.then(|| Zeroizing::new(self.original.clone())));}- let providers = document- .object(&document.root, "providers")?- .ok_or_else(|| qoder_error("owned provider missing"))?;- // A user may have added comments/foreign members since Apply. Preserve those exact bytes,- // including an empty providers container, instead of replaying a whole-file backup.- Ok(Some(document.edit(&providers, &self.provider_id, None)?))+ // Remove only members whose exact ownership was verified; preserve foreign JSONC bytes.+ let mut bytes = Zeroizing::new(+ current+ .ok_or_else(|| qoder_error("owned provider missing"))?+ .to_vec(),+ );+ for id in self.owned_providers().keys() {+ let document = Document::parse(&bytes)?;+ let providers = document+ .object(&document.root, "providers")?+ .ok_or_else(|| qoder_error("owned provider missing"))?;+ bytes = document.edit(&providers, id, None)?;+ }+ Ok(Some(bytes))}}diff --git a/crates/integrations/src/agents/filesystem_tests/pi.rs b/crates/integrations/src/agents/filesystem_tests/pi.rsindex 55fae8a2..f19c1903 100644--- a/crates/integrations/src/agents/filesystem_tests/pi.rs+++ b/crates/integrations/src/agents/filesystem_tests/pi.rs@@ -112,9 +112,10 @@ fn pi_default_reference_is_protected_independently_of_provider_file() {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(+ assert!(current.removes_default("hiroute-main-test",&[hiroute_domain::AdditionalAgentModelV1 {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,alias: "selected".into(),context_window_tokens: 16384,max_output_tokens: 4096diff --git a/crates/integrations/src/agents/pi_native.rs b/crates/integrations/src/agents/pi_native.rsindex b0997a10..8f1f5023 100644--- a/crates/integrations/src/agents/pi_native.rs+++ b/crates/integrations/src/agents/pi_native.rs@@ -24,11 +24,20 @@ pub struct PiDefaultModel {}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))+ self.provider.as_deref().is_some_and(|selected_provider| {+ let owned_namespace = selected_provider == provider+ || selected_provider+ .strip_prefix(&format!("{provider}-"))+ .is_some_and(|s| s.len() == 32 && s.bytes().all(|b| b.is_ascii_hexdigit()));+ owned_namespace+ && self.model.as_ref().is_none_or(|selected| {+ !models.iter().any(|m| {+ &m.alias == selected+ && hiroute_domain::additional_model_provider_for(provider, models, m)+ == selected_provider+ })+ })+ })}}diff --git a/crates/integrations/src/agents/pi_runtime.rs b/crates/integrations/src/agents/pi_runtime.rsindex ac9071db..c86c87ce 100644--- a/crates/integrations/src/agents/pi_runtime.rs+++ b/crates/integrations/src/agents/pi_runtime.rs@@ -4,6 +4,21 @@ 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");+/// Native SDKs append different resource paths: Anthropic owns `/v1/messages`,+/// while OpenAI Responses appends `/responses`. Used by saved and Worker routes.+pub fn pi_native_provider_api(+ protocol: hiroute_domain::AgentIngressProtocolV1,+ gateway_v1_base: &str,+) -> Result<(&'static str, &str), super::AgentFilesystemScanError> {+ let root = gateway_v1_base+ .strip_suffix("/v1")+ .ok_or(super::AgentFilesystemScanError::InvalidConfig)?;+ Ok(match protocol {+ hiroute_domain::AgentIngressProtocolV1::Responses => ("openai-responses", gateway_v1_base),+ hiroute_domain::AgentIngressProtocolV1::Messages => ("anthropic-messages", root),+ })+}+pub struct PiCliInstallation {pub package_root: PathBuf,pub version: String,diff --git a/crates/integrations/src/agents/qoder.rs b/crates/integrations/src/agents/qoder.rsindex f34ba0da..6f006313 100644--- a/crates/integrations/src/agents/qoder.rs+++ b/crates/integrations/src/agents/qoder.rs@@ -62,6 +62,7 @@ impl QoderNativeContext {}pub struct QoderTransientRouteInput<'a> {+ pub protocol: hiroute_domain::AgentIngressProtocolV1,pub provider_id: &'a str,/// Explicit numeric loopback origin followed by /v1, without query or credentials.pub endpoint: &'a str,@@ -106,6 +107,7 @@ pub fn render_qoder_transient_route(input.endpoint,&format!("${{{}}}", input.credential_env),vec![model],+ input.protocol,);provider["model"] = input.alias.into();provider["routing"] = json!({@@ -147,6 +149,7 @@ mod tests {#[test]fn frozen_alias_is_preserved_and_credentials_remain_environment_references() {let route = render_qoder_transient_route(QoderTransientRouteInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,provider_id: "hiroute-worker-123",endpoint: "http://127.0.0.1:1234/v1",alias: "plan/branch:cheap",@@ -179,6 +182,7 @@ mod tests {] {assert!(render_qoder_transient_route(QoderTransientRouteInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,provider_id: "hiroute",endpoint,alias: "plan/one",diff --git a/crates/integrations/src/agents/qoder_budget.rs b/crates/integrations/src/agents/qoder_budget.rsindex e0fce6d2..c34c7a2e 100644--- a/crates/integrations/src/agents/qoder_budget.rs+++ b/crates/integrations/src/agents/qoder_budget.rs@@ -21,6 +21,7 @@ pub fn pi_plan_token_budget() -> Result<QoderTokenBudget, QoderNativeError> {let (context, output) = plan_token_budgets(plan)?;let declaration = hiroute_domain::AdditionalAgentModelV1 {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,alias: "hiroute-budget".into(),context_window_tokens: context,max_output_tokens: output,diff --git a/crates/integrations/src/agents/qoder_budget_tests.rs b/crates/integrations/src/agents/qoder_budget_tests.rsindex 989dd66c..4144b1f8 100644--- a/crates/integrations/src/agents/qoder_budget_tests.rs+++ b/crates/integrations/src/agents/qoder_budget_tests.rs@@ -125,6 +125,7 @@ fn renderer_requires_a_usable_worker_budget_and_keeps_probe_budget_separate() {] {let route =crate::agents::render_qoder_transient_route(super::super::QoderTransientRouteInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,provider_id: "hiroute-budget-test",endpoint: "http://127.0.0.1:4321/v1",alias: "plan/branch:cheap",diff --git a/crates/integrations/src/agents/qoder_discovery.rs b/crates/integrations/src/agents/qoder_discovery.rsindex 3241692d..c2ae7dad 100644--- a/crates/integrations/src/agents/qoder_discovery.rs+++ b/crates/integrations/src/agents/qoder_discovery.rs@@ -12,6 +12,34 @@ impl FilesystemAgentScannerV1 {/// Identity only. Discovery does not read settings; explicit configuration effects own/// one additional provider in this file, independently of collaboration discovery.+ /// Resolve only a managed plan's current or historical native selector; no configuration writes.+ pub fn qoder_saved_plan_selector(+ &self,+ namespace: &str,+ alias: &str,+ ) -> Result<String, QoderNativeError> {+ let bytes = crate::agents::filesystem_config::read_system_config_bytes(+ &self.qoder_user_config_target(),+ )+ .map_err(|_| qoder_error("saved model configuration"))?+ .ok_or_else(|| qoder_error("saved model configuration"))?+ .0;+ let value = crate::agents::additional_native::parse_native_jsonc(&bytes)?;+ let current = hiroute_domain::additional_model_plan_provider_id(namespace, alias);+ let matches = [namespace, current.as_str()]+ .into_iter()+ .filter(|id| {+ value["providers"][*id]["models"]+ .as_array()+ .is_some_and(|models| models.iter().any(|m| m["model"].as_str() == Some(alias)))+ })+ .collect::<Vec<_>>();+ if matches.len() != 1 {+ return Err(qoder_error("saved model identity"));+ }+ Ok(format!("{}/{}", matches[0], alias))+ }+pub fn qoder_user_config_target(&self) -> PathBuf {self.layout.qoder_config_root.join("settings.json")}diff --git a/crates/integrations/src/agents/qoder_native_tests.rs b/crates/integrations/src/agents/qoder_native_tests.rsindex 2a224d14..6933d647 100644--- a/crates/integrations/src/agents/qoder_native_tests.rs+++ b/crates/integrations/src/agents/qoder_native_tests.rs@@ -9,6 +9,7 @@ fn models() -> Vec<AdditionalAgentModelV1> {["plan-branch-cheap", "hiroute/0011223344556677"].into_iter().map(|alias| AdditionalAgentModelV1 {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,alias: alias.into(),context_window_tokens: 32_768,max_output_tokens: 4096,@@ -16,6 +17,14 @@ fn models() -> Vec<AdditionalAgentModelV1> {.collect()}+fn provider(alias: &str) -> String {+ let model = models().into_iter().find(|m| m.alias == alias).unwrap();+ hiroute_domain::additional_model_provider_for(PROVIDER, &models(), &model)+}+fn first_provider() -> String {+ provider("plan-branch-cheap")+}+fn token(byte: u8) -> AgentAccessGrantMaterial {AgentAccessGrantMaterial::from_csprng_entropy([byte; 32])}@@ -59,22 +68,21 @@ fn two_additional_routes_keep_native_default_extensions_and_foreign_provider_bytlet text = std::str::from_utf8(&edit.bytes).unwrap();assert!(text.contains("// user's preferred native model"));assert!(text.contains("\"user-models\": {\"apiKey\":\"native-secret\", \"unknown\": [1,2]}"));- let provider = &configured["providers"][PROVIDER];- assert_eq!(provider["protocol"], "openai-responses");- assert_eq!(provider["baseUrl"], ENDPOINT);- assert_eq!(- provider["apiKey"],- std::str::from_utf8(token(3).expose()).unwrap()- );- let native_models = provider["models"].as_array().unwrap();- assert_eq!(native_models.len(), models().len());- for (native, model) in native_models.iter().zip(models()) {+ for model in models() {+ let provider = &configured["providers"][&provider(&model.alias)];+ assert_eq!(provider["protocol"], "openai-responses");+ assert_eq!(provider["baseUrl"], ENDPOINT);+ assert_eq!(+ provider["apiKey"],+ std::str::from_utf8(token(3).expose()).unwrap()+ );+ assert_eq!(provider["models"].as_array().unwrap().len(), 1);+ let native = &provider["models"][0];assert_eq!(native["model"], model.alias);assert_eq!(native["contextWindow"], 32_768);assert_eq!(native["maxOutputTokens"], 4096);+ assert!(provider.get("routing").is_none());}- assert!(provider.get("model").is_none());- assert!(provider.get("routing").is_none());assert!(configured.get("modelConfigs").is_none());assert_eq!(edit.restore@@ -105,8 +113,8 @@ fn unrelated_edits_survive_rotation_and_final_restore_without_adopting_owned_dri).unwrap();assert_ne!(- value(&rotated.bytes)["providers"][PROVIDER]["apiKey"],- value(&first.bytes)["providers"][PROVIDER]["apiKey"]+ value(&rotated.bytes)["providers"][&first_provider()]["apiKey"],+ value(&first.bytes)["providers"][&first_provider()]["apiKey"]);let restored = rotated.restore@@ -119,10 +127,14 @@ fn unrelated_edits_survive_rotation_and_final_restore_without_adopting_owned_dri.unwrap().contains("/* user changed this */"));- assert!(value(&restored)["providers"].get(PROVIDER).is_none());+ assert!(+ value(&restored)["providers"]+ .get(first_provider())+ .is_none()+ );// A user edit within the owned node remains a conflict even if all declared routes survive.let mut drift = value(&rotated.bytes);- drift["providers"][PROVIDER]["routing"] = json!({"compact":"user-selected"});+ drift["providers"][&first_provider()]["routing"] = json!({"compact":"user-selected"});let drift = serde_json::to_vec(&drift).unwrap();assert!(!rotated.restore.applied(Some(&drift)).unwrap());assert!(rotated.restore.restore(Some(&drift)).is_err());@@ -144,7 +156,7 @@ fn unrelated_edits_survive_rotation_and_final_restore_without_adopting_owned_drifn removing_selected_native_default_requires_user_switch_but_retaining_it_is_allowed() {let first = install(Some(br#"{"model":{"name":"auto"}}"#));let mut current = value(&first.bytes);- current["model"]["name"] = format!("{PROVIDER}/plan-branch-cheap").into();+ current["model"]["name"] = format!("{}/plan-branch-cheap", first_provider()).into();let current = serde_json::to_vec(¤t).unwrap();assert_eq!(first@@ -179,7 +191,7 @@ fn removing_selected_native_default_requires_user_switch_but_retaining_it_is_all.unwrap();assert_eq!(value(&adjusted.bytes)["model"]["name"],- format!("{PROVIDER}/plan-branch-cheap")+ format!("{}/plan-branch-cheap", first_provider()));let mut switched = value(&adjusted.bytes);switched["model"]["name"] = "user-provider/user-model".into();@@ -233,17 +245,29 @@ fn restore_only_removes_owned_member_at_every_position_preserving_other_jsonc_bylet rendered = serde_json::to_vec_pretty(¤t).unwrap();let restored = first.restore.restore(Some(&rendered)).unwrap().unwrap();let mut expected = current;- expected["providers"]- .as_object_mut()- .unwrap()- .remove(PROVIDER);+ for model in models() {+ expected["providers"]+ .as_object_mut()+ .unwrap()+ .remove(&provider(&model.alias));+ }assert_eq!(value(&restored), expected);}// A changed file must take the conditional removal path, preserving the complete foreign// byte sequence even when the user reordered the owned provider among other members.- let first = install(Some(br#"{"model":{"name":"auto"},"providers":{}}"#));- let provider = serde_json::to_string(&value(&first.bytes)["providers"][PROVIDER]).unwrap();- let owned = format!("\"{PROVIDER}\" : {provider}");+ let first = configure(+ AgentKindV1::Qoder,+ Some(br#"{"model":{"name":"auto"},"providers":{}}"#),+ PROVIDER,+ ENDPOINT,+ &models()[..1],+ &token(3),+ None,+ )+ .unwrap();+ let provider =+ serde_json::to_string(&value(&first.bytes)["providers"][&first_provider()]).unwrap();+ let owned = format!("\"{}\" : {provider}", first_provider());for (members, expected) in [(" $OWNED /* own */ ,\n \"a\" : 1 ,\t\"z\":2 ",@@ -387,3 +411,148 @@ fn declarations_reject_unknown_budget_duplicate_alias_and_unowned_namespace() {validate_declaration(hiroute_domain::AgentKindV1::Qoder, PROVIDER, ENDPOINT, &[]).is_err());}++#[test]+fn per_plan_protocols_keep_provider_identity_and_restore_both_without_foreign_changes() {+ for kind in [AgentKindV1::Qoder, AgentKindV1::Pi] {+ let endpoint = if kind == AgentKindV1::Pi {+ "http://127.0.0.1:4321/v1"+ } else {+ ENDPOINT+ };+ let original = br#"{"providers":{"foreign":{"apiKey":"keep"}}}"#;+ let mut models = models();+ models[1].protocol = hiroute_domain::AgentIngressProtocolV1::Messages;+ let first = configure(+ kind,+ Some(original),+ PROVIDER,+ endpoint,+ &models,+ &token(3),+ None,+ )+ .unwrap();+ let document = value(&first.bytes);+ assert_eq!(document["providers"].as_object().unwrap().len(), 3);+ let key = if kind == AgentKindV1::Pi {+ "api"+ } else {+ "protocol"+ };+ assert_eq!(+ document["providers"][provider(&models[0].alias)][key],+ "openai-responses"+ );+ assert_eq!(+ document["providers"][provider(&models[1].alias)][key],+ if kind == AgentKindV1::Pi {+ "anthropic-messages"+ } else {+ "anthropic"+ }+ );+ if kind == AgentKindV1::Pi {+ // Native SDK request paths must resolve to the public Gateway endpoints.+ let responses = document["providers"][provider(&models[0].alias)]["baseUrl"]+ .as_str()+ .unwrap();+ let messages = document["providers"][provider(&models[1].alias)]["baseUrl"]+ .as_str()+ .unwrap();+ assert_eq!(+ format!("{responses}/responses"),+ "http://127.0.0.1:4321/v1/responses"+ );+ assert_eq!(+ format!("{messages}/v1/messages"),+ "http://127.0.0.1:4321/v1/messages"+ );+ }+ let untouched = document["providers"][provider(&models[1].alias)].clone();+ models[0].protocol = hiroute_domain::AgentIngressProtocolV1::Messages;+ let next = configure(+ kind,+ Some(&first.bytes),+ PROVIDER,+ endpoint,+ &models,+ &token(3),+ Some(&first.restore),+ )+ .unwrap();+ assert_eq!(+ value(&next.bytes)["providers"][provider(&models[1].alias)],+ untouched+ );+ let recovered = Restore::decode(&next.restore.encode().unwrap()).unwrap();+ assert_eq!(+ recovered+ .restore(Some(&next.bytes))+ .unwrap()+ .unwrap()+ .as_slice(),+ original+ );+ }+}++#[test]+fn historical_single_provider_record_restores_and_upgrades_without_claiming_foreign_nodes() {+ let original = br#"{"providers":{"foreign":{"keep":true}}}"#;+ let old_provider = json!({"type":"openai-compatible","protocol":"openai-responses","apiKey":"historical-owned-token","models":[{"model":"plan-branch-cheap"}]});+ let mut old_file = value(original);+ old_file["providers"][PROVIDER] = old_provider.clone();+ let old_bytes = serde_json::to_vec(&old_file).unwrap();+ // Historical V1 wire layout, independent of the current Restore serializer.+ let header = serde_json::to_vec(&json!({"schema":"hiroute.qoder-native-restore/v1","provider_id":PROVIDER,"provider_digest":digest(&old_provider).unwrap(),"rendered_digest":CanonicalDigest::of_bytes(&old_bytes),"original_exists":true})).unwrap();+ let mut envelope = (header.len() as u32).to_le_bytes().to_vec();+ envelope.extend(header);+ envelope.extend(original);+ let old = Restore::decode(&envelope).unwrap();+ assert_eq!(+ old.restore(Some(&old_bytes)).unwrap().unwrap().as_slice(),+ original+ );+ let upgraded = configure(+ AgentKindV1::Qoder,+ Some(&old_bytes),+ PROVIDER,+ ENDPOINT,+ &models(),+ &token(7),+ Some(&old),+ )+ .unwrap();+ assert!(value(&upgraded.bytes)["providers"].get(PROVIDER).is_none());+ assert_eq!(+ value(&upgraded.bytes)["providers"]+ .as_object()+ .unwrap()+ .len(),+ 3+ );+ assert_eq!(+ upgraded+ .restore+ .restore(Some(&upgraded.bytes))+ .unwrap()+ .unwrap()+ .as_slice(),+ original+ );+ let mut selected = old_file;+ selected["model"] = json!({"name":format!("{PROVIDER}/plan-branch-cheap")});+ assert!(+ configure(+ AgentKindV1::Qoder,+ Some(&serde_json::to_vec(&selected).unwrap()),+ PROVIDER,+ ENDPOINT,+ &models(),+ &token(7),+ Some(&old)+ )+ .is_err()+ );+}diff --git a/crates/integrations/src/agents/qoder_probe.rs b/crates/integrations/src/agents/qoder_probe.rsindex c7fe4bfe..e2b8305a 100644--- a/crates/integrations/src/agents/qoder_probe.rs+++ b/crates/integrations/src/agents/qoder_probe.rs@@ -232,6 +232,7 @@ impl QoderCollaborationProbe {.map_err(|_| qoder_error("loopback address"))?);let route = render_qoder_transient_route(QoderTransientRouteInput {+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,provider_id: "hiroute-native-probe",endpoint: &endpoint,alias: MODEL,diff --git a/crates/integrations/src/agents/qoder_provider.rs b/crates/integrations/src/agents/qoder_provider.rsindex 8a0ec991..35edb999 100644--- a/crates/integrations/src/agents/qoder_provider.rs+++ b/crates/integrations/src/agents/qoder_provider.rs@@ -71,7 +71,16 @@ pub(super) fn model(Ok(model)}-pub(super) fn provider(endpoint: &str, credential: &str, models: Vec<Value>) -> Value {- json!({"type":"openai-compatible", "protocol":"openai-responses", "authType":"bearer",+pub(super) fn provider(+ endpoint: &str,+ credential: &str,+ models: Vec<Value>,+ protocol: hiroute_domain::AgentIngressProtocolV1,+) -> Value {+ let protocol = match protocol {+ hiroute_domain::AgentIngressProtocolV1::Responses => "openai-responses",+ hiroute_domain::AgentIngressProtocolV1::Messages => "anthropic",+ };+ json!({"type":"openai-compatible", "protocol":protocol, "authType":"bearer","baseUrl":endpoint, "apiKey":credential, "models":models})}diff --git a/docs/code-map/testing.md b/docs/code-map/testing.mdindex d58b2332..520c78de 100644--- a/docs/code-map/testing.md+++ b/docs/code-map/testing.md@@ -193,3 +193,17 @@ the main runner. Standalone editor pages must request stable scenario IDs andrequired IDs too; positional slices can silently select different cases afteranother feature adds scenarios. Keep their retained assertions visible in thefixture result, even when the main suite exercises the same components.+++Per-plan protocol changes reuse additional-model and native-context journeys. The+additional-model scenario selects Responses and Messages simultaneously and checks+native reads, credential rotation, independent restore and default protection.+`HIROUTE_PRODUCT_AGENT_PROTOCOL=messages` runs the existing Qoder/Pi Worker and+Continue journey on Messages; the default retains Responses. Unit tests cover+per-alias authorization after Gateway restart and recommendation fallback coverage.+An old single-provider restore fixture proves ownership recovery, not native execution.++Dual-protocol saved-route reports include the native provider and observed source+protocol. A removed-route negative witness must use that route's previously+successful protocol and check the typed authorization error plus zero upstream+requests. An unknown HTTP endpoint is not proof that route authority was revoked.diff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.mdindex 7dd2cd19..5b525b19 100644--- a/docs/code-map/worker-context.md+++ b/docs/code-map/worker-context.md@@ -235,7 +235,7 @@ 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;+Pi discovery applies provider `baseUrl` to inherited catalog models while preserving their native API; provider `api` defaults apply only to explicit models;explicit model overrides retain their precedence. Additional `authHeader` authenticationis reported as not importable until the import contract can preserve it. A valid Claudeprepare does not depend on unrelated Pi configuration being readable.@@ -246,3 +246,37 @@ missing targets and invalid replacement content still fail closed. The Pi nativesuite covers both threshold compaction and recoverable-length compaction followed by exactContinue. Concurrent-route acceptance checks rejected HTTP attempts as well as acceptedmodel receipts, so a rejected wrong credential/endpoint/model cannot disappear from evidence.+++### Explicit protocol per plan++Qoder/Pi additional models use one owned native provider per Plan, with a stable+context namespace and alias-derived identity. Each selected Plan has an explicit+Responses/Messages choice in settings; `work.protocol` is the independent frozen+Worker choice. Protocol advice is computed from every active candidate and fallback;+conversion-capable profiles are not described as native support. Advice never changes+the user's selection or makes a model call.++`AgentModelGrantV2.route_protocols` seals exact per-alias overrides. Gateway publication,+restart, catalog and dispatch preserve them; a credential for one alias/protocol does+not authorize a sibling alias on that protocol. Keep Worker grants single-protocol and+Continue bound to the saved Work plan, even after new settings are published.++The shared native writer owns a set of provider members in one existing Operation.+It verifies every owned digest before edits, preserves foreign JSONC members and+checks native default references before removal. V1 restore records retain their+single-provider meaning; only V2 records are produced for new per-plan writes. Never+infer ownership from a `hiroute-` name or silently change an existing native default.++Native API base URLs are adapter contracts, not interchangeable protocol labels.+Pi's shared `pi_native_provider_api` in the runtime adapter is used by both saved+providers and Worker rendering: the Anthropic SDK appends `/v1/messages`, while+OpenAI appends `/responses`. Test the resulting request path as well as the API+field; reusing a `/v1` base blindly can pass configuration tests and fail real calls.++Native acceptance also exercises receipt identity, not just successful output.+Qoder's session header uses the existing observation identity producer for both+protocols; its native receipt lookup must retain the protocol in the trusted HMAC+scope. Native Messages tools can carry the known cache and eager-streaming hints:+the shared Gateway adapter preserves them on native forwarding while still+rejecting unknown executable tool fields and endpoint/credential overrides.diff --git a/scripts/test-agent-product-support.py b/scripts/test-agent-product-support.pyindex 7a2bc9ce..612b1316 100644--- a/scripts/test-agent-product-support.py+++ b/scripts/test-agent-product-support.py@@ -112,5 +112,27 @@ class NativeProcessTests(unittest.TestCase):neighbor.wait(timeout=5)+class RemovedRouteWitnessTests(unittest.TestCase):+ def test_messages_revocation_uses_messages_and_refuses_missing_http_endpoint_as_proof(self):+ from unittest.mock import patch+ import json+ import additional_model_product as journey+ source = SimpleNamespace(request_count=lambda: 0)+ calls = []+ response = SimpleNamespace(status=422, read=lambda: b'{"code":"AGENT_PROTOCOL_UNSUPPORTED"}')+ connection = SimpleNamespace(request=lambda *args, **kwargs: calls.append((args, kwargs)),+ getresponse=lambda: response, close=lambda: None)+ with patch.object(journey.http.client, 'HTTPConnection', return_value=connection):+ journey.reject_gateway_request(SimpleNamespace(port=1), 'synthetic', 'removed', 'messages',+ [source], ('AGENT_PROTOCOL_UNSUPPORTED',))+ self.assertEqual(calls[0][0], ('POST', journey.TAIL + '/messages'))+ self.assertEqual(json.loads(calls[0][1]['body'])['messages'][0]['role'], 'user')+ response.status = 404+ response.read = lambda: b'{"code":"INGRESS_PROTOCOL_NOT_AVAILABLE"}'+ with self.assertRaises(AssertionError):+ journey.reject_gateway_request(SimpleNamespace(port=1), 'synthetic', 'removed', 'messages',+ [source], ('AGENT_PROTOCOL_UNSUPPORTED',))++if __name__ == '__main__':unittest.main()diff --git a/scripts/test-native-context-product.py b/scripts/test-native-context-product.pyindex 454f92de..a3eb9dcb 100644--- a/scripts/test-native-context-product.py+++ b/scripts/test-native-context-product.py@@ -288,18 +288,29 @@ class NativeContextOracleTests(unittest.TestCase):self.assertEqual(save.call_args.kwargs['protocol'], protocol)self.assertEqual(save.call_args.kwargs['variant'], 'neighbor')- def test_plan_replacement_changes_the_actual_route(self):- product = Mock(root=self.root, worker_work={'protocol': 'responses', 'harness': 'codex_cli'})- product.preview.return_value = {'preview_id': 'new-route'}- upstream = Mock(controls=self.root)- with patch('native_context_product.NativeContextUpstream', return_value=upstream), \- patch('native_context_product.save_native_source', return_value={'binding_id': 'new-binding'}) as save, \- patch('native_context_product.plan_change', return_value={'change': 'new-route'}) as change:- self.assertIs(publish_replacement_route(product, {'harness': 'codex'}), upstream)- self.assertEqual(upstream.model, 'gpt-5.5')- self.assertEqual(save.call_args.kwargs['upstream_model_id'], 'gpt-5.5')- self.assertEqual(change.call_args.kwargs['candidates'], [{'binding_id': 'new-binding'}])- product.apply.assert_called_once()+ def test_plan_replacement_changes_source_and_both_protocols_for_multi_protocol_agents(self):+ for index, (harness, worker, protocol) in enumerate((('codex','codex_cli','responses'),+ ('qoder','qoder_cli','responses'), ('qoder','qoder_cli','messages'),+ ('pi','pi','responses'), ('pi','pi','messages'))):+ root = self.root / str(index)+ root.mkdir()+ work = {'protocol':protocol, 'harness':worker}+ product = Mock(root=root, worker_work=work)+ product.preview.return_value = {'preview_id': 'new-route'}+ upstream = Mock(controls=root)+ with patch('native_context_product.NativeContextUpstream', return_value=upstream), \+ patch('native_context_product.save_native_source', return_value={'binding_id': 'new-binding'}) as save, \+ patch('native_context_product.plan_change', return_value={'change': 'new-route'}) as change:+ self.assertIs(publish_replacement_route(product, {'harness':harness}), upstream)+ expected = protocol if harness == 'codex' else ('messages' if protocol == 'responses' else 'responses')+ self.assertEqual(save.call_args.kwargs['protocol'], expected)+ self.assertEqual(change.call_args.kwargs['work']['protocol'], expected)+ self.assertEqual(product.worker_work, work)+ self.assertEqual(product.worker_work['protocol'], protocol)+ self.assertEqual(upstream.model, 'gpt-5.5')+ self.assertEqual(save.call_args.kwargs['upstream_model_id'], 'gpt-5.5')+ self.assertEqual(change.call_args.kwargs['candidates'], [{'binding_id': 'new-binding'}])+ product.apply.assert_called_once()def test_frozen_route_requires_old_source_traffic_and_rejects_new_route_traffic(self):replacement = Mock(controls=self.root)@@ -308,6 +319,9 @@ class NativeContextOracleTests(unittest.TestCase):with self.assertRaisesRegex(AssertionError, 'original source'):assert_frozen_route([continued], 1, replacement)assert_frozen_route([continued], 0, replacement)+ with self.assertRaisesRegex(AssertionError, 'frozen protocol'):+ assert_frozen_route([dict(continued, protocol='messages')], 0, replacement, 'responses')+ assert_frozen_route([dict(continued, protocol='responses')], 0, replacement, 'responses')(self.root / 'native-context-events.jsonl').write_text(json.dumps(continued) + '\n')with self.assertRaisesRegex(AssertionError, 'newly published route'):assert_frozen_route([continued], 0, replacement)@@ -411,5 +425,40 @@ class NativeContextOracleTests(unittest.TestCase):self.assertFalse((home / '.claude').exists())+class NativeProtocolWitnessTests(unittest.TestCase):+ def test_correlated_tool_results_follow_wire_protocol_not_agent_name(self):+ responses = {'input':[{'type':'function_call_output','call_id':'actual','output':'receipt'},+ {'role':'user','content':'prompt echo receipt'}]}+ messages = {'system':'not a tool result', 'messages':[+ {'role':'user','content':[{'type':'tool_result','tool_use_id':'actual','content':'receipt'},+ {'type':'tool_result','tool_use_id':'failed','content':'spoofed','is_error':True}]},+ {'role':'assistant','content':[{'type':'tool_result','tool_use_id':'spoof','content':'spoofed'}]}]}+ for harness in ('qoder','pi'):+ for body in (responses, messages):+ with self.subTest(harness=harness, body=body):+ self.assertEqual(fixture.tool_results(body, harness), {'actual':'receipt'})++ def test_messages_text_and_skill_expansion_keep_content_and_exact_directory_guards(self):+ directory = Path('/fixture/skill')+ body = {'system':'system marker','messages':[+ {'role':'assistant','content':'Base directory for this skill: /fixture/skill\n\nwrong role'},+ {'role':'user','content':[{'type':'text','text':'Base directory for this skill: /fixture/skill-other\n\nwrong directory'}]},+ {'role':'user','content':[{'type':'text','text':'Base directory for this skill: /fixture/skill\n\nactual contents'}]}],+ 'metadata':{'text':'not content'}}+ self.assertIn('system marker', fixture.native_text(body))+ self.assertIn('actual contents', fixture.native_text(body))+ self.assertNotIn('not content', fixture.native_text(body))+ self.assertEqual(list(fixture.qoder_skill_expansions(body, directory)), ['actual contents'])++ def test_messages_budget_keeps_the_same_frozen_limit_assertion(self):+ value = {'harness':'qoder','expected_max_output_tokens':4096,'skills':[], 'receipt':'done'}+ body = {'max_tokens':4096,'messages':[{'role':'user','content':[+ {'type':'tool_result','tool_use_id':'native_context_execute','content':'done'}]}]}+ self.assertEqual(fixture.decision(value, body)['text'], 'done')+ body['max_tokens'] = 8192+ with self.assertRaisesRegex(AssertionError, 'frozen source output budget'):+ fixture.decision(value, body)++if __name__ == '__main__':unittest.main()diff --git a/tools/e2e-harness/src/p0/production/current_inputs.rs b/tools/e2e-harness/src/p0/production/current_inputs.rsindex b701e723..44f42ed4 100644--- a/tools/e2e-harness/src/p0/production/current_inputs.rs+++ b/tools/e2e-harness/src/p0/production/current_inputs.rs@@ -67,6 +67,7 @@ impl CurrentUpstream {)],}],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "oracle-grant".into(),generation: 1,bearer_token_sha256: client_digest.into(),diff --git a/tools/e2e-harness/tests/p0_gateway_protocol/continuation.rs b/tools/e2e-harness/tests/p0_gateway_protocol/continuation.rsindex 449a3251..1e0b9693 100644--- a/tools/e2e-harness/tests/p0_gateway_protocol/continuation.rs+++ b/tools/e2e-harness/tests/p0_gateway_protocol/continuation.rs@@ -623,6 +623,7 @@ fn snapshot(],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "continuation-grant".into(),generation: 1,bearer_token_sha256: token_sha256("continuation-token"),@@ -649,6 +650,7 @@ fn snapshot(.collect(),},GrantV1 {+ route_protocols: Default::default(),grant_id: "other-grant".into(),generation: 1,bearer_token_sha256: token_sha256("other-token"),diff --git a/tools/e2e-harness/tests/p0_gateway_protocol/process.rs b/tools/e2e-harness/tests/p0_gateway_protocol/process.rsindex 934d5e43..65288c79 100644--- a/tools/e2e-harness/tests/p0_gateway_protocol/process.rs+++ b/tools/e2e-harness/tests/p0_gateway_protocol/process.rs@@ -176,6 +176,7 @@ fn snapshot(provider_authority: &str) -> GatewayPublicationSnapshotV3 {].into_iter().map(|protocol| GrantV1 {+ route_protocols: Default::default(),grant_id: format!("protocol-grant-{}", protocol.path()),generation: 1,bearer_token_sha256: token_sha256(&format!("protocol-token-{}", protocol.path())),diff --git a/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix.rs b/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix.rsindex 1dad119e..c4cc135e 100644--- a/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix.rs+++ b/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix.rs@@ -387,6 +387,7 @@ fn snapshot(.into_iter().filter(|protocol| pairs.iter().any(|(ingress, _)| ingress == protocol)).map(|protocol| GrantV1 {+ route_protocols: Default::default(),grant_id: format!("protocol-grant-{}", protocol_name(protocol)),generation: 1,bearer_token_sha256: token_sha256(&format!(diff --git a/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix/native_protocol_paths.rs b/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix/native_protocol_paths.rsindex 871e6915..36d42ace 100644--- a/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix/native_protocol_paths.rs+++ b/tools/e2e-harness/tests/p0_gateway_protocol/production_matrix/native_protocol_paths.rs@@ -64,6 +64,7 @@ fn one_registered_native_source_uses_matching_messages_and_responses_provider_pa[IngressProtocol::Responses, IngressProtocol::Messages].into_iter().map(|protocol| GrantV1 {+ route_protocols: Default::default(),grant_id: format!("shared-grant-{}", protocol_name(protocol)),generation: 1,bearer_token_sha256: token_sha256(&format!(@@ -367,6 +368,7 @@ fn real_glm_messages_native_path_handles_repeated_small_and_large_requests() {candidates: vec![candidate],}],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "real-glm-probe-grant".into(),generation: 1,bearer_token_sha256: token_sha256("protocol-token-messages"),diff --git a/tools/e2e-harness/tests/p0_gateway_protocol/responses_chat_tools.rs b/tools/e2e-harness/tests/p0_gateway_protocol/responses_chat_tools.rsindex c1d7d892..bd054ee1 100644--- a/tools/e2e-harness/tests/p0_gateway_protocol/responses_chat_tools.rs+++ b/tools/e2e-harness/tests/p0_gateway_protocol/responses_chat_tools.rs@@ -560,6 +560,7 @@ fn responses_chat_tools_snapshot(candidates: vec![chat, fallback],}],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "responses-chat-tools-grant".into(),generation: 1,bearer_token_sha256: token_sha256("responses-chat-tools-token"),diff --git a/tools/e2e-harness/tests/p0_gateway_request_authority.rs b/tools/e2e-harness/tests/p0_gateway_request_authority.rsindex 9ad47a57..a74ee412 100644--- a/tools/e2e-harness/tests/p0_gateway_request_authority.rs+++ b/tools/e2e-harness/tests/p0_gateway_request_authority.rs@@ -90,6 +90,7 @@ fn snapshot(publication_revision: u64, fast_plan_revision: u64) -> GatewayPublic},],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "agent-a".into(),generation: 3,bearer_token_sha256: token_sha256("test-agent-token"),diff --git a/tools/e2e-harness/tests/p0_gateway_request_authority/fixtures.rs b/tools/e2e-harness/tests/p0_gateway_request_authority/fixtures.rsindex afef832f..7f266c80 100644--- a/tools/e2e-harness/tests/p0_gateway_request_authority/fixtures.rs+++ b/tools/e2e-harness/tests/p0_gateway_request_authority/fixtures.rs@@ -54,6 +54,7 @@ pub(super) fn wire_snapshot(provider_authority: &str) -> GatewayPublicationSnaps],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "wire-grant".into(),generation: 5,bearer_token_sha256: token_sha256("wire-token"),@@ -61,6 +62,7 @@ pub(super) fn wire_snapshot(provider_authority: &str) -> GatewayPublicationSnapsroutes: plan_routes(&[("wire-fast", 41), ("wire-deep", 42)]),},GrantV1 {+ route_protocols: Default::default(),grant_id: "wire-messages-grant".into(),generation: 5,bearer_token_sha256: token_sha256("wire-messages-token"),@@ -102,6 +104,7 @@ pub(super) fn live_snapshot()],}],vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "live-grant".into(),generation: 1,bearer_token_sha256: token_sha256("live-wire-token"),diff --git a/tools/e2e-harness/tests/runtime_support/publication.rs b/tools/e2e-harness/tests/runtime_support/publication.rsindex 18019f56..c17c7b89 100644--- a/tools/e2e-harness/tests/runtime_support/publication.rs+++ b/tools/e2e-harness/tests/runtime_support/publication.rs@@ -227,6 +227,7 @@ pub(super) fn snapshot(].into_iter().map(|(protocol, token)| GrantV1 {+ route_protocols: Default::default(),grant_id: format!("runtime-grant-{}", protocol.path()),generation: 1,bearer_token_sha256: token_sha256(token),@@ -236,6 +237,7 @@ pub(super) fn snapshot(.collect()} else {vec![GrantV1 {+ route_protocols: Default::default(),grant_id: "runtime-grant".into(),generation: 1,bearer_token_sha256: token_sha256(TOKEN),@@ -330,6 +332,7 @@ pub(super) fn make_isolated_fixed_grants(snapshot: &mut GatewayPublicationSnapsh}).collect();GrantV1 {+ route_protocols: Default::default(),grant_id: format!("isolated-grant-{index}"),generation: 1,bearer_token_sha256: token_sha256(&format!("isolated-token-{index}")),diff --git a/tools/product-e2e/tests/PI_INTEGRATION.md b/tools/product-e2e/tests/PI_INTEGRATION.mdindex 04c8deb4..4cd48de9 100644--- a/tools/product-e2e/tests/PI_INTEGRATION.md+++ b/tools/product-e2e/tests/PI_INTEGRATION.md@@ -69,8 +69,9 @@ Cheap local interface/ownership regressions are in`crates/integrations/src/agents/pi_sdk_contract.test.mjs`; synthetic release labelsprove 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+Main-Agent model settings own one provider member per selected Plan in `models.json`+and the local grant inside that private file. Each provider uses the user-selected+Responses or Messages protocol; restoring removes only the owned provider set. Pi's separate user `settings.json` defaultis a transaction dependency checked again at activation/retry. Project defaultsare native project configuration outside this global default ownership contract.A helper or OAuth key can be reported but never imported by executing it.@@ -102,3 +103,12 @@ 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.++## Dual-protocol acceptance++The saved-model journey creates a Responses Plan and a Messages Plan in the same+native configuration and checks actual source protocol receipts for both. Reuse+the native context/Continue journey with `HIROUTE_PRODUCT_AGENT_PROTOCOL=responses`+and `HIROUTE_PRODUCT_AGENT_PROTOCOL=messages` to cover both frozen Worker routes.+This selector changes fixture inputs, never the production protocol or native CLI.+Record both protocol outcomes explicitly; one successful default run is insufficient.diff --git a/tools/product-e2e/tests/QODER_DELEGATION.md b/tools/product-e2e/tests/QODER_DELEGATION.mdindex 6e3fea83..604846f1 100644--- a/tools/product-e2e/tests/QODER_DELEGATION.md+++ b/tools/product-e2e/tests/QODER_DELEGATION.md@@ -273,3 +273,13 @@ These checks reject missing explicit context, shadow user Skills, wrong roleendpoints, fabricated/uncorrelated completion, changed borrowed files and missingdisk artifacts. They also retain the existing SSE/ownership/boundary assertions.They start neither a native Agent nor HiRoute and cannot establish product support.++## Dual-protocol acceptance++The persisted-model journey configures one owned provider per Plan: one Responses+and one Messages (`anthropic`) provider, with ordinary native calls and upstream+protocol receipts. Run the existing Worker context/Continue journey once with+`HIROUTE_PRODUCT_AGENT_PROTOCOL=responses` and once with+`HIROUTE_PRODUCT_AGENT_PROTOCOL=messages`; record each outcome separately.+Keep the dedicated logged-in context requirements above. The fixture selector+does not override saved production choices or the frozen protocol of a task.