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: configurable AgentPlan context windows and version-independent clients (#10)
澄潭c4728aeb1100
diff --git a/apps/desktop/src/agent-capability-preview.tsx b/apps/desktop/src/agent-capability-preview.tsxnew file mode 100644index 00000000..2efb9f54--- /dev/null+++ b/apps/desktop/src/agent-capability-preview.tsx@@ -0,0 +1,28 @@+import React, { useEffect, useState } from 'react';+import { invoke } from '@tauri-apps/api/core';+import { type Plan, type Options } from './plan-editor';++/** Read-only projection; saving still rechecks the exact publication and native configuration. */+export function AgentCapabilityPreview({ agent, plans, language }: { agent: 'codex' | 'claude'; plans: Plan[]; language: 'zh' | 'en' }) {+ const [result, setResult] = useState<Options[] | null>(null);+ const [failed, setFailed] = useState(false);+ const fingerprint = JSON.stringify(plans);+ useEffect(() => {+ let current = true;+ setResult(null); setFailed(false);+ const selected = JSON.parse(fingerprint) as Plan[];+ void Promise.all(selected.map(plan => invoke<Options>('plan_editor_options', { input: { published_plan: { plan_id: plan.agent_plan_id, revision: plan.agent_plan_revision } } }))).then(value => { if (current) setResult(value); }).catch(() => { if (current) setFailed(true); });+ return () => { current = false; };+ }, [fingerprint]);+ if (!plans.length) return null;+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;+ const windows = result?.map(option => agent === 'codex' ? option.codex_capabilities?.state === 'available' ? option.codex_capabilities.context_window : null : option.claude_capabilities?.state === 'available' ? option.claude_capabilities.context_window : null);+ return <div className="option-panel" data-agent-capability-preview={agent} aria-live="polite">+ <strong>{agent === 'codex' ? 'Codex' : 'Claude Code'} · {text('能力预览', 'Capability preview')}</strong>+ {failed ? <p>{text('暂时无法获取能力预览;请重新打开配置重试。', 'Capability preview is unavailable. Reopen settings to retry.')}</p> : !result ? <p>{text('正在核对所选计划…', 'Checking selected plans…')}</p> : <>+ {plans.map((plan, index) => <p key={plan.agent_plan_id}>{plan.desired.display_name} · {windows?.[index] != null ? `${windows[index]!.toLocaleString()} tokens` : text('当前不可用,请检查计划的入口能力和窗口', 'Unavailable; check plan ingress capabilities and window')}</p>)}+ {agent === 'claude' && windows?.every(value => value != null) && <p>{text('进程共同自动压缩窗口', 'Shared process auto-compact window')} · {Math.min(...windows as number[]).toLocaleString()} tokens</p>}+ </>}+ <p className="field-help">{agent === 'claude' ? text('三个预设共享最小窗口(100K–1M);保留的原生模型可能更早压缩。', 'The three presets share the smallest window (100K–1M); preserved native models may compact earlier.') : text('各计划分别使用自己的窗口。', 'Each plan uses its own window.')}{text('保存时重新核对;重新启动客户端后加载,当前会话不会立即改变。', 'Rechecked on save and loaded after restarting the client; current sessions do not change immediately.')}</p>+ </div>;+}diff --git a/apps/desktop/src/agents.tsx b/apps/desktop/src/agents.tsxindex 30421f19..8bb1caf6 100644--- a/apps/desktop/src/agents.tsx+++ b/apps/desktop/src/agents.tsx@@ -1,3 +1,4 @@+import { AgentCapabilityPreview } from './agent-capability-preview';import { BrandIcon, Dialog, Disclosure, ProductPage, UiIcon } from './ui';import { confirmDiscard, useDiscardGuard } from './ui/discard-guard';import React, { useEffect, useRef, useState } from 'react';@@ -639,12 +640,6 @@ export function Agents({title: text('已定位 Agent,但它当前不可执行', 'The Agent was located but is not executable'),detail: text('请检查目标是否为普通可执行文件。安装目录的组写权限本身不会阻止接入。', 'Check that the target is a regular executable file. Group-writable installation directories do not block routing.'),};- case 'executable_probe_timed_out':- return {- label: text('检查超时', 'Check timed out'),- title: text('Agent 版本检查超时', 'The Agent version check timed out'),- detail: text('探测进程已回收;可以重新扫描后再进行真实验证。', 'The probe process was cleaned up. Scan again before live verification.'),- };case 'executable_probe_unavailable':return {label: text('命令检查失败', 'Command check failed'),@@ -778,6 +773,14 @@ export function Agents({? text('当前默认模型名称或所选路由无法用于 Codex Responses。请在“默认选择”中改选已勾选且支持该入口的路由;若要保留原生模型,请先接入对应来源。配置未修改。', 'The current default model name or a selected route cannot be used by Codex Responses. Under Default selection, choose an enabled route that supports this ingress; to preserve a native model, connect its source first. Configuration was not changed.'): block.reason === 'model_plan_unavailable' && selected?.agent_id === 'agent_codex_default'? text('所选路由、固定来源或当前默认模型无法用于 Codex Responses。请核对路由是否已启用并支持该入口协议,或改选可用路由;配置未修改。', 'A selected route, fixed source, or current default model cannot be used by Codex Responses. Check that the route is enabled and supports this ingress protocol, or choose an available route. Configuration was not changed.')+ : block.reason === 'codex_context_override'+ ? text('Codex 的显式窗口配置会覆盖计划设置。请移除有效配置中的 model_context_window 和 model_auto_compact_token_limit 后重试;HiRoute 不会删除这些配置。', 'Explicit Codex window settings override the plan. Remove model_context_window and model_auto_compact_token_limit from the effective configuration and retry; HiRoute will not delete these settings.')+ : block.reason === 'claude_plan_capability_unavailable'+ ? text('所选计划无法满足 Claude Code 的工具调用或流式请求能力,请检查全部候选模型。', 'A selected plan cannot meet Claude Code tool or streaming requirements. Check all candidate models.')+ : block.reason === 'claude_context_override'+ ? text('Claude Code 存在窗口覆盖或禁用自动压缩的设置。请移除进程、项目或托管配置中的窗口覆盖,以及禁用压缩的环境变量后重试。', 'Claude Code has window overrides or compaction disabled. Remove process, project, or managed window overrides and compaction-disabling environment variables, then retry.')+ : block.reason === 'claude_context_window_unsupported'+ ? text('所选计划的共同窗口低于 Claude Code 的 100K 最低值。请调整计划窗口或使用 Codex。', 'The shared plan window is below Claude Code’s 100K minimum. Adjust the plan window or use Codex.'): block.reason === 'skill_file_conflict'? text('同名任务委派技能内容不同;原文件已保留。请先移走或明确处理该文件后再预览。', 'A task delegation skill with different content already exists. The original was preserved; move or explicitly resolve it before previewing again.'): capabilities.has('skill_loading') || capabilities.has('trusted_cli_execution')@@ -931,6 +934,7 @@ export function Agents({{modelFormInvalid && <span className="oc-inline-error">{text('至少将一个预设映射到可用智能路由,或保留已有固定模型。', 'Map at least one preset to an enabled smart route, or retain an existing fixed model.')}</span>}{!enabledPlans.length && <div className="callout"><UiIcon name="route" /><div><span>{text('先创建并启用一条智能路由。', 'Create and enable a smart route first.')}</span></div>{onCreatePlan && <button className="btn" type="button" onClick={createPlanFromEditor}>{text('创建路由', 'Create route')}</button>}</div>}</div>}+ {facetEnabled && editor.facet === 'model' && <AgentCapabilityPreview agent={selected.agent_id === 'agent_claude_default' ? 'claude' : 'codex'} language={language} plans={enabledPlans.filter(plan => selected.agent_id === 'agent_claude_default' ? Object.values(editorValues.claudePresets).some(choice => choice.kind === 'plan' && choice.plan_id === plan.agent_plan_id) : editorValues.allowedPlanIds.includes(plan.agent_plan_id))} />}{facetEnabled && editor.facet === 'collaboration' && <fieldset className="worker-choices"><legend className="field-label">{text('委派时机', 'When to delegate')}</legend><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="explicit" checked={editorValues.triggerMode === 'explicit'} onChange={() => setTriggerMode('explicit')} /><div><strong>{text('仅在明确要求时', 'Only when explicitly requested')}</strong><span>{text('只有当你要求执行、委派或交给 Worker 时,Agent 才会启动任务。', 'The Agent starts a task only when you ask it to execute, delegate, or hand work to a Worker.')}</span></div></label><label className="check-row"><input type="radio" name="agent-collaboration-trigger" value="delegate_by_default" checked={editorValues.triggerMode === 'delegate_by_default'} onChange={() => setTriggerMode('delegate_by_default')} /><div><strong>{text('默认由 Agent 判断', 'Let the Agent decide by default')}</strong><span>{text('Agent 可以主动委派适合执行的任务;明确要求只回答时不会启动任务。', 'The Agent may proactively delegate suitable work, but will not start a task when you explicitly ask for an answer only.')}</span></div></label><p className="field-help">{text('可用执行路由由当前路由目录决定,这里不维护第二份名单。', 'Available execution routes come from the current route catalog; this setting does not maintain a second list.')}</p></fieldset>}{!selectionKnown && <div className="callout warn" role="alert"><UiIcon name="warning" /><span>{text('当前配置状态无法核实,不能覆盖保存。请刷新或处理配置变化。', 'The current setting cannot be verified. Refresh or resolve configuration changes before saving.')}</span></div>}</fieldset>diff --git a/apps/desktop/src/plan-context-window.ts b/apps/desktop/src/plan-context-window.tsnew file mode 100644index 00000000..aa1bdff4--- /dev/null+++ b/apps/desktop/src/plan-context-window.ts@@ -0,0 +1,10 @@+export type ContextWindowBounds = { maximum_tokens: number; default_tokens: number };++export function contextWindowError(value: number | undefined, bounds: ContextWindowBounds | null | undefined, language: 'zh' | 'en'): string | null {+ if (value === undefined) return null;+ const zh = language === 'zh';+ if (!Number.isSafeInteger(value) || value < 1) return zh ? '上下文窗口必须是正整数。' : 'The context window must be a positive integer.';+ if (!bounds) return zh ? '尚未确认候选共同窗口上界,请完成模型配置后重试。' : 'The shared context limit is not yet known. Complete the model configuration and try again.';+ if (value > bounds.maximum_tokens) return zh ? `上下文窗口不能超过候选共同上界 ${bounds.maximum_tokens.toLocaleString()} tokens。` : `The context window cannot exceed the shared candidate limit of ${bounds.maximum_tokens.toLocaleString()} tokens.`;+ return null;+}diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsxindex 4b8929d7..903f5b1c 100644--- a/apps/desktop/src/plan-editor.tsx+++ b/apps/desktop/src/plan-editor.tsx@@ -1,3 +1,4 @@+import { contextWindowError, type ContextWindowBounds } from './plan-context-window';import { ProviderIcon } from './ui/ProviderIcon';import { connectionName } from './ui/provider-identity';import { planErrorCode, planErrorMessage } from './plan-editor-errors';@@ -23,7 +24,7 @@ type SmartClassifier = { kind: 'local_rules' } | {};type Smart = { economy: Selection[]; primary: Selection[]; primary_fallback: 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: { maximum_attempts: number; request_timeout_ms: number; attempt_timeout_ms: number } };+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 Draft = { draft_id: string; plan_id?: string; base_head_revision?: number; revision: number; editor: Editor };type Native = NativeReasoning;@@ -32,8 +33,9 @@ type CodexCapabilityLimit = { kind: 'context_window' | 'image_input'; binding_idtype 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')[] }| { state: 'unavailable'; issues: CodexCapabilityIssue[] };-type Options = { suggested_alias: string | null; candidates: Candidate[]; free_suggestions: { candidates: { selection: Selection }[]; unavailable: Record<string, string> } | null; codex_capabilities: CodexCapabilities | null };-type ValidationIssue = { message: string; group?: string; bindingId?: string; field?: 'alias' };+export type ClaudeCapabilities = { state: 'available'; context_window: number; plan_window: number } | { state: 'unavailable'; reason: string };+export type Options = { claude_capabilities?: ClaudeCapabilities | null; context_window: ContextWindowBounds | null; suggested_alias: string | null; candidates: Candidate[]; free_suggestions: { candidates: { selection: Selection }[]; unavailable: Record<string, string> } | null; codex_capabilities: CodexCapabilities | null };+type ValidationIssue = { message: string; group?: string; bindingId?: string; field?: 'alias' | 'context_window' };type ClassifierDecisionTestResult = { outcome: 'passed' | 'failed'; branch_id?: string | null; duration_millis?: number | null; failure_code?: string | null };const DEFAULT_CLASSIFIER_TIMEOUT_MS = 3000;const MAX_CLASSIFIER_TIMEOUT_MS = 3_600_000;@@ -110,6 +112,7 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drconst [base, setBase] = useState(() => ({ expected_head_revision: draft ? draft.base_head_revision ?? null : plan?.head.head_revision ?? null, expected_draft_revision: draft?.revision ?? null }));const [options, setOptions] = useState<Options | null>(null), [busy, setBusy] = useState(false), [error, setError] = useState('');const [baseline, setBaseline] = useState(() => JSON.stringify(editor));+ const [previewAgent, setPreviewAgent] = useState<'codex' | 'claude'>('codex');const [notice, setNotice] = useState('');const [keywordInput, setKeywordInput] = useState('');const [invalidFields, setInvalidFields] = useState(false);@@ -166,7 +169,7 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drconst management = await invoke<{ sources: { models: unknown[] }[] }>('compute_management_snapshot');if (!current) return;if (!management.sources.some(source => source.models.length > 0)) {- setOptions({ suggested_alias: null, candidates: [], free_suggestions: null, codex_capabilities: null });+ setOptions({ context_window: null, suggested_alias: null, candidates: [], free_suggestions: null, codex_capabilities: null });setOptionsError('');} else {setOptionsError(text('暂时无法读取可用于路由的模型,当前编辑已保留。', 'Unable to read routable models. Your edits are preserved.'));@@ -191,6 +194,8 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drreturn { field: 'alias', message: text('接入模型名只能使用小写字母、数字和连字符。', 'The connection model name may contain lowercase letters, numbers, and hyphens only.') };}if (!options) return { message: text('模型信息仍在读取,请稍后再试。', 'Model information is still loading. Try again shortly.') };+ const windowError = contextWindowError(editor.limits.context_window_tokens, options.context_window, language);+ if (windowError) return { field: 'context_window', message: windowError };if (editor.mode === 'smart_saving' && editor.smart.classifier.kind === 'rest') {const classifier = editor.smart.classifier;if (!validClassifierEndpoint(classifier.endpoint) || !validClassifierTimeout(classifier.timeout_ms) || !validClassifierAuthHeader(classifier.auth_header)) {@@ -246,6 +251,8 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Drconst details = input?.closest('details');if (details) details.open = true;input?.focus();+ } else if (issue.field === 'context_window') {+ document.querySelector<HTMLInputElement>('.plan-context-window-field')?.focus();} else if (issue.group === 'executor') {document.querySelector<HTMLElement>('.v3-executors button')?.focus();} else if (issue.group === 'classifier') {@@ -466,7 +473,19 @@ export const PlanEditor = forwardRef<PlanEditorHandle, { plan?: Plan; draft?: Dr<Disclosure className="native-details keywords" label={text('关键词规则', 'Keyword rules')} language={language}><div className="editor-section-heading"><div><h3>{text('强制使用主力组合的关键词', 'Keywords that force the primary group')}</h3><p>{text('默认规则会识别多目标、架构、调试、跨文件和较长任务;REST 服务失败时也使用这些规则。', 'Default rules recognize multi-goal, architecture, debugging, cross-file and longer tasks; these rules are also used when the REST service fails.')}</p></div></div><div className="keyword-box">{editor.smart.complex_keywords.filter(Boolean).map(word => <span className="keyword-chip" key={word}>{word}<button type="button" aria-label={`${text('移除关键词', 'Remove keyword')} ${word}`} onClick={() => update({ smart: { ...editor.smart, complex_keywords: editor.smart.complex_keywords.filter(value => value !== word) } })}><UiIcon name="close" /></button></span>)}</div><div className="keyword-add"><input className="input" value={keywordInput} maxLength={64} placeholder={text('输入一个关键词或短语', 'Enter a keyword or phrase')} onChange={event => setKeywordInput(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); const word = keywordInput.trim(); if (word && !editor.smart.complex_keywords.includes(word)) update({ smart: { ...editor.smart, complex_keywords: [...editor.smart.complex_keywords, word] } }); setKeywordInput(''); } }} /><button className="btn" type="button" onClick={() => { const word = keywordInput.trim(); if (word && !editor.smart.complex_keywords.includes(word)) update({ smart: { ...editor.smart, complex_keywords: [...editor.smart.complex_keywords, word] } }); setKeywordInput(''); }}>{text('添加', 'Add')}</button></div></Disclosure></section>}{editor.mode === 'free_first' && <section className="editor-section"><div className="editor-section-heading"><div><h3>{text('免费候选', 'Free candidates')}</h3><p>{text('当前候选与顺序在发布后保持固定。', 'Candidates and order stay fixed after publication.')}</p></div><button className="btn" type="button" onClick={() => void useAllFree()}>{text('使用当前全部可用免费模型', 'Use all available free models')}</button></div><div className="free-lane">{group(text('免费模型', 'Free models'), text('固定顺序', 'Fixed order'), editor.free.candidates, candidates => update({ free: { ...editor.free, candidates } }), { free: true, preferred: 'low', groupId: 'free' })}</div><div className="editor-section-heading fallback-heading"><div><h3>{text('免费模型都不可用时', 'When all free models are unavailable')}</h3></div></div><div className="option-panel"><button type="button" className="option-row" aria-pressed={!editor.free.primary_fallback} onClick={() => update({ free: { ...editor.free, primary_fallback: false } })}><div><strong>{text('停止并提示,只使用免费模型', 'Stop and report; free models only')}</strong><span>{text('绝不会进入订阅或付费模型', 'Never use subscription or paid models')}</span></div><span className={`badge ${!editor.free.primary_fallback ? 'info' : ''} no-dot`}>{!editor.free.primary_fallback ? text('已选择', 'Selected') : text('选择', 'Choose')}</span></button><button type="button" className="option-row" aria-pressed={editor.free.primary_fallback} onClick={() => update({ free: { ...editor.free, primary_fallback: true } })}><div><strong>{text('继续使用主力模型', 'Continue with primary models')}</strong><span>{text('只有免费池全部不可用时才进入主力组合', 'Use primary only when the free pool is unavailable')}</span></div><span className={`badge ${editor.free.primary_fallback ? 'info' : ''} no-dot`}>{editor.free.primary_fallback ? text('已选择', 'Selected') : text('选择', 'Choose')}</span></button></div>{editor.free.primary_fallback && <div className="free-lane">{group(text('主力模型', 'Primary models'), text('免费池的兜底', 'Fallback for free pool'), editor.free.primary, primary => update({ free: { ...editor.free, primary } }), { preferred: 'high', primary: true, groupId: 'free-primary' })}</div>}</section>}- {codexCapabilities && <section className="editor-section codex-capability-summary" data-codex-capability-state={codexCapabilities.state}><div className="editor-section-heading"><div><h3>{text('对 Codex 的能力预览', 'Codex capability preview')}</h3><p>{text('依据当前编辑内容及候选的 Codex Responses 入口能力计算。上游使用其他协议时仍可能通过 HiRoute 适配;发布和接入时会重新核对,预览不代表真实客户端验证。', 'Calculated from the current edit and candidate Codex Responses ingress capabilities. HiRoute may adapt another upstream protocol; publication and connection recheck compatibility, and this preview is not a live client verification.')}</p></div></div>{codexCapabilities.state === 'available' ? <div className="option-panel"><div className="option-row" data-codex-capability-summary><div><strong>{text(`上下文 ${formatContext(codexCapabilities.context_window)} · 输入 ${codexCapabilities.input_modalities.includes('image') ? '文本/图片' : '文本'}`, `Context ${formatContext(codexCapabilities.context_window)} · Input ${codexCapabilities.input_modalities.includes('image') ? 'text/images' : 'text'}`)}</strong><span>{text('推理强度由路由配置决定', 'Reasoning effort is determined by the route configuration')}</span></div></div>{codexCapabilities.limitations.map(limit => <div className="callout warn" role="status" data-codex-capability-limit={limit.kind} key={limit.kind}><UiIcon name="warning" /><div><strong>{limit.kind === 'context_window' ? text('候选收窄了共同上下文', 'A candidate narrows the shared context') : text('候选收窄了图片输入', 'A candidate narrows image input')}</strong><p>{limit.kind === 'context_window' ? text(`${capabilityBindings(limit.binding_ids)} 将共同上下文限制为 ${formatContext(codexCapabilities.context_window)}。`, `${capabilityBindings(limit.binding_ids)} limits the shared context to ${formatContext(codexCapabilities.context_window)}.`) : text(`${capabilityBindings(limit.binding_ids)} 不支持完整的 Codex 图片输入;最终目录只声明文本。`, `${capabilityBindings(limit.binding_ids)} does not support complete Codex image input, so the final catalog declares text only.`)}</p></div></div>)}{codexCapabilities.fixed_limits.includes('parallel_tool_calls_disabled') && <div className="callout" data-codex-fixed-limit="parallel_tool_calls_disabled"><UiIcon name="info" /><div><strong>{text('HiRoute 当前固定使用串行工具调用', 'HiRoute currently uses serial tool calls')}</strong><p>{text('这是当前实现限制,不由任何候选模型造成。', 'This is a fixed implementation limit, not a candidate-model limitation.')}</p></div></div>}</div> : <div className="callout bad" role="alert" data-codex-capability-unavailable><UiIcon name="warning" /><div><strong>{text('无法生成可靠的 Codex 客户端能力', 'Reliable Codex client capabilities are unavailable')}</strong>{codexCapabilities.issues.map((issue, index) => <p key={`${issue.kind}:${issue.binding_id ?? index}`}>{capabilityIssue(issue)}</p>)}</div></div>}</section>}+ <section className="editor-section" data-plan-context-window>+ <div className="editor-section-heading"><div><h3>{text('上下文窗口', 'Context window')}</h3><p>{text('默认最多使用 272,000 tokens;可在候选共同上界内调整。较大的窗口可能增加上下文与缓存费用。', 'Defaults to at most 272,000 tokens. Adjust within the shared candidate limit. Larger windows may increase context and cache costs.')}</p></div></div>+ <label className="field"><span className="field-label">{text('自定义窗口 · tokens(留空使用默认值)', 'Custom window · tokens (leave empty for default)')}</span>+ <input className="input plan-context-window-field" type="number" min="1" step="1" max={options?.context_window?.maximum_tokens} placeholder={String(options?.context_window?.default_tokens ?? 272000)} value={editor.limits.context_window_tokens ?? ''} aria-invalid={Boolean(editor.limits.context_window_tokens !== undefined && contextWindowError(editor.limits.context_window_tokens, options?.context_window, language))} onChange={event => update({ limits: { ...editor.limits, context_window_tokens: event.target.value === '' ? undefined : Number(event.target.value) } })} />+ </label>+ <p className="field-help">{text('已接入的 Agent 需重新保存模型设置并重新启动,才能加载更新后的窗口;进行中的会话不会立即改变。', 'For an existing Codex connection, save the Agent model settings again and restart Codex to load the updated window. Running sessions do not change immediately.')}</p>+ <button type="button" className="btn" disabled={editor.limits.context_window_tokens === undefined} onClick={() => update({ limits: { ...editor.limits, context_window_tokens: undefined } })}>{text('恢复默认', 'Restore default')}</button>+ <p className="field-help">{options?.context_window ? text(`默认 ${options.context_window.default_tokens.toLocaleString()} tokens · 候选共同上界 ${options.context_window.maximum_tokens.toLocaleString()} tokens`, `Default ${options.context_window.default_tokens.toLocaleString()} tokens · Shared candidate limit ${options.context_window.maximum_tokens.toLocaleString()} tokens`) : text('完成候选配置后显示可用上界。', 'Complete the candidate configuration to see the available limit.')}</p>+ {editor.limits.context_window_tokens !== undefined && contextWindowError(editor.limits.context_window_tokens, options?.context_window, language) && <p className="oc-inline-error" role="alert">{contextWindowError(editor.limits.context_window_tokens, options?.context_window, language)}</p>}+ </section>+ <section className="editor-section"><label className="field-label">{text('目标 Agent 能力预览', 'Target Agent capability preview')}<select className="select" value={previewAgent} onChange={event => setPreviewAgent(event.target.value as 'codex' | 'claude')}><option value="codex">Codex</option><option value="claude">Claude Code</option></select></label></section>+ {previewAgent === 'claude' && <section className="editor-section"><h3>Claude Code</h3>{options?.claude_capabilities?.state === 'available' ? <><p>{text(`自动压缩窗口最多 ${formatContext(options.claude_capabilities.context_window)} tokens`, `Auto-compact window up to ${formatContext(options.claude_capabilities.context_window)} tokens`)}</p><p className="field-help">{text('作用于整个 Claude Code 进程;接入多个计划时取最小窗口,原生模型可能更早压缩。接入时会核对窗口、配置冲突和请求能力。', 'Applies to the whole Claude Code process. Multiple plans share the smallest window; native models may compact earlier. Connection checks window constraints, configuration conflicts and request capabilities.')}</p></> : <p className="field-help">{options?.claude_capabilities?.state === 'unavailable' && options.claude_capabilities.reason === 'context_window_below_minimum' ? text('Claude Code 自动压缩窗口最低为 100K;请调整计划窗口或使用 Codex。', 'Claude Code requires an auto-compact window of at least 100K. Adjust the plan window or use Codex.') : text('当前候选或窗口尚不能用于 Claude Code;需要可用的 Messages 入口和有效窗口。', 'The current candidates or window are unavailable for Claude Code. A usable Messages ingress and valid window are required.')}</p>}</section>}+ {previewAgent === 'codex' && codexCapabilities && <section className="editor-section codex-capability-summary" data-codex-capability-state={codexCapabilities.state}><div className="editor-section-heading"><div><h3>{text('对 Codex 的能力预览', 'Codex capability preview')}</h3><p>{text('依据当前编辑内容及候选的 Codex Responses 入口能力计算。上游使用其他协议时仍可能通过 HiRoute 适配;发布和接入时会重新核对,预览不代表真实客户端验证。', 'Calculated from the current edit and candidate Codex Responses ingress capabilities. HiRoute may adapt another upstream protocol; publication and connection recheck compatibility, and this preview is not a live client verification.')}</p></div></div>{codexCapabilities.state === 'available' ? <div className="option-panel"><div className="option-row" data-codex-capability-summary><div><strong>{text(`上下文 ${formatContext(codexCapabilities.context_window)} · 输入 ${codexCapabilities.input_modalities.includes('image') ? '文本/图片' : '文本'}`, `Context ${formatContext(codexCapabilities.context_window)} · Input ${codexCapabilities.input_modalities.includes('image') ? 'text/images' : 'text'}`)}</strong><span>{text('推理强度由路由配置决定', 'Reasoning effort is determined by the route configuration')}</span></div></div>{codexCapabilities.limitations.map(limit => <div className="callout warn" role="status" data-codex-capability-limit={limit.kind} key={limit.kind}><UiIcon name="warning" /><div><strong>{limit.kind === 'context_window' ? text('候选收窄了共同上下文', 'A candidate narrows the shared context') : text('候选收窄了图片输入', 'A candidate narrows image input')}</strong><p>{limit.kind === 'context_window' ? text(`${capabilityBindings(limit.binding_ids)} 将共同上下文限制为 ${formatContext(options?.context_window?.maximum_tokens ?? codexCapabilities.context_window)}。`, `${capabilityBindings(limit.binding_ids)} limits the shared context to ${formatContext(options?.context_window?.maximum_tokens ?? codexCapabilities.context_window)}.`) : text(`${capabilityBindings(limit.binding_ids)} 不支持完整的 Codex 图片输入;最终目录只声明文本。`, `${capabilityBindings(limit.binding_ids)} does not support complete Codex image input, so the final catalog declares text only.`)}</p></div></div>)}{codexCapabilities.fixed_limits.includes('parallel_tool_calls_disabled') && <div className="callout" data-codex-fixed-limit="parallel_tool_calls_disabled"><UiIcon name="info" /><div><strong>{text('HiRoute 当前固定使用串行工具调用', 'HiRoute currently uses serial tool calls')}</strong><p>{text('这是当前实现限制,不由任何候选模型造成。', 'This is a fixed implementation limit, not a candidate-model limitation.')}</p></div></div>}</div> : <div className="callout bad" role="alert" data-codex-capability-unavailable><UiIcon name="warning" /><div><strong>{text('无法生成可靠的 Codex 客户端能力', 'Reliable Codex client capabilities are unavailable')}</strong>{codexCapabilities.issues.map((issue, index) => <p key={`${issue.kind}:${issue.binding_id ?? index}`}>{capabilityIssue(issue)}</p>)}</div></div>}</section>}<section className="editor-section" data-route-group="executor"><div className="editor-section-heading"><div><h3>{text('任务委派', 'Task delegation')}</h3><p>{text('关闭时只使用模型路由,不显示或检测本机执行环境。', 'When off, this plan only routes models and does not show or detect a local execution environment.')}</p></div></div><div className="option-panel"><button type="button" className="option-row" aria-pressed={editor.delegation_enabled} onClick={() => update({ delegation_enabled: !editor.delegation_enabled })}><div><strong>{text('允许委派任务给执行 Agent', 'Allow delegation to an execution agent')}</strong><span>{text('开启后需要为这份计划选择一个执行 Agent;安装缺失不会阻止保存。', 'When enabled, choose one execution agent for this plan. Missing installation does not block saving.')}</span></div><span className={`switch${editor.delegation_enabled ? ' on' : ''}`} aria-hidden="true" /></button></div>{editor.delegation_enabled && <div className="field"><label className="field-label">{text('执行任务的 Agent', 'Task execution agent')}</label><p className="field-help">{text('每份计划选择一个执行 Agent,不做自动回退。', 'Choose one execution agent per plan; there is no automatic fallback.')}</p><div className="v3-executors">{([['codex_cli', 'Codex CLI', text('使用 Codex CLI 执行委派任务', 'Use Codex CLI for delegated tasks')],diff --git a/apps/desktop/tests/plan-context-window.test.mjs b/apps/desktop/tests/plan-context-window.test.mjsnew file mode 100644index 00000000..62eb3eb8--- /dev/null+++ b/apps/desktop/tests/plan-context-window.test.mjs@@ -0,0 +1,19 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { contextWindowError } from '../src/plan-context-window.ts';++test('default and custom windows allow the full proven range', () => {+ const bounds = { maximum_tokens: 1050000, default_tokens: 272000 };+ for (const value of [undefined, 1, 128000, 272000, 500000, 1050000]) {+ assert.equal(contextWindowError(value, bounds, 'zh'), null);+ }+ for (const value of [0, -1, 1.5, NaN, Infinity, 1050001]) {+ assert.ok(contextWindowError(value, bounds, 'en'));+ }+});++test('candidate changes invalidate custom values without changing them', () => {+ assert.match(contextWindowError(500000, { maximum_tokens: 64000, default_tokens: 64000 }, 'zh'), /64,000/);+ assert.ok(contextWindowError(500000, null, 'en'));+ assert.equal(contextWindowError(undefined, null, 'en'), null);+});diff --git a/apps/desktop/tests/v3/browser/product-fixtures.ts b/apps/desktop/tests/v3/browser/product-fixtures.tsindex 06891f16..19365732 100644--- a/apps/desktop/tests/v3/browser/product-fixtures.ts+++ b/apps/desktop/tests/v3/browser/product-fixtures.ts@@ -579,12 +579,13 @@ export function mockProductInvoke(command: string, payload: Record<string, any>},};if (command === 'plan_editor_options') return {+ context_window: fresh || !payload?.input?.editor ? null : { maximum_tokens: 64000, default_tokens: 64000 },suggested_alias: 'hiroute-daily-coding',candidates: fresh ? [] : readyManagement.sources.flatMap(source => source.models.map(model => ({ binding_id: model.binding_id, model_configuration_id: model.catalog_configuration_id ?? model.upstream_model_id, display_name: model.display_name, reasoning: model.native_reasoning ?? { kind: 'fixed', profile: 'provider-default' }, billing_class: model.presentation?.billing_class ?? 'unknown', routable: source.state === 'ready', ingress_protocols: ['responses', 'messages'] }))),free_suggestions: fresh ? { candidates: [], unavailable: {} } : { candidates: [{ selection: { binding_id: 'binding/free/deepseek' } }, { selection: { binding_id: 'binding/free/glm' } }, { selection: { binding_id: 'binding/free/qwen' } }], unavailable: {} },codex_capabilities: fresh || !payload?.input?.editor ? null : {state: 'available',- context_window: 64000,+ context_window: payload?.input?.editor?.limits?.context_window_tokens ?? 64000,input_modalities: ['text'],reasoning: 'route_configuration',limitations: [diff --git a/assets/agent-profiles/current/profile-seed.json b/assets/agent-profiles/current/profile-seed.jsonindex fe5beec0..dda6b740 100644--- a/assets/agent-profiles/current/profile-seed.json+++ b/assets/agent-profiles/current/profile-seed.json@@ -1,151 +1 @@-{- "schema": "hiroute.agent-profiles-artifact/v1",- "tool_version": "hiroute-release-facts/1",- "profiles": [- {- "schema": "hiroute.agent-profile/v1",- "profile_id": "claude-messages-v1",- "integration_profile_ref": "builtin/claude-messages/v1",- "kind": "claude_code",- "exact_versions": [- "2.1.0",- "2.1.231"- ],- "ingress_protocol": "messages",- "config_precedence": [- "managed",- "process",- "launch",- "project",- "user"- ],- "owned_config_fields": [- {- "field_id": "base_endpoint",- "path": "env.ANTHROPIC_BASE_URL",- "write_layer": "user"- },- {- "field_id": "default_model",- "path": "env.ANTHROPIC_MODEL",- "write_layer": "user"- },- {- "field_id": "default_opus_model",- "path": "env.ANTHROPIC_DEFAULT_OPUS_MODEL",- "write_layer": "user"- },- {- "field_id": "default_sonnet_model",- "path": "env.ANTHROPIC_DEFAULT_SONNET_MODEL",- "write_layer": "user"- },- {- "field_id": "default_haiku_model",- "path": "env.ANTHROPIC_DEFAULT_HAIKU_MODEL",- "write_layer": "user"- },- {- "field_id": "small_fast_model",- "path": "env.ANTHROPIC_SMALL_FAST_MODEL",- "write_layer": "user"- },- {- "field_id": "auth_helper",- "path": "apiKeyHelper",- "write_layer": "user"- },- {- "field_id": "auth_environment",- "path": "hiroute.auth_environment",- "write_layer": "user"- }- ],- "dynamic_catalog": false,- "static_catalog_fallback": false,- "native_subagent_routing": false,- "managed_launch": {- "exact_version": "2.1.231",- "settings_argument": "--settings",- "environment_removals": [- "ANTHROPIC_API_KEY",- "ANTHROPIC_AUTH_TOKEN",- "ANTHROPIC_BASE_URL",- "ANTHROPIC_CUSTOM_HEADERS",- "ANTHROPIC_MODEL",- "CLAUDE_CODE_USE_BEDROCK",- "CLAUDE_CODE_USE_FOUNDRY",- "CLAUDE_CODE_USE_VERTEX"- ],- "caller_forbidden_options": [- "--anthropic-api-key",- "--anthropic-auth-token",- "--api-key",- "--api-key-helper",- "--auth-token",- "--base-url",- "--bedrock",- "--custom-headers",- "--foundry",- "--provider",- "--use-bedrock",- "--use-foundry",- "--use-vertex",- "--vertex"- ]- }- },- {- "schema": "hiroute.agent-profile/v1",- "profile_id": "codex-responses-v1",- "integration_profile_ref": "builtin/codex-responses/v1",- "kind": "codex",- "exact_versions": [],- "ingress_protocol": "responses",- "config_precedence": [- "process",- "launch",- "project",- "user",- "managed"- ],- "owned_config_fields": [- {- "field_id": "provider",- "path": "model_provider",- "write_layer": "user"- },- {- "field_id": "default_model",- "path": "model",- "write_layer": "user"- },- {- "field_id": "base_endpoint",- "path": "model_providers.hiroute.base_url",- "write_layer": "user"- },- {- "field_id": "wire_api",- "path": "model_providers.hiroute.wire_api",- "write_layer": "user"- },- {- "field_id": "static_catalog",- "path": "model_catalog_json",- "write_layer": "user"- }- ],- "dynamic_catalog": true,- "static_catalog_fallback": true,- "native_subagent_routing": true,- "spawn_guidance": {- "tool_name": "spawn_agent",- "registration_id": "codex.builtin.spawn-agent.v1",- "begin_marker": "Available model overrides (optional; inherited parent model is preferred):",- "end_marker": "Spawn arguments:",- "expected_shape_digest": "sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"- }- }- ]-}+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/1","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}}]}diff --git a/assets/release-facts/current/bundle/agent-profiles.json b/assets/release-facts/current/bundle/agent-profiles.jsonindex 524fe391..c6aa6d12 100644--- a/assets/release-facts/current/bundle/agent-profiles.json+++ b/assets/release-facts/current/bundle/agent-profiles.json@@ -1 +1 @@-{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","exact_versions":["2.1.0","2.1.231"],"ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"exact_version":"2.1.231","settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","exact_versions":[],"ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}}]}+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}}]}diff --git a/contracts/cli/agent-plan-catalog-query.v2.schema.json b/contracts/cli/agent-plan-catalog-query.v2.schema.jsonindex 277fa577..07b9159a 100644--- a/contracts/cli/agent-plan-catalog-query.v2.schema.json+++ b/contracts/cli/agent-plan-catalog-query.v2.schema.json@@ -277,6 +277,11 @@"minimum": 1000,"type": "integer"},+ "context_window_tokens": {+ "maximum": 9223372036854775807,+ "minimum": 1,+ "type": "integer"+ },"maximum_attempts": {"maximum": 64,"minimum": 1,diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.jsonindex 31ff31dc..3b624b4f 100644--- a/contracts/cli/contract-set.v1.json+++ b/contracts/cli/contract-set.v1.json@@ -3,7 +3,7 @@"files": {"agent-check-request.v1.schema.json": "sha256:fbd9e9b19282a5ed8c3e30b5ae16538bc01318a70e4bb7c7a55e8e0472553feb","agent-launch-descriptor-request.v1.schema.json": "sha256:28f2f9d2d7f9a1618bea0f13383002429bc9e0ff56166cbee86958a245d0fd48",- "agent-plan-catalog-query.v2.schema.json": "sha256:c9dab9d3152c36449467f67de229836cff18cc3c5e7cdcdea719361aa9724676",+ "agent-plan-catalog-query.v2.schema.json": "sha256:087d87b25abed26e284e2e796e6480517b13b29bdfa7b5241a93b4d376889931","coverage-manifest.v1.json": "sha256:76d8776f13d953fd0b1c0387ba877c30fba7ecf564d927d131cb7e76b3f5a822","delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878","delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93",@@ -19,10 +19,10 @@"manifest.v1.json": "sha256:c602e9b661621403bc05405674f5522604be0e716a886673776199492f686f75","operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f","operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850",- "plan-content-change.v2.schema.json": "sha256:1706ccfd7aa0abe34b1253bcf43d746b01af059ded980cc2dc430633569c20ca",- "plan-draft-change.v1.schema.json": "sha256:8f3cf4a330260b241e8a751f99d706043e946b344f8d18e09d1081d47d3554b9",- "plan-editor.v2.schema.json": "sha256:8e1dc12e825826e1703664b7124d291ffd6ec2061dd49660f763609511319ff5",- "plan-lifecycle-change.v1.schema.json": "sha256:ff8ec4ff9bbf32fac6584b0a8dbd46e8724c4b55b6c09dd375ab2995af393132",+ "plan-content-change.v2.schema.json": "sha256:f92e2b43598a5f3e26dd2242ab404f306a53beefd8046fef2cb356e1aef5c27b",+ "plan-draft-change.v1.schema.json": "sha256:8767cc1a4d32f1f3b0ccffafb083a160ba94d6577bbcbe9312b0b2fed6490344",+ "plan-editor.v2.schema.json": "sha256:54cbbcec4fbfc7d41b4d87a734e422cec9e6d07e5e8abac511f33e4530a5658f",+ "plan-lifecycle-change.v1.schema.json": "sha256:3858708d1a5baa3b4acd1be2a69dd9698b11785ef3d013d6f88c7429a6ed833d","planned-manifest.v1.json": "sha256:eac0c7583245a881de141f9b8d853a86efb3f9ef8fa9a3ffb3ed75d759467072","session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44","session-lookup.v1.schema.json": "sha256:0c9e0ea31bdde7f720a9a17e8dc175902a20b3fb92abc21ce4bdae9fc3d97587",diff --git a/contracts/cli/plan-content-change.v2.schema.json b/contracts/cli/plan-content-change.v2.schema.jsonindex 304a448f..27c50924 100644--- a/contracts/cli/plan-content-change.v2.schema.json+++ b/contracts/cli/plan-content-change.v2.schema.json@@ -277,6 +277,11 @@"minimum": 1000,"type": "integer"},+ "context_window_tokens": {+ "maximum": 9223372036854775807,+ "minimum": 1,+ "type": "integer"+ },"maximum_attempts": {"maximum": 64,"minimum": 1,diff --git a/contracts/cli/plan-draft-change.v1.schema.json b/contracts/cli/plan-draft-change.v1.schema.jsonindex 35f43453..7669e0bc 100644--- a/contracts/cli/plan-draft-change.v1.schema.json+++ b/contracts/cli/plan-draft-change.v1.schema.json@@ -277,6 +277,11 @@"minimum": 1000,"type": "integer"},+ "context_window_tokens": {+ "maximum": 9223372036854775807,+ "minimum": 1,+ "type": "integer"+ },"maximum_attempts": {"maximum": 64,"minimum": 1,diff --git a/contracts/cli/plan-editor.v2.schema.json b/contracts/cli/plan-editor.v2.schema.jsonindex 15238b5d..ed69f8fe 100644--- a/contracts/cli/plan-editor.v2.schema.json+++ b/contracts/cli/plan-editor.v2.schema.json@@ -277,6 +277,11 @@"minimum": 1000,"type": "integer"},+ "context_window_tokens": {+ "maximum": 9223372036854775807,+ "minimum": 1,+ "type": "integer"+ },"maximum_attempts": {"maximum": 64,"minimum": 1,diff --git a/contracts/cli/plan-lifecycle-change.v1.schema.json b/contracts/cli/plan-lifecycle-change.v1.schema.jsonindex 47032381..bc93a5dd 100644--- a/contracts/cli/plan-lifecycle-change.v1.schema.json+++ b/contracts/cli/plan-lifecycle-change.v1.schema.json@@ -277,6 +277,11 @@"minimum": 1000,"type": "integer"},+ "context_window_tokens": {+ "maximum": 9223372036854775807,+ "minimum": 1,+ "type": "integer"+ },"maximum_attempts": {"maximum": 64,"minimum": 1,diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.jsonindex ca961297..e0e168ad 100644--- a/contracts/compatibility-support.v1.json+++ b/contracts/compatibility-support.v1.json@@ -731,5 +731,56 @@"crates/domain/src/publication/mod.rs","crates/gateway/src/publication/tests.rs","tools/e2e-harness/tests/p0_gateway_request_authority.rs"+ ],+ "field_compatibility_support": [+ {+ "contract": "hiroute.settings-claude-model-file/v1",+ "field": "snapshot.context_window_tokens",+ "mode": "recovery_read_only",+ "owner": "agent-connections",+ "reason": "Immutable pre-window Claude operations omit the field. Preserve their serialized digest and native restoration facts; new plan configurations always seal the window.",+ "removal_condition": "Retire only after all retained operations and supported backups contain no pre-window snapshots.",+ "allowed_paths": [+ "crates/application/src/agent_connection/claude_model_journal.rs"+ ]+ },+ {+ "contract": "hiroute.managed-claude-launch-descriptor/v2",+ "field": "context_window_tokens",+ "mode": "recovery_read_only",+ "owner": "agent-connections",+ "reason": "A descriptor reconstructed from a pre-window immutable settings operation has no managed context policy. It retains that operation’s behavior until settings are saved again.",+ "removal_condition": "Retire with the pre-window settings operation recovery reader.",+ "allowed_paths": [+ "crates/domain/src/agents/managed_launch.rs",+ "crates/daemon/src/control/runtime/agent_connection.rs"+ ]+ },+ {+ "contract": "hiroute.agent-profile/v1",+ "field": "exact_versions / managed_launch.exact_version",+ "mode": "recovery_read_only",+ "owner": "agent-connections",+ "reason": "Historical profile labels remain readable without participating in validation or admission. Current producers omit both fields.",+ "removal_condition": "No supported backup or frozen fixture contains legacy client-version profile labels.",+ "allowed_paths": [+ "crates/domain/src/agents/profile.rs",+ "crates/domain/src/agents/managed_launch.rs"+ ]+ },+ {+ "contract": "hiroute.agent-profile/v1",+ "field": "legacy version-bound observation digest",+ "mode": "recovery_read_only",+ "owner": "agent-connections",+ "reason": "Verify retained successful managed-launch Operations using their immutable diagnostic label and current physical identity/configuration/evidence. Never accept a new baseline or write this digest. Includes the original pre-window process digest format; any current context environment override prevents that fallback.",+ "removal_condition": "All supported successful managed-launch Operations use version-neutral observations.",+ "allowed_paths": [+ "crates/integrations/src/agents/claude_observation.rs",+ "crates/integrations/src/agents/filesystem.rs",+ "crates/daemon/src/control/runtime/agent_connection.rs",+ "crates/integrations/src/agents/filesystem_config.rs"+ ]+ }]}diff --git a/crates/application-api/src/generated/plan_authoring.rs b/crates/application-api/src/generated/plan_authoring.rsindex 6737a35f..3fcbfe41 100644--- a/crates/application-api/src/generated/plan_authoring.rs+++ b/crates/application-api/src/generated/plan_authoring.rs@@ -28,6 +28,7 @@ fn definitions() -> Value {"attempt_timeout_ms",],json!({+ "context_window_tokens":{"type":"integer","minimum":1,"maximum":9223372036854775807u64},"maximum_attempts":{"type":"integer","minimum":1,"maximum":64},"request_timeout_ms":{"type":"integer","minimum":1000,"maximum":3600000},"attempt_timeout_ms":{"type":"integer","minimum":1000,"maximum":3600000}}),);let classifier = json!({"oneOf":[diff --git a/crates/application-api/src/lib.rs b/crates/application-api/src/lib.rsindex 29eb6a23..5d7dd80d 100644--- a/crates/application-api/src/lib.rs+++ b/crates/application-api/src/lib.rs@@ -55,8 +55,7 @@ pub use hiroute_domain::delegation::{WorkspaceAccessV1,};pub use hiroute_domain::{- AgentActivationModeV1, AgentPlanId, CHANGE_SPEC_SCHEMA_V1,- CLAUDE_CODE_MANAGED_LAUNCH_VERSION_V1, CanonicalDigest, ChangeSpecV1,+ AgentActivationModeV1, AgentPlanId, CHANGE_SPEC_SCHEMA_V1, CanonicalDigest, ChangeSpecV1,ComputeCredentialSelectionError, ComputeCredentialSelectionV2, ContentMode,HIDDEN_AGENT_GRANT_HELPER_VERB_V1, MANAGED_CLAUDE_SETTING_SOURCES_ARGUMENT_V1,MANAGED_CLAUDE_SETTINGS_ARGUMENT_V1, ManagedClaudeLaunchDescriptorV2, ManagedLaunchProfileV1,diff --git a/crates/application-api/src/plan_authoring.rs b/crates/application-api/src/plan_authoring.rsindex 1bc89266..40f00557 100644--- a/crates/application-api/src/plan_authoring.rs+++ b/crates/application-api/src/plan_authoring.rs@@ -244,6 +244,8 @@ pub enum CodexClientCapabilityPreviewV1 {#[derive(Clone, Debug, Default, Deserialize, Serialize)]#[serde(deny_unknown_fields)]pub struct PlanEditorOptionsRequestV1 {+ #[serde(default)]+ pub published_plan: Option<PublishedPlanCapabilityRequestV1>,#[serde(default)]pub display_name: Option<String>,#[serde(default)]@@ -260,6 +262,8 @@ pub struct PlanEditorOptionsRequestV1 {#[derive(Clone, Debug, Deserialize, Serialize)]#[serde(deny_unknown_fields)]pub struct PlanEditorOptionsV1 {+ pub claude_capabilities: Option<ClaudeClientCapabilityPreviewV1>,+ pub context_window: Option<PlanContextWindowPreviewV1>,pub suggested_alias: Option<ModelAlias>,pub candidates: Vec<PlanCandidateOptionV1>,pub free_suggestions: Option<FreeSuggestionsV1>,@@ -267,3 +271,30 @@ pub struct PlanEditorOptionsV1 {pub codex_capabilities: Option<CodexClientCapabilityPreviewV1>,pub revisions: RevisionSetV1,}++/// Independent capability bound remains visible when a saved custom window becomes invalid.+#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct PlanContextWindowPreviewV1 {+ pub maximum_tokens: u64,+ pub default_tokens: u64,+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]+pub enum ClaudeClientCapabilityPreviewV1 {+ Available {+ context_window: u64,+ plan_window: u64,+ },+ Unavailable {+ reason: String,+ },+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct PublishedPlanCapabilityRequestV1 {+ pub plan_id: hiroute_domain::AgentPlanId,+ pub revision: u64,+}diff --git a/crates/application/src/agent_connection/claude_model_journal.rs b/crates/application/src/agent_connection/claude_model_journal.rsindex 6e3a6560..932a003e 100644--- a/crates/application/src/agent_connection/claude_model_journal.rs+++ b/crates/application/src/agent_connection/claude_model_journal.rs@@ -12,6 +12,8 @@ const SCHEMA: &str = "hiroute.settings-claude-model-file/v1";#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]pub struct ClaudeLaunchSnapshotIntent {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub context_window_tokens: Option<u64>,pub native_presets: AgentClaudePresetValuesV2,pub presets: AgentClaudePresetValuesV2,pub executable: String,@@ -169,6 +171,9 @@ fn validate_payload(payload: &ClaudeModelFilePayload) -> Result<(), OperationValtrusted_hiroute_executable,} => {if !local_gateway_base_url(gateway_base_url)+ || snapshot.context_window_tokens.is_some_and(|value| {+ hiroute_domain::claude_context_window(value) != Some(value)+ })|| change.validate().is_err()|| change.fields.iter().any(|field| {!matches!(@@ -179,6 +184,8 @@ fn validate_payload(payload: &ClaudeModelFilePayload) -> Result<(), OperationVal| "env.ANTHROPIC_DEFAULT_OPUS_MODEL"| "env.ANTHROPIC_DEFAULT_SONNET_MODEL"| "env.ANTHROPIC_DEFAULT_HAIKU_MODEL"+ | "env.CLAUDE_CODE_AUTO_COMPACT_WINDOW"+ | "env.CLAUDE_CODE_MAX_CONTEXT_TOKENS")})|| !Path::new(trusted_hiroute_executable).is_absolute()@@ -244,6 +251,7 @@ mod tests {).unwrap(),snapshot: Box::new(ClaudeLaunchSnapshotIntent {+ context_window_tokens: None,native_presets: AgentClaudePresetValuesV2 {opus: Some("Vendor/Opus[1m]".into()),sonnet: None,diff --git a/crates/application/src/agent_connection/planner.rs b/crates/application/src/agent_connection/planner.rsindex f81c6dbc..ceea62e6 100644--- a/crates/application/src/agent_connection/planner.rs+++ b/crates/application/src/agent_connection/planner.rs@@ -54,6 +54,13 @@ impl AgentConnectionPlanningFactsV1 {{proof.observed_at_unix_ms = 0;}+ for facts in [&mut first, &mut second] {+ facts.installation.version.clear();+ facts.installation.profile.legacy_exact_versions.clear();+ if let Some(profile) = &mut facts.installation.profile.managed_launch {+ profile.legacy_exact_version.clear();+ }+ }first == second}}@@ -407,7 +414,8 @@ impl AgentConnectionPlanner {facts.before_fingerprints.model_catalog,&ModelCatalogPayloadV1 {delivery,- client_version: facts.installation.version.clone(),+ // Diagnostic output must not change an accepted configuration payload.+ client_version: "not-probed".into(),renderer_ref: format!("{}/catalog-renderer/v1",profile.integration_profile_ref@@ -703,7 +711,6 @@ fn validate_wire_spec(}if spec.agent_id != facts.installation.agent_id|| spec.profile_id != profile.profile_id- || spec.installed_version != facts.installation.version|| !valid_registered_endpoint(&facts.gateway){return Err(AgentConnectionPlanningError::ProfileMismatch);diff --git a/crates/application/src/agent_connection/restore.rs b/crates/application/src/agent_connection/restore.rsindex 2485b8b9..96105e60 100644--- a/crates/application/src/agent_connection/restore.rs+++ b/crates/application/src/agent_connection/restore.rs@@ -93,8 +93,6 @@ impl AgentConnectionRestorePointV1 {|| !valid_identifier(&self.agent_id)|| !valid_identifier(&self.profile_id)|| !valid_identifier(&self.integration_profile_ref)- || self.installed_version.is_empty()- || self.installed_version.len() > 64{return Err(AgentConnectionPlanningError::ProfileMismatch);}@@ -210,7 +208,6 @@ pub fn preview_agent_connection_restore(}if spec.agent_id != restore_point.agent_id|| spec.profile_id != restore_point.profile_id- || spec.installed_version != restore_point.installed_version|| spec.restore_point_ref != restore_point.restore_point_ref|| facts.installation.agent_id != restore_point.agent_id|| profile.profile_id != restore_point.profile_iddiff --git a/crates/application/src/agent_connection/settings.rs b/crates/application/src/agent_connection/settings.rsindex 04a2050a..cb1a401a 100644--- a/crates/application/src/agent_connection/settings.rs+++ b/crates/application/src/agent_connection/settings.rs@@ -12,6 +12,9 @@ use serde::{Deserialize, Serialize};use std::collections::{BTreeMap, BTreeSet};pub struct AgentSettingsFacts {+ pub codex_context_override: bool,+ pub claude_context_override: bool,+ pub claude_plan_capability_unavailable: bool,pub context_id: String,pub dependency_digest: CanonicalDigest,pub capabilities: AgentCapabilitySet,@@ -83,6 +86,8 @@ pub enum CodexCatalogProducerKindV1 {#[derive(Clone, Debug, Serialize)]pub struct AgentSettingsPreview {+ pub context_windows: BTreeMap<String, u64>,+ pub claude_context_window: Option<u64>,pub spec: AgentSettingsSpecV2,pub dependency_digest: CanonicalDigest,pub accept_digest: CanonicalDigest,@@ -106,6 +111,10 @@ pub struct AgentSettingsBlock {#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]#[serde(rename_all = "snake_case")]pub enum SettingsBlockReason {+ CodexContextOverride,+ ClaudeContextOverride,+ ClaudePlanCapabilityUnavailable,+ ClaudeContextWindowUnsupported,CapabilityUnavailable,ModelPlanUnavailable,NativeModelCoverageUnavailable,@@ -213,6 +222,17 @@ pub fn preview_agent_settings({return Err(SettingsPlanningError::InvalidSelection);}+ if matches!(settings, AgentModelSelectionV2::CodexDefault { .. })+ && !settings.allowed_plan_ids().is_empty()+ && facts.codex_context_override+ {+ blockers.push(AgentSettingsBlock {+ facet: AgentSettingsFacet::Model,+ reason: SettingsBlockReason::CodexContextOverride,+ capabilities: Vec::new(),+ model_ids: Vec::new(),+ });+ }let grant = derive_model_grant(settings, facts);match grant {Ok(grant) => {@@ -380,18 +400,74 @@ pub fn preview_agent_settings()}).collect::<Vec<_>>();+ let context_windows = match model_grant+ .as_ref()+ .map(|grant| plan_context_windows(grant, facts.model_publication.as_ref()))+ .transpose()+ {+ Ok(windows) => windows.unwrap_or_default(),+ Err(_) => {+ blockers.push(AgentSettingsBlock {+ facet: AgentSettingsFacet::Model,+ reason: SettingsBlockReason::ModelPlanUnavailable,+ capabilities: Vec::new(),+ model_ids: Vec::new(),+ });+ BTreeMap::new()+ }+ };+ let claude_context_window = if matches!(+ &spec.model,+ AgentFacetIntent::Configure {+ settings: AgentModelSelectionV2::ClaudeLauncher { .. }+ }+ ) && !context_windows.is_empty()+ {+ if facts.claude_plan_capability_unavailable {+ blockers.push(AgentSettingsBlock {+ facet: AgentSettingsFacet::Model,+ reason: SettingsBlockReason::ClaudePlanCapabilityUnavailable,+ capabilities: Vec::new(),+ model_ids: Vec::new(),+ });+ }+ let window = context_windows+ .values()+ .copied()+ .min()+ .and_then(hiroute_domain::claude_context_window);+ if facts.claude_context_override || window.is_none() {+ blockers.push(AgentSettingsBlock {+ facet: AgentSettingsFacet::Model,+ reason: if facts.claude_context_override {+ SettingsBlockReason::ClaudeContextOverride+ } else {+ SettingsBlockReason::ClaudeContextWindowUnsupported+ },+ capabilities: Vec::new(),+ model_ids: Vec::new(),+ });+ }+ window+ } else {+ None+ };let accept_digest = CanonicalDigest::of(&("hiroute.agent-settings-preview/v2",&spec,&facts.dependency_digest,proofs,&model_grant,+ &context_windows,+ claude_context_window,&collaboration_trigger_mode,&facts.restore_points,&blockers,)).map_err(|_| SettingsPlanningError::Encoding)?;Ok(AgentSettingsPreview {+ context_windows,+ claude_context_window,spec,dependency_digest: facts.dependency_digest.clone(),accept_digest,@@ -552,3 +628,43 @@ pub use confirmation::*;#[cfg(test)]mod tests;++/// Bind displayed and installed windows to the same exact publication used to derive the grant.+pub fn plan_context_windows(+ grant: &AgentModelGrantV2,+ publication: Option<&GatewayPublicationV1>,+) -> Result<BTreeMap<String, u64>, SettingsPlanningError> {+ let mut windows = BTreeMap::new();+ for (name, route) in &grant.routes {+ if let AgentModelRouteV2::Plan {+ plan_id,+ revision,+ semantic_digest,+ ..+ } = route+ {+ let plan = publication+ .and_then(|p| {+ p.plans.iter().find(|p| {+ p.agent_plan_id() == plan_id && p.body.agent_plan_revision == *revision+ })+ })+ .ok_or(SettingsPlanningError::InvalidSelection)?;+ let plan = plan+ .clone()+ .into_current()+ .map_err(|_| SettingsPlanningError::InvalidSelection)?;+ if &plan.body.materialized_route_digest != semantic_digest {+ return Err(SettingsPlanningError::InvalidSelection);+ }+ windows.insert(+ name.clone(),+ plan.body+ .materialized+ .context_window_tokens()+ .map_err(|_| SettingsPlanningError::InvalidSelection)?,+ );+ }+ }+ Ok(windows)+}diff --git a/crates/application/src/agent_connection/settings/tests.rs b/crates/application/src/agent_connection/settings/tests.rsindex 73e564e3..5b554d14 100644--- a/crates/application/src/agent_connection/settings/tests.rs+++ b/crates/application/src/agent_connection/settings/tests.rs@@ -24,6 +24,9 @@ fn facts() -> AgentSettingsFacts {).unwrap();AgentSettingsFacts {+ codex_context_override: false,+ claude_context_override: false,+ claude_plan_capability_unavailable: false,context_id: "agent-context/test".into(),dependency_digest,capabilities,@@ -431,6 +434,9 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {).unwrap();AgentSettingsFacts {+ codex_context_override: false,+ claude_context_override: false,+ claude_plan_capability_unavailable: false,context_id: "agent-context/test".into(),dependency_digest,capabilities,@@ -527,6 +533,16 @@ fn codex_plan_selections_preview_only_with_catalog_facts() {assert!(without_client.blockers.is_empty());assert!(without_client.model_grant.is_some());+ no_detected_surface.codex_context_override = true;+ let conflict =+ preview_agent_settings(spec(plan_selection.clone()), &no_detected_surface).unwrap();+ assert!(+ conflict+ .blockers+ .iter()+ .any(|block| block.reason == SettingsBlockReason::CodexContextOverride)+ );+// Catalog facts make the same plan selection preview cleanly.let mut proven_facts = codex_facts(Some(SettingsModelCatalogFacts {source_revision: "be6e8eac029b183056b7e4402879f15d2c85f61b".into(),@@ -977,3 +993,69 @@ fn login_item_intent_binds_only_active_host_declarations() {);}}++#[test]+fn claude_settings_share_the_smallest_published_window_and_block_overrides() {+ let original = crate::compiler::test_fixtures::compiled_publication(1);+ let mut plans: Vec<_> = original.plans.clone();+ for (plan, window) in plans.iter_mut().zip([100_000, 120_000]) {+ let body = std::sync::Arc::make_mut(&mut plan.body);+ body.materialized.attempt_owned.limits.context_window_tokens = Some(window);+ body.materialized_route_digest = body.materialized.route_digest().unwrap();+ *plan = hiroute_domain::CompiledAgentPlanV1::seal_current(body.clone()).unwrap();+ }+ let ids: Vec<_> = plans+ .iter()+ .map(|plan| plan.agent_plan_id().clone())+ .collect();+ let publication = GatewayPublicationV1::seal(+ original.workspace_id,+ original.authority_id,+ original.authority_epoch,+ original.publication_revision,+ original.catalog_renderer_revision,+ original.alias_registry,+ plans,+ Vec::new(),+ )+ .unwrap();+ let spec: AgentSettingsSpecV2 = serde_json::from_value(json!({+ "schema_version":{"major":2,"minor":0}, "context_id":"agent-context/test",+ "model":{"intent":"configure","settings":{"mode":"claude_launcher","surfaces":["claude_cli"],"fixed_models":[],"preset_mappings":{+ "opus":{"kind":"plan","plan_id":ids[0]},"sonnet":{"kind":"plan","plan_id":ids[1]},"haiku":{"kind":"preserve_native"}}}}+ })).unwrap();+ let mut facts = facts();+ facts.model_publication = Some(publication);+ facts.native_claude_presets = Some(hiroute_domain::AgentClaudePresetValuesV2 {+ opus: None,+ sonnet: None,+ haiku: None,+ });+ let preview = preview_agent_settings(spec.clone(), &facts).unwrap();+ assert_eq!(preview.claude_context_window, Some(100_000));+ assert_eq!(+ preview+ .context_windows+ .values()+ .copied()+ .collect::<BTreeSet<_>>(),+ [100_000, 120_000].into()+ );+ facts.claude_context_override = true;+ let blocked = preview_agent_settings(spec.clone(), &facts).unwrap();+ assert!(+ blocked+ .blockers+ .iter()+ .any(|block| block.reason == SettingsBlockReason::ClaudeContextOverride)+ );+ facts.claude_context_override = false;+ facts.claude_plan_capability_unavailable = true;+ let blocked = preview_agent_settings(spec, &facts).unwrap();+ assert!(+ blocked+ .blockers+ .iter()+ .any(|block| block.reason == SettingsBlockReason::ClaudePlanCapabilityUnavailable)+ );+}diff --git a/crates/application/src/agent_connection/settings_input.rs b/crates/application/src/agent_connection/settings_input.rsindex 916e6efc..7f411cea 100644--- a/crates/application/src/agent_connection/settings_input.rs+++ b/crates/application/src/agent_connection/settings_input.rs@@ -102,7 +102,7 @@ impl AgentSettingsPlanningInput {.map(|catalog| catalog.content_digest.clone()),}),SettingsModelTargetFacts::Claude(claude) => {- let snapshot = claude_model_snapshot(+ let mut snapshot = claude_model_snapshot(settings,grant,claude,@@ -111,12 +111,14 @@ impl AgentSettingsPlanningInput {.as_ref().ok_or_else(invalid)?,)?;+ snapshot.context_window_tokens = preview.claude_context_window;SettingsModelAction::Claude(ClaudeModelFileAction::Configure {previous_operation: file.active_configuration.clone(),change: claude_native_change(&snapshot,claude,&self.facts.context_id,+ file.active_configuration.is_some(),)?,snapshot: Box::new(snapshot),gateway_base_url: claude.gateway_base_url.clone(),@@ -417,6 +419,7 @@ fn claude_model_snapshot(.claude_preset_values(settings, native_presets).map_err(|_| invalid())?;Ok(ClaudeLaunchSnapshotIntent {+ context_window_tokens: None,native_presets: native_presets.clone(),presets,executable: facts.executable.clone().ok_or_else(invalid)?,@@ -428,6 +431,7 @@ fn claude_native_change(snapshot: &ClaudeLaunchSnapshotIntent,facts: &SettingsClaudeModelFacts,context_id: &str,+ reconfigure: bool,) -> Result<hiroute_domain::AgentConfigChangeV1, OperationValidationError> {let invalid = || OperationValidationError::UnregisteredEffectPlan;let endpoint = facts@@ -456,6 +460,17 @@ fn claude_native_change(value.as_ref().map(|value| json!(value)),);}+ for key in hiroute_domain::CLAUDE_CONTEXT_ENVIRONMENT {+ if snapshot.context_window_tokens.is_none() && !reconfigure {+ continue;+ }+ desired.insert(+ format!("env.{key}"),+ snapshot+ .context_window_tokens+ .map(|value| json!(value.to_string())),+ );+ }hiroute_domain::AgentConfigChangeV1::preview(&facts.user_document, desired).map_err(|_| invalid())}diff --git a/crates/application/src/agent_connection/tests.rs b/crates/application/src/agent_connection/tests.rsindex ff5ef7f1..20099175 100644--- a/crates/application/src/agent_connection/tests.rs+++ b/crates/application/src/agent_connection/tests.rs@@ -34,12 +34,16 @@ fn agent_connection_apply_requires_current_action_evidence_even_for_listed_versi#[test]fn agent_connection_current_proof_allows_unlisted_version_without_version_allowlist() {- let mut input = facts(AgentKindV1::Codex);- input.installation.version = "future-unlisted-build".into();- input.installation.profile.exact_versions.clear();- let mut request = spec(AgentKindV1::Codex, false, false);- request.installed_version = input.installation.version.clone();- assert!(AgentConnectionPlanner::preview_connect(request, input).is_ok());+ for kind in [AgentKindV1::Codex, AgentKindV1::ClaudeCode] {+ for version in ["0.0.1", "99.1.2", "", "unparseable version"] {+ let mut input = facts(kind);+ input.installation.version = version.into();+ // The request deliberately retains its earlier diagnostic version.+ assert!(+ AgentConnectionPlanner::preview_connect(spec(kind, false, false), input).is_ok()+ );+ }+ }}fn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {@@ -85,7 +89,7 @@ fn profile(kind: AgentKindV1) -> AgentProfileV1 {profile_id: "codex-responses-v1".to_owned(),integration_profile_ref: "builtin/codex-responses/v1".to_owned(),kind,- exact_versions: BTreeSet::from([CODEX_VERIFIED_VERSION_V1.to_owned()]),+ legacy_exact_versions: BTreeSet::from([CODEX_VERIFIED_VERSION_V1.to_owned()]),ingress_protocol: AgentIngressProtocolV1::Responses,config_precedence: precedence,owned_config_fields: vec![@@ -115,7 +119,7 @@ fn profile(kind: AgentKindV1) -> AgentProfileV1 {profile_id: "claude-messages-v1".to_owned(),integration_profile_ref: "builtin/claude-messages/v1".to_owned(),kind,- exact_versions: BTreeSet::from([CLAUDE_CODE_VERIFIED_VERSION_V1.to_owned()]),+ legacy_exact_versions: BTreeSet::from([CLAUDE_CODE_VERIFIED_VERSION_V1.to_owned()]),ingress_protocol: AgentIngressProtocolV1::Messages,config_precedence: precedence,owned_config_fields: vec![@@ -197,10 +201,7 @@ fn plans() -> Vec<PublishedAgentPlanV1> {fn facts(kind: AgentKindV1) -> AgentConnectionPlanningFactsV1 {let installation = installation(kind);- let activation_mode = if installation- .profile- .supports_managed_launch(&installation.version)- {+ let activation_mode = if installation.profile.supports_managed_launch() {hiroute_domain::AgentActivationModeV1::ManagedLaunch} else {hiroute_domain::AgentActivationModeV1::ManagedConfiguration@@ -406,9 +407,9 @@ fn agent_connection_exact_2_1_231_uses_managed_launch_without_persistent_config(facts.installation.profile- .exact_versions+ .legacy_exact_versions.insert("2.1.231".to_owned());- facts.installation.profile.managed_launch = Some(ManagedLaunchProfileV1::claude_code_2_1_231());+ facts.installation.profile.managed_launch = Some(ManagedLaunchProfileV1::claude_code());facts.activation_mode = hiroute_domain::AgentActivationModeV1::ManagedLaunch;let mut spec = spec(AgentKindV1::ClaudeCode, false, false);spec.installed_version = "2.1.231".to_owned();@@ -601,14 +602,16 @@ fn agent_connection_restore_reuses_typed_transaction_and_exact_restore_point() {installed_version: CODEX_VERIFIED_VERSION_V1.to_owned(),restore_point_ref: "restore/codex/1".to_owned(),};- for observed_version in [CODEX_VERIFIED_VERSION_V1, "future-unlisted-build"] {+ for observed_version in ["0.0.1", "99.1.2", "", "unparseable version"] {let mut current_installation = installation(AgentKindV1::Codex);current_installation.version = observed_version.into();current_installation.capability_evidence.retain(|proof| {proof.capability != hiroute_domain::AgentCapability::IngressAuthentication});+ let mut current_spec = restore_spec.clone();+ current_spec.installed_version = observed_version.into();let outcome = preview_agent_connection_restore(- restore_spec.clone(),+ current_spec,restore_point.clone(),AgentConnectionRestorePlanningFactsV1 {installation: current_installation,@@ -707,6 +710,28 @@ fn repeated_planning_snapshot_ignores_probe_time_but_not_proof_or_native_changeshiroute_domain::CanonicalDigest::of_bytes(b"different-proof-input");assert!(!first.same_snapshot(&changed));changed = later;- changed.installation.version = "replaced".into();- assert!(!first.same_snapshot(&changed));+ changed.installation.version = "different diagnostic label".into();+ assert!(first.same_snapshot(&changed));+}++#[test]+fn client_version_changes_do_not_invalidate_configuration_snapshot() {+ for kind in [AgentKindV1::Codex, AgentKindV1::ClaudeCode] {+ let original = facts(kind);+ for version in ["0.0.1", "99.1.2", "", "unparseable version"] {+ let mut changed = original.clone();+ changed.installation.version = version.into();+ changed.installation.profile.legacy_exact_versions.clear();+ assert!(original.same_snapshot(&changed));+ let request = spec(kind, kind == AgentKindV1::Codex, false);+ let before =+ AgentConnectionPlanner::preview_connect(request.clone(), original.clone()).unwrap();+ let after = AgentConnectionPlanner::preview_connect(request, changed.clone()).unwrap();+ assert_eq!(before.change_digest, after.change_digest);+ assert_eq!(before.effects, after.effects);+ changed.installation.observation_digest =+ hiroute_domain::CanonicalDigest::of_bytes(b"different executable or configuration");+ assert!(!original.same_snapshot(&changed));+ }+ }}diff --git a/crates/application/src/client_access/editor_options.rs b/crates/application/src/client_access/editor_options.rsindex 57d98cb9..6f0dca63 100644--- a/crates/application/src/client_access/editor_options.rs+++ b/crates/application/src/client_access/editor_options.rs@@ -63,8 +63,43 @@ pub(super) fn dispatch(.map_err(|_| ErrorCode::InvalidArguments)}).transpose()?;- let codex_capabilities =- codex_capabilities(payload.editor.as_ref(), &state.facts, port.as_ref())?;+ if payload.published_plan.is_some() && payload.editor.is_some() {+ return Err(ErrorCode::InvalidArguments);+ }+ let (codex_capabilities, claude_capabilities, context_window) = if let Some(reference) =+ &payload.published_plan+ {+ let publication = state+ .active_publication+ .as_ref()+ .ok_or(ErrorCode::ResourceNotFound)?;+ let plan = published_preview_plan(publication, reference)?;+ let upper = plan+ .body+ .materialized+ .context_window_upper_bound()+ .map_err(|_| ErrorCode::CapabilityDenied)?;+ (+ Some(+ port.codex_client_capability_preview(&plan)+ .map_err(map_control_error)?,+ ),+ Some(+ port.claude_client_capability_preview(&plan)+ .map_err(map_control_error)?,+ ),+ Some(PlanContextWindowPreviewV1 {+ maximum_tokens: upper,+ default_tokens: upper.min(hiroute_domain::DEFAULT_PLAN_CONTEXT_WINDOW_TOKENS),+ }),+ )+ } else {+ (+ codex_capabilities(payload.editor.as_ref(), &state.facts, port.as_ref())?,+ claude_capabilities(payload.editor.as_ref(), &state.facts, port.as_ref()),+ context_window_preview(payload.editor.as_ref(), &state.facts),+ )+ };let candidates = state.facts.candidates@@ -84,6 +119,8 @@ pub(super) fn dispatch(}).collect();Ok(PlanEditorOptionsV1 {+ claude_capabilities,+ context_window,suggested_alias,candidates,ratings,@@ -127,6 +164,28 @@ fn codex_capabilities(.map_err(map_control_error)}+fn context_window_preview(+ editor: Option<&PlanEditorStateV2>,+ facts: &crate::compiler::AgentPlanCompilationFactsV1,+) -> Option<PlanContextWindowPreviewV1> {+ let mut editor = editor?.clone();+ // Inspect the capability ceiling even when the custom setting exceeds new candidates.+ editor.limits.context_window_tokens = None;+ let configuration = editor.effective().ok()?;+ let identity = AgentPlanIdentityV1 {+ agent_plan_id: AgentPlanId::parse("plan/context-window-preview").ok()?,+ model_alias: ModelAlias::parse("hiroute-context-window-preview").ok()?,+ display_name: configuration.display_name.clone(),+ purpose: configuration.purpose.clone(),+ };+ let plan = compile_agent_plan_v2(identity, 1, &configuration, facts).ok()?;+ let maximum_tokens = plan.body.materialized.context_window_upper_bound().ok()?;+ Some(PlanContextWindowPreviewV1 {+ maximum_tokens,+ default_tokens: maximum_tokens.min(hiroute_domain::DEFAULT_PLAN_CONTEXT_WINDOW_TOKENS),+ })+}+fn compilation_unavailable(error: &AgentPlanCompilerError) -> CodexClientCapabilityPreviewV1 {let binding_id = match error {AgentPlanCompilerError::UnknownBinding(binding_id)@@ -142,6 +201,60 @@ fn compilation_unavailable(error: &AgentPlanCompilerError) -> CodexClientCapabil}}+fn claude_capabilities(+ editor: Option<&PlanEditorStateV2>,+ facts: &crate::compiler::AgentPlanCompilationFactsV1,+ port: &dyn crate::control::RoutingFactsPort,+) -> Option<ClaudeClientCapabilityPreviewV1> {+ let editor = editor?;+ let unavailable = |reason: &str| {+ Some(ClaudeClientCapabilityPreviewV1::Unavailable {+ reason: reason.into(),+ })+ };+ let Ok(configuration) = editor.effective() else {+ return None;+ };+ let identity = AgentPlanIdentityV1 {+ agent_plan_id: AgentPlanId::parse("plan/claude-capability-preview").ok()?,+ model_alias: ModelAlias::parse("hiroute-claude-capability-preview").ok()?,+ display_name: configuration.display_name.clone(),+ purpose: configuration.purpose.clone(),+ };+ let Ok(plan) = compile_agent_plan_v2(identity, 1, &configuration, facts) else {+ return unavailable("plan_compilation");+ };+ Some(+ port.claude_client_capability_preview(&plan)+ .unwrap_or_else(|_| ClaudeClientCapabilityPreviewV1::Unavailable {+ reason: "request_capabilities".into(),+ }),+ )+}++fn published_preview_plan(+ publication: &hiroute_domain::GatewayPublicationV1,+ reference: &PublishedPlanCapabilityRequestV1,+) -> Result<hiroute_domain::CompiledAgentPlanV1, ErrorCode> {+ if !publication+ .published_agent_plans()+ .map_err(|_| ErrorCode::Internal)?+ .iter()+ .any(|plan| plan.agent_plan_id == reference.plan_id && plan.active)+ {+ return Err(ErrorCode::ResourceNotFound);+ }+ let plan = publication+ .plans+ .iter()+ .find(|plan| plan.agent_plan_id() == &reference.plan_id)+ .ok_or(ErrorCode::ResourceNotFound)?;+ if plan.body.agent_plan_revision != reference.revision {+ return Err(ErrorCode::RevisionConflict);+ }+ plan.clone().into_current().map_err(|_| ErrorCode::Internal)+}+#[cfg(test)]mod tests {use super::*;@@ -212,6 +325,51 @@ mod tests {}}+ #[test]+ fn claude_deployment_preview_reads_the_published_revision_not_current_candidate_facts() {+ let publication = crate::compiler::test_fixtures::compiled_publication(1);+ let active = publication+ .published_agent_plans()+ .unwrap()+ .into_iter()+ .find(|plan| plan.active)+ .unwrap();+ let mut reference = PublishedPlanCapabilityRequestV1 {+ plan_id: active.agent_plan_id.clone(),+ revision: active.agent_plan_revision,+ };+ let exact = published_preview_plan(&publication, &reference).unwrap();+ let original = publication+ .plans+ .iter()+ .find(|plan| plan.agent_plan_id() == &reference.plan_id)+ .unwrap()+ .clone()+ .into_current()+ .unwrap();+ assert_eq!(exact, original);+ // A newer draft or changed model metadata cannot be mistaken for a saved revision.+ reference.revision += 1;+ assert!(matches!(+ published_preview_plan(&publication, &reference),+ Err(ErrorCode::RevisionConflict)+ ));+ }++ #[test]+ fn context_bound_survives_a_custom_value_invalidated_by_candidates() {+ let mut value = editor();+ value.limits.context_window_tokens = Some(1_050_000);+ let bounds = context_window_preview(Some(&value), &compilation_facts()).unwrap();+ assert!(bounds.maximum_tokens < 1_050_000);+ assert_eq!(bounds.default_tokens, bounds.maximum_tokens.min(272_000));+ assert!(matches!(+ codex_capabilities(Some(&value), &compilation_facts(), &PreviewPort::default())+ .unwrap(),+ Some(CodexClientCapabilityPreviewV1::Unavailable { .. })+ ));+ }+#[test]fn complete_editor_compiles_with_current_facts_before_capability_analysis() {let port = PreviewPort::default();diff --git a/crates/application/src/compiler/explicit/tests.rs b/crates/application/src/compiler/explicit/tests.rsindex 8b8248b0..5d3a9306 100644--- a/crates/application/src/compiler/explicit/tests.rs+++ b/crates/application/src/compiler/explicit/tests.rs@@ -315,3 +315,48 @@ fn fixed_name_colliding_with_an_allowed_plan_alias_is_rejected_before_publicatioAgentConnectionError::InvalidGrant);}++#[test]+fn context_window_is_bounded_persisted_and_changes_the_route_digest() {+ let mut desired = desired();+ let facts = compilation_facts();+ let default = compile(&desired, &facts).unwrap();+ let upper = default+ .body+ .materialized+ .context_window_upper_bound()+ .unwrap();+ assert_eq!(+ default.body.materialized.context_window_tokens().unwrap(),+ upper.min(272_000)+ );+ desired.limits.context_window_tokens = Some(64_000);+ let custom = compile(&desired, &facts).unwrap();+ assert_eq!(+ custom.body.materialized.context_window_tokens().unwrap(),+ 64_000+ );+ assert_ne!(+ default.body.materialized_route_digest,+ custom.body.materialized_route_digest+ );+ let version = PlanVersionV1::new(WorkspaceId::default(), desired.clone(), custom).unwrap();+ let saved: PlanVersionV1 =+ serde_json::from_value(serde_json::to_value(&version).unwrap()).unwrap();+ assert_eq!(saved, version);+ for invalid in [0, upper + 1, u64::MAX] {+ desired.limits.context_window_tokens = Some(invalid);+ assert!(compile(&desired, &facts).is_err());+ }+ desired.limits.context_window_tokens = Some(upper);+ assert!(compile(&desired, &facts).is_ok());+ let mut changed = facts;+ for profile in &mut changed.candidates[0].protocol_profiles {+ profile.capability.context.max_input_tokens = GatewayCriticalFactV1::Exact(32_000);+ }+ // Changing an active candidate's bound must not silently lower the saved custom value.+ if let AgentPlanStrategyV2::Custom { candidates } = &mut desired.strategy {+ candidates[0].binding_id = changed.candidates[0].binding.binding_id.clone();+ }+ assert!(compile(&desired, &changed).is_err());+}diff --git a/crates/application/src/compiler/test_fixtures.rs b/crates/application/src/compiler/test_fixtures.rsindex b032e43d..749d2b12 100644--- a/crates/application/src/compiler/test_fixtures.rs+++ b/crates/application/src/compiler/test_fixtures.rs@@ -541,6 +541,7 @@ fn requirements() -> CapabilityRequirementsV1 {fn limits() -> RoutingLimitsV1 {RoutingLimitsV1 {+ context_window_tokens: None,maximum_attempts: 6,request_timeout_ms: 120_000,attempt_timeout_ms: 60_000,diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rsindex 27053230..4b6e957c 100644--- a/crates/application/src/control/mod.rs+++ b/crates/application/src/control/mod.rs@@ -490,6 +490,13 @@ pub trait ComputeManagementControlPort: Send + Sync {}pub trait RoutingFactsPort: Send + Sync {+ fn claude_client_capability_preview(+ &self,+ _plan: &hiroute_domain::CompiledAgentPlanV1,+ ) -> Result<hiroute_application_api::ClaudeClientCapabilityPreviewV1, ControlReadError> {+ Err(ControlReadError::Unavailable)+ }+fn codex_client_capability_preview(&self,_plan: &hiroute_domain::CompiledAgentPlanV1,diff --git a/crates/application/src/control_plane/agent_settings.rs b/crates/application/src/control_plane/agent_settings.rsindex 3df4e275..f5e29bfc 100644--- a/crates/application/src/control_plane/agent_settings.rs+++ b/crates/application/src/control_plane/agent_settings.rs@@ -86,6 +86,10 @@ pub(crate) fn preview(}(hiroute_application_api::AgentFacetIntent::Keep, _) => json!({"action":"keep"}),};+ if !preview.context_windows.is_empty() {+ result["model_effect"]["context_windows"] = json!(preview.context_windows);+ result["model_effect"]["claude_context_window"] = json!(preview.claude_context_window);+ }succeeded(result, request.request_id)}diff --git a/crates/cli/src/managed_launch.rs b/crates/cli/src/managed_launch.rsindex 7726b179..b6caea88 100644--- a/crates/cli/src/managed_launch.rs+++ b/crates/cli/src/managed_launch.rs@@ -81,7 +81,7 @@ pub(crate) fn parse_invocation(AgentGrantRawRequestV1::new(&connection_id).map_err(|_| ManagedLaunchFailure::InvalidArguments)?;- let profile = ManagedLaunchProfileV1::claude_code_2_1_231();+ let profile = ManagedLaunchProfileV1::claude_code();let mut child_arguments = Vec::new();let mut user_settings = json!({});let mut rest = &arguments[index..];diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rsindex 54dd5c73..1fbfda90 100644--- a/crates/daemon/src/control/runtime/agent_connection.rs+++ b/crates/daemon/src/control/runtime/agent_connection.rs@@ -35,7 +35,7 @@ struct ActiveJoinV1 {impl LocalControlAdapter {fn active_join(&self, connection_id: &str) -> Result<ActiveJoinV1, ControlReadError> {// The scanner is deliberately invoked for every join. A descriptor or raw-token request- // never inherits a prior Preview's executable, version, or auth-precedence observation.+ // never inherits a prior Preview's executable or auth-precedence observation.let (connection, operation) = self.latest_connection_operation(connection_id)?;let discovery = self.exact_discovery(&connection.connection.agent_id,@@ -47,14 +47,16 @@ impl LocalControlAdapter {};match connection.connection.activation_mode {AgentActivationModeV1::ManagedLaunch => {- if installation.observation_digest != connection.observation_digest {+ if installation.observation_digest != connection.observation_digest+ && !self.scanner.matches_legacy_claude_observation(+ &connection.installed_version,+ &connection.observation_digest,+ )+ {return Err(ControlReadError::Denied);}let preflight = discovery.managed_launch.ok_or(ControlReadError::Denied)?;- if !preflight.is_launchable()- || preflight.exact_version != connection.installed_version- || preflight.executable.is_empty()- {+ if !preflight.is_launchable() || preflight.executable.is_empty() {return Err(ControlReadError::Denied);}}@@ -254,15 +256,12 @@ impl LocalControlAdapter {.discovered_credential.as_ref().is_some_and(|descriptor| self.scanner.is_claude_user_credential(descriptor));- let activation_mode = if installation- .profile- .supports_managed_launch(&installation.version)- && !persistent_claude_source- {- AgentActivationModeV1::ManagedLaunch- } else {- AgentActivationModeV1::ManagedConfiguration- };+ let activation_mode =+ if installation.profile.supports_managed_launch() && !persistent_claude_source {+ AgentActivationModeV1::ManagedLaunch+ } else {+ AgentActivationModeV1::ManagedConfiguration+ };let current_config = AgentConfigDocumentV1 {fields: installation.effective_config@@ -274,9 +273,6 @@ impl LocalControlAdapter {let mut blockers = Vec::new();if activation_mode == AgentActivationModeV1::ManagedLaunch {let preflight = discovery.managed_launch.ok_or(ControlReadError::Corrupt)?;- if preflight.exact_version != installation.version {- return Err(ControlReadError::Corrupt);- }warnings.extend(preflight.warnings.iter().map(|warning| WarningV1 {code: warning.code.clone(),details_schema: "hiroute.managed-launch-warning/v1".to_owned(),@@ -521,7 +517,7 @@ impl AgentConnectionControlPort for LocalControlAdapter {return Err(ControlReadError::Denied);}let executable = expected_snapshot.executable.as_str();- let descriptor = ManagedClaudeLaunchDescriptorV2::trusted(+ let mut descriptor = ManagedClaudeLaunchDescriptorV2::trusted(request.connection_id.clone(),"claude-messages-v1",executable,@@ -533,6 +529,10 @@ impl AgentConnectionControlPort for LocalControlAdapter {runtime.trusted_hiroute_executable,).map_err(|_| ControlReadError::Corrupt)?;+ descriptor.context_window_tokens = expected_snapshot.context_window_tokens;+ descriptor+ .validate()+ .map_err(|_| ControlReadError::Corrupt)?;Ok(descriptor)}}@@ -737,10 +737,7 @@ mod tests {let observed = adapter.exact_discovery(&spec.agent_id, &spec.profile_id, &spec.installed_version).unwrap();- assert_eq!(- observed.managed_launch.as_ref().unwrap().exact_version,- "2.1.231"- );+ assert!(observed.managed_launch.as_ref().unwrap().is_launchable());let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(spec.agent_id.clone(),spec.profile_id.clone(),@@ -1058,8 +1055,8 @@ mod tests {.require_action(hiroute_domain::AgentAction::ConfigureModel).is_err());- // An installation that drifted off the verified managed-launch version keeps its- // grant frozen out of the active join: neither launch nor raw resolution recovers.+ // Replacing the executable invalidates its identity proof, independently of the+ // diagnostic version printed by that executable.assert!(adapter.resolve_active_agent_grant(&connection_id).is_err());}}diff --git a/crates/daemon/src/control/runtime/routing.rs b/crates/daemon/src/control/runtime/routing.rsindex 22e9f425..f343ca5a 100644--- a/crates/daemon/src/control/runtime/routing.rs+++ b/crates/daemon/src/control/runtime/routing.rs@@ -15,6 +15,13 @@ use hiroute_domain::{use super::LocalControlAdapter;impl RoutingFactsPort for LocalControlAdapter {+ fn claude_client_capability_preview(+ &self,+ plan: &hiroute_domain::CompiledAgentPlanV1,+ ) -> Result<hiroute_application_api::ClaudeClientCapabilityPreviewV1, ControlReadError> {+ Ok(hiroute_integrations::agents::claude_plan_capability_preview(plan))+ }+fn codex_client_capability_preview(&self,plan: &hiroute_domain::CompiledAgentPlanV1,diff --git a/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs b/crates/daemon/src/control/runtime/settings_entry_facets_tests.rsindex 3c6589d9..7766eaa4 100644--- a/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs+++ b/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs@@ -141,17 +141,15 @@ fn v2_settings_dispatch_claude_configures_and_formally_restores_owned_user_file("ANTHROPIC_BASE_URL": "https://open.bigmodel.cn/api/anthropic","ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-5.3[1m]","ANTHROPIC_AUTH_TOKEN": "fixture-user-token",+ "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "500000",+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "900000","UNRELATED": "keep-me"}});fs::write(&settings, serde_json::to_vec_pretty(&original).unwrap()).unwrap();fs::set_permissions(&settings, fs::Permissions::from_mode(0o600)).unwrap();let executable = root.path().join("claude-fixture");- fs::write(- &executable,- b"#!/bin/sh\nprintf '2.1.231 (Claude Code)\\n'\n",- )- .unwrap();+ fs::write(&executable, b"#!/bin/sh\nprintf '2.1.0 (Claude Code)\\n'\n").unwrap();fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();let mut layout = AgentFilesystemLayoutV1::from_process(&home, root.path());@@ -278,15 +276,34 @@ fn v2_settings_dispatch_claude_configures_and_formally_restores_owned_user_file(.unwrap().iter().any(|agent| {- agent["agent_id"] == "agent_claude_default" && agent["supported"] == false+ agent["agent_id"] == "agent_claude_default" && agent["supported"] == true}));- let settings_preview = ordinary.dispatch_wire(request(- "PreviewAgentConnectionChange",- json!({"spec":spec}),- None,- ));- assert!(settings_preview.error.is_none(), "{settings_preview:?}");+ // Version diagnostics cannot add blockers to Plan-window configuration.+ for script in [+ "#!/bin/sh\nexit 9\n",+ "#!/bin/sh\nprintf 'unknown client version\\n'\n",+ "#!/bin/sh\nprintf '2.1.0 (Claude Code)\\n'\n",+ ] {+ fs::write(&executable, script).unwrap();+ let settings_preview = ordinary.dispatch_wire(request(+ "PreviewAgentConnectionChange",+ json!({"spec":spec}),+ None,+ ));+ assert!(settings_preview.error.is_none(), "{settings_preview:?}");+ let settings_preview = settings_preview.data.unwrap();+ assert_eq!(settings_preview["blockers"], unproven["blockers"]);+ assert_eq!(+ settings_preview["model_effect"]["claude_context_window"],+ unproven["model_effect"]["claude_context_window"]+ );+ assert!(+ settings_preview["model_effect"]["claude_context_window"]+ .as_u64()+ .is_some()+ );+ }fs::write(&executable, original_executable).unwrap();let service = LocalControlDaemon::new(ApplicationService::new(@@ -400,6 +417,18 @@ fn v2_settings_dispatch_claude_configures_and_formally_restores_owned_user_file("http://127.0.0.1:5837");assert_eq!(launch_descriptor["grant_generation"], 1);+ let window = launch_descriptor["context_window_tokens"]+ .as_u64()+ .expect("Claude launch carries plan window");+ assert!((100_000..=272_000).contains(&window));+ assert_eq!(+ native["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],+ window.to_string()+ );+ assert_eq!(+ native["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],+ window.to_string()+ );assert_eq!(launch_descriptor["presets"],json!({"opus":native["env"]["ANTHROPIC_DEFAULT_OPUS_MODEL"],diff --git a/crates/daemon/src/control/runtime/settings_facts.rs b/crates/daemon/src/control/runtime/settings_facts.rsindex aa8214fa..bba42d62 100644--- a/crates/daemon/src/control/runtime/settings_facts.rs+++ b/crates/daemon/src/control/runtime/settings_facts.rs@@ -763,7 +763,37 @@ impl LocalControlAdapter {== hiroute_domain::CollaborationSkillFileOwnership::BorrowedIdentical&& record.contexts.contains(&spec.context_id)});+ let codex_context_override = class == SettingsAgentClass::Codex+ && matches!(&spec.model, AgentFacetIntent::Configure { settings } if !settings.allowed_plan_ids().is_empty())+ && hiroute_integrations::codex_has_context_override(+ &hiroute_integrations::CodexConfigurationScope::user_file(+ self.scanner.codex_user_config_target(),+ ),+ )+ .map_err(|_| ControlReadError::Unavailable)?;+ let claude_plan_capability_unavailable = if let (+ SettingsAgentClass::Claude,+ AgentFacetIntent::Configure { settings },+ Some(publication),+ ) = (class, &spec.model, active.as_ref())+ {+ settings.allowed_plan_ids().iter().any(|id| publication.plans.iter().find(|plan| plan.agent_plan_id() == id).is_none_or(|plan| {+ let Ok(plan) = plan.clone().into_current() else { return true; };+ matches!(hiroute_integrations::agents::claude_plan_capability_preview(&plan), hiroute_application_api::ClaudeClientCapabilityPreviewV1::Unavailable { reason } if reason != "context_window_below_minimum")+ }))+ } else {+ false+ };+ let claude_context_override = class == SettingsAgentClass::Claude+ && matches!(&spec.model, AgentFacetIntent::Configure { settings } if !settings.allowed_plan_ids().is_empty())+ && self+ .scanner+ .claude_context_override()+ .map_err(|_| ControlReadError::Unavailable)?;let dependency_digest = CanonicalDigest::of(&serde_json::json!({+ "claude_context_override": claude_context_override,+ "claude_plan_capability_unavailable": claude_plan_capability_unavailable,+ "codex_context_override": codex_context_override,"context":spec.context_id,"agent":class.context_segment(),"observation":installation.observation_digest,"claude_executable": if class == SettingsAgentClass::Claude { claude_executable.as_deref() } else { None },"capabilities":semantic_evidence,"content":expected_content,"fingerprint":before_fingerprint,@@ -844,6 +874,9 @@ impl LocalControlAdapter {template,},facts: AgentSettingsFacts {+ codex_context_override,+ claude_context_override,+ claude_plan_capability_unavailable,context_id: spec.context_id.clone(),dependency_digest,capabilities,diff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rsindex 103c0824..372c6ffb 100644--- a/crates/daemon/src/control/runtime/settings_status.rs+++ b/crates/daemon/src/control/runtime/settings_status.rs@@ -183,12 +183,24 @@ impl LocalControlAdapter {let (active_grant, configured_join) = match action {ModelAction::Configure => {let file_applied = if class == SettingsAgentClass::Claude {- hiroute_integrations::claude_native_configuration_is_applied(- &self.artifacts,- &operation.operation_id,- intent,- )- .map_err(super::map_port)?+ let policy =+ hiroute_application::agent_connection::decode_settings_claude_model_file(+ intent,+ )+ .map_err(super::map_port)?;+ let window_owned = matches!(policy.change, hiroute_application::agent_connection::ClaudeModelFileAction::Configure { snapshot, .. } if snapshot.context_window_tokens.is_some());+ let context_conflict = window_owned+ && self+ .scanner+ .claude_context_override()+ .map_err(|_| ControlReadError::Corrupt)?;+ !context_conflict+ && hiroute_integrations::claude_native_configuration_is_applied(+ &self.artifacts,+ &operation.operation_id,+ intent,+ )+ .map_err(super::map_port)?&& !self.scanner.claude_native_routing_conflict()diff --git a/crates/daemon/src/delegation/installation.rs b/crates/daemon/src/delegation/installation.rsindex ea692c84..38c5d55c 100644--- a/crates/daemon/src/delegation/installation.rs+++ b/crates/daemon/src/delegation/installation.rs@@ -350,7 +350,27 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {} else {None};+ if installation.harness == WorkerHarnessV1::ClaudeCode+ && !matches!(+ hiroute_integrations::agents::claude_plan_capability_preview(&input.compiled_plan),+ hiroute_application_api::ClaudeClientCapabilityPreviewV1::Available { .. }+ )+ {+ return Err(DelegationErrorV1::CapabilityUnavailable);+ }CandidateWorkerProfile::build(ProfileInput {+ claude_context_window: if installation.harness == WorkerHarnessV1::ClaudeCode {+ Some(+ input+ .compiled_plan+ .body+ .materialized+ .context_window_tokens()+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?,+ )+ } else {+ None+ },harness: installation.harness,adapter: &installation.adapter,harness_binary: &installation.harness_binary,diff --git a/crates/daemon/src/delegation/installation/availability.rs b/crates/daemon/src/delegation/installation/availability.rsindex 3cbf141f..1475c21d 100644--- a/crates/daemon/src/delegation/installation/availability.rs+++ b/crates/daemon/src/delegation/installation/availability.rs@@ -155,6 +155,47 @@ mod tests {WorkerExecutorAvailabilityRegistry::new(Arc::new(StaticSelections(configurations)))}+ #[test]+ #[cfg(unix)]+ fn worker_installation_accepts_every_diagnostic_version_without_running_it() {+ use std::os::unix::fs::PermissionsExt;+ let root = tempfile::tempdir().unwrap();+ let binary = root.path().join("worker");+ let marker = root.path().join("version-was-run");+ for harness in [WorkerHarnessV1::CodexCli, WorkerHarnessV1::ClaudeCode] {+ for output in ["0.0.1", "99.1.2", "", "not a version"] {+ fs::write(+ &binary,+ format!(+ "#!/bin/sh\ntouch '{}'\nprintf '%s' '{}'\n",+ marker.display(),+ output+ ),+ )+ .unwrap();+ fs::set_permissions(&binary, fs::Permissions::from_mode(0o700)).unwrap();+ let config = WorkerInstallationConfig {+ harness,+ adapter: binary.clone(),+ harness_binary: binary.clone(),+ node_binary: None,+ };+ assert!(check_installation(&config).is_ok());+ let snapshot = registry(vec![config]).snapshot();+ assert_eq!(+ snapshot+ .executors+ .iter()+ .find(|item| item.harness == harness)+ .unwrap()+ .state,+ State::Ready+ );+ assert!(!marker.exists());+ }+ }+ }+#[test]fn installed_is_launchable_not_behavior_verified_and_contents_are_not_pinned() {let root = tempfile::tempdir().unwrap();diff --git a/crates/daemon/src/delegation/installation/installation_probe.rs b/crates/daemon/src/delegation/installation/installation_probe.rsindex 9a7a618a..4808628b 100644--- a/crates/daemon/src/delegation/installation/installation_probe.rs+++ b/crates/daemon/src/delegation/installation/installation_probe.rs@@ -291,6 +291,7 @@ fn build_profile(};let catalog = (worker == WorkerHarnessV1::CodexCli).then(|| test_codex_catalog(PROBE_MODEL));CandidateWorkerProfile::build(ProfileInput {+ claude_context_window: None,harness: worker,adapter,harness_binary: harness,diff --git a/crates/daemon/src/delegation/lifecycle/tests.rs b/crates/daemon/src/delegation/lifecycle/tests.rsindex e863fc3c..ee437aef 100644--- a/crates/daemon/src/delegation/lifecycle/tests.rs+++ b/crates/daemon/src/delegation/lifecycle/tests.rs@@ -211,6 +211,7 @@ fn inputs() -> (WorkerLaunchRequest, AcpRunInput, tempfile::TempDir) {delegation_depth: 1,};let profile = CandidateWorkerProfile::build(ProfileInput {+ claude_context_window: None,harness: WorkerHarnessV1::CodexCli,adapter: &adapter,harness_binary: &harness,diff --git a/crates/daemon/src/delegation/profile/mod.rs b/crates/daemon/src/delegation/profile/mod.rsindex 7b069f37..246cfbee 100644--- a/crates/daemon/src/delegation/profile/mod.rs+++ b/crates/daemon/src/delegation/profile/mod.rs@@ -19,6 +19,7 @@ pub(crate) use materials::native_history;pub use materials::{RunMaterialFile, RunMaterials, SessionRootUse, TaskSessionRoot};pub struct ProfileInput<'a> {+ pub claude_context_window: Option<u64>,pub harness: WorkerHarnessV1,pub adapter: &'a Path,pub harness_binary: &'a Path,@@ -192,6 +193,13 @@ impl CandidateWorkerProfile {env.insert("HIROUTE_RUN_TOKEN".into(), Zeroizing::new(token.to_owned()));}WorkerHarnessV1::ClaudeCode => {+ if let Some(window) = input.claude_context_window {+ let values = hiroute_domain::claude_context_environment(window)+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;+ for (key, value) in values {+ env.insert(key, Zeroizing::new(value));+ }+ }env.insert("CLAUDE_CODE_EXECUTABLE".into(),Zeroizing::new(path_string(input.harness_binary)?),diff --git a/crates/daemon/src/delegation/profile/tests.rs b/crates/daemon/src/delegation/profile/tests.rsindex 45de016e..d57bfdd5 100644--- a/crates/daemon/src/delegation/profile/tests.rs+++ b/crates/daemon/src/delegation/profile/tests.rs@@ -90,6 +90,7 @@ fn try_request_at_with_catalog(revoked: false,};CandidateWorkerProfile::build(ProfileInput {+ claude_context_window: Some(272_000),harness,adapter: Path::new("/trusted/adapter"),harness_binary: Path::new("/trusted/harness"),@@ -250,6 +251,14 @@ fn managed_codex_profile_routes_only_through_run_env_without_embedding_secret_infn managed_claude_profile_disables_ambient_settings_and_native_delegation() {let profile = request(WorkerHarnessV1::ClaudeCode, "run-secret-b");assert_eq!(profile.env["ANTHROPIC_AUTH_TOKEN"].as_str(), "run-secret-b");+ assert_eq!(+ profile.env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"].as_str(),+ "272000"+ );+ assert_eq!(+ profile.env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"].as_str(),+ "272000"+ );assert_eq!(profile.env["ANTHROPIC_BASE_URL"].as_str(),"http://127.0.0.1:44123"diff --git a/crates/daemon/tests/local_worker_support/mod.rs b/crates/daemon/tests/local_worker_support/mod.rsindex 54196b4c..eacfd5c0 100644--- a/crates/daemon/tests/local_worker_support/mod.rs+++ b/crates/daemon/tests/local_worker_support/mod.rs@@ -48,6 +48,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 {+ claude_context_window: None,harness: WorkerHarnessV1::CodexCli,adapter: &binary,harness_binary: &binary,diff --git a/crates/daemon/tests/support/model_connections_product.py b/crates/daemon/tests/support/model_connections_product.pyindex e8971c28..268daccd 100644--- a/crates/daemon/tests/support/model_connections_product.py+++ b/crates/daemon/tests/support/model_connections_product.py@@ -153,7 +153,8 @@ def declared(value):def save_native_source(product, upstream, token=None, unknown=False,- protocol='responses', upstream_model_id=MODEL, variant=''):+ protocol='responses', upstream_model_id=MODEL, variant='',+ context_tokens=32768):status = control(product, 'GetClientServiceStatus', {})['data']suffix = ('-unknown' if unknown else '') + ('-' + variant if variant else '')candidate_ref = 'candidate/native/product' + suffix@@ -196,7 +197,7 @@ def save_native_source(product, upstream, token=None, unknown=False,'tool': declared(True),'vision': declared(False),'streaming': declared(True),- 'context_tokens': declared(32768),+ 'context_tokens': declared(context_tokens),'max_output_tokens': declared(4096),'native_reasoning': declared({'kind': 'fixed', 'profile': 'provider-default'}),diff --git a/crates/daemon/tests/support/plan_content_process.py b/crates/daemon/tests/support/plan_content_process.pyindex 0ac86487..08f700fc 100644--- a/crates/daemon/tests/support/plan_content_process.py+++ b/crates/daemon/tests/support/plan_content_process.py@@ -34,17 +34,27 @@ def scenario(repository, boundary):product.stop()product.start(boundary)editor = dict(product.editor, display_name='资料整理', purpose='Updated complete purpose',+ limits=dict(product.editor['limits'], context_window_tokens=16384),work={'harness': 'claude_code', 'protocol': 'messages'})change = {'schema': 'hiroute.plan-content-change/v2','target': {'intent': 'update', 'plan_id': product.plan_id, 'expected_head_revision': 1},'editor': editor, 'consumed_draft': None}operations_before = operation_count(product)+ if boundary is None:+ for invalid in [0, 1.5, 9223372036854775807]:+ rejected_change = json.loads(json.dumps(change))+ rejected_change['editor']['limits']['context_window_tokens'] = invalid+ code, rejected = product.cli('routing preview', {'change': rejected_change}, success=False)+ assert code != 0, rejected+ assert operation_count(product) == operations_before+ assert read_content(product) == (head, versions)preview = product.preview('routing preview', {'change': change})assert operation_count(product) == operations_before, 'Preview created an Operation'assert read_content(product) == (head, versions), 'Preview published content'assert product.catalog()[0] == catalog, 'Preview changed the installed catalog'assert preview['plan_head']['model_alias'] == product.model_aliasassert preview['plan_version']['configuration']['work'] == editor['work']+ assert preview['plan_version']['compiled']['body']['materialized']['attempt_owned']['limits']['context_window_tokens'] == 16384result, body, capability = product.apply('routing apply', 'ApplyAgentPlanChange', preview,{'change': change}, 'content-two', crash=bool(boundary))if boundary:@@ -76,7 +86,8 @@ def draft_scenario(repository):bootstrap(product)before = read_content(product)before_models = product.catalog()[0]- editor = dict(product.editor, display_name='尚未完成的草稿', requirements={+ editor = dict(product.editor, display_name='尚未完成的草稿',+ limits=dict(product.editor['limits'], context_window_tokens=32768), requirements={'tool': False, 'vision': False, 'streaming': False,'minimum_context_tokens': 0, 'minimum_output_tokens': 0})draft = {'schema': 'hiroute.plan-draft/v1', 'workspace_id': 'personal/default',diff --git a/crates/daemon/tests/support/usage_query_gateway_product.py b/crates/daemon/tests/support/usage_query_gateway_product.pyindex 20bb3ad8..2adf8655 100644--- a/crates/daemon/tests/support/usage_query_gateway_product.py+++ b/crates/daemon/tests/support/usage_query_gateway_product.py@@ -294,7 +294,9 @@ def run(repository, expected_sha=None, desktop_data_root=None):plans = {}for protocol in PROTOCOLS:saved = save_native_source(product, upstream, NATIVE_TOKEN,- protocol=protocol, variant=protocol)+ protocol=protocol, variant=protocol,+ # Claude requires at least 100K after output reservation.+ context_tokens=131072 if protocol == 'messages' else 32768)plan_id, alias = publish_plan(product, saved['binding_id'], protocol)plans[protocol] = plan_idagent = ('agent_codex_default' if protocol == 'responses'diff --git a/crates/domain/src/agents/context_window.rs b/crates/domain/src/agents/context_window.rsnew file mode 100644index 00000000..5141a1b0--- /dev/null+++ b/crates/domain/src/agents/context_window.rs@@ -0,0 +1,46 @@+//! Client-specific adaptation of a Plan's context budget.+use std::collections::BTreeMap;++pub const CLAUDE_CONTEXT_ENVIRONMENT: [&str; 2] = [+ "CLAUDE_CODE_AUTO_COMPACT_WINDOW",+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS",+];+pub const CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT: [&str; 7] = [+ "CLAUDE_CODE_AUTO_COMPACT_WINDOW",+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS",+ "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE",+ "CLAUDE_CODE_DISABLE_1M_CONTEXT",+ "CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT",+ "DISABLE_COMPACT",+ "DISABLE_AUTO_COMPACT",+];++/// Claude's documented auto-compact range is 100K..1M. Never round a small Plan up.+pub fn claude_context_window(tokens: u64) -> Option<u64> {+ (tokens >= 100_000).then_some(tokens.min(1_000_000))+}++pub fn claude_context_environment(tokens: u64) -> Option<BTreeMap<String, String>> {+ let window = claude_context_window(tokens)?.to_string();+ Some(+ CLAUDE_CONTEXT_ENVIRONMENT+ .into_iter()+ .map(|key| (key.to_owned(), window.clone()))+ .collect(),+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn claude_window_never_expands_a_small_plan() {+ assert_eq!(claude_context_window(99_999), None);+ assert_eq!(claude_context_window(100_000), Some(100_000));+ assert_eq!(claude_context_window(272_000), Some(272_000));+ assert_eq!(claude_context_window(1_050_000), Some(1_000_000));+ let env = claude_context_environment(272_000).unwrap();+ assert_eq!(env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], "272000");+ assert_eq!(env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "272000");+ }+}diff --git a/crates/domain/src/agents/managed_launch.rs b/crates/domain/src/agents/managed_launch.rsindex ffaa1e0c..9db3b2e4 100644--- a/crates/domain/src/agents/managed_launch.rs+++ b/crates/domain/src/agents/managed_launch.rs@@ -7,7 +7,6 @@ use crate::{AgentClaudePresetValuesV2, CanonicalDigest, valid_client_model_name}pub const MANAGED_CLAUDE_LAUNCH_DESCRIPTOR_SCHEMA_V2: &str ="hiroute.managed-claude-launch-descriptor/v2";-pub const CLAUDE_CODE_MANAGED_LAUNCH_VERSION_V1: &str = "2.1.231";pub const HIDDEN_AGENT_GRANT_HELPER_VERB_V1: &str = "__internal-agent-grant-v1";pub const MANAGED_CLAUDE_SETTINGS_ARGUMENT_V1: &str = "--settings";pub const MANAGED_CLAUDE_SETTING_SOURCES_ARGUMENT_V1: &str = "--setting-sources";@@ -54,18 +53,22 @@ pub enum AgentActivationModeV1 {#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]pub struct ManagedLaunchProfileV1 {- /// The exact installation version whose managed-launch capability has been verified- /// empirically; discovery refuses the managed boundary for any other version.- pub exact_version: String,+ /// Recovery-only historical label, excluded from capability validation.+ #[serde(+ default,+ rename = "exact_version",+ skip_serializing_if = "String::is_empty"+ )]+ pub legacy_exact_version: String,pub settings_argument: String,pub environment_removals: BTreeSet<String>,pub caller_forbidden_options: BTreeSet<String>,}impl ManagedLaunchProfileV1 {- pub fn claude_code_2_1_231() -> Self {+ pub fn claude_code() -> Self {Self {- exact_version: CLAUDE_CODE_MANAGED_LAUNCH_VERSION_V1.to_owned(),+ legacy_exact_version: String::new(),settings_argument: MANAGED_CLAUDE_SETTINGS_ARGUMENT_V1.to_owned(),environment_removals: MANAGED_CLAUDE_ENVIRONMENT_REMOVALS_V1.into_iter()@@ -79,7 +82,11 @@ impl ManagedLaunchProfileV1 {}pub fn validate(&self) -> Result<(), ManagedLaunchError> {- if self != &Self::claude_code_2_1_231() {+ let trusted = Self::claude_code();+ if self.settings_argument != trusted.settings_argument+ || self.environment_removals != trusted.environment_removals+ || self.caller_forbidden_options != trusted.caller_forbidden_options+ {return Err(ManagedLaunchError::UntrustedProfile);}Ok(())@@ -101,6 +108,8 @@ impl ManagedLaunchProfileV1 {#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]pub struct ManagedClaudeLaunchDescriptorV2 {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub context_window_tokens: Option<u64>,pub schema: String,pub connection_id: String,pub profile_id: String,@@ -134,6 +143,7 @@ impl ManagedClaudeLaunchDescriptorV2 {let connection_id = connection_id.into();let helper_executable = trusted_hiroute_executable.into();let value = Self {+ context_window_tokens: None,schema: MANAGED_CLAUDE_LAUNCH_DESCRIPTOR_SCHEMA_V2.to_owned(),connection_id: connection_id.clone(),profile_id: profile_id.into(),@@ -155,7 +165,10 @@ impl ManagedClaudeLaunchDescriptorV2 {}pub fn validate(&self) -> Result<(), ManagedLaunchError> {- if self.schema != MANAGED_CLAUDE_LAUNCH_DESCRIPTOR_SCHEMA_V2+ if self+ .context_window_tokens+ .is_some_and(|value| crate::claude_context_window(value) != Some(value))+ || self.schema != MANAGED_CLAUDE_LAUNCH_DESCRIPTOR_SCHEMA_V2|| self.grant_generation == 0|| !valid_connection_id(&self.connection_id)|| !valid_identifier(&self.profile_id)diff --git a/crates/domain/src/agents/mod.rs b/crates/domain/src/agents/mod.rsindex 821d67b6..2d2287d9 100644--- a/crates/domain/src/agents/mod.rs+++ b/crates/domain/src/agents/mod.rs@@ -2,6 +2,7 @@mod capability;mod collaboration;+mod context_window;mod emulator;mod managed_launch;mod model_grant;@@ -14,6 +15,7 @@ mod surface_check;pub use capability::*;pub use collaboration::*;+pub use context_window::*;pub use emulator::*;pub use managed_launch::*;pub use model_grant::*;diff --git a/crates/domain/src/agents/profile.rs b/crates/domain/src/agents/profile.rsindex 7797af5e..27b70a13 100644--- a/crates/domain/src/agents/profile.rs+++ b/crates/domain/src/agents/profile.rs@@ -152,9 +152,13 @@ pub struct AgentProfileV1 {pub profile_id: String,pub integration_profile_ref: String,pub kind: AgentKindV1,- /// Optional exact labels used by adapters with a version-bound managed-launch contract.- /// This set is not general installation admission; Codex intentionally leaves it empty.- pub exact_versions: BTreeSet<String>,+ /// Recovery-only labels from historical profiles; never used for client admission.+ #[serde(+ default,+ rename = "exact_versions",+ skip_serializing_if = "BTreeSet::is_empty"+ )]+ pub legacy_exact_versions: BTreeSet<String>,pub ingress_protocol: AgentIngressProtocolV1,pub config_precedence: Vec<ConfigLayerV1>,pub owned_config_fields: Vec<OwnedConfigFieldV1>,@@ -174,13 +178,6 @@ impl AgentProfileV1 {}validate_identifier(&self.profile_id)?;validate_identifier(&self.integration_profile_ref)?;- if self- .exact_versions- .iter()- .any(|version| !valid_exact_version(version))- {- return Err(AgentProfileError::InvalidVersionSet);- }let expected_precedence = self.kind.config_precedence();if self.config_precedence.as_slice() != expected_precedence {return Err(AgentProfileError::InvalidConfigPrecedence);@@ -212,7 +209,6 @@ impl AgentProfileV1 {if let Some(managed_launch) = &self.managed_launch&& (self.kind != AgentKindV1::ClaudeCode|| self.ingress_protocol != AgentIngressProtocolV1::Messages- || !self.exact_versions.contains(&managed_launch.exact_version)|| managed_launch.validate().is_err()){return Err(AgentProfileError::InvalidManagedLaunch);@@ -224,15 +220,10 @@ impl AgentProfileV1 {}}- /// Adapter-declared exact labels. Main-Agent actions do not infer admission from this set.- pub fn supports_exact_version(&self, version: &str) -> bool {- self.exact_versions.contains(version)- }-- pub fn supports_managed_launch(&self, version: &str) -> bool {+ pub fn supports_managed_launch(&self) -> bool {self.managed_launch.as_ref()- .is_some_and(|capability| capability.exact_version == version)+ .is_some_and(|capability| capability.validate().is_ok())}pub const fn client_protocol(&self) -> AgentIngressProtocolV1 {@@ -334,14 +325,6 @@ impl SupportedAgentInstallationV1 {}}-fn valid_exact_version(value: &str) -> bool {- !value.is_empty()- && value.len() <= 64- && value- .bytes()- .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+' | b'_'))-}-fn validate_identifier(value: &str) -> Result<(), AgentProfileError> {let valid = !value.is_empty()&& value.len() <= 256@@ -381,8 +364,6 @@ pub enum AgentProfileError {UnsupportedSchema,#[error("Agent profile identifier is invalid")]InvalidIdentifier,- #[error("Agent profile contains invalid diagnostic version labels")]- InvalidVersionSet,#[error("Agent profile config precedence is not the frozen effective order")]InvalidConfigPrecedence,#[error("Agent profile config field is invalid")]diff --git a/crates/domain/src/agents/tests.rs b/crates/domain/src/agents/tests.rsindex 664bc25d..9bd0224d 100644--- a/crates/domain/src/agents/tests.rs+++ b/crates/domain/src/agents/tests.rs@@ -11,7 +11,7 @@ fn profile(kind: AgentKindV1, protocol: AgentIngressProtocolV1) -> AgentProfileVprofile_id: format!("{}.verified.v1", kind.as_str()),integration_profile_ref: format!("integration/{}/v1", kind.as_str()),kind,- exact_versions: BTreeSet::from(["1.2.3".to_owned()]),+ legacy_exact_versions: BTreeSet::from(["1.2.3".to_owned()]),ingress_protocol: protocol,config_precedence: kind.config_precedence().to_vec(),owned_config_fields: vec![@@ -37,8 +37,6 @@ fn profile(kind: AgentKindV1, protocol: AgentIngressProtocolV1) -> AgentProfileVfn agents_profiles_bind_protocol_to_exact_kind_and_version() {let codex = profile(AgentKindV1::Codex, AgentIngressProtocolV1::Responses);assert!(codex.validate().is_ok());- assert!(codex.supports_exact_version("1.2.3"));- assert!(!codex.supports_exact_version("1.2.4"));let mut invalid = codex;invalid.ingress_protocol = AgentIngressProtocolV1::Messages;@@ -76,7 +74,7 @@ fn agents_probe_has_no_caller_control_over_protocol_or_prompt() {}#[test]-fn managed_launch_profile_is_backward_compatible_and_exact_version_only() {+fn managed_launch_profile_preserves_legacy_labels_without_admission() {let legacy = profile(AgentKindV1::ClaudeCode, AgentIngressProtocolV1::Messages);let encoded = serde_json::to_value(&legacy).unwrap();assert!(encoded.get("managed_launch").is_none());@@ -84,14 +82,20 @@ fn managed_launch_profile_is_backward_compatible_and_exact_version_only() {assert_eq!(decoded.managed_launch, None);let mut managed = legacy;- managed- .exact_versions- .insert(CLAUDE_CODE_MANAGED_LAUNCH_VERSION_V1.to_owned());- managed.managed_launch = Some(ManagedLaunchProfileV1::claude_code_2_1_231());- assert!(managed.validate().is_ok());- assert!(managed.supports_managed_launch("2.1.231"));- assert!(!managed.supports_managed_launch("2.1.230"));- assert!(!managed.supports_managed_launch("2.1.232"));+ managed.managed_launch = Some(ManagedLaunchProfileV1::claude_code());+ for label in ["2.1.0", "99.1.2", "", "unparseable version"] {+ managed.legacy_exact_versions = [label.to_owned()].into();+ managed+ .managed_launch+ .as_mut()+ .unwrap()+ .legacy_exact_version = label.into();+ assert!(managed.validate().is_ok());+ assert!(managed.supports_managed_launch());+ }+ managed.managed_launch.as_mut().unwrap().settings_argument = "--untrusted".into();+ assert!(managed.validate().is_err());+ assert!(!managed.supports_managed_launch());}#[test]diff --git a/crates/domain/src/operation/agent_connection.rs b/crates/domain/src/operation/agent_connection.rsindex 70892ed0..5be27636 100644--- a/crates/domain/src/operation/agent_connection.rs+++ b/crates/domain/src/operation/agent_connection.rs@@ -495,7 +495,6 @@ impl TransactionPlanV1 {|| desired_digest("grant_digest")? != payload.connection.grant.digest|| desired_digest("publication_digest")? != payload.publication_digest|| desired_digest("config_change_digest")? != payload.config_change_digest- || installed_version.is_empty(){return Err(OperationValidationError::UnregisteredEffectPlan);}diff --git a/crates/domain/src/routing/authoring/tests.rs b/crates/domain/src/routing/authoring/tests.rsindex 71c1ddcd..5fd9af59 100644--- a/crates/domain/src/routing/authoring/tests.rs+++ b/crates/domain/src/routing/authoring/tests.rs@@ -102,3 +102,24 @@ fn draft_bounds_do_not_require_a_publishable_name_purpose_or_budget() {draft.candidates = vec![draft.candidates[0].clone(); 129];assert!(draft.validate_draft().is_err());}++#[test]+fn context_window_round_trips_without_changing_omitted_legacy_limits() {+ let mut value = editor();+ let old = serde_json::to_value(&value).unwrap();+ assert!(old["limits"].get("context_window_tokens").is_none());+ value.limits.context_window_tokens = Some(500_000);+ let saved: PlanEditorStateV2 =+ serde_json::from_value(serde_json::to_value(&value).unwrap()).unwrap();+ assert_eq!(+ saved.effective().unwrap().limits.context_window_tokens,+ Some(500_000)+ );+ value.limits.context_window_tokens = None;+ assert_eq!(serde_json::to_value(&value).unwrap(), old);+ for invalid in [serde_json::json!(-1), serde_json::json!(1.5)] {+ let mut wire = old.clone();+ wire["limits"]["context_window_tokens"] = invalid;+ assert!(serde_json::from_value::<PlanEditorStateV2>(wire).is_err());+ }+}diff --git a/crates/domain/src/routing/context_window.rs b/crates/domain/src/routing/context_window.rsnew file mode 100644index 00000000..d5a18e3e--- /dev/null+++ b/crates/domain/src/routing/context_window.rs@@ -0,0 +1,52 @@+//! Plan client context policy, independent of model capability declarations.+use super::{CompiledPlanError, DEFAULT_PLAN_CONTEXT_WINDOW_TOKENS, MaterializedAgentPlanV1};++impl MaterializedAgentPlanV1 {+ /// All active groups and their published ingress profiles must support the chosen window.+ pub fn context_window_upper_bound(&self) -> Result<u64, CompiledPlanError> {+ let mut upper = None;+ for candidate in self.attempt_owned.groups.iter().flat_map(|g| &g.candidates) {+ if candidate.protocol_profiles.is_empty() {+ return Err(CompiledPlanError::InvalidLimits);+ }+ for profile in &candidate.protocol_profiles {+ let context = &profile.capability.context;+ let input = context+ .max_input_tokens+ .exact()+ .copied()+ .ok_or(CompiledPlanError::InvalidLimits)?;+ let output = context+ .max_output_tokens+ .exact()+ .copied()+ .ok_or(CompiledPlanError::InvalidLimits)?;+ let total = context+ .max_total_tokens+ .exact()+ .copied()+ .ok_or(CompiledPlanError::InvalidLimits)?;+ let reasoning = profile.reasoning_profile_for(&candidate.exact_reasoning)?;+ let reservation = output+ .checked_add(reasoning.additional_reservation_tokens)+ .ok_or(CompiledPlanError::InvalidLimits)?;+ let window =+ total.map_or(input, |total| input.min(total.saturating_sub(reservation)));+ if window == 0 || output == 0 || window > i64::MAX as u64 {+ return Err(CompiledPlanError::InvalidLimits);+ }+ upper = Some(upper.map_or(window, |previous: u64| previous.min(window)));+ }+ }+ upper.ok_or(CompiledPlanError::InvalidLimits)+ }++ pub fn context_window_tokens(&self) -> Result<u64, CompiledPlanError> {+ let upper = self.context_window_upper_bound()?;+ match self.attempt_owned.limits.context_window_tokens {+ Some(value) if value == 0 || value > upper => Err(CompiledPlanError::InvalidLimits),+ Some(value) => Ok(value),+ None => Ok(upper.min(DEFAULT_PLAN_CONTEXT_WINDOW_TOKENS)),+ }+ }+}diff --git a/crates/domain/src/routing/materialized.rs b/crates/domain/src/routing/materialized.rsindex 5e91d3ea..e694c22f 100644--- a/crates/domain/src/routing/materialized.rs+++ b/crates/domain/src/routing/materialized.rs@@ -397,6 +397,9 @@ impl MaterializedAgentPlanV1 {}super::ordering::validate_ordering_facts(group)?;}+ if self.attempt_owned.limits.context_window_tokens.is_some() {+ self.context_window_tokens()?;+ }validate_request_groups(&self.request_owned, &groups)}diff --git a/crates/domain/src/routing/mod.rs b/crates/domain/src/routing/mod.rsindex 179c3d28..8cb4d414 100644--- a/crates/domain/src/routing/mod.rs+++ b/crates/domain/src/routing/mod.rs@@ -6,6 +6,7 @@mod authoring;mod classifier;+mod context_window;mod gateway_execution;mod materialized;mod ordering;diff --git a/crates/domain/src/routing/strategy.rs b/crates/domain/src/routing/strategy.rsindex 0e4ae021..eb364b92 100644--- a/crates/domain/src/routing/strategy.rs+++ b/crates/domain/src/routing/strategy.rs@@ -60,9 +60,14 @@ impl CapabilityRequirementsV1 {}}+pub const DEFAULT_PLAN_CONTEXT_WINDOW_TOKENS: u64 = 272_000;+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]#[serde(deny_unknown_fields)]pub struct RoutingLimitsV1 {+ /// None follows the bounded default; omission preserves historical signed digests.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub context_window_tokens: Option<u64>,pub maximum_attempts: u16,pub request_timeout_ms: u64,pub attempt_timeout_ms: u64,@@ -70,7 +75,10 @@ pub struct RoutingLimitsV1 {impl RoutingLimitsV1 {pub fn validate(&self) -> Result<(), RoutingStrategyError> {- if !(1..=64).contains(&self.maximum_attempts)+ if self+ .context_window_tokens+ .is_some_and(|value| value == 0 || value > i64::MAX as u64)+ || !(1..=64).contains(&self.maximum_attempts)|| !(1_000..=3_600_000).contains(&self.request_timeout_ms)|| !(1_000..=self.request_timeout_ms).contains(&self.attempt_timeout_ms){diff --git a/crates/integrations/src/agents/claude_capabilities.rs b/crates/integrations/src/agents/claude_capabilities.rsnew file mode 100644index 00000000..efccf98e--- /dev/null+++ b/crates/integrations/src/agents/claude_capabilities.rs@@ -0,0 +1,55 @@+//! The minimum request shape emitted by an ordinary Claude Code conversation.+use hiroute_application_api::ClaudeClientCapabilityPreviewV1;+use hiroute_domain::{CompiledAgentPlanV1, UpstreamProtocol};+use hiroute_gateway::server::{+ core_runtime::profiles::CandidateProtocolProfile, request_plan::IngressProtocol,+};++pub fn claude_plan_capability_preview(+ plan: &CompiledAgentPlanV1,+) -> ClaudeClientCapabilityPreviewV1 {+ let unavailable = |reason: &str| ClaudeClientCapabilityPreviewV1::Unavailable {+ reason: reason.into(),+ };+ if plan.validate().is_err() {+ return unavailable("invalid_compiled_plan");+ }+ let mut requirements = super::codex_catalog_plan::requirements(false);+ requirements.ingress_protocol = IngressProtocol::Messages;+ requirements.mid_conversation_instructions = false;+ for candidate in plan+ .body+ .materialized+ .attempt_owned+ .groups+ .iter()+ .flat_map(|group| &group.candidates)+ {+ let Some(profile) = candidate+ .protocol_profiles+ .iter()+ .find(|profile| profile.ingress_protocol == UpstreamProtocol::Messages)+ else {+ return unavailable("messages_protocol");+ };+ let Ok(value) = serde_json::to_value(profile) else {+ return unavailable("request_capabilities");+ };+ let Ok(profile) = serde_json::from_value::<CandidateProtocolProfile>(value) else {+ return unavailable("request_capabilities");+ };+ if profile.validate(&requirements).is_err() {+ return unavailable("request_capabilities");+ }+ }+ let Ok(plan_window) = plan.body.materialized.context_window_tokens() else {+ return unavailable("context_window");+ };+ let Some(context_window) = hiroute_domain::claude_context_window(plan_window) else {+ return unavailable("context_window_below_minimum");+ };+ ClaudeClientCapabilityPreviewV1::Available {+ context_window,+ plan_window,+ }+}diff --git a/crates/integrations/src/agents/claude_observation.rs b/crates/integrations/src/agents/claude_observation.rsindex 7cf52cf3..0b06e13e 100644--- a/crates/integrations/src/agents/claude_observation.rs+++ b/crates/integrations/src/agents/claude_observation.rs@@ -4,6 +4,14 @@ use super::*;pub(super) fn main_claude_observation(version: &str,observations: &[ObservedClaudeSettings],+) -> (AgentDiscoveryOutcomeV1, bool) {+ main_claude_observation_with_format(version, observations, false)+}++pub(super) fn main_claude_observation_with_format(+ version: &str,+ observations: &[ObservedClaudeSettings],+ legacy: bool,) -> (AgentDiscoveryOutcomeV1, bool) {let mut observation = base_observation("agent_claude_default",@@ -77,7 +85,18 @@ pub(super) fn main_claude_observation(.iter().map(|item| (&item.source_ref, &item.digest, item.revision)).collect::<Vec<_>>();- let digest = CanonicalDigest::of(&(&observation, inputs)).expect("bounded native observation");+ let digest = if legacy {+ CanonicalDigest::of(&(&observation, inputs))+ } else {+ CanonicalDigest::of(&(+ &observation.schema,+ &observation.agent_id,+ observation.kind,+ &observation.config,+ inputs,+ ))+ }+ .expect("bounded native observation");let mut outcome = resolve_agent_observation(observation);let conflict = same_layer_secret_conflict(observations)|| matches!(diff --git a/crates/integrations/src/agents/codex_catalog.rs b/crates/integrations/src/agents/codex_catalog.rsindex 26c5dd17..42edf0ca 100644--- a/crates/integrations/src/agents/codex_catalog.rs+++ b/crates/integrations/src/agents/codex_catalog.rs@@ -8,6 +8,10 @@ pub const CODEX_CATALOG_SOURCE_REVISION: &str = "be6e8eac029b183056b7e4402879f15#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]pub enum CodexCatalogError {+ #[error(+ "remove model_context_window and model_auto_compact_token_limit from the effective Codex configuration before using plan windows"+ )]+ ContextOverride,#[error("the catalog selection fields are invalid or ambiguous")]InvalidCatalog,#[error("the native default cannot be resolved")]diff --git a/crates/integrations/src/agents/codex_catalog_plan.rs b/crates/integrations/src/agents/codex_catalog_plan.rsindex 12ef747b..131bc061 100644--- a/crates/integrations/src/agents/codex_catalog_plan.rs+++ b/crates/integrations/src/agents/codex_catalog_plan.rs@@ -264,6 +264,9 @@ pub fn codex_plan_capability_preview(plan: &CompiledAgentPlanV1) -> CodexClientCif image {input_modalities.push(CodexInputModalityV1::Image);}+ let Ok(context_window) = plan.body.materialized.context_window_tokens() else {+ return unavailable(CodexCapabilityIssueKindV1::ContextWindow, None);+ };CodexClientCapabilityPreviewV1::Available {context_window,input_modalities,@@ -298,7 +301,7 @@ fn unavailable(}}-fn requirements(image: bool) -> RequestCapabilityRequirementsV1 {+pub(super) fn requirements(image: bool) -> RequestCapabilityRequirementsV1 {RequestCapabilityRequirementsV1 {ingress_protocol: IngressProtocol::Responses,text: true,diff --git a/crates/integrations/src/agents/codex_catalog_plan_tests.rs b/crates/integrations/src/agents/codex_catalog_plan_tests.rsindex 94105bb3..2e5ec6d5 100644--- a/crates/integrations/src/agents/codex_catalog_plan_tests.rs+++ b/crates/integrations/src/agents/codex_catalog_plan_tests.rs@@ -607,3 +607,138 @@ fn generic_prompt_and_test_catalog_are_exact_pinned_assets() {);assert!(include_str!("codex_generic_prompt.license").contains("Apache License"));}++#[test]+fn context_window_default_custom_and_worker_catalog_agree() {+ let mut large = plan();+ for candidate in std::sync::Arc::make_mut(&mut large.body)+ .materialized+ .attempt_owned+ .groups+ .iter_mut()+ .flat_map(|g| &mut g.candidates)+ {+ for profile in &mut candidate.protocol_profiles {+ let context = &mut profile.capability.context;+ context.max_input_tokens = GatewayCriticalFactV1::Exact(1_050_000);+ context.max_output_tokens = GatewayCriticalFactV1::Exact(128_000);+ context.max_total_tokens = GatewayCriticalFactV1::Exact(Some(1_178_000));+ }+ }+ let large = reseal(large);+ assert_eq!(+ large+ .body+ .materialized+ .context_window_upper_bound()+ .unwrap(),+ 1_050_000+ );+ for (setting, expected) in [+ (None, 272_000),+ (Some(128_000), 128_000),+ (Some(500_000), 500_000),+ (Some(1_050_000), 1_050_000),+ ] {+ let mut selected = large.clone();+ std::sync::Arc::make_mut(&mut selected.body)+ .materialized+ .attempt_owned+ .limits+ .context_window_tokens = setting;+ let selected = reseal(selected);+ let entry = plan_entry(&selected, 0).unwrap();+ assert_eq!(entry["context_window"], expected);+ assert_eq!(entry["max_context_window"], expected);+ let worker: Value =+ serde_json::from_slice(&codex_private_worker_catalog(&selected).unwrap()).unwrap();+ assert_eq!(worker["models"][0], entry);+ assert!(+ matches!(codex_plan_capability_preview(&selected), CodexClientCapabilityPreviewV1::Available { context_window, .. } if context_window == expected)+ );+ }+}++#[test]+fn context_window_overrides_block_plan_catalog_without_editing_user_files() {+ let root = tempfile::tempdir().unwrap();+ let config = root.path().join("config.toml");+ let mut scope = CodexConfigurationScope::user_file(config.clone());+ let plan = plan();+ for key in ["model_context_window", "model_auto_compact_token_limit"] {+ let content = format!("{key} = 900000\n");+ std::fs::write(&config, &content).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&config, std::fs::Permissions::from_mode(0o600)).unwrap();+ }+ assert!(matches!(+ sample_codex_hiroute_only_catalog_plan(+ &scope,+ std::slice::from_ref(&plan),+ plan.model_alias().as_str()+ ),+ Err(CodexCatalogError::ContextOverride)+ ));+ assert_eq!(std::fs::read_to_string(&config).unwrap(), content);+ std::fs::write(&config, "").unwrap();+ scope.cli_overrides.push(format!("{key}=900000"));+ assert!(matches!(+ sample_codex_hiroute_only_catalog_plan(+ &scope,+ std::slice::from_ref(&plan),+ plan.model_alias().as_str()+ ),+ Err(CodexCatalogError::ContextOverride)+ ));+ scope.cli_overrides.clear();+ }+ assert!(+ sample_codex_hiroute_only_catalog_plan(+ &scope,+ std::slice::from_ref(&plan),+ plan.model_alias().as_str()+ )+ .is_ok()+ );+}++#[test]+fn claude_capability_preview_rejects_missing_tools_and_streaming_in_any_candidate() {+ use crate::agents::claude_plan_capability_preview;+ use hiroute_application_api::ClaudeClientCapabilityPreviewV1 as Preview;+ assert!(matches!(+ claude_plan_capability_preview(&plan()),+ Preview::Available { .. }+ ));+ for missing_tools in [true, false] {+ let mut value = plan();+ let candidate = &mut std::sync::Arc::make_mut(&mut value.body)+ .materialized+ .attempt_owned+ .groups[0]+ .candidates[1];+ for profile in &mut candidate.protocol_profiles {+ if profile.ingress_protocol == UpstreamProtocol::Messages {+ if missing_tools {+ profile.capability.request.function_tools = GatewayFidelityV1::Unsupported;+ } else {+ profile.capability.native_streaming = GatewayCriticalFactV1::Exact(false);+ }+ }+ }+ assert!(+ matches!(claude_plan_capability_preview(&reseal(value)), Preview::Unavailable { reason } if reason == "request_capabilities")+ );+ }+ let mut value = plan();+ std::sync::Arc::make_mut(&mut value.body)+ .materialized+ .attempt_owned+ .limits+ .context_window_tokens = Some(99_999);+ assert!(+ matches!(claude_plan_capability_preview(&reseal(value)), Preview::Unavailable { reason } if reason == "context_window_below_minimum")+ );+}diff --git a/crates/integrations/src/agents/codex_catalog_source.rs b/crates/integrations/src/agents/codex_catalog_source.rsindex b1e7f4c1..ee546625 100644--- a/crates/integrations/src/agents/codex_catalog_source.rs+++ b/crates/integrations/src/agents/codex_catalog_source.rs@@ -305,6 +305,11 @@ pub fn sample_codex_catalog_plan(retained_models: Option<&std::collections::BTreeSet<String>>,) -> Result<CodexCatalogPlan, super::CodexCatalogError> {use super::CodexCatalogSelection;+ if !plans.is_empty()+ && super::codex_has_context_override(scope).map_err(catalog_source_error)?+ {+ return Err(super::CodexCatalogError::ContextOverride);+ }let configured = match baseline {CodexCatalogBaseline::Original(Some(path)) => {let before = sample_codex_configuration(scope).map_err(catalog_source_error)?;@@ -379,6 +384,11 @@ pub fn sample_codex_hiroute_only_catalog_plan(let bytes =serde_json::to_vec(&catalog).map_err(|_| super::CodexCatalogError::InvalidCatalog)?;let content_digest = CanonicalDigest::of_bytes(&bytes);+ if !plans.is_empty()+ && super::codex_has_context_override(scope).map_err(catalog_source_error)?+ {+ return Err(super::CodexCatalogError::ContextOverride);+ }let observed = sample_codex_configuration(scope).map_err(catalog_source_error)?;let dependency_digest = CanonicalDigest::of(&("hiroute-only-codex-catalog/v1",diff --git a/crates/integrations/src/agents/codex_layers.rs b/crates/integrations/src/agents/codex_layers.rsindex 4385f667..5688e1e2 100644--- a/crates/integrations/src/agents/codex_layers.rs+++ b/crates/integrations/src/agents/codex_layers.rs@@ -214,6 +214,13 @@ pub fn sample_codex_configuration(})}+pub fn codex_has_context_override(scope: &CodexConfigurationScope) -> Result<bool, Error> {+ let config = sample_codex_configuration(scope)?;+ Ok(["model_context_window", "model_auto_compact_token_limit"]+ .iter()+ .any(|key| config.source_document.contains_key(key)))+}+fn merge_source(target: &mut toml_edit::Table,source: &toml_edit::Table,@@ -226,7 +233,12 @@ fn merge_source(if depth == 0&& !matches!(key,- "model" | "model_provider" | "model_providers" | "model_catalog_json"+ "model"+ | "model_provider"+ | "model_providers"+ | "model_catalog_json"+ | "model_context_window"+ | "model_auto_compact_token_limit"){continue;@@ -249,6 +261,15 @@ fn collect(digest: &CanonicalDigest,output: &mut BTreeMap<String, (ConfigLayerV1, String, CanonicalDigest)>,) -> Result<(), Error> {+ for key in ["model_context_window", "model_auto_compact_token_limit"] {+ if let Some(item) = table.get(key) {+ let value = item+ .as_integer()+ .filter(|value| *value > 0)+ .ok_or(Error::InvalidConfig)?;+ output.insert(key.to_owned(), (layer, value.to_string(), digest.clone()));+ }+ }for key in ["model", "model_provider", "model_catalog_json"] {if let Some(item) = table.get(key) {let value = item.as_str().ok_or(Error::InvalidConfig)?;diff --git a/crates/integrations/src/agents/discovery.rs b/crates/integrations/src/agents/discovery.rsindex e25190dc..d5b3487a 100644--- a/crates/integrations/src/agents/discovery.rs+++ b/crates/integrations/src/agents/discovery.rs@@ -39,7 +39,7 @@ pub enum AgentReportOnlyReasonV1 {ExecutableProbeTimedOut,ExecutableProbeUnavailable,UnknownObservationSchema,- UnknownVersion,+ UnknownProfile,AmbiguousProfile,ConflictingEffectiveConfig,InvalidObservation,@@ -68,8 +68,13 @@ pub enum AgentDiscoveryOutcomeV1 {}pub fn resolve_agent_observation(observation: AgentScanObservationV1) -> AgentDiscoveryOutcomeV1 {- let observation_digest = CanonicalDigest::of(&observation)- .unwrap_or_else(|_| CanonicalDigest::of_bytes(b"invalid-agent-observation"));+ let observation_digest = CanonicalDigest::of(&(+ &observation.schema,+ &observation.agent_id,+ observation.kind,+ &observation.config,+ ))+ .unwrap_or_else(|_| CanonicalDigest::of_bytes(b"invalid-agent-observation"));let report = |reason| AgentDiscoveryOutcomeV1::ReportOnly {agent_id: observation.agent_id.clone(),kind: observation.kind,@@ -80,10 +85,7 @@ pub fn resolve_agent_observation(observation: AgentScanObservationV1) -> AgentDiif observation.schema != AGENT_SCAN_OBSERVATION_SCHEMA_V1 {return report(AgentReportOnlyReasonV1::UnknownObservationSchema);}- if !valid_agent_id(&observation.agent_id)- || observation.version.len() > 128- || observation.version.contains('\0')- {+ if !valid_agent_id(&observation.agent_id) {return report(AgentReportOnlyReasonV1::InvalidObservation);}let profiles = builtin_agent_profiles()@@ -92,7 +94,7 @@ pub fn resolve_agent_observation(observation: AgentScanObservationV1) -> AgentDi.collect::<Vec<_>>();let [profile] = profiles.as_slice() else {return report(if profiles.is_empty() {- AgentReportOnlyReasonV1::UnknownVersion+ AgentReportOnlyReasonV1::UnknownProfile} else {AgentReportOnlyReasonV1::AmbiguousProfile});diff --git a/crates/integrations/src/agents/executable.rs b/crates/integrations/src/agents/executable.rsindex 8d954872..b743ca2c 100644--- a/crates/integrations/src/agents/executable.rs+++ b/crates/integrations/src/agents/executable.rs@@ -27,7 +27,6 @@ pub(super) enum ProbeFailure {Failed,TimedOut,OutputLimit,- InvalidOutput,}pub(super) fn executable_probe(path: &Path) -> ExecutableProbe {@@ -43,16 +42,21 @@ fn probe(path: &Path, timeout: Duration) -> ExecutableProbe {let Some(canonical_path) = canonical.to_str().map(str::to_owned) else {return ExecutableProbe::Unknown(ProbeFailure::Unavailable);};- match bounded_version(&canonical, timeout) {- Ok(bytes) => match parse_version(&bytes) {- Some(version) => ExecutableProbe::Installed(ExecutableObservationV1 {- version,- canonical_path,- }),- None => ExecutableProbe::Unknown(ProbeFailure::InvalidOutput),- },- Err(reason) => ExecutableProbe::Unknown(reason),- }+ let version = match bounded_version(&canonical, timeout) {+ Ok(bytes) => parse_version(&bytes).unwrap_or_default(),+ Err(ProbeFailure::LaunchFailed(code)) => {+ return ExecutableProbe::Unknown(ProbeFailure::LaunchFailed(code));+ }+ Err(ProbeFailure::NotExecutable) => {+ return ExecutableProbe::Unknown(ProbeFailure::NotExecutable);+ }+ // The process started: version diagnostics cannot establish capability or deny admission.+ Err(_) => String::new(),+ };+ ExecutableProbe::Installed(ExecutableObservationV1 {+ version,+ canonical_path,+ })}pub(super) fn resolve(path: &Path) -> Result<Option<PathBuf>, ProbeFailure> {diff --git a/crates/integrations/src/agents/executable/tests.rs b/crates/integrations/src/agents/executable/tests.rsindex d1d4d427..09be24cd 100644--- a/crates/integrations/src/agents/executable/tests.rs+++ b/crates/integrations/src/agents/executable/tests.rs@@ -19,7 +19,7 @@ fn agent_probe_missing_and_failed_probe_are_distinct() {let path = program(dir.path(), "exit 2");assert!(matches!(probe(&path, Duration::from_secs(1)),- ExecutableProbe::Unknown(ProbeFailure::Failed)+ ExecutableProbe::Installed(ExecutableObservationV1 { version, .. }) if version.is_empty()));}@@ -47,14 +47,8 @@ fn agent_probe_timeout_kills_process_group_without_waiting_for_output_eof() {let dir = tempfile::tempdir().unwrap();let path = program(dir.path(), "sleep 30 & wait");let start = Instant::now();- match probe(&path, Duration::from_millis(80)) {- ExecutableProbe::Unknown(ProbeFailure::TimedOut) => {}- ExecutableProbe::Unknown(reason) => {- panic!("timeout probe failed before timeout: {reason:?}")- }- ExecutableProbe::Installed(_) => panic!("timeout probe unexpectedly exited successfully"),- ExecutableProbe::NotFound => panic!("timeout probe disappeared"),- }+ assert!(matches!(probe(&path, Duration::from_millis(80)),+ ExecutableProbe::Installed(ExecutableObservationV1 { version, .. }) if version.is_empty()));assert!(start.elapsed() < Duration::from_secs(2));}@@ -67,7 +61,7 @@ fn agent_probe_output_is_bounded() {);assert!(matches!(probe(&path, Duration::from_secs(1)),- ExecutableProbe::Unknown(ProbeFailure::OutputLimit)+ ExecutableProbe::Installed(ExecutableObservationV1 { version, .. }) if version.is_empty()));}diff --git a/crates/integrations/src/agents/filesystem.rs b/crates/integrations/src/agents/filesystem.rsindex c16ddc0f..2cf232e4 100644--- a/crates/integrations/src/agents/filesystem.rs+++ b/crates/integrations/src/agents/filesystem.rs@@ -8,8 +8,8 @@ use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use hiroute_domain::{- AgentConfigDocumentV1, AgentKindV1, CLAUDE_CODE_MANAGED_LAUNCH_VERSION_V1, CanonicalDigest,- ConfigLayerV1, ProtectedSecret, SupportedAgentInstallationV1,+ AgentConfigDocumentV1, AgentKindV1, CanonicalDigest, ConfigLayerV1, ProtectedSecret,+ SupportedAgentInstallationV1,};use serde::{Deserialize, Serialize};use serde_json::json;@@ -144,6 +144,7 @@ impl AgentFilesystemLayoutV1 {"ANTHROPIC_SMALL_FAST_MODEL",].into_iter()+ .chain(hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT).filter_map(|name| {std::env::var(name).ok()@@ -185,6 +186,8 @@ impl AgentFilesystemLayoutV1 {pub struct FilesystemAgentScannerV1 {pub(super) layout: AgentFilesystemLayoutV1,registry: ClaudeRegistrationIndexV1,+ legacy_recovery_version: Option<String>,+ legacy_process_format: bool,#[cfg(unix)]codex_ingress: std::sync::Arc<std::sync::Mutex<Option<super::CodexIngressEvidence>>>,#[cfg(unix)]@@ -237,6 +240,8 @@ impl FilesystemAgentScannerV1 {Self {layout,registry,+ legacy_recovery_version: None,+ legacy_process_format: false,#[cfg(unix)]codex_ingress: Default::default(),#[cfg(unix)]@@ -323,6 +328,26 @@ impl FilesystemAgentScannerV1 {}}+ /// Read-only verifier for a pre-version-neutral successful Operation. The old label is+ /// supplied by that immutable Operation, never by current client output. All physical+ /// identity, permissions, configuration and native evidence are still sampled normally.+ pub fn matches_legacy_claude_observation(+ &self,+ recorded_version: &str,+ expected: &CanonicalDigest,+ ) -> bool {+ let mut recovery = self.clone();+ recovery.legacy_recovery_version = Some(recorded_version.to_owned());+ [false, true].into_iter().any(|legacy_process_format| {+ recovery.legacy_process_format = legacy_process_format;+ recovery.scan().into_iter().any(|found| {+ matches!(found.outcome, AgentDiscoveryOutcomeV1::Supported { installation }+ if installation.profile.kind == AgentKindV1::ClaudeCode && &installation.observation_digest == expected)+ && found.managed_launch.is_some_and(|preflight| preflight.is_launchable())+ })+ })+ }+pub fn scan(&self) -> Vec<FilesystemAgentDiscoveryV1> {let mut results = vec![self.scan_codex()];match executable_probe(&self.layout.claude_executable) {@@ -548,6 +573,11 @@ impl FilesystemAgentScannerV1 {.as_ref().map(|value| value.version.clone()).unwrap_or_default();+ let version = self+ .legacy_recovery_version+ .as_ref()+ .unwrap_or(&version)+ .clone();// Settings writes bind the actual executable and target file, not the native// endpoint/model registration used by ordinary account discovery. A user may// switch an otherwise runnable Claude installation from an unknown provider.@@ -569,7 +599,12 @@ impl FilesystemAgentScannerV1 {&self.layout.process_environment,&self.layout.process_environment_presence,) {- Ok(observed) => observations.push(observed),+ Ok(mut observed) => {+ if self.legacy_process_format {+ super::filesystem_config::recover_pre_context_process_digest(&mut observed);+ }+ observations.push(observed);+ }Err(error) => {return FilesystemAgentDiscoveryV1 {outcome: configuration_failure_outcome(error.report_reason()),@@ -585,12 +620,13 @@ impl FilesystemAgentScannerV1 {let main_observations =main_observation::resolve_project_local_fields(&self.layout, &observations);let (observed_outcome, main_conflict) =- main_observation::main_claude_observation(&version, &main_observations);+ main_observation::main_claude_observation_with_format(+ &version,+ &main_observations,+ self.legacy_recovery_version.is_some(),+ );let mut outcome = executable_outcome.unwrap_or(observed_outcome);- let managed_launch = if let Some(executable) = executable- .as_ref()- .filter(|_| for_settings || version == CLAUDE_CODE_MANAGED_LAUNCH_VERSION_V1)- {+ let managed_launch = if let Some(executable) = executable.as_ref() {let profile = match &outcome {AgentDiscoveryOutcomeV1::Supported { installation } => {installation.profile.managed_launch.as_ref()@@ -609,7 +645,6 @@ impl FilesystemAgentScannerV1 {};Some(ManagedClaudeLaunchPreflightV1::from_observations(executable.canonical_path.clone(),- profile.exact_version.clone(),profile,&observations,))@@ -619,10 +654,15 @@ impl FilesystemAgentScannerV1 {if let (Some(preflight), AgentDiscoveryOutcomeV1::Supported { installation }) =(&managed_launch, &mut outcome){+ let mut preflight_value =+ serde_json::to_value(preflight).expect("serializable preflight");+ if let Some(version) = &self.legacy_recovery_version {+ preflight_value["exact_version"] = serde_json::json!(version);+ }installation.observation_digest = CanonicalDigest::of(&("hiroute.managed-launch-observation/v1",&installation.observation_digest,- preflight,+ preflight_value,)).unwrap_or_else(|_| CanonicalDigest::of_bytes(b"invalid-managed-launch-observation"));}diff --git a/crates/integrations/src/agents/filesystem/claude_settings.rs b/crates/integrations/src/agents/filesystem/claude_settings.rsindex 56006457..a60be281 100644--- a/crates/integrations/src/agents/filesystem/claude_settings.rs+++ b/crates/integrations/src/agents/filesystem/claude_settings.rs@@ -1,6 +1,20 @@use super::*;impl FilesystemAgentScannerV1 {+ pub fn claude_context_override(&self) -> Result<bool, AgentFilesystemScanError> {+ Ok(self.claude_observations()?.iter().any(|observation| {+ observation+ .settings+ .env+ .context_environment+ .keys()+ .any(|key| {+ observation.layer != ConfigLayerV1::User+ || !hiroute_domain::CLAUDE_CONTEXT_ENVIRONMENT.contains(&key.as_str())+ })+ }))+ }+/// User-file edits cannot override another active settings source or inherited process/// authentication. Report that boundary before promising ordinary-CLI routing.pub fn claude_native_routing_conflict(&self) -> Result<bool, AgentFilesystemScanError> {@@ -55,6 +69,11 @@ impl FilesystemAgentScannerV1 {.ok_or(AgentFilesystemScanError::InvalidConfig)?;let env = &user.settings.env;let mut fields = BTreeMap::new();+ for key in hiroute_domain::CLAUDE_CONTEXT_ENVIRONMENT {+ if let Some(value) = env.context_environment.get(key) {+ fields.insert(format!("env.{key}"), json!(value));+ }+ }for (path, value) in [("env.ANTHROPIC_BASE_URL", env.base_url.as_deref()),("env.ANTHROPIC_MODEL", env.model.as_deref()),diff --git a/crates/integrations/src/agents/filesystem_config.rs b/crates/integrations/src/agents/filesystem_config.rsindex 1803ff61..6fe3f12d 100644--- a/crates/integrations/src/agents/filesystem_config.rs+++ b/crates/integrations/src/agents/filesystem_config.rs@@ -172,6 +172,14 @@ impl ClaudeSource {small_fast_model: process.get("ANTHROPIC_SMALL_FAST_MODEL").map(|value| value.as_str().to_owned()),+ context_environment: hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT+ .into_iter()+ .filter_map(|key| {+ process+ .get(key)+ .map(|value| (key.to_owned(), value.as_str().to_owned()))+ })+ .collect(),present_environment_fields: process_presence.clone(),},api_key_helper_present: false,@@ -243,6 +251,14 @@ impl ClaudeSource {small_fast_model: process.get("ANTHROPIC_SMALL_FAST_MODEL").map(|value| value.as_str().to_owned()),+ context_environment: hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT+ .into_iter()+ .filter_map(|key| {+ process+ .get(key)+ .map(|value| (key.to_owned(), value.as_str().to_owned()))+ })+ .collect(),present_environment_fields: process_presence.clone(),},api_key_helper_present: false,@@ -283,6 +299,7 @@ pub(super) struct ClaudeSettingsSubset {#[derive(Clone, Default)]pub(super) struct ClaudeEnvironmentSubset {+ pub(super) context_environment: BTreeMap<String, String>,pub(super) base_url: Option<String>,pub(super) model: Option<String>,pub(super) default_opus_model: Option<String>,@@ -361,6 +378,13 @@ impl<'de> Deserialize<'de> for ClaudeEnvironmentSubset {let mut result = ClaudeEnvironmentSubset::default();while let Some(key) = map.next_key::<String>()? {match key.as_str() {+ key if hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT+ .contains(&key) =>+ {+ result+ .context_environment+ .insert(key.to_owned(), map.next_value()?);+ }"ANTHROPIC_BASE_URL" => {result.base_url = Some(map.next_value()?);result.present_environment_fields.insert(key);@@ -638,6 +662,36 @@ fn source_ref(path: &Path, layer: ConfigLayerV1) -> String {format!("claude/settings/{}", &digest.as_str()[7..39])}+/// Historical process-source hash from 9e1ddbb. Only the recovery verifier uses it;+/// never hide newly observed context settings behind an older digest format.+pub(super) fn recover_pre_context_process_digest(observed: &mut ObservedClaudeSettings) {+ if observed.layer != ConfigLayerV1::Process+ || !observed.settings.env.context_environment.is_empty()+ {+ return;+ }+ let settings = &observed.settings;+ let present = settings+ .env+ .present_environment_fields+ .iter()+ .cloned()+ .collect::<Vec<_>>()+ .join(",");+ observed.digest = CanonicalDigest::of_bytes(+ format!(+ "{}\0{}\0{}\0{}\0{}",+ settings.env.base_url.as_deref().unwrap_or(""),+ settings.env.model.as_deref().unwrap_or(""),+ settings.env.default_opus_model.as_deref().unwrap_or(""),+ present,+ settings.api_key_helper_present+ )+ .as_bytes(),+ );+ observed.revision = revision_from_digest(&observed.digest);+}+fn safe_settings_digest(settings: &ClaudeSettingsSubset) -> CanonicalDigest {let present = settings.env@@ -648,12 +702,13 @@ fn safe_settings_digest(settings: &ClaudeSettingsSubset) -> CanonicalDigest {.join(",");CanonicalDigest::of_bytes(format!(- "{}\0{}\0{}\0{}\0{}",+ "{}\0{}\0{}\0{}\0{}\0{:?}",settings.env.base_url.as_deref().unwrap_or(""),settings.env.model.as_deref().unwrap_or(""),settings.env.default_opus_model.as_deref().unwrap_or(""),present,settings.api_key_helper_present,+ settings.env.context_environment,).as_bytes(),)diff --git a/crates/integrations/src/agents/filesystem_config/native.rs b/crates/integrations/src/agents/filesystem_config/native.rsindex a59889d2..b6fb04f6 100644--- a/crates/integrations/src/agents/filesystem_config/native.rs+++ b/crates/integrations/src/agents/filesystem_config/native.rs@@ -1,7 +1,7 @@//! Native field rendering and ownership, shared by persistent and isolated file effects.use super::*;-const CLAUDE_MANAGED_PATHS: [&str; 8] = [+const CLAUDE_MANAGED_PATHS: [&str; 10] = ["apiKeyHelper","hiroute.auth_environment","env.ANTHROPIC_BASE_URL",@@ -10,6 +10,8 @@ const CLAUDE_MANAGED_PATHS: [&str; 8] = ["env.ANTHROPIC_DEFAULT_SONNET_MODEL","env.ANTHROPIC_DEFAULT_HAIKU_MODEL","env.ANTHROPIC_SMALL_FAST_MODEL",+ "env.CLAUDE_CODE_AUTO_COMPACT_WINDOW",+ "env.CLAUDE_CODE_MAX_CONTEXT_TOKENS",];/// Renders one exact semantic change into Claude Code's user settings while preserving every@@ -86,13 +88,36 @@ pub(in crate::agents) fn rebase_claude_change_bytes(if !claude_change_bytes_are_applied(current, previous_change)? {return Err(AgentFilesystemScanError::SourceChanged);}- let rendered = render_claude_change_bytes(current, change)?;+ // Check the accepted before-values before constructing the release transition.+ render_claude_change_bytes(current, change)?;let base = claude_document_from_bytes(base)?;+ let desired_change: BTreeMap<_, _> =+ change+ .fields+ .iter()+ .map(|field| {+ let after = if field.after.is_none()+ && field.path.strip_prefix("env.").is_some_and(|key| {+ hiroute_domain::CLAUDE_CONTEXT_ENVIRONMENT.contains(&key)+ }) {+ base.fields.get(&field.path).cloned()+ } else {+ field.after.clone()+ };+ (field.path.clone(), after)+ })+ .collect();+ let adjusted = AgentConfigChangeV1::preview(+ &claude_document_from_bytes(current)?,+ desired_change.clone(),+ )+ .map_err(|_| AgentFilesystemScanError::InvalidDescriptor)?;+ let rendered = render_claude_change_bytes(current, &adjusted)?;let desired = CLAUDE_MANAGED_PATHS.into_iter().map(|path| {- let after = if let Some(field) = change.fields.iter().find(|field| field.path == path) {- field.after.clone()+ let after = if let Some(after) = desired_change.get(path) {+ after.clone()} else if let Some(field) = previous_change.fields.iter()@@ -419,19 +444,11 @@ fn validate_change(change: &AgentConfigChangeV1) -> Result<(), AgentFilesystemScchange.validate().map_err(|_| AgentFilesystemScanError::InvalidDescriptor)?;- if change.fields.iter().any(|field| {- !matches!(- field.path.as_str(),- "apiKeyHelper"- | "hiroute.auth_environment"- | "env.ANTHROPIC_BASE_URL"- | "env.ANTHROPIC_MODEL"- | "env.ANTHROPIC_DEFAULT_OPUS_MODEL"- | "env.ANTHROPIC_DEFAULT_SONNET_MODEL"- | "env.ANTHROPIC_DEFAULT_HAIKU_MODEL"- | "env.ANTHROPIC_SMALL_FAST_MODEL"- )- }) {+ if change+ .fields+ .iter()+ .any(|field| !CLAUDE_MANAGED_PATHS.contains(&field.path.as_str()))+ {return Err(AgentFilesystemScanError::InvalidDescriptor);}Ok(())diff --git a/crates/integrations/src/agents/filesystem_layer_tests.rs b/crates/integrations/src/agents/filesystem_layer_tests.rsindex d9be497e..1fd2f36c 100644--- a/crates/integrations/src/agents/filesystem_layer_tests.rs+++ b/crates/integrations/src/agents/filesystem_layer_tests.rs@@ -1,7 +1,7 @@use super::*;#[test]-fn main_claude_project_layer_is_not_erased_by_worker_version_support() {+fn main_claude_project_layer_and_managed_launch_are_version_independent() {for version in [CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1, "9.9.999"] {let directory = tempfile::tempdir().unwrap();let layout = layout_with_claude_version(directory.path(), version);@@ -29,10 +29,7 @@ fn main_claude_project_layer_is_not_erased_by_worker_version_support() {.require_action(hiroute_domain::AgentAction::RestoreModel).is_ok());- assert_eq!(- found.managed_launch.is_some(),- version == CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1- );+ assert!(found.managed_launch.is_some());}}diff --git a/crates/integrations/src/agents/filesystem_tests.rs b/crates/integrations/src/agents/filesystem_tests.rsindex c3f267d0..b9c705d8 100644--- a/crates/integrations/src/agents/filesystem_tests.rs+++ b/crates/integrations/src/agents/filesystem_tests.rs@@ -89,7 +89,7 @@ fn layout_with_claude_version(root: &Path, claude_version: &str) -> AgentFilesys}#[test]-fn filesystem_scanner_exact_versions_registers_claude_and_never_serializes_token() {+fn filesystem_scanner_registers_claude_and_never_serializes_token() {let directory = tempfile::tempdir().unwrap();let layout = layout(directory.path());write_secret_settings(@@ -126,7 +126,11 @@ fn filesystem_scanner_exact_versions_registers_claude_and_never_serializes_token);let encoded = serde_json::to_string(&results).unwrap();assert!(!encoded.contains("secret-do-not-serialize"));- assert!(!encoded.contains(directory.path().to_string_lossy().as_ref()));+ // Internal launch preflight includes its executable; public discovery remains path-free.+ let public =+ serde_json::to_string(&results.iter().map(|item| &item.outcome).collect::<Vec<_>>())+ .unwrap();+ assert!(!public.contains(directory.path().to_string_lossy().as_ref()));let secret = scanner.read_discovered_secret(claude.discovered_credential.as_ref().unwrap()).unwrap();@@ -530,206 +534,6 @@ fn process_discovery_reference_is_presence_bound_and_secret_is_read_only_on_dema);}-#[test]-fn managed_2_1_231_sanitizes_inherited_env_and_keeps_compute_discovery() {- let directory = tempfile::tempdir().unwrap();- let layout =- layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1)- .with_process_value(- "ANTHROPIC_BASE_URL",- "https://open.bigmodel.cn/api/anthropic",- )- .with_process_value("ANTHROPIC_MODEL", "glm-5.3")- .with_process_value("ANTHROPIC_AUTH_TOKEN", "process-secret")- .with_process_value("CLAUDE_CODE_USE_BEDROCK", "1");- let scanner = FilesystemAgentScannerV1::new(layout, registry());- let result = scanner- .scan()- .into_iter()- .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")- .unwrap();-- assert!(matches!(- result.outcome,- AgentDiscoveryOutcomeV1::Supported { .. }- ));- assert!(result.claude_configuration.is_some());- assert!(result.discovered_credential.is_some());- let preflight = result.managed_launch.as_ref().unwrap();- assert!(preflight.is_launchable());- assert_eq!(preflight.warnings.len(), 1);- assert_eq!(preflight.warnings[0].code, MANAGED_LAUNCH_ENV_SANITIZED_V1);- assert_eq!(- preflight.inherited_environment_removals,- BTreeSet::from([- "ANTHROPIC_AUTH_TOKEN".to_owned(),- "ANTHROPIC_BASE_URL".to_owned(),- "ANTHROPIC_MODEL".to_owned(),- "CLAUDE_CODE_USE_BEDROCK".to_owned(),- ])- );- let encoded = serde_json::to_string(&result).unwrap();- assert!(!encoded.contains("process-secret"));-}--#[test]-fn managed_2_1_231_isolates_user_settings_and_keeps_compute_discovery() {- let directory = tempfile::tempdir().unwrap();- let layout =- layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1);- write_secret_settings(- &layout.claude_user_settings,- json!({- "apiKeyHelper": "do-not-run --secret",- "env": {- "ANTHROPIC_BASE_URL": "https://open.bigmodel.cn/api/anthropic",- "ANTHROPIC_MODEL": "claude-opus-5",- "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-5.3[1m]",- "ANTHROPIC_AUTH_TOKEN": "user-secret"- }- }),- );- let result = FilesystemAgentScannerV1::new(layout, registry())- .scan()- .into_iter()- .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")- .unwrap();-- assert!(result.claude_configuration.is_some());- assert!(result.discovered_credential.is_some());- let preflight = result.managed_launch.as_ref().unwrap();- assert!(preflight.is_launchable());- assert!(preflight.conflicts.is_empty());- let encoded = serde_json::to_string(&result).unwrap();- assert!(!encoded.contains("user-secret"));- assert!(!encoded.contains("do-not-run"));-}--#[test]-fn managed_2_1_231_blocks_auth_routing_fields_from_every_nonprocess_layer() {- let directory = tempfile::tempdir().unwrap();- let mut layout =- layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1);- let launch = directory.path().join("launch/settings.json");- let managed = directory.path().join("managed/settings.json");- layout.claude_launch_settings = Some(launch.clone());- layout.claude_managed_settings = vec![managed.clone()];- write_secret_settings(&launch, json!({"apiKeyHelper": "must-not-run"}));- write_secret_settings(- &layout.claude_project_settings[0],- json!({"env": {"ANTHROPIC_BASE_URL": "https://attacker.invalid"}}),- );- write_secret_settings(- &layout.claude_user_settings,- json!({"env": {"ANTHROPIC_MODEL": "untrusted-model"}}),- );- write_secret_settings(&managed, json!({"env": {"CLAUDE_CODE_USE_VERTEX": "1"}}));-- let result = FilesystemAgentScannerV1::new(layout, registry())- .scan()- .into_iter()- .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")- .unwrap();- let preflight = result.managed_launch.unwrap();- assert_eq!(- preflight- .conflicts- .iter()- .map(|conflict| conflict.layer)- .collect::<BTreeSet<_>>(),- BTreeSet::from([ConfigLayerV1::Launch, ConfigLayerV1::Managed])- );- assert!(- preflight- .conflicts- .iter()- .all(|conflict| conflict.code == AGENT_AUTH_PRECEDENCE_CONFLICT_V1)- );- assert!(- !serde_json::to_string(&preflight)- .unwrap()- .contains("must-not-run")- );-}--#[test]-fn managed_2_1_231_isolates_multiple_project_settings() {- let directory = tempfile::tempdir().unwrap();- let mut layout =- layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1);- let second = directory.path().join("project-2/.claude/settings.json");- layout.claude_project_settings.push(second.clone());- for (path, endpoint, token) in [- (- &layout.claude_project_settings[0],- "https://open.bigmodel.cn/api/anthropic",- "first-secret",- ),- (&second, "https://attacker.invalid", "second-secret"),- ] {- write_secret_settings(- path,- json!({"env": {- "ANTHROPIC_BASE_URL": endpoint,- "ANTHROPIC_MODEL": "glm-5.3",- "ANTHROPIC_AUTH_TOKEN": token,- }}),- );- }- let result = FilesystemAgentScannerV1::new(layout, registry())- .scan()- .into_iter()- .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")- .unwrap();-- assert!(matches!(- result.outcome,- AgentDiscoveryOutcomeV1::Supported { .. }- ));- let AgentDiscoveryOutcomeV1::Supported { installation } = &result.outcome else {- unreachable!()- };- assert!(- installation- .require_action(hiroute_domain::AgentAction::RestoreModel)- .is_err()- );- assert!(result.claude_configuration.is_none());- assert!(result.discovered_credential.is_none());- let preflight = result.managed_launch.unwrap();- assert!(preflight.is_launchable());- assert!(preflight.conflicts.is_empty());- let encoded = serde_json::to_string(&preflight).unwrap();- assert!(!encoded.contains("first-secret"));- assert!(!encoded.contains("second-secret"));-}--#[test]-fn managed_launch_is_exactly_2_1_231_only() {- for (version, supported, managed) in [- (CLAUDE_CODE_VERIFIED_VERSION_V1, true, false),- ("2.1.230", true, false),- (CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1, true, true),- ("2.1.232", true, false),- ] {- let directory = tempfile::tempdir().unwrap();- let result = FilesystemAgentScannerV1::new(- layout_with_claude_version(directory.path(), version),- registry(),- )- .scan()- .into_iter()- .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")- .unwrap();- assert_eq!(- matches!(result.outcome, AgentDiscoveryOutcomeV1::Supported { .. }),- supported,- "unexpected support state for {version}"- );- assert_eq!(result.managed_launch.is_some(), managed, "{version}");- }-}-#[cfg(unix)]#[test]fn symlink_fails_closed_but_readable_0644_config_does_not_require_hardening() {@@ -1129,3 +933,6 @@ mod source_candidate_tests;#[path = "filesystem_layer_tests.rs"]mod layer_tests;++#[path = "filesystem_tests/managed_launch.rs"]+mod managed_launch_tests;diff --git a/crates/integrations/src/agents/filesystem_tests/claude_routing.rs b/crates/integrations/src/agents/filesystem_tests/claude_routing.rsindex 23492b97..f19ef677 100644--- a/crates/integrations/src/agents/filesystem_tests/claude_routing.rs+++ b/crates/integrations/src/agents/filesystem_tests/claude_routing.rs@@ -10,11 +10,7 @@ fn claude_settings_discovery_does_not_gate_save_on_version_probe() {let ordinary = scanner.scan();assert!(ordinary.iter().any(|item| matches!(&item.outcome,- AgentDiscoveryOutcomeV1::ReportOnly {- agent_id,- reason: AgentReportOnlyReasonV1::ExecutableProbeUnavailable,- ..- } if agent_id == "agent_claude_default"+ AgentDiscoveryOutcomeV1::Supported { installation } if installation.agent_id == "agent_claude_default")));let settings = scanner.claude_settings_discovery(false);assert!(matches!(@@ -219,3 +215,180 @@ fn claude_managed_helper_detects_auth_added_after_a_token_free_save() {);}}++#[test]+fn claude_context_policy_detects_overrides_and_restores_owned_values() {+ let directory = tempfile::tempdir().unwrap();+ let layout = layout(directory.path());+ let original = json!({"env": {"CLAUDE_CODE_AUTO_COMPACT_WINDOW":"500000", "CLAUDE_CODE_MAX_CONTEXT_TOKENS":"900000", "UNRELATED":"keep"}});+ write_secret_settings(&layout.claude_user_settings, original.clone());+ let scanner = FilesystemAgentScannerV1::new(layout.clone(), registry());+ assert!(!scanner.claude_context_override().unwrap());+ let before = scanner.claude_user_config_document().unwrap();+ let desired = hiroute_domain::claude_context_environment(272_000)+ .unwrap()+ .into_iter()+ .map(|(key, value)| (format!("env.{key}"), Some(json!(value))))+ .collect();+ let change = hiroute_domain::AgentConfigChangeV1::preview(&before, desired).unwrap();+ let rendered = scanner.render_claude_user_config_change(&change).unwrap();+ let parsed: serde_json::Value = serde_json::from_slice(&rendered).unwrap();+ assert_eq!(parsed["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], "272000");+ assert_eq!(parsed["env"]["UNRELATED"], "keep");+ let restored = crate::agents::filesystem_config::restore_claude_change_bytes(+ &rendered,+ &serde_json::to_vec(&original).unwrap(),+ &change,+ )+ .unwrap();+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&restored).unwrap(),+ original+ );+ for key in hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT {+ let scanner =+ FilesystemAgentScannerV1::new(layout.clone().with_process_value(key, "1"), registry());+ assert!(scanner.claude_context_override().unwrap(), "{key}");+ }+ write_secret_settings(+ &directory.path().join("project/.claude/settings.json"),+ json!({"env":{"DISABLE_COMPACT":"1"}}),+ );+ assert!(scanner.claude_context_override().unwrap());+}++#[test]+fn claude_context_policy_release_rebases_to_original_preferences() {+ use crate::agents::filesystem_config::{+ rebase_claude_change_bytes, render_claude_change_bytes,+ };+ let directory = tempfile::tempdir().unwrap();+ let layout = layout(directory.path());+ let original = json!({"env":{"CLAUDE_CODE_AUTO_COMPACT_WINDOW":"500000"}});+ write_secret_settings(&layout.claude_user_settings, original.clone());+ let scanner = FilesystemAgentScannerV1::new(layout.clone(), registry());+ let before = scanner.claude_user_config_document().unwrap();+ let first = hiroute_domain::AgentConfigChangeV1::preview(+ &before,+ hiroute_domain::claude_context_environment(272_000)+ .unwrap()+ .into_iter()+ .map(|(key, value)| (format!("env.{key}"), Some(json!(value))))+ .collect(),+ )+ .unwrap();+ let original_bytes = serde_json::to_vec(&original).unwrap();+ let current = render_claude_change_bytes(&original_bytes, &first).unwrap();+ fs::write(&layout.claude_user_settings, current.as_slice()).unwrap();+ let release = hiroute_domain::AgentConfigChangeV1::preview(+ &scanner.claude_user_config_document().unwrap(),+ hiroute_domain::CLAUDE_CONTEXT_ENVIRONMENT+ .into_iter()+ .map(|key| (format!("env.{key}"), None))+ .collect(),+ )+ .unwrap();+ let (rendered, rebased) =+ rebase_claude_change_bytes(¤t, &original_bytes, &first, &release).unwrap();+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(&rendered).unwrap(),+ original+ );+ rebased.validate().unwrap();+}++#[test]+fn claude_version_diagnostics_do_not_change_admission_or_dependency_identity() {+ let root = tempfile::tempdir().unwrap();+ let layout = layout(root.path());+ let diagnostic = root.path().join("diagnostic");+ // Change output without changing the executable inode, content or permissions.+ fs::write(+ &layout.claude_executable,+ format!("#!/bin/sh\ncat '{}'\n", diagnostic.display()),+ )+ .unwrap();+ let scanner = FilesystemAgentScannerV1::new(layout.clone(), registry());+ let mut digest = None;+ let mut legacy = scanner.clone();+ legacy.legacy_recovery_version = Some("2.1.231".into());+ legacy.legacy_process_format = true;+ fs::write(&diagnostic, "2.1.231").unwrap();+ let legacy_digest = legacy+ .scan()+ .into_iter()+ .find_map(|found| match found.outcome {+ AgentDiscoveryOutcomeV1::Supported { installation }+ if installation.profile.kind == AgentKindV1::ClaudeCode =>+ {+ Some(installation.observation_digest)+ }+ _ => None,+ })+ .unwrap();+ for label in [+ Some("0.0.1"),+ Some("99.1.2"),+ Some(""),+ Some("not a version"),+ None,+ ] {+ if let Some(label) = label {+ fs::write(&diagnostic, label).unwrap();+ } else {+ fs::remove_file(&diagnostic).unwrap();+ }+ let found = scanner+ .scan()+ .into_iter()+ .find(|item| outcome_agent_id(&item.outcome) == "agent_claude_default")+ .unwrap();+ let AgentDiscoveryOutcomeV1::Supported { installation } = found.outcome else {+ panic!("diagnostic output cannot deny admission");+ };+ assert!(found.managed_launch.unwrap().is_launchable());+ assert!(scanner.matches_legacy_claude_observation("2.1.231", &legacy_digest));+ if let Some(expected) = &digest {+ assert_eq!(&installation.observation_digest, expected);+ } else {+ digest = Some(installation.observation_digest);+ }+ }+ fs::write(&layout.claude_executable, "#!/bin/sh\nexit 0\n").unwrap();+ let found = scanner+ .scan()+ .into_iter()+ .find(|item| outcome_agent_id(&item.outcome) == "agent_claude_default")+ .unwrap();+ let AgentDiscoveryOutcomeV1::Supported { installation } = found.outcome else {+ panic!("executable remains installed");+ };+ assert_ne!(Some(installation.observation_digest), digest);+ assert!(!scanner.matches_legacy_claude_observation("2.1.231", &legacy_digest));+}++#[test]+fn legacy_process_digest_matches_the_pre_window_contract_fixture() {+ use crate::agents::filesystem_config::{ClaudeSource, recover_pre_context_process_digest};+ let mut observation = ClaudeSource::Process+ .read(&BTreeMap::new(), &BTreeSet::new())+ .unwrap();+ recover_pre_context_process_digest(&mut observation);+ // Frozen hash of the original five-field representation from 9e1ddbb:+ // four empty strings followed by the helper-presence boolean.+ assert_eq!(+ observation.digest.as_str(),+ "sha256:2e119288169c0e9f0d13cc0bf91861599ef9958a275c54dd87fdabe72e5d5d9d"+ );+ let original = observation.digest.clone();+ observation+ .settings+ .env+ .context_environment+ .insert("DISABLE_COMPACT".into(), "1".into());+ observation.digest = CanonicalDigest::of_bytes(b"current format with context override");+ let current = observation.digest.clone();+ recover_pre_context_process_digest(&mut observation);+ assert_eq!(observation.digest, current);+ assert_ne!(observation.digest, original);+}diff --git a/crates/integrations/src/agents/filesystem_tests/managed_launch.rs b/crates/integrations/src/agents/filesystem_tests/managed_launch.rsnew file mode 100644index 00000000..683ea7c2--- /dev/null+++ b/crates/integrations/src/agents/filesystem_tests/managed_launch.rs@@ -0,0 +1,203 @@+use super::*;++#[test]+fn managed_launch_sanitizes_inherited_env_and_keeps_compute_discovery() {+ let directory = tempfile::tempdir().unwrap();+ let layout =+ layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1)+ .with_process_value(+ "ANTHROPIC_BASE_URL",+ "https://open.bigmodel.cn/api/anthropic",+ )+ .with_process_value("ANTHROPIC_MODEL", "glm-5.3")+ .with_process_value("ANTHROPIC_AUTH_TOKEN", "process-secret")+ .with_process_value("CLAUDE_CODE_USE_BEDROCK", "1");+ let scanner = FilesystemAgentScannerV1::new(layout, registry());+ let result = scanner+ .scan()+ .into_iter()+ .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")+ .unwrap();++ assert!(matches!(+ result.outcome,+ AgentDiscoveryOutcomeV1::Supported { .. }+ ));+ assert!(result.claude_configuration.is_some());+ assert!(result.discovered_credential.is_some());+ let preflight = result.managed_launch.as_ref().unwrap();+ assert!(preflight.is_launchable());+ assert_eq!(preflight.warnings.len(), 1);+ assert_eq!(preflight.warnings[0].code, MANAGED_LAUNCH_ENV_SANITIZED_V1);+ assert_eq!(+ preflight.inherited_environment_removals,+ BTreeSet::from([+ "ANTHROPIC_AUTH_TOKEN".to_owned(),+ "ANTHROPIC_BASE_URL".to_owned(),+ "ANTHROPIC_MODEL".to_owned(),+ "CLAUDE_CODE_USE_BEDROCK".to_owned(),+ ])+ );+ let encoded = serde_json::to_string(&result).unwrap();+ assert!(!encoded.contains("process-secret"));+}++#[test]+fn managed_launch_isolates_user_settings_and_keeps_compute_discovery() {+ let directory = tempfile::tempdir().unwrap();+ let layout =+ layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1);+ write_secret_settings(+ &layout.claude_user_settings,+ json!({+ "apiKeyHelper": "do-not-run --secret",+ "env": {+ "ANTHROPIC_BASE_URL": "https://open.bigmodel.cn/api/anthropic",+ "ANTHROPIC_MODEL": "claude-opus-5",+ "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-5.3[1m]",+ "ANTHROPIC_AUTH_TOKEN": "user-secret"+ }+ }),+ );+ let result = FilesystemAgentScannerV1::new(layout, registry())+ .scan()+ .into_iter()+ .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")+ .unwrap();++ assert!(result.claude_configuration.is_some());+ assert!(result.discovered_credential.is_some());+ let preflight = result.managed_launch.as_ref().unwrap();+ assert!(preflight.is_launchable());+ assert!(preflight.conflicts.is_empty());+ let encoded = serde_json::to_string(&result).unwrap();+ assert!(!encoded.contains("user-secret"));+ assert!(!encoded.contains("do-not-run"));+}++#[test]+fn managed_launch_blocks_auth_routing_fields_from_every_nonprocess_layer() {+ let directory = tempfile::tempdir().unwrap();+ let mut layout =+ layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1);+ let launch = directory.path().join("launch/settings.json");+ let managed = directory.path().join("managed/settings.json");+ layout.claude_launch_settings = Some(launch.clone());+ layout.claude_managed_settings = vec![managed.clone()];+ write_secret_settings(&launch, json!({"apiKeyHelper": "must-not-run"}));+ write_secret_settings(+ &layout.claude_project_settings[0],+ json!({"env": {"ANTHROPIC_BASE_URL": "https://attacker.invalid"}}),+ );+ write_secret_settings(+ &layout.claude_user_settings,+ json!({"env": {"ANTHROPIC_MODEL": "untrusted-model"}}),+ );+ write_secret_settings(&managed, json!({"env": {"CLAUDE_CODE_USE_VERTEX": "1"}}));++ let result = FilesystemAgentScannerV1::new(layout, registry())+ .scan()+ .into_iter()+ .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")+ .unwrap();+ let preflight = result.managed_launch.unwrap();+ assert_eq!(+ preflight+ .conflicts+ .iter()+ .map(|conflict| conflict.layer)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from([ConfigLayerV1::Launch, ConfigLayerV1::Managed])+ );+ assert!(+ preflight+ .conflicts+ .iter()+ .all(|conflict| conflict.code == AGENT_AUTH_PRECEDENCE_CONFLICT_V1)+ );+ assert!(+ !serde_json::to_string(&preflight)+ .unwrap()+ .contains("must-not-run")+ );+}++#[test]+fn managed_launch_isolates_multiple_project_settings() {+ let directory = tempfile::tempdir().unwrap();+ let mut layout =+ layout_with_claude_version(directory.path(), CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1);+ let second = directory.path().join("project-2/.claude/settings.json");+ layout.claude_project_settings.push(second.clone());+ for (path, endpoint, token) in [+ (+ &layout.claude_project_settings[0],+ "https://open.bigmodel.cn/api/anthropic",+ "first-secret",+ ),+ (&second, "https://attacker.invalid", "second-secret"),+ ] {+ write_secret_settings(+ path,+ json!({"env": {+ "ANTHROPIC_BASE_URL": endpoint,+ "ANTHROPIC_MODEL": "glm-5.3",+ "ANTHROPIC_AUTH_TOKEN": token,+ }}),+ );+ }+ let result = FilesystemAgentScannerV1::new(layout, registry())+ .scan()+ .into_iter()+ .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")+ .unwrap();++ assert!(matches!(+ result.outcome,+ AgentDiscoveryOutcomeV1::Supported { .. }+ ));+ let AgentDiscoveryOutcomeV1::Supported { installation } = &result.outcome else {+ unreachable!()+ };+ assert!(+ installation+ .require_action(hiroute_domain::AgentAction::RestoreModel)+ .is_err()+ );+ assert!(result.claude_configuration.is_none());+ assert!(result.discovered_credential.is_none());+ let preflight = result.managed_launch.unwrap();+ assert!(preflight.is_launchable());+ assert!(preflight.conflicts.is_empty());+ let encoded = serde_json::to_string(&preflight).unwrap();+ assert!(!encoded.contains("first-secret"));+ assert!(!encoded.contains("second-secret"));+}++#[test]+fn managed_launch_accepts_old_new_and_unparseable_versions() {+ for (version, supported, managed) in [+ (CLAUDE_CODE_VERIFIED_VERSION_V1, true, true),+ ("0.0.1", true, true),+ (CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1, true, true),+ ("99.1.2", true, true),+ ("", true, true),+ ("unparseable version", true, true),+ ] {+ let directory = tempfile::tempdir().unwrap();+ let result = FilesystemAgentScannerV1::new(+ layout_with_claude_version(directory.path(), version),+ registry(),+ )+ .scan()+ .into_iter()+ .find(|result| outcome_agent_id(&result.outcome) == "agent_claude_default")+ .unwrap();+ assert_eq!(+ matches!(result.outcome, AgentDiscoveryOutcomeV1::Supported { .. }),+ supported,+ "unexpected support state for {version}"+ );+ assert_eq!(result.managed_launch.is_some(), managed, "{version}");+ }+}diff --git a/crates/integrations/src/agents/managed_launch.rs b/crates/integrations/src/agents/managed_launch.rsindex 1c1a5954..379072f0 100644--- a/crates/integrations/src/agents/managed_launch.rs+++ b/crates/integrations/src/agents/managed_launch.rs@@ -64,7 +64,6 @@ pub struct AgentAuthPrecedenceConflictV1 {#[serde(deny_unknown_fields)]pub struct ManagedClaudeLaunchPreflightV1 {pub executable: String,- pub exact_version: String,pub inherited_environment_removals: BTreeSet<String>,pub warnings: Vec<ManagedLaunchWarningV1>,pub conflicts: Vec<AgentAuthPrecedenceConflictV1>,@@ -73,7 +72,6 @@ pub struct ManagedClaudeLaunchPreflightV1 {impl ManagedClaudeLaunchPreflightV1 {pub(super) fn from_observations(executable: String,- exact_version: String,profile: &ManagedLaunchProfileV1,observations: &[super::filesystem_config::ObservedClaudeSettings],) -> Self {@@ -125,7 +123,6 @@ impl ManagedClaudeLaunchPreflightV1 {.collect();Self {executable,- exact_version,inherited_environment_removals,warnings,conflicts,@@ -211,6 +208,12 @@ fn configure_command(if let Some(haiku) = &descriptor.presets.haiku {command.env("ANTHROPIC_DEFAULT_HAIKU_MODEL", haiku);}+ if let Some(window) = descriptor.context_window_tokens {+ for key in hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT {+ command.env_remove(key);+ }+ command.envs(hiroute_domain::claude_context_environment(window).expect("validated window"));+ }command.arg(MANAGED_CLAUDE_SETTINGS_ARGUMENT_V1).arg(overlay)@@ -357,6 +360,16 @@ fn write_overlay(for (name, value) in managed_env {env.insert(name, value);}+ if let Some(window) = descriptor.context_window_tokens {+ for key in hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT {+ env.remove(key);+ }+ for (key, value) in+ hiroute_domain::claude_context_environment(window).expect("validated window")+ {+ env.insert(key, json!(value));+ }+ }overlay.insert("env".to_owned(), Value::Object(env));overlay.insert("apiKeyHelper".to_owned(), json!(helper_command));serde_json::to_writer(file, &Value::Object(overlay))@@ -380,3 +393,46 @@ const MANAGED_CLAUDE_ENVIRONMENT: [&str; 11] = ["CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX",];++#[cfg(test)]+mod context_window_tests {+ use super::*;++ #[test]+ fn managed_claude_context_window_overrides_caller_settings_and_process_environment() {+ let mut descriptor = ManagedClaudeLaunchDescriptorV2::trusted(+ "agent-connection/context-test",+ "claude-messages-v1",+ "/trusted/claude",+ hiroute_domain::CanonicalDigest::of_bytes(b"snapshot"),+ 1,+ hiroute_domain::CanonicalDigest::of_bytes(b"publication"),+ "http://127.0.0.1:4321",+ hiroute_domain::AgentClaudePresetValuesV2 {+ opus: Some("hiroute-plan".into()),+ sonnet: None,+ haiku: None,+ },+ "/trusted/hiroute",+ )+ .unwrap();+ descriptor.context_window_tokens = Some(272_000);+ descriptor.validate().unwrap();+ let file = tempfile::NamedTempFile::new().unwrap();+ write_overlay(&mut file.reopen().unwrap(), &descriptor, &json!({"theme":"dark", "env":{"DISABLE_COMPACT":"1", "CLAUDE_CODE_AUTO_COMPACT_WINDOW":"900000", "UNRELATED":"keep"}})).unwrap();+ let overlay: Value = serde_json::from_reader(file.reopen().unwrap()).unwrap();+ assert_eq!(overlay["theme"], "dark");+ assert_eq!(overlay["env"]["UNRELATED"], "keep");+ assert_eq!(overlay["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], "272000");+ assert_eq!(overlay["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "272000");+ assert!(overlay["env"].get("DISABLE_COMPACT").is_none());+ let mut command = Command::new("/trusted/claude");+ configure_command(&mut command, &descriptor, file.path(), &[]);+ let environment: std::collections::BTreeMap<_, _> = command.get_envs().collect();+ assert_eq!(+ environment[OsStr::new("CLAUDE_CODE_AUTO_COMPACT_WINDOW")],+ Some(OsStr::new("272000"))+ );+ assert_eq!(environment[OsStr::new("DISABLE_COMPACT")], None);+ }+}diff --git a/crates/integrations/src/agents/mod.rs b/crates/integrations/src/agents/mod.rsindex 06d9e2c4..d32bd968 100644--- a/crates/integrations/src/agents/mod.rs+++ b/crates/integrations/src/agents/mod.rs@@ -1,9 +1,11 @@//! Built-in Codex and managed Claude Code integration profiles.+mod claude_capabilities;mod claude_native_effects;mod codex_catalog;mod codex_catalog_effects;mod codex_catalog_plan;+pub use claude_capabilities::claude_plan_capability_preview;mod codex_catalog_schema;mod codex_catalog_source;mod codex_config;diff --git a/crates/integrations/src/agents/registry.rs b/crates/integrations/src/agents/registry.rsindex 548897fe..b6e0dd12 100644--- a/crates/integrations/src/agents/registry.rs+++ b/crates/integrations/src/agents/registry.rs@@ -6,7 +6,9 @@ use hiroute_domain::{};use serde_json::json;+#[cfg(test)]pub const CLAUDE_CODE_VERIFIED_VERSION_V1: &str = "2.1.0";+#[cfg(test)]pub const CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1: &str = "2.1.231";pub const CODEX_PROFILE_ID_V1: &str = "codex-responses-v1";pub const CLAUDE_PROFILE_ID_V1: &str = "claude-messages-v1";@@ -26,7 +28,7 @@ pub fn codex_profile_v1() -> AgentProfileV1 {kind: AgentKindV1::Codex,// Codex versions are diagnostic only. MVP admission never uses a binary-version// allowlist; concrete Desktop and CLI surfaces locate and launch their actual engine.- exact_versions: BTreeSet::new(),+ legacy_exact_versions: BTreeSet::new(),ingress_protocol: AgentIngressProtocolV1::Responses,config_precedence: AgentKindV1::Codex.config_precedence().to_vec(),owned_config_fields: vec![@@ -60,10 +62,7 @@ pub fn claude_code_profile_v1() -> AgentProfileV1 {profile_id: CLAUDE_PROFILE_ID_V1.to_owned(),integration_profile_ref: CLAUDE_INTEGRATION_PROFILE_REF_V1.to_owned(),kind: AgentKindV1::ClaudeCode,- exact_versions: BTreeSet::from([- CLAUDE_CODE_VERIFIED_VERSION_V1.to_owned(),- CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1.to_owned(),- ]),+ legacy_exact_versions: BTreeSet::new(),ingress_protocol: AgentIngressProtocolV1::Messages,config_precedence: AgentKindV1::ClaudeCode.config_precedence().to_vec(),owned_config_fields: vec![@@ -83,7 +82,7 @@ pub fn claude_code_profile_v1() -> AgentProfileV1 {static_catalog_fallback: false,native_subagent_routing: false,spawn_guidance: None,- managed_launch: Some(ManagedLaunchProfileV1::claude_code_2_1_231()),+ managed_launch: Some(ManagedLaunchProfileV1::claude_code()),}}diff --git a/crates/integrations/tests/agent_profiles.rs b/crates/integrations/tests/agent_profiles.rsindex 7e1208fd..4c0fe848 100644--- a/crates/integrations/tests/agent_profiles.rs+++ b/crates/integrations/tests/agent_profiles.rs@@ -1,7 +1,6 @@use hiroute_domain::{AgentIngressProtocolV1, AgentKindV1, AgentProfilesArtifactV1, ConfigLayerV1};use hiroute_integrations::{AGENT_SCAN_OBSERVATION_SCHEMA_V1, AgentDiscoveryOutcomeV1, AgentScanObservationV1,- CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1, CLAUDE_CODE_VERIFIED_VERSION_V1,builtin_agent_profiles, builtin_agent_profiles_artifact, resolve_agent_observation,};@@ -19,14 +18,14 @@ fn agent_profiles_generated_artifact_has_builtin_registry_as_its_only_source() {}#[test]-fn agent_profiles_freeze_managed_versions_protocol_precedence_and_owned_fields() {+fn agent_profiles_freeze_protocol_precedence_and_owned_fields_without_version_gates() {let artifact = builtin_agent_profiles_artifact();let codex = artifact.profiles.iter().find(|profile| profile.kind == AgentKindV1::Codex).unwrap();- assert!(codex.exact_versions.is_empty());+ assert!(codex.legacy_exact_versions.is_empty());assert_eq!(codex.ingress_protocol, AgentIngressProtocolV1::Responses);assert_eq!(codex.config_precedence,@@ -46,30 +45,16 @@ fn agent_profiles_freeze_managed_versions_protocol_precedence_and_owned_fields().iter().find(|profile| profile.kind == AgentKindV1::ClaudeCode).unwrap();- assert_eq!(claude.exact_versions.len(), 2);- assert!(- claude- .exact_versions- .contains(CLAUDE_CODE_VERIFIED_VERSION_V1)- );- assert!(- claude- .exact_versions- .contains(CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1)- );+ assert!(claude.legacy_exact_versions.is_empty());assert_eq!(claude.ingress_protocol, AgentIngressProtocolV1::Messages);assert!(claude.field("base_endpoint").is_some());- assert!(!claude.supports_managed_launch(CLAUDE_CODE_VERIFIED_VERSION_V1));- assert!(claude.supports_managed_launch(CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1));+ assert!(claude.supports_managed_launch());assert_eq!(claude.managed_launch.as_ref().unwrap(),- &hiroute_domain::ManagedLaunchProfileV1::claude_code_2_1_231()+ &hiroute_domain::ManagedLaunchProfileV1::claude_code());- for version in [- CLAUDE_CODE_VERIFIED_VERSION_V1,- CLAUDE_CODE_VERIFIED_VERSION_2_1_231_V1,- ] {+ for version in ["2.1.0", "2.1.231"] {let observation = AgentScanObservationV1 {schema: AGENT_SCAN_OBSERVATION_SCHEMA_V1.into(),agent_id: format!("agent/claude-{version}"),diff --git a/crates/observation/src/query_v2/tests.rs b/crates/observation/src/query_v2/tests.rsindex e3c4eccf..7587429a 100644--- a/crates/observation/src/query_v2/tests.rs+++ b/crates/observation/src/query_v2/tests.rs@@ -346,11 +346,29 @@ fn query_workers_are_bounded_and_released_on_drop() {Err(ObservationV2Error::Busy));drop(permits);- assert!(- store- .observed_requests(&reader(None), &query(50), 500)- .is_ok()+ // Prove that all worker slots were returned, independently of SQLite/OS query+ // execution and its separate deadline. Public query tests cover successful reads.+ let mut reacquired = (0..4)+ .map(|_| {+ store+ .query_permit()+ .expect("dropped worker slot must be reusable")+ })+ .collect::<Vec<_>>();+ assert_eq!(+ store.observed_requests(&reader(None), &query(50), 500),+ Err(ObservationV2Error::Busy));+ drop(reacquired.pop());+ let replacement = store+ .query_permit()+ .expect("one released slot must be reusable");+ assert!(matches!(+ store.query_permit(),+ Err(ObservationV2Error::Busy)+ ));+ drop(replacement);+ drop(reacquired);}#[test]diff --git a/e2e/product/golden/agents/agent-connection-boundary.v1.json b/e2e/product/golden/agents/agent-connection-boundary.v1.jsonindex a32f4b14..ba7a530a 100644--- a/e2e/product/golden/agents/agent-connection-boundary.v1.json+++ b/e2e/product/golden/agents/agent-connection-boundary.v1.json@@ -8,5 +8,5 @@"composition_owner": "TASK-142003","codex_protocol": "responses","claude_protocol": "messages",- "unknown_version_behavior": "report_only"+ "unknown_version_behavior": "capability_based"}diff --git a/e2e/product/scenarios/agents/agent-connection-contract.v1.json b/e2e/product/scenarios/agents/agent-connection-contract.v1.jsonindex 74f3e6cf..a0252105 100644--- a/e2e/product/scenarios/agents/agent-connection-contract.v1.json+++ b/e2e/product/scenarios/agents/agent-connection-contract.v1.json@@ -11,7 +11,7 @@"grant_catalog_overlay_exact","installed-standalone-headless-management-loop","optional_exact_marker_rewrite",- "unknown_version_report_only"+ "client_version_diagnostic_only"],"scenario_states": [{diff --git a/tools/product-e2e/src/agents/mod.rs b/tools/product-e2e/src/agents/mod.rsindex 6a661767..6d43b6c3 100644--- a/tools/product-e2e/src/agents/mod.rs+++ b/tools/product-e2e/src/agents/mod.rs@@ -48,7 +48,7 @@ impl AgentConnectionContractV1 {"grant_catalog_overlay_exact".to_owned(),PRODUCTION_EVIDENCE.to_owned(),"optional_exact_marker_rewrite".to_owned(),- "unknown_version_report_only".to_owned(),+ "client_version_diagnostic_only".to_owned(),]){return Err(AgentConnectionContractError::InvalidContract);diff --git a/tools/product-e2e/src/smoke/fixtures.rs b/tools/product-e2e/src/smoke/fixtures.rsindex 3e7cd58a..1a5a5b6a 100644--- a/tools/product-e2e/src/smoke/fixtures.rs+++ b/tools/product-e2e/src/smoke/fixtures.rs@@ -41,14 +41,19 @@ pub fn discovery(root: &Path, secret: &str) -> Result<(PathBuf, PathBuf)> {))?;for (binary, profile_id, prefix, diagnostic_version) in [("codex", "codex-responses-v1", "codex-cli", Some("99.99.99")),- ("claude", "claude-messages-v1", "Claude Code", None),+ (+ "claude",+ "claude-messages-v1",+ "Claude Code",+ Some("unknown"),+ ),] {let profile = profiles["profiles"].as_array().and_then(|p| p.iter().find(|p| p["profile_id"] == profile_id)).ok_or(super::SmokeError("invalid_agent_fixture"))?;let version = diagnostic_version- .or_else(|| profile["exact_versions"][0].as_str())+ .or_else(|| profile["diagnostic_version"].as_str()).ok_or(super::SmokeError("invalid_agent_fixture"))?;require(versiondiff --git a/tools/product-e2e/tests/agent_connection.rs b/tools/product-e2e/tests/agent_connection.rsindex 0d228b4c..02e6cbc1 100644--- a/tools/product-e2e/tests/agent_connection.rs+++ b/tools/product-e2e/tests/agent_connection.rs@@ -156,7 +156,7 @@ fn agent_connection_boundary_golden_records_public_completion() {assert_eq!(golden.composition_owner, PRODUCTION_EVIDENCE_OWNER);assert_eq!(golden.codex_protocol, "responses");assert_eq!(golden.claude_protocol, "messages");- assert_eq!(golden.unknown_version_behavior, "report_only");+ assert_eq!(golden.unknown_version_behavior, "capability_based");let states = BTreeSet::from([golden.profile_grant_catalog_contract,diff --git a/tools/product-e2e/tests/bundled_release_data.rs b/tools/product-e2e/tests/bundled_release_data.rsindex 524746b9..5fe78214 100644--- a/tools/product-e2e/tests/bundled_release_data.rs+++ b/tools/product-e2e/tests/bundled_release_data.rs@@ -66,7 +66,7 @@ fn bundled_current_agent_profiles_are_exact_typed_artifacts() {.find(|profile| profile.kind == AgentKindV1::Codex).unwrap();assert!(- codex.exact_versions.is_empty(),+ codex.legacy_exact_versions.is_empty(),"Codex discovery must not reintroduce a binary-version admission gate");let claude = artifact@@ -74,14 +74,7 @@ fn bundled_current_agent_profiles_are_exact_typed_artifacts() {.iter().find(|profile| profile.kind == AgentKindV1::ClaudeCode).unwrap();- assert_eq!(- claude- .exact_versions- .iter()- .map(String::as_str)- .collect::<Vec<_>>(),- ["2.1.0", "2.1.231"]- );+ assert!(claude.legacy_exact_versions.is_empty());}#[test]