Skip to content

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.

feat(opencode): integrate native Agent and Worker support (#180)

澄潭a3c8ebfebee1
diff --git a/Cargo.lock b/Cargo.lock
index 6712bb91..8f87e5f6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2536,6 +2536,7 @@ dependencies = [
"http",
"nix",
"reqwest",
+ "rusqlite",
"rustix",
"semver",
"serde",
diff --git a/apps/desktop/src/features/WorkerDependencies.tsx b/apps/desktop/src/features/WorkerDependencies.tsx
index cd556f43..5924a838 100644
--- a/apps/desktop/src/features/WorkerDependencies.tsx
+++ b/apps/desktop/src/features/WorkerDependencies.tsx
@@ -53,7 +53,7 @@ export function WorkerDependencies({
}) {
const zh = language === 'zh';
const text = (cn: string, en: string) => zh ? cn : en;
- const name = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', qoder_cli: 'Qoder CLI', pi: 'Pi', deepseek_harness: 'DeepSeek Harness' }[harness];
+ const name = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', qoder_cli: 'Qoder CLI', pi: 'Pi', deepseek_harness: 'DeepSeek Harness', opencode: 'OpenCode' }[harness];
const components = workerDependencyComponents(harness);
const [view, setView] = useState<WorkerDependenciesView | null>(null);
const [selection, setSelection] = useState<WorkerDependencySelectionRequest | null>(null);
@@ -125,7 +125,7 @@ export function WorkerDependencies({
setSelection(current => ({
harness,
cli_path: '',
- ...((harness === 'qoder_cli' || harness === 'deepseek_harness') ? {} : { ...(harness === 'pi' ? {} : { adapter_path: '' }), node_path: null }),
+ ...((harness === 'qoder_cli' || harness === 'deepseek_harness' || harness === 'opencode') ? {} : { ...(harness === 'pi' ? {} : { adapter_path: '' }), node_path: null }),
expected_selection_revision: view ? workerDependencyRevision(view, harness) : 0,
...current,
...patch,
@@ -141,7 +141,7 @@ export function WorkerDependencies({
setError('');
setNotice('');
try {
- const input = harness === 'qoder_cli'
+ const input = workerDependencyComponents(harness).length === 1
? { harness, cli_path: selection.cli_path, expected_selection_revision: selection.expected_selection_revision }
: harness === 'pi' ? { harness, cli_path: selection.cli_path, node_path: selection.node_path, expected_selection_revision: selection.expected_selection_revision } : selection;
const prepared = await invoke<Confirmation>('worker_dependencies_select_prepare', { input });
@@ -222,10 +222,12 @@ export function WorkerDependencies({
{text('选择已安装的 Qoder CLI(qoder 或 qodercli)。需要登录时,请在终端正常启动该 CLI 并完成登录,再返回使用。', 'Select your installed Qoder CLI (qoder or qodercli). When sign-in is needed, start that CLI normally in a terminal and sign in, then return here.')} {' '}
<a href="https://docs.qoder.com/cli/installation" target="_blank" rel="noreferrer" onClick={event => void openInstallationGuide(event)}>{text('官方安装与升级说明', 'Official installation and upgrade guide')}</a>
</p>}
+ {harness === 'opencode' && <p className="field-help" data-opencode-installation-guide>{text('Worker 目前支持官方 npm 平台包中的 OpenCode 1.19.3。请选择包内的原生程序。', 'Workers currently support OpenCode 1.19.3 from its official npm platform package. Select the native executable inside that package.')}</p>}
{harness === 'deepseek_harness' && <p className="field-help" data-dsh-installation-guide>{text('安装官方 dsh CLI 并检测安装位置。npm 安装需要受支持的 Node.js;任务通过原生 ACP 执行,无需连接组件。', 'Install the official dsh CLI and detect its location. npm installations need supported Node.js; tasks use native ACP with no adapter.')}</p>}
{harness === 'pi' && <p className="field-help" data-pi-installation-guide>{text('使用官方 npm 安装的 Pi 和 Node.js。检测安装位置后,保存时会检查所需能力;也可查看安装命令。', 'Use the official npm installation of Pi and Node.js. Detect installation paths; saving checks the required capabilities. Installation commands are also available.')}</p>}
{!view && <div className="option-panel"><div className="option-row"><div><strong>{text('检测本机安装', 'Detect local installation')}</strong><span>{harness === 'qoder_cli'
? text('查找当前环境中的 Qoder CLI。', 'Find Qoder CLI in the current environment.')
+ : components.length === 1 ? text(`查找当前环境中的 ${name}。`, `Find ${name} in the current environment.`)
: harness === 'pi' ? text('查找 Pi 和 Node.js。', 'Find Pi and Node.js.') : text(`查找 ${name}、连接组件和必要的 Node.js。`, `Find ${name}, its adapter, and Node.js when required.`)}</span></div><button className="btn btn-primary" type="button" disabled={refreshing} onClick={() => void discover()}>{refreshing ? text('正在检测…', 'Detecting…') : text('一键检测', 'Detect')}</button></div></div>}
{view && <div className={`callout ${state === 'configured' ? 'good' : state === 'found' ? '' : 'warn'}`}>
diff --git a/apps/desktop/src/features/agents/AdditionalModelEditor.tsx b/apps/desktop/src/features/agents/AdditionalModelEditor.tsx
index 03cd0971..08b4f8a8 100644
--- a/apps/desktop/src/features/agents/AdditionalModelEditor.tsx
+++ b/apps/desktop/src/features/agents/AdditionalModelEditor.tsx
@@ -32,7 +32,7 @@ export function AdditionalModelEditor({ agent, values, plans, language, disabled
</fieldset>
<div className="additional-model-editor__help">
{agent.agent_id === 'agent_qoder_default' && <p className="field-help" data-qoder-login-prerequisite>{text('使用这些路由前,请先在对应的 Qoder CLI 中通过 /login 登录。保存路由不会完成 Qoder 登录。', 'Before using these routes, sign in with /login in the corresponding Qoder CLI. Saving routes does not sign in to Qoder.')}</p>}
- <p className="field-help" data-agent-activation>{dsh ? text('保存后启动 dsh web,在模型选择器中选用 HiRoute 路由。此配置作用于标准 web profile;其他 profile 保留原有配置。', 'After saving, start dsh web and select a HiRoute route in the model picker. This configures the standard web profile; other profiles retain their configuration.') : text(`保存后重新启动 ${name},通过 /model 明确选用已添加的 HiRoute 路由。未选择时继续使用原来的模型。`, `Restart ${name} after saving, then explicitly select an added HiRoute route with /model. Otherwise it keeps using your previous model.`)}</p>
+ <p className="field-help" data-agent-activation>{agent.agent_id === 'agent_opencode_default' ? text('保存后重新启动 OpenCode,在模型选择器中选用已添加的 HiRoute 路由。', 'Restart OpenCode after saving and select an added HiRoute route in the model picker.') : dsh ? text('保存后启动 dsh web,在模型选择器中选用 HiRoute 路由。此配置作用于标准 web profile;其他 profile 保留原有配置。', 'After saving, start dsh web and select a HiRoute route in the model picker. This configures the standard web profile; other profiles retain their configuration.') : text(`保存后重新启动 ${name},通过 /model 明确选用已添加的 HiRoute 路由。未选择时继续使用原来的模型。`, `Restart ${name} after saving, then explicitly select an added HiRoute route with /model. Otherwise it keeps using your previous model.`)}</p>
<p className="field-help">{text(`在 HiRoute 中调整或移除这些路由。如果已将某条路由设为 ${name} 默认模型,移除前请先在 ${name} 中切换到其他模型。`, `Adjust or remove these routes in HiRoute. If one is now your ${name} default, switch to another model in ${name} before removing it.`)}</p>
</div>
{invalid && <span className="oc-inline-error">{text(`至少选择一条已启用路由,并取消不可用的选择。`, `Select at least one enabled route and remove unavailable selections.`)}</span>}
diff --git a/apps/desktop/src/features/agents/AgentModelEditor.tsx b/apps/desktop/src/features/agents/AgentModelEditor.tsx
index b078e8a3..24045104 100644
--- a/apps/desktop/src/features/agents/AgentModelEditor.tsx
+++ b/apps/desktop/src/features/agents/AgentModelEditor.tsx
@@ -29,6 +29,7 @@ export function AgentModelEditor(props: AgentModelEditorProps) {
case 'hermes': return <HermesModelEditor {...props} />;
case 'codex': return <CodexModelEditor {...props} />;
case 'claude': return <ClaudeModelEditor {...props} />;
+ case 'opencode':
case 'dsh':
case 'pi':
case 'qoder': return <AdditionalModelEditor {...props} />;
@@ -53,6 +54,7 @@ export function modelSelectionSummary(selection: AgentModelSelection | null | un
? text('三个档位共用:', 'All presets use: ') + (planName(sharedPlan) ?? text('当前路由不可用', 'Current route unavailable'))
: Object.entries(selection.preset_mappings).map(([preset, choice]) => `${preset[0].toUpperCase() + preset.slice(1)}: ${choice.kind === 'plan' ? planName(choice.plan_id) ?? text('当前路由不可用', 'Current route unavailable') : text('保留原生', 'Native')}`).join(' · ');
}
+ case 'opencode_additional':
case 'dsh_additional':
case 'pi_additional':
case 'qoder_additional':
diff --git a/apps/desktop/src/features/agents/README.md b/apps/desktop/src/features/agents/README.md
index e1cc8d32..9bffd806 100644
--- a/apps/desktop/src/features/agents/README.md
+++ b/apps/desktop/src/features/agents/README.md
@@ -16,7 +16,7 @@ to their production owners and executable contracts.
| [ecosystems.ts](ecosystems.ts) | Explicit current Agent identity, display name, brand and surface labels. Unknown discovered identities have no settings editor. |
| [editor-state.ts](editor-state.ts) | Draft initialization, dirty comparison and local form completeness. Only a trusted first connection can preselect a sole enabled route. Existing mappings, including unavailable choices, are retained. |
| [settings-request.ts](settings-request.ts) | Ecosystem-specific intent construction, independent model/management/collaboration restore intents, token changes that retain the saved selection, and capability-based prerequisite check selection. |
-| [AgentModelEditor.tsx](AgentModelEditor.tsx) | Explicit composition of [Codex](CodexModelEditor.tsx), [Claude](ClaudeModelEditor.tsx) and [Qoder](AdditionalModelEditor.tsx) forms and their saved-selection summary. Codex allowlist/default/native retention, Claude preset mappings and Qoder additional routes remain different concepts. |
+| [AgentModelEditor.tsx](AgentModelEditor.tsx) | Explicit composition of [Codex](CodexModelEditor.tsx), [Claude](ClaudeModelEditor.tsx) and [supplementary route](AdditionalModelEditor.tsx) forms and their saved-selection summary. Codex allowlist/default/native retention, Claude preset mappings and supplementary routes remain different concepts. |
| [AgentSettingsFeedback.tsx](AgentSettingsFeedback.tsx) | Presentation of authoritative Preview blockers. |
| [HermesModelEditor.tsx](HermesModelEditor.tsx), [HermesRootFields.tsx](HermesRootFields.tsx) | One Plan/protocol and explicit effective profile; root fields are shared with source scan. Automatic adapter preparation and unobserved native loading stay distinct. |
| [collaboration-check-feedback.ts](collaboration-check-feedback.ts) | Versioned collaboration-check failures become safe login, Skill recovery and retry guidance; native output is never display text. |
@@ -25,8 +25,8 @@ to their production owners and executable contracts.
| [mutation-feedback.ts](mutation-feedback.ts) | Submitted, pre-apply cancelled and uncertain outcomes; truthful disable/recovery messages. |
| [Agents page](../../agents.tsx) | Snapshot refresh, selected Agent/tab, in-memory draft and mode, discard guard, native calls, Operation handoff, confirmation-dependent copy effect and task-history composition. |
-Qoder, Pi and DSH share the additional-route editor and explicitly selected Plan IDs
-through `qoder_additional`, `pi_additional` and `dsh_additional`. It does not
+Qoder, Pi, DSH and OpenCode share the additional-route editor and explicitly selected Plan IDs
+through `qoder_additional`, `pi_additional`, `dsh_additional` and `opencode_additional`. It does not
edit the native default or show native catalogs, fixed-source choices or import controls.
Hermes selects one default main-model Plan. Its management Skill has independent
prepare/restore controls and needs no model connection or published Plan. Model
@@ -73,7 +73,10 @@ keeps the model routes. Token updates retain the saved ecosystem-specific select
Task collaboration remains independently usable without any model connection or
published Plan: its form submits `model: keep`. DSH configures the standard Web profile model picker; global provider shadowing is
reported by the backend before Apply. Each selected Plan has its own provider and
-user-selected Responses/Messages protocol.
+user-selected Responses/Messages protocol. OpenCode uses its saved native model picker;
+its native default and small-model choices remain independent. Relevant native references
+are backend Preview facts: removing a referenced selector retains the draft and explains
+how to change that reference before restoring.
Both model-capable status and actual
collaboration-only status retain this path. Capability and installed-Skill checks
@@ -83,7 +86,10 @@ Context IDs bind requests and are not user-facing configuration scopes. Show onl
readable locations already supplied by the native projection (native configuration and Skill directories/files); do not infer a path from an opaque context ID.
The Plan editor owns its single-CLI installation selection through
[WorkerDependencies](../WorkerDependencies.tsx); `qoder` and `qodercli` paths are presented
-as returned by discovery, without adapter or Node placeholders.
+as returned by discovery, without adapter or Node placeholders. OpenCode also selects
+only its native executable. Its Worker format prerequisite is separate from ordinary
+model configuration and collaboration capability; installation guidance names the
+supported official package without adding a setup wizard.
The page owns interaction state so changing forms does not create another submission or
Operation store. The native session owns confirmation, protected token registration and
@@ -139,7 +145,8 @@ additional enable/save steps or model-verification badges on the settings page.
| First enable, exact existing selections, unknown state and discard protection | [agent-editor-state.test.mjs](../../../tests/agent-editor-state.test.mjs) |
| Correct ecosystem intent, independent restores, saved-selection token rotation and unsupported identity rejection | [agent-settings-request.test.mjs](../../../tests/agent-settings-request.test.mjs) |
| Collaboration without a model or published Plan, prerequisite failure/retry and restore; independent single-CLI selection | `qoder.collaboration.enable-without-model`, `qoder.collaboration.retry-and-restore`, `qoder.installation.single-cli` in the browser scenarios; [status projection](../../../tests/agent-status.test.mjs) |
-| Additional routes, cancelled drafts, unavailable saved routes, token rotation and independent restores | `qoder.routing.additional-plans`, `qoder.routing.adjust-and-restore`; the native [settings session](../../../src-tauri/src/agent_session.rs) and [check session](../../../src-tauri/src/agent_check_session.rs) retain protected-boundary tests. Browser IPC does not prove native settings preservation or real provider calls. |
+| Additional routes, cancelled drafts, unavailable saved routes, token rotation and independent restores | `qoder.routing.additional-plans`, `qoder.routing.adjust-and-restore`, `opencode.routing.additional-plans`, `opencode.routing.default-in-use`; the native [settings session](../../../src-tauri/src/agent_session.rs) and [check session](../../../src-tauri/src/agent_check_session.rs) retain protected-boundary tests. Browser IPC does not prove native settings preservation or real provider calls. |
+| OpenCode native-only installation selection and independent saved Harness choices | `opencode.installation.single-cli` in the [routing browser scenarios](../../../tests/v3/browser/routing-worker-scenarios.mjs). |
| Submission uncertainty and restore-first feedback | [agent-mutation-feedback.test.mjs](../../../tests/agent-mutation-feedback.test.mjs) |
| Same successful Operation and fresh target before copying; discovery versus applicability | [codex-launch.test.mjs](../../../tests/codex-launch.test.mjs), [codex-surfaces.test.mjs](../../../tests/codex-surfaces.test.mjs) |
| Reachable forms, cancellation, mappings and native clipboard IPC selection | [Agent browser scenarios](../../../tests/v3/browser/agent-trust-scenarios.mjs), [clipboard.test.mjs](../../../tests/clipboard.test.mjs) |
diff --git a/apps/desktop/src/features/agents/ecosystems.ts b/apps/desktop/src/features/agents/ecosystems.ts
index d4c77527..c4694e8f 100644
--- a/apps/desktop/src/features/agents/ecosystems.ts
+++ b/apps/desktop/src/features/agents/ecosystems.ts
@@ -1,10 +1,11 @@
+import type { BrandKind } from '../../ui/BrandIcon';
import type { Agent, AgentModelSelection, AgentModelSurface } from './types';
/** A supported integration stays discoverable before a native profile is selected.
* This entry is presentation only: no context or settings authority is invented.
*/
export function agentPageEntries(agents: Agent[]): Agent[] {
- const supported = ['agent_claude_default', 'agent_codex_default', 'agent_dsh_default', 'agent_pi_default', 'agent_qoder_default', 'agent_hermes_default'];
+ const supported = ['agent_claude_default', 'agent_codex_default', 'agent_dsh_default', 'agent_pi_default', 'agent_qoder_default', 'agent_hermes_default', 'agent_opencode_default'];
const missing: Agent[] = supported.filter(id => !agents.some(agent => agent.agent_id === id)).map(agent_id => ({
agent_id, version: '', context_id: null,
configuration_state: agent_id === 'agent_hermes_default' ? 'profile_not_selected' : 'not_discovered',
@@ -13,13 +14,14 @@ export function agentPageEntries(agents: Agent[]): Agent[] {
return missing.length ? [...agents, ...missing] : agents;
}
-export type AgentEcosystem = 'codex' | 'claude' | 'qoder' | 'pi' | 'dsh' | 'hermes';
+export type AgentEcosystem = 'codex' | 'claude' | 'qoder' | 'pi' | 'dsh' | 'hermes' | 'opencode';
/** Only these current integrations have settings editors; discovery is independent. */
export function agentEcosystem(agentId: string): AgentEcosystem | null {
switch (agentId) {
case 'agent_codex_default': return 'codex';
case 'agent_claude_default': return 'claude';
+ case 'agent_opencode_default': return 'opencode';
case 'agent_dsh_default': return 'dsh';
case 'agent_pi_default': return 'pi';
case 'agent_qoder_default': return 'qoder';
@@ -30,7 +32,7 @@ export function agentEcosystem(agentId: string): AgentEcosystem | null {
export function agentSupportsModelRouting(agentId: string): boolean {
const ecosystem = agentEcosystem(agentId);
- return ecosystem === 'codex' || ecosystem === 'claude' || ecosystem === 'qoder' || ecosystem === 'pi' || ecosystem === 'dsh' || ecosystem === 'hermes';
+ return ecosystem === 'codex' || ecosystem === 'claude' || ecosystem === 'qoder' || ecosystem === 'pi' || ecosystem === 'dsh' || ecosystem === 'hermes' || ecosystem === 'opencode';
}
/** A saved selection must belong to the actual integration, including token-only edits. */
@@ -38,6 +40,7 @@ export function agentModelSelectionMatches(agentId: string, selection: AgentMode
switch (agentEcosystem(agentId)) {
case 'codex': return selection.mode === 'codex_default';
case 'claude': return selection.mode === 'claude_launcher';
+ case 'opencode': return selection.mode === 'opencode_additional';
case 'dsh': return selection.mode === 'dsh_additional';
case 'pi': return selection.mode === 'pi_additional';
case 'hermes': return selection.mode === 'hermes_default';
@@ -50,6 +53,7 @@ export function agentDisplayName(agentId: string, language: 'zh' | 'en'): string
switch (agentEcosystem(agentId)) {
case 'codex': return 'Codex';
case 'claude': return 'Claude Code';
+ case 'opencode': return 'OpenCode';
case 'dsh': return 'DeepSeek Harness';
case 'pi': return 'Pi';
case 'qoder': return 'Qoder';
@@ -58,13 +62,14 @@ export function agentDisplayName(agentId: string, language: 'zh' | 'en'): string
}
}
-export function agentBrand(agentId: string): 'codex' | 'claude-code' | 'qoder' | 'pi' | 'dsh' | 'hermes' | 'agent' {
+export function agentBrand(agentId: string): BrandKind {
switch (agentEcosystem(agentId)) {
case 'codex': return 'codex';
case 'claude': return 'claude-code';
case 'dsh': return 'dsh';
case 'pi': return 'pi';
case 'qoder': return 'qoder';
+ case 'opencode': return 'opencode';
case 'hermes': return 'hermes';
default: return 'agent';
}
@@ -76,6 +81,7 @@ export function surfaceName(surface: AgentModelSurface): string {
case 'codex_cli': return 'Codex CLI';
case 'claude_cli': return 'Claude Code CLI';
case 'dsh_cli': return 'DeepSeek Harness';
+ case 'opencode_cli': return 'OpenCode';
case 'pi_cli': return 'Pi CLI';
case 'qoder_cli': return 'Qoder CLI';
case 'hermes_cli': return 'Hermes';
diff --git a/apps/desktop/src/features/agents/editor-state.ts b/apps/desktop/src/features/agents/editor-state.ts
index d037ed69..e17f890e 100644
--- a/apps/desktop/src/features/agents/editor-state.ts
+++ b/apps/desktop/src/features/agents/editor-state.ts
@@ -99,7 +99,7 @@ export function agentEditorSeed(
const currentModel = facet === 'model' ? agentModelStatus(agent)?.current_selection : undefined;
const codex = currentModel?.mode === 'codex_default' ? currentModel : undefined;
const claude = currentModel?.mode === 'claude_launcher' ? currentModel : undefined;
- const qoder = (currentModel?.mode === 'qoder_additional' || currentModel?.mode === 'pi_additional' || currentModel?.mode === 'dsh_additional') ? currentModel : undefined;
+ const qoder = (currentModel?.mode === 'qoder_additional' || currentModel?.mode === 'pi_additional' || currentModel?.mode === 'dsh_additional' || currentModel?.mode === 'opencode_additional') ? currentModel : undefined;
const collaboration = facet === 'collaboration'
&& selection
&& 'trigger_mode' in selection
@@ -117,7 +117,7 @@ export function agentEditorSeed(
fixedModels: currentModel && 'fixed_models' in currentModel ? currentModel.fixed_models : [],
nativeModelMode: codex?.native_model_mode ?? 'hiroute_only',
allowedPlanIds: codex?.allowed_plan_ids ?? qoder?.allowed_plan_ids
- ?? (initialPlan && (ecosystem === 'codex' || ecosystem === 'qoder' || ecosystem === 'pi' || ecosystem === 'dsh') ? [initialPlan] : []),
+ ?? (initialPlan && (ecosystem === 'codex' || ecosystem === 'qoder' || ecosystem === 'pi' || ecosystem === 'dsh' || ecosystem === 'opencode') ? [initialPlan] : []),
defaultChoice: codex?.default_selection ?? (initialPlan && ecosystem === 'codex'
? { kind: 'plan', plan_id: initialPlan } : { kind: 'preserve_native' }),
claudePresets: claude?.preset_mappings ?? {
@@ -148,7 +148,7 @@ export function agentModelFormInvalid(agent: Agent | undefined, editorValues: Ag
if (agentEcosystem(agent.agent_id) === 'hermes') {
return !agent.native_target || !enabledPlanIds.includes(editorValues.hermesPlanId);
}
- if (['qoder', 'pi', 'dsh'].includes(agentEcosystem(agent.agent_id) ?? '')) {
+ if (['qoder', 'pi', 'dsh', 'opencode'].includes(agentEcosystem(agent.agent_id) ?? '')) {
return editorValues.allowedPlanIds.length === 0
|| editorValues.allowedPlanIds.some(id => !enabledPlanIds.includes(id));
}
diff --git a/apps/desktop/src/features/agents/settings-request.ts b/apps/desktop/src/features/agents/settings-request.ts
index 9742f524..b10502d2 100644
--- a/apps/desktop/src/features/agents/settings-request.ts
+++ b/apps/desktop/src/features/agents/settings-request.ts
@@ -49,6 +49,9 @@ export function agentSettingsSpec(agent: Agent, facet: AgentFacet, restore: bool
preset_mappings: values.claudePresets,
};
break;
+ case 'opencode':
+ settings = { mode: 'opencode_additional', allowed_plan_ids: values.allowedPlanIds, plan_protocols: Object.fromEntries(values.allowedPlanIds.map(id => [id, values.planProtocols?.[id] ?? 'responses'])) };
+ break;
case 'dsh':
settings = { mode: 'dsh_additional', allowed_plan_ids: values.allowedPlanIds, plan_protocols: Object.fromEntries(values.allowedPlanIds.map(id => [id, values.planProtocols?.[id] ?? 'responses'])) };
break;
diff --git a/apps/desktop/src/features/agents/types.ts b/apps/desktop/src/features/agents/types.ts
index f4785bd4..dcbca774 100644
--- a/apps/desktop/src/features/agents/types.ts
+++ b/apps/desktop/src/features/agents/types.ts
@@ -39,7 +39,7 @@ export type CollaborationStatus = {
restore_point_ref: string | null;
current_selection?: { trigger_mode: AgentCollaborationTriggerMode } | null;
};
-export type AgentModelSurface = 'codex_cli' | 'codex_desktop' | 'claude_cli' | 'qoder_cli' | 'pi_cli' | 'dsh_cli' | 'hermes_cli';
+export type AgentModelSurface = 'codex_cli' | 'codex_desktop' | 'claude_cli' | 'qoder_cli' | 'pi_cli' | 'dsh_cli' | 'hermes_cli' | 'opencode_cli';
export type AgentReasoningSelection =
| { kind: 'profile'; profile: string }
| { kind: 'toggle'; enabled: boolean }
@@ -91,6 +91,7 @@ export type QoderModelSelection = {
};
export type PiModelSelection = { mode: 'pi_additional'; plan_protocols?: Record<string, 'responses' | 'messages'>; allowed_plan_ids: string[] };
export type DshModelSelection = { mode: 'dsh_additional'; plan_protocols?: Record<string, 'responses' | 'messages'>; allowed_plan_ids: string[] };
+export type OpenCodeModelSelection = { mode: 'opencode_additional'; plan_protocols?: Record<string, 'responses' | 'messages'>; allowed_plan_ids: string[] };
export type AgentNativeTarget = { kind: 'hermes'; config_root: string };
export type HermesModelSelection = { mode: 'hermes_default'; plan_id: string; protocol: 'chat_completions' | 'responses' | 'messages' };
export type SkillResourceStatus = {
@@ -98,7 +99,7 @@ export type SkillResourceStatus = {
shared_context_count: number; native_available: boolean | null; runtime_loading: 'unobserved';
};
export type ManagementSkillStatus = { resource?: SkillResourceStatus; schema: string; state: string; restore_point_ref: string | null; operation_id: string | null; operation_state: string | null };
-export type AgentModelSelection = HermesModelSelection | CodexModelSelection | ClaudeModelSelection | QoderModelSelection | PiModelSelection | DshModelSelection;
+export type AgentModelSelection = HermesModelSelection | OpenCodeModelSelection | CodexModelSelection | ClaudeModelSelection | QoderModelSelection | PiModelSelection | DshModelSelection;
export type AgentSurfaceResult = {
surface: AgentModelSurface;
applied_revision: number;
diff --git a/apps/desktop/src/features/trial/model.ts b/apps/desktop/src/features/trial/model.ts
index a7342cba..74b6ec0e 100644
--- a/apps/desktop/src/features/trial/model.ts
+++ b/apps/desktop/src/features/trial/model.ts
@@ -34,7 +34,7 @@ export function trialMappingValues(agent: Agent, planId: string, mapping: TrialM
return { ...values, claudePresets: { ...values.claudePresets, ...Object.fromEntries(mapping.presets.map(preset => [preset, { kind: 'plan', plan_id: planId }])) } };
}
if (ecosystem === 'codex') return { ...values, allowedPlanIds: [...new Set([...values.allowedPlanIds, planId])], defaultChoice: { kind: 'plan' as const, plan_id: planId } };
- if (['dsh', 'pi', 'qoder'].includes(ecosystem ?? '')) return { ...values, allowedPlanIds: [...new Set([...values.allowedPlanIds, planId])], planProtocols: { ...values.planProtocols, [planId]: 'responses' as const } };
+ if (['dsh', 'pi', 'qoder', 'opencode'].includes(ecosystem ?? '')) return { ...values, allowedPlanIds: [...new Set([...values.allowedPlanIds, planId])], planProtocols: { ...values.planProtocols, [planId]: 'responses' as const } };
throw new Error('AGENT_UNSUPPORTED');
}
diff --git a/apps/desktop/src/features/trust/DivisionDraftDialog.tsx b/apps/desktop/src/features/trust/DivisionDraftDialog.tsx
index 688fc62e..48285387 100644
--- a/apps/desktop/src/features/trust/DivisionDraftDialog.tsx
+++ b/apps/desktop/src/features/trust/DivisionDraftDialog.tsx
@@ -6,7 +6,7 @@ import { divisionDraft, divisionSource } from './division-draft';
import { protectionExplanation } from './protection-copy';
type Harness = NonNullable<Editor['work']>['harness'];
-const harnessNames: Record<Harness, string> = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', deepseek_harness: 'DeepSeek Harness', pi: 'Pi', qoder_cli: 'Qoder CLI' };
+const harnessNames: Record<Harness, string> = { codex_cli: 'Codex CLI', claude_code: 'Claude Code', deepseek_harness: 'DeepSeek Harness', pi: 'Pi', qoder_cli: 'Qoder CLI', opencode: 'OpenCode' };
export function DivisionDraftDialog({ plan, editor, branch, language, options, onClose, onDraft }: { plan: Plan; editor: Editor; branch: string; language: 'zh' | 'en'; options: Options | null; onClose(): void; onDraft(editor: Editor): Promise<boolean> }) {
const text = (zh: string, en: string) => language === 'zh' ? zh : en;
const source = useMemo(() => divisionSource(editor, branch), [editor, branch]);
diff --git a/apps/desktop/src/features/worker-dependencies-state.ts b/apps/desktop/src/features/worker-dependencies-state.ts
index 7b944aeb..fdcb0be5 100644
--- a/apps/desktop/src/features/worker-dependencies-state.ts
+++ b/apps/desktop/src/features/worker-dependencies-state.ts
@@ -1,4 +1,4 @@
-export type WorkerHarness = 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi' | 'deepseek_harness';
+export type WorkerHarness = 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi' | 'deepseek_harness' | 'opencode';
export type WorkerDependencyComponent = 'cli' | 'adapter' | 'node';
export type WorkerDependencyCandidateState = 'found' | 'missing' | 'invalid' | 'unavailable';
@@ -37,12 +37,12 @@ export type WorkerDependencySelectionRequest = WorkerDependencySelection & {
};
export function workerDependencyComponents(harness: WorkerHarness): WorkerDependencyComponent[] {
- return (harness === 'qoder_cli' || harness === 'deepseek_harness') ? ['cli'] : harness === 'pi' ? ['cli', 'node'] : ['cli', 'adapter', 'node'];
+ return (harness === 'qoder_cli' || harness === 'deepseek_harness' || harness === 'opencode') ? ['cli'] : harness === 'pi' ? ['cli', 'node'] : ['cli', 'adapter', 'node'];
}
export function workerDependencySelectionComplete(selection: WorkerDependencySelection | null): boolean {
if (!selection?.cli_path) return false;
- return (selection.harness === 'qoder_cli' || selection.harness === 'deepseek_harness')
+ return (selection.harness === 'qoder_cli' || selection.harness === 'deepseek_harness' || selection.harness === 'opencode')
? selection.adapter_path == null && selection.node_path == null
: selection.harness === 'pi' ? selection.adapter_path == null && Boolean(selection.node_path) : Boolean(selection.adapter_path);
}
@@ -95,7 +95,7 @@ export function recommendedWorkerDependencies(
if (selected) {
return {
...selected,
- ...((harness === 'qoder_cli' || harness === 'deepseek_harness') ? {} : { node_path: selected.node_path ?? null }),
+ ...((harness === 'qoder_cli' || harness === 'deepseek_harness' || harness === 'opencode') ? {} : { node_path: selected.node_path ?? null }),
expected_selection_revision: workerDependencyRevision(view, harness),
};
}
@@ -104,7 +104,7 @@ export function recommendedWorkerDependencies(
return {
harness,
cli_path: found('cli')?.path ?? '',
- ...((harness === 'qoder_cli' || harness === 'deepseek_harness') ? {} : {
+ ...((harness === 'qoder_cli' || harness === 'deepseek_harness' || harness === 'opencode') ? {} : {
...(harness === 'pi' ? {} : { adapter_path: found('adapter')?.path ?? '' }),
node_path: found('node')?.path ?? null,
}),
@@ -123,13 +123,13 @@ export function workerDependencySelectionState(
&& candidate.component === component
&& candidate.path === path)?.state
: undefined;
- const nodeRequired = harness === 'pi' || harness !== 'qoder_cli' && harness !== 'deepseek_harness' && (Boolean(request.node_path)
+ const nodeRequired = harness === 'pi' || harness !== 'qoder_cli' && harness !== 'deepseek_harness' && harness !== 'opencode' && (Boolean(request.node_path)
|| (!selected && view.install_hints.some(hint => hint.harness === harness
&& hint.component === 'node'
&& hint.reason_code === 'worker.dependencies.install_required')));
const complete = workerDependencySelectionComplete(request)
&& fact('cli', request.cli_path) === 'found'
- && (harness === 'qoder_cli' || harness === 'deepseek_harness' || harness === 'pi' || fact('adapter', request.adapter_path) === 'found')
+ && (harness === 'qoder_cli' || harness === 'deepseek_harness' || harness === 'opencode' || harness === 'pi' || fact('adapter', request.adapter_path) === 'found')
&& (!nodeRequired || fact('node', request.node_path) === 'found');
if (selected && complete) return 'configured';
if (complete) return 'found';
diff --git a/apps/desktop/src/occami/styles.css b/apps/desktop/src/occami/styles.css
index 03578971..63fd6073 100644
--- a/apps/desktop/src/occami/styles.css
+++ b/apps/desktop/src/occami/styles.css
@@ -42,6 +42,8 @@
.hr-brand-icon.agent-avatar[data-size='large'] {width:48px;height:48px;}
.hr-brand-icon img,.hr-brand-icon svg {display:block;width:100%;height:100%;}
.hr-brand-icon[data-brand='codex'] img {position:absolute;inset:0;}
+.hr-brand-icon[data-brand='opencode'] {color:var(--text);}
+.hr-brand-icon[data-brand='opencode'] svg {width:70%;height:70%;}
.hr-brand-icon__dark {display:none!important;}
.occami-root[data-theme='dark'] .hr-brand-icon__dark {display:block!important;}
.occami-root[data-theme='dark'] .hr-brand-icon__light {display:none!important;}
diff --git a/apps/desktop/src/plan-editor-errors.ts b/apps/desktop/src/plan-editor-errors.ts
index 79e1e50f..b05cc460 100644
--- a/apps/desktop/src/plan-editor-errors.ts
+++ b/apps/desktop/src/plan-editor-errors.ts
@@ -1,7 +1,7 @@
export type ModelBudgetConflict = {
schema: 'hiroute.agent-model-budget-conflict/v1';
blockers: {
- agent_kind: 'qoder' | 'pi' | 'deepseek_harness'; context_id: string;
+ agent_kind: 'qoder' | 'pi' | 'deepseek_harness' | 'opencode'; context_id: string;
plan_id: string; model_alias: string;
reason: 'capacity_reduced' | 'plan_missing' | 'budget_unavailable';
declared: { context_window_tokens: number; max_output_tokens: number };
@@ -19,7 +19,7 @@ export function modelBudgetConflict(error: unknown): ModelBudgetConflict | null
&& positive(value.context_window_tokens) && positive(value.max_output_tokens);
if (value?.schema !== 'hiroute.agent-model-budget-conflict/v1' || !Array.isArray(value.blockers) || !value.blockers.length) return null;
const valid = value.blockers.every(blocker => blocker
- && ['qoder', 'pi', 'deepseek_harness'].includes(blocker.agent_kind)
+ && ['qoder', 'pi', 'deepseek_harness', 'opencode'].includes(blocker.agent_kind)
&& typeof blocker.context_id === 'string' && /^agent-context\/[A-Za-z0-9/_:-]{1,242}$/.test(blocker.context_id)
&& typeof blocker.plan_id === 'string' && /^[A-Za-z0-9/_:-]{1,256}$/.test(blocker.plan_id)
&& typeof blocker.model_alias === 'string' && /^(?:hiroute\/[0-9a-f]{16}|[a-z0-9][a-z0-9._-]{0,63})$/.test(blocker.model_alias)
@@ -45,7 +45,7 @@ export function planErrorMessage(error: unknown, language: 'zh' | 'en'): string
const conflict = modelBudgetConflict(error);
if (conflict && planErrorCode(error) === 'AGENT_MODEL_BUDGET_CONFLICT') {
const zh = language === 'zh';
- const names = { qoder: 'Qoder', pi: 'Pi', deepseek_harness: 'DeepSeek Harness' };
+ const names = { qoder: 'Qoder', pi: 'Pi', deepseek_harness: 'DeepSeek Harness', opencode: 'OpenCode' };
const number = (value: number) => value.toLocaleString('en-US');
const blockers = conflict.blockers.map(blocker => {
const changes: string[] = [];
diff --git a/apps/desktop/src/plan-editor.tsx b/apps/desktop/src/plan-editor.tsx
index e693f855..8ff949fd 100644
--- a/apps/desktop/src/plan-editor.tsx
+++ b/apps/desktop/src/plan-editor.tsx
@@ -26,7 +26,7 @@ import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } f
import { invoke } from './host';
export type Selection = { binding_id: string; reasoning?: { kind: 'profile'; profile: string } | { kind: 'toggle'; enabled: boolean } | { kind: 'budget'; tokens: number } };
type Mode = 'fixed_model' | 'smart_saving' | 'free_first' | 'custom_branches';
-type Work = { harness: 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi' | 'deepseek_harness'; protocol: 'responses' | 'messages' };
+type Work = { harness: 'codex_cli' | 'claude_code' | 'qoder_cli' | 'pi' | 'deepseek_harness' | 'opencode'; protocol: 'responses' | 'messages' };
type SmartClassifier = Classifier;
// Inactive inputs belong to this editing session, never to the persisted plan.
export type PlanEditorMemory = { branchRouting?: BranchRouting; customWindowTokens?: number };
@@ -456,8 +456,9 @@ const LoadedPlanEditor = forwardRef<PlanEditorHandle, PlanEditorProps & { initia
['deepseek_harness', 'DeepSeek Harness', text('原生 ACP 任务委派', 'Native ACP task delegation')],
['pi', 'Pi', text('使用 Pi 执行委派任务', 'Use Pi for delegated tasks')],
['qoder_cli', 'Qoder CLI', text('使用 Qoder CLI 执行委派任务', 'Use Qoder CLI for delegated tasks')],
- ] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => { if (editor.work?.harness !== value) update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } }); }}><BrandIcon kind={value === 'codex_cli' ? 'codex' : value === 'claude_code' ? 'claude-code' : value === 'pi' ? 'pi' : value === 'deepseek_harness' ? 'dsh' : 'qoder'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}
- {editor.work && (editor.work.harness === 'pi' || editor.work.harness === 'deepseek_harness' || editor.work.harness === 'qoder_cli') && <AgentProtocolChoice name={editor.display_name || text('任务路由', 'Task route')} language={language} value={editor.work.protocol} advice={workerProtocolAdvice(editor, options)} onChange={protocol => update({ work: { ...editor.work!, protocol } })} />}
+ ['opencode', 'OpenCode', text('使用 OpenCode 执行委派任务', 'Use OpenCode for delegated tasks')],
+ ] as const).map(([value, title, description]) => <button className={`v3-executor${editor.work?.harness === value ? ' selected' : ''}`} type="button" key={value} aria-pressed={editor.work?.harness === value} onClick={() => { if (editor.work?.harness !== value) update({ work: { harness: value, protocol: value === 'claude_code' ? 'messages' : 'responses' } }); }}><BrandIcon kind={value === 'codex_cli' ? 'codex' : value === 'claude_code' ? 'claude-code' : value === 'pi' ? 'pi' : value === 'deepseek_harness' ? 'dsh' : value === 'opencode' ? 'opencode' : 'qoder'} label={`${title} logo`} /><div><strong>{title}</strong><span>{description}</span></div>{editor.work?.harness === value && <UiIcon name="check" />}</button>)}</div>{validationIssue?.group === 'executor' && <p className="oc-inline-error route-lane-error">{validationIssue.message}</p>}
+ {editor.work && (editor.work.harness === 'pi' || editor.work.harness === 'deepseek_harness' || editor.work.harness === 'qoder_cli' || editor.work.harness === 'opencode') && <AgentProtocolChoice name={editor.display_name || text('任务路由', 'Task route')} language={language} value={editor.work.protocol} advice={workerProtocolAdvice(editor, options)} onChange={protocol => update({ work: { ...editor.work!, protocol } })} />}
{editor.work && <WorkerDependencies key={editor.work.harness} harness={editor.work.harness} language={language} active={active && moreSettingsOpen} onOperation={onOperation} />}
</div>}</section>
</Disclosure>
diff --git a/apps/desktop/src/ui/BrandIcon.tsx b/apps/desktop/src/ui/BrandIcon.tsx
index 8033b36f..c336d149 100644
--- a/apps/desktop/src/ui/BrandIcon.tsx
+++ b/apps/desktop/src/ui/BrandIcon.tsx
@@ -9,13 +9,14 @@ import pi from './assets/pi.svg';
import dsh from './assets/providers/deepseek.svg';
import hermes from './assets/hermes.svg';
-export type BrandKind = 'codex' | 'claude-code' | 'qoder' | 'pi' | 'dsh' | 'hermes' | 'agent' | 'model';
+export type BrandKind = 'codex' | 'claude-code' | 'qoder' | 'pi' | 'dsh' | 'hermes' | 'opencode' | 'agent' | 'model';
export function agentBrandFromId(agentId: string): BrandKind {
const normalized = agentId.toLowerCase();
if (normalized.includes('codex')) return 'codex';
if (normalized.includes('claude')) return 'claude-code';
if (normalized.includes('qoder')) return 'qoder';
+ if (normalized.includes('opencode')) return 'opencode';
if (normalized === 'agent_dsh_default') return 'dsh';
if (normalized === 'agent_pi_default') return 'pi';
if (normalized === 'agent_hermes_default') return 'hermes';
@@ -59,6 +60,15 @@ export function BrandIcon({
</span>;
}
+ if (kind === 'opencode') {
+ return <span className={classes} data-size={size} data-brand={kind} {...accessibility}>
+ <svg viewBox="0 0 16 20" fill="none" aria-hidden="true">
+ <path d="M12 16H4V8H12V16Z" fill="currentColor" opacity=".3" />
+ <path d="M12 4H4V16H12V4ZM16 20H0V0H16V20Z" fill="currentColor" />
+ </svg>
+ </span>;
+ }
+
return (
<span className={classes} data-size={size} data-brand={kind} {...accessibility}>
<svg viewBox="0 0 48 48" fill="none" aria-hidden="true">
diff --git a/apps/desktop/src/ui/assets/BRAND_ASSETS.md b/apps/desktop/src/ui/assets/BRAND_ASSETS.md
index 6811f46e..6f2d37bc 100644
--- a/apps/desktop/src/ui/assets/BRAND_ASSETS.md
+++ b/apps/desktop/src/ui/assets/BRAND_ASSETS.md
@@ -23,6 +23,12 @@ These assets identify third-party Agent integrations inside HiRoute. They do not
- SHA-256: `5e1843cb50c4613855024453e76d5c06d2ca5562efebc12b4fcd80cf9ece1dd0`.
- The SVG is copied without shape or color changes and appears beside the Qoder name to identify the integration. The mark belongs to Qoder and does not imply endorsement.
+## OpenCode
+
+- Artwork: the inline `Mark` in `BrandIcon.tsx`, from the official [OpenCode v1.19.3 logo component](https://github.com/anomalyco/opencode/blob/v1.19.3/packages/ui/src/components/logo.tsx).
+- The two path shapes and 16×20 proportions are preserved. Its neutral foreground and shadow follow the active HiRoute theme, with clear space inside the existing avatar.
+- Use the mark beside the accurate OpenCode name to identify the integration. OpenCode owns the mark; this use does not imply endorsement.
+
## Hermes
- File: `hermes.svg`
diff --git a/apps/desktop/tests/agent-discovery.test.mjs b/apps/desktop/tests/agent-discovery.test.mjs
index 1cf2c550..ec8120c4 100644
--- a/apps/desktop/tests/agent-discovery.test.mjs
+++ b/apps/desktop/tests/agent-discovery.test.mjs
@@ -10,7 +10,9 @@ test('custom targets survive a new reader but confer no discovered context or wr
assert.equal(saveAgentDiscoveryTargets([target], storage), true);
assert.deepEqual(loadAgentDiscoveryTargets(storage), [target]);
const rows = agentPageEntries([]);
- assert.equal(rows.length, 6);
+ assert.equal(rows.length, 7);
+ assert.ok(rows.some(row => row.agent_id === "agent_opencode_default"));
+ assert.ok(rows.some(row => row.agent_id === "agent_hermes_default"));
for (const row of rows) {
assert.equal(agentDiscoveryState(row), 'not_discovered');
assert.equal(row.context_id, null); assert.equal(row.settings, null);
diff --git a/apps/desktop/tests/agent-status.test.mjs b/apps/desktop/tests/agent-status.test.mjs
index 14e52d55..2337edee 100644
--- a/apps/desktop/tests/agent-status.test.mjs
+++ b/apps/desktop/tests/agent-status.test.mjs
@@ -49,7 +49,7 @@ test('Agent presentation follows configuration and recovery rather than model ve
import { agentModelPlanIds } from '../src/features/agents/status.ts';
test('plan usage covers every typed model selection and excludes restored connections', () => {
- for (const mode of ['qoder_additional', 'pi_additional', 'dsh_additional']) {
+ for (const mode of ['qoder_additional', 'pi_additional', 'dsh_additional', 'opencode_additional']) {
assert.deepEqual(agentModelPlanIds({ mode, allowed_plan_ids: ['plan/free', 'plan/free'] }), ['plan/free']);
}
assert.deepEqual(agentModelPlanIds({ mode: 'codex_default', allowed_plan_ids: ['plan/free'], default_selection: { kind: 'plan', plan_id: 'plan/default' } }), ['plan/free', 'plan/default']);
diff --git a/apps/desktop/tests/plan-editor-errors.test.mjs b/apps/desktop/tests/plan-editor-errors.test.mjs
index 3d118732..bb53c3a0 100644
--- a/apps/desktop/tests/plan-editor-errors.test.mjs
+++ b/apps/desktop/tests/plan-editor-errors.test.mjs
@@ -9,14 +9,14 @@ test('backend envelope is decoded without exposing payloads or stack traces', ()
});
test('all live consumers and both capacity dimensions are shown without native payloads', () => {
const blocker = (kind, context) => ({ agent_kind: kind, context_id: `agent-context/${context}/sha256:abc`, plan_id: 'plan/free', model_alias: 'free.plan', reason: 'capacity_reduced', declared: { context_window_tokens: 262144, max_output_tokens: 235929 }, proposed: { context_window_tokens: 262144, max_output_tokens: 131072 } });
- const conflict = { schema: 'hiroute.agent-model-budget-conflict/v1', blockers: [blocker('pi', 'pi'), blocker('deepseek_harness', 'dsh')] };
+ const conflict = { schema: 'hiroute.agent-model-budget-conflict/v1', blockers: [blocker('pi', 'pi'), blocker('deepseek_harness', 'dsh'), blocker('opencode', 'opencode')] };
const error = { envelope: { error: { code: 'REVISION_CONFLICT', details: 'private-native-config', model_budget_conflict: conflict } } };
assert.equal(planErrorCode(error), 'AGENT_MODEL_BUDGET_CONFLICT');
const message = planErrorMessage(error, 'zh');
- assert.match(message, /Pi「free.plan」.*最大输出 235,929 → 131,072.*DeepSeek Harness「free.plan」/);
+ assert.match(message, /Pi「free.plan」.*最大输出 235,929 → 131,072.*DeepSeek Harness「free.plan」.*OpenCode「free.plan」/);
assert.doesNotMatch(message, /Qoder|private-native-config|上下文 262/);
assert.match(message, /取消接入受影响计划.*任务协作无需停用.*输入已保留/);
- assert.match(planErrorMessage({ safe_error_code: 'AGENT_MODEL_BUDGET_CONFLICT', model_budget_conflict: conflict }, 'en'), /Pi.*max output.*DeepSeek Harness/);
+ assert.match(planErrorMessage({ safe_error_code: 'AGENT_MODEL_BUDGET_CONFLICT', model_budget_conflict: conflict }, 'en'), /Pi.*max output.*DeepSeek Harness.*OpenCode/);
const contextOnly = { ...conflict, blockers: [{ ...blocker('qoder', 'qoder'), proposed: { context_window_tokens: 32000, max_output_tokens: 235929 } }] };
assert.match(planErrorMessage({ code: 'QODER_MODEL_BUDGET_CONFLICT', model_budget_conflict: contextOnly }, 'zh'), /Qoder.*上下文 262,144 → 32,000/);
for (const reason of ['plan_missing', 'budget_unavailable']) {
diff --git a/apps/desktop/tests/trial-mapping.test.mjs b/apps/desktop/tests/trial-mapping.test.mjs
index 87245784..3092330b 100644
--- a/apps/desktop/tests/trial-mapping.test.mjs
+++ b/apps/desktop/tests/trial-mapping.test.mjs
@@ -4,6 +4,14 @@ import { currentPrimary, trialMappingValues, initialTrialMapping } from '../src/
import { agentEditorSeed, editorFingerprint } from '../src/features/agents/editor-state.ts';
const native = { agent_id:'agent_claude_default', context_id:'claude/context', status_error:null, settings:{state:'not_configured'} };
const configured = { ...native, settings:{state:'configured',current_selection:{mode:'claude_launcher',surfaces:['claude_cli'],fixed_models:[],preset_mappings:{opus:{kind:'plan',plan_id:'primary'},sonnet:{kind:'plan',plan_id:'separate'},haiku:{kind:'preserve_native'}}}} };
+for(const ecosystem of ['dsh','pi','qoder','opencode']) test(`${ecosystem} trial appends its route while retaining existing protocols`,()=>{
+ const agent={...native,agent_id:`agent_${ecosystem}_default`,context_id:`${ecosystem}/context`,settings:{state:'configured',current_selection:{mode:`${ecosystem}_additional`,allowed_plan_ids:['original'],plan_protocols:{original:'messages'}}}};
+ const before=structuredClone(agent);
+ const values=trialMappingValues(agent,'trial',{agentId:agent.agent_id,presets:[]});
+ assert.deepEqual(values.allowedPlanIds,['original','trial']);
+ assert.deepEqual(values.planProtocols,{original:'messages',trial:'responses'});
+ assert.deepEqual(agent,before);
+});
test('first Claude trial maps only the explicitly selected Opus preset',()=>{
const values=trialMappingValues(native,'trial',{agentId:native.agent_id,presets:['opus']});
assert.deepEqual(values.claudePresets,{opus:{kind:'plan',plan_id:'trial'},sonnet:{kind:'preserve_native'},haiku:{kind:'preserve_native'}});
diff --git a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs
index d285b9a4..beeecebf 100644
--- a/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/agent-trust-scenarios.mjs
@@ -74,14 +74,14 @@ const scenarios = [
agent.context_id = null; agent.settings = null; agent.status_error = 'AGENT_STATUS_UNAVAILABLE'; agent.configuration_state = 'profile_unavailable';
c().refresh(); await tick();
await until(() => document.querySelector('[data-agent-discovery="unavailable"]'), 'Unreadable default profile');
- assert(rows().length === 1 && document.querySelectorAll('.native-list .list-row').length === c().agents.agents.length, 'An unreadable profile hid or duplicated Agents');
+ assert(rows().length === 1 && document.querySelectorAll('.native-list .list-row').length === 7, 'An unreadable profile hid or duplicated Agents');
assert(facet('model').disabled && !document.querySelector('[data-hermes-select-root]').disabled, 'Unreadable profile has settings authority or cannot change directory');
}),
scenario('hermes.discovery.parallel-entry', ['hermes', 'agent-discovery'], 'Hermes remains alongside other Agents and selects its profile from details without writes', async () => {
c().reset(); await tick();
const hermesRows = () => [...document.querySelectorAll('.native-list .list-row')].filter(row => row.textContent.includes('Hermes'));
await until(() => hermesRows().length === 1, 'Unscoped Hermes list row');
- assert(document.querySelectorAll('.native-list .list-row').length === c().agents.agents.length + 1, 'Existing Agent entries changed');
+ assert(document.querySelectorAll('.native-list .list-row').length === 7, 'Existing Agent entries changed');
assert(!document.querySelector('[data-hermes-select-root]'), 'Hermes directory control leaked into another Agent');
assert(![...document.querySelectorAll('button')].some(button => button.textContent === '选择 Hermes 配置目录'), 'Hermes has a page-level directory entry');
hermesRows()[0].click();
@@ -140,7 +140,7 @@ const scenarios = [
await until(() => calls('agent_snapshot').at(-1)?.payload.nativeTargets?.length === 1, 'Remembered target reread');
[...document.querySelectorAll('.native-list .list-row')].find(row => row.textContent.includes('Hermes')).click();
await until(() => document.querySelector('[data-agent-discovery="unavailable"]'), 'Unavailable retained profile');
- assert(document.querySelectorAll('.native-list .list-row').length === 6, 'One failed target hid another Agent');
+ assert(document.querySelectorAll('.native-list .list-row').length === 7, 'One failed target hid another Agent');
assert(document.querySelector('[data-hermes-profile]').textContent.includes('/tmp/hermes-profile-fixture'), 'Failed read lost the selected root');
assert(facet('model').disabled && facet('management_skill').disabled && facet('collaboration').disabled, 'A preference became settings authority');
assert(configureSpecs().length === 0 && calls('check_agent_live').length === 0, 'Discovery wrote settings or called a model');
@@ -777,6 +777,31 @@ const scenarios = [
assert(!c().commands.some(({ command }) => /subscription|discovered_model|model_catalog/.test(command)), 'Additional routing opened model discovery or import');
assert(calls('check_agent_live').length === 0, 'Saving routes implicitly invoked a model');
}),
+ scenario('opencode.routing.additional-plans', ['opencode'], 'OpenCode adds selected routes without replacing native models or applying a cancelled draft', async () => {
+ c().reset(); c().agents = c().opencodeFresh(); c().agents.plans = c().registered().plans; await tick();
+ await until(() => facet('model'), 'OpenCode optional model routing');
+ assert(document.querySelector('[data-agent-id="agent_opencode_default"] .detail-hero [data-brand="opencode"] svg'), 'OpenCode details are missing their official mark');
+ assert(document.querySelector('.native-list [data-brand="opencode"] svg'), 'OpenCode list is missing its official mark');
+ await openEditor('model');
+ const pick = () => [...dialog().querySelectorAll('[data-agent-plan-id] input')].slice(0, 2).forEach(input => input.click());
+ pick(); await tick();
+ assert(dialog().textContent.includes('当前默认模型保持不变') && dialog().textContent.includes('模型选择器'), 'Additional routing does not explain native preservation and selection');
+ assert(!dialog().querySelector('[data-agent-default], [data-client-model-id], [data-agent-fixed-models]'), 'OpenCode borrowed native model, source or default controls');
+ assert(dialog().querySelectorAll('[data-plan-protocol] select').length === 2, 'Each selected route needs its own protocol choice');
+ [...dialog().querySelectorAll('button')].find(button => button.textContent === '取消').click(); await tick();
+ assert(configureSpecs().length === 0 && !dialog(), 'Cancelling OpenCode model draft changed configuration');
+ await openEditor('model'); pick(); await tick();
+ const selected = [...dialog().querySelectorAll('[data-agent-plan-id]')].filter(row => row.querySelector('input').checked).map(row => row.dataset.agentPlanId);
+ changeSelect(dialog().querySelector(`[data-agent-plan-id="${selected[1]}"] [data-plan-protocol] select`), 'messages');
+ await tick();
+ await save();
+ const spec = configureSpecs().at(-1);
+ assert(JSON.stringify(spec.model.settings) === JSON.stringify({ mode: 'opencode_additional', allowed_plan_ids: selected,
+ plan_protocols: { [selected[0]]: 'responses', [selected[1]]: 'messages' } }), 'OpenCode changed the ecosystem, selected routes or their independent protocols');
+ assert(spec.collaboration.intent === 'keep' && !spec.restore_native_model, 'Model save changed collaboration or a native default');
+ assert(!c().commands.some(({ command }) => /subscription|discovered_model|model_catalog/.test(command)), 'Additional routing opened model discovery or import');
+ assert(calls('check_agent_live').length === 0, 'Saving routes implicitly invoked a model');
+ }),
scenario('qoder.routing.adjust-and-restore', ['qoder', 'qoder-model-routing'], 'Qoder repairs selected routes, rotates their token and restores each facet independently', async () => {
c().reset(); c().agents = c().qoderRouted();
const unavailablePlan = c().agents.agents[0].settings.current_selection.allowed_plan_ids[1];
@@ -827,7 +852,7 @@ const scenarios = [
await until(() => configureSpecs().some(spec => spec.collaboration.intent === 'restore'), 'independent collaboration restore');
assert(configureSpecs().at(-1).model.intent === 'keep' && agent.settings.current_selection.mode === 'qoder_additional', 'Collaboration restore removed model routes');
}),
- ...['pi', 'dsh'].map(ecosystem => scenario(`${ecosystem}.routing.default-in-use`, ['agent-recovery'], `${ecosystem} preserves a route used by its native default and directs recovery to the selected client`, async () => {
+ ...['pi', 'dsh', 'opencode'].map(ecosystem => scenario(`${ecosystem}.routing.default-in-use`, ['agent-recovery'], `${ecosystem} preserves a route used by its native default and directs recovery to the selected client`, async () => {
c().reset(); c().agents = c().additionalRouted(ecosystem); await tick();
await until(() => facet('model')?.textContent === '调整' && !facet('model').disabled, 'additional model routing');
const agent = c().agents.agents[0];
diff --git a/apps/desktop/tests/v3/browser/agent-trust.tsx b/apps/desktop/tests/v3/browser/agent-trust.tsx
index 84ce6801..725ee56f 100644
--- a/apps/desktop/tests/v3/browser/agent-trust.tsx
+++ b/apps/desktop/tests/v3/browser/agent-trust.tsx
@@ -130,7 +130,7 @@ function splitCodexStatus(): AgentSnapshot {
return snapshot;
}
-function additionalAgent(configured: boolean, ecosystem: 'qoder' | 'pi' | 'dsh' = 'qoder'): AgentSnapshot {
+function additionalAgent(configured: boolean, ecosystem: 'qoder' | 'pi' | 'dsh' | 'opencode' = 'qoder'): AgentSnapshot {
const context = `agent-context/${ecosystem}/sha256:${'a'.repeat(64)}`;
return {
trusted_authority: true, plans: { plans: [] },
@@ -150,7 +150,7 @@ function additionalAgent(configured: boolean, ecosystem: 'qoder' | 'pi' | 'dsh'
};
}
-function additionalRouted(ecosystem: 'qoder' | 'pi' | 'dsh' = 'qoder'): AgentSnapshot {
+function additionalRouted(ecosystem: 'qoder' | 'pi' | 'dsh' | 'opencode' = 'qoder'): AgentSnapshot {
const snapshot = additionalAgent(true, ecosystem);
snapshot.plans = structuredClone(readyAgents.plans);
const agent = modelAgent(snapshot, `agent_${ecosystem}_default`);
@@ -188,6 +188,7 @@ const control = {
qoderConfigured: () => additionalAgent(true),
qoderRouted: () => additionalRouted(),
additionalRouted,
+ opencodeFresh:()=>additionalAgent(false,"opencode"),
hermesFresh: () => hermesAgent(),
hermesConfigured: () => hermesAgent(true),
};
diff --git a/apps/desktop/tests/v3/browser/product-fixtures.ts b/apps/desktop/tests/v3/browser/product-fixtures.ts
index 47f0c902..adc7fd3a 100644
--- a/apps/desktop/tests/v3/browser/product-fixtures.ts
+++ b/apps/desktop/tests/v3/browser/product-fixtures.ts
@@ -577,14 +577,15 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
continue_session: { state: 'unavailable', reason: 'resume_unavailable' },
restricted_policy: { state: 'unknown', reason: 'restricted_policy_unverified' },
},
- { harness: 'qoder_cli', state: 'unavailable', reason: workerSelections.has('qoder_cli') ? 'runtime_unverified' : 'installation_not_configured', start_approve_all: unavailable, cancel: unavailable, continue_session: unavailable, restricted_policy: unavailable },
+ ...['qoder_cli', 'deepseek_harness', 'opencode'].map(harness => ({ harness, state: 'unavailable', reason: workerSelections.has(harness) ? 'runtime_unverified' : 'installation_not_configured', start_approve_all: unavailable, cancel: unavailable, continue_session: unavailable, restricted_policy: unavailable })),
],
};
}
if (command === 'worker_dependencies_discover' || command === 'worker_dependencies_select_confirm') {
const confirmed = command === 'worker_dependencies_select_confirm' ? preparedWorkerSelection : null;
const harness = confirmed?.harness ?? payload?.input?.harness ?? 'claude_code';
- const name = harness === 'codex_cli' ? 'codex' : harness === 'qoder_cli' ? 'qoder' : 'claude';
+ const name = harness === 'codex_cli' ? 'codex' : harness === 'qoder_cli' ? 'qoder' : harness === 'opencode' ? 'opencode' : 'claude';
+ const native = harness === 'qoder_cli' || harness === 'opencode';
if (confirmed) {
const { expected_selection_revision: _revision, ...installation } = confirmed;
workerSelections.set(harness, installation);
@@ -593,7 +594,7 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
const selection = selected ?? {
harness,
cli_path: `/usr/local/bin/${name}`,
- ...(harness === 'qoder_cli' ? {} : {
+ ...(native ? {} : {
adapter_path: `/usr/local/lib/${name}-acp/adapter.js`,
node_path: '/usr/local/bin/node',
}),
@@ -601,10 +602,10 @@ export function mockProductInvoke(command: string, payload: Record<string, any>
const data = {
schema: 'hiroute.worker-dependencies-view/v1',
selection_revisions: [{ harness, revision: 1 }],
- selected: harness === 'qoder_cli' && !selected ? [] : [selection],
+ selected: native && !selected ? [] : [selection],
candidates: [
{ harness, component: 'cli', path: selection.cli_path, source: 'selected', state: 'found' },
- ...(harness === 'qoder_cli' ? [] : [
+ ...(native ? [] : [
{ harness, component: 'adapter', path: selection.adapter_path, source: 'selected', state: 'found' },
{ harness, component: 'node', path: selection.node_path, source: 'selected', state: 'found' },
]),
diff --git a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
index 72535520..0fc4ec27 100644
--- a/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/product-shell-scenarios.mjs
@@ -901,24 +901,25 @@ const scenarios = [
assert(contextWindow.value === '32000' && !contextWindow.disabled && !button('发布更改').disabled, 'Checkpoint failure discarded or locked the local edit');
assert(calls('preview_agent_settings').length === 0 && calls('check_agent_live').length === 0, 'Checkpoint failure implicitly changed an Agent connection or called a model');
}),
- scenario('desktop.routing.additional-budget-consumers', ['routing-editor', 'pi', 'dsh'], 'Both admission and checkpoint failures identify Pi/DSH and keep the route draft', async () => {
+ scenario('desktop.routing.additional-budget-consumers', ['routing-editor', 'pi', 'dsh', 'opencode'], 'Both admission and checkpoint failures identify installed additional consumers and keep the route draft', async () => {
for (const checkpoint of [false, true]) {
await fresh(() => {
const plan = c().desktop.catalog.plans[0];
const base = c().agents.agents[0];
- for (const [id, mode] of [['agent_pi_default', 'pi_additional'], ['agent_dsh_default', 'dsh_additional']]) {
+ for (const [id, mode] of [['agent_pi_default', 'pi_additional'], ['agent_dsh_default', 'dsh_additional'], ['agent_opencode_default', 'opencode_additional']]) {
c().agents.agents.push({ ...base, agent_id: id, context_id: `agent-context/${mode}/sha256:abc`, settings: { ...base.settings, current_selection: { mode, allowed_plan_ids: [plan.agent_plan_id] } } });
}
const conflict = { schema: 'hiroute.agent-model-budget-conflict/v1', blockers: [
{ agent_kind: 'pi', context_id: 'agent-context/pi/sha256:abc', plan_id: plan.agent_plan_id, model_alias: plan.model_alias, reason: 'capacity_reduced', declared: { context_window_tokens: 262144, max_output_tokens: 235929 }, proposed: { context_window_tokens: 262144, max_output_tokens: 131072 } },
{ agent_kind: 'deepseek_harness', context_id: 'agent-context/dsh/sha256:abc', plan_id: plan.agent_plan_id, model_alias: plan.model_alias, reason: 'capacity_reduced', declared: { context_window_tokens: 262144, max_output_tokens: 235929 }, proposed: { context_window_tokens: 262144, max_output_tokens: 131072 } },
+ { agent_kind: 'opencode', context_id: 'agent-context/opencode/sha256:abc', plan_id: plan.agent_plan_id, model_alias: plan.model_alias, reason: 'capacity_reduced', declared: { context_window_tokens: 262144, max_output_tokens: 235929 }, proposed: { context_window_tokens: 262144, max_output_tokens: 131072 } },
] };
c().handlers.preview_plan_editor = checkpoint ? () => ({ state: 'applied', operation: operation() }) : () => { throw { source: 'backend', envelope: { error: { code: 'REVISION_CONFLICT', model_budget_conflict: conflict } } }; };
c().handlers.observe_operation = () => ({ ...operation('rolled_back'), sequence: 2, safe_error_code: 'AGENT_MODEL_BUDGET_CONFLICT', model_budget_conflict: conflict });
});
await routing();
const usage = document.querySelector('.plan-editor .agent-card-list');
- assert(usage?.textContent.includes('Pi') && usage.textContent.includes('DeepSeek Harness') && !usage.textContent.includes('Qoder'), 'Where it is used omits the actual Pi/DSH connections or includes an unrelated Qoder');
+ assert(usage?.textContent.includes('Pi') && usage.textContent.includes('DeepSeek Harness') && usage.textContent.includes('OpenCode') && !usage.textContent.includes('Qoder'), 'Where it is used omits an installed additional consumer or includes an unrelated Qoder');
const name = document.querySelector('.plan-identity-fields input');
const draftName = 'Budget retained draft with a long route name';
setInput(name, draftName);
@@ -930,7 +931,7 @@ const scenarios = [
await click('发布更改');
await until(() => (checkpoint ? feedback() : document.querySelector('.plan-editor [role="alert"]'))?.textContent.includes('最大输出 235,929 → 131,072'), 'typed output-budget rejection');
const message = (checkpoint ? feedback() : document.querySelector('.plan-editor [role="alert"]')).textContent;
- assert(message.includes('Pi') && message.includes('DeepSeek Harness') && !message.includes('Qoder') && message.includes('任务协作无需停用'), 'Recovery guidance misattributes the constraint');
+ assert(message.includes('Pi') && message.includes('DeepSeek Harness') && message.includes('OpenCode') && !message.includes('Qoder') && message.includes('任务协作无需停用'), 'Recovery guidance misattributes the constraint');
assert(name.value === draftName && !name.disabled && !button('发布更改').disabled, 'Budget rejection discarded or locked the draft');
assert(calls('preview_agent_settings').length === 0 && calls('check_agent_live').length === 0, 'Budget rejection implicitly changed native routes or called a model');
}
diff --git a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
index 8d14b1e5..edb7574b 100644
--- a/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
+++ b/apps/desktop/tests/v3/browser/routing-worker-scenarios.mjs
@@ -125,12 +125,12 @@ const scenarios = [
assert(cli && !document.querySelector('#worker-qoder_cli-adapter') && !document.querySelector('#worker-qoder_cli-node'), 'Qoder did not render exactly its one CLI input');
assert(!document.querySelector('.worker-dependencies').textContent.includes('Node.js'), 'Qoder advertised an unnecessary runtime');
assert(document.querySelector('[data-qoder-installation-guide] a').href === 'https://docs.qoder.com/cli/installation', 'Official installation guidance is missing');
- setInput(cli, '/home/fixture/.local/bin/qodercli'); await tick();
+ setInput(cli, '/opt/hiroute-fixtures/bin/qodercli'); await tick();
assert(!button('使用此安装').disabled, 'A standalone Qoder CLI required adapter placeholders');
button('使用此安装').click();
await until(() => document.querySelector('.worker-dependencies .badge.good'), 'Qoder selection persisted');
const request = trace().requests.find(item => item.command === 'worker_dependencies_select_prepare').payload.input;
- assert(request.harness === 'qoder_cli' && request.cli_path === '/home/fixture/.local/bin/qodercli', 'The selected CLI did not cross the public boundary');
+ assert(request.harness === 'qoder_cli' && request.cli_path === '/opt/hiroute-fixtures/bin/qodercli', 'The selected CLI did not cross the public boundary');
assert(!('adapter_path' in request) && !('node_path' in request), 'Qoder request did not omit unsupported components');
assert(calls('worker_dependencies_select_prepare') === 1 && calls('worker_dependencies_select_confirm') === 1, 'One click did not commit exactly once');
containingButton('Claude Code').click();
@@ -142,6 +142,42 @@ const scenarios = [
button('更换或高级设置').click(); await tick();
assert(document.querySelector('#worker-qoder_cli-cli')?.value === request.cli_path, 'Switching away lost the Qoder installation');
}),
+ scenario('opencode.installation.single-cli', ['opencode'], 'OpenCode saves one CLI and switching execution Agents retains their independent installations', async () => {
+ if (!document.querySelector('#worker-claude_code-cli')) {
+ containingButton('Claude Code').click();
+ await until(() => button('更换或高级设置'), 'Claude installation before switching');
+ button('更换或高级设置').click(); await tick();
+ }
+ const previousClaude = document.querySelector('#worker-claude_code-cli').value;
+ trace().commands.length = 0; trace().requests.length = 0;
+ containingButton('OpenCode').click();
+ await until(() => button('一键检测'), 'OpenCode detection action');
+ assert(document.querySelector('.v3-executor.selected [data-brand="opencode"] svg'), 'OpenCode executor is missing its official mark');
+ assert(calls('worker_dependencies_select_prepare') === 0, 'Choosing OpenCode saved an installation implicitly');
+ button('一键检测').click();
+ await until(() => button('使用此安装'), 'single CLI recommendation');
+ button('高级设置').click(); await tick();
+ const cli = document.querySelector('#worker-opencode-cli');
+ assert(cli && !document.querySelector('#worker-opencode-adapter') && !document.querySelector('#worker-opencode-node'), 'OpenCode did not render exactly its one CLI input');
+ assert(!document.querySelector('.worker-dependencies').textContent.includes('Node.js'), 'OpenCode advertised an unnecessary runtime');
+ assert(document.querySelector('[data-opencode-installation-guide]')?.textContent.includes('1.19.3'),'OpenCode supported installation is not explained');
+ setInput(cli, '/opt/hiroute-fixtures/bin/opencode'); await tick();
+ assert(!button('使用此安装').disabled, 'A standalone OpenCode required adapter placeholders');
+ button('使用此安装').click();
+ await until(() => document.querySelector('.worker-dependencies .badge.good'), 'OpenCode selection persisted');
+ const request = trace().requests.find(item => item.command === 'worker_dependencies_select_prepare').payload.input;
+ assert(request.harness === 'opencode' && request.cli_path === '/opt/hiroute-fixtures/bin/opencode', 'The selected CLI did not cross the public boundary');
+ assert(!('adapter_path' in request) && !('node_path' in request), 'OpenCode request did not omit unsupported components');
+ assert(calls('worker_dependencies_select_prepare') === 1 && calls('worker_dependencies_select_confirm') === 1, 'One click did not commit exactly once');
+ containingButton('Claude Code').click();
+ await until(() => button('更换或高级设置'), 'existing Claude installation');
+ button('更换或高级设置').click(); await tick();
+ assert(document.querySelector('#worker-claude_code-cli')?.value === previousClaude, 'OpenCode replaced the previously saved Claude installation');
+ containingButton('OpenCode').click();
+ await until(() => button('更换或高级设置'), 'saved OpenCode installation');
+ button('更换或高级设置').click(); await tick();
+ assert(document.querySelector('#worker-opencode-cli')?.value === request.cli_path, 'Switching away lost the OpenCode installation');
+ }),
...[['pi', 'Pi'], ['qoder_cli', 'Qoder CLI']].map(([harness, title]) =>
scenario(`routing.protocol.${harness.replace("_cli", "")}-reselection`, ['route-save'], `${title} retains an explicit protocol when reselected and saved`, async () => {
const executor = () => [...document.querySelectorAll('.v3-executor')].find(node => node.querySelector('strong')?.textContent === title);
diff --git a/apps/desktop/tests/v3/browser/scenario-requirements.mjs b/apps/desktop/tests/v3/browser/scenario-requirements.mjs
index 1a5df5b8..19451e48 100644
--- a/apps/desktop/tests/v3/browser/scenario-requirements.mjs
+++ b/apps/desktop/tests/v3/browser/scenario-requirements.mjs
@@ -36,6 +36,8 @@ export const agentTrustRequired = ['codex.restore.conflict-active',
'qoder.routing.resume-pending',
'pi.routing.default-in-use',
'dsh.routing.default-in-use',
+ 'opencode.routing.default-in-use',
+ 'opencode.routing.additional-plans',
'agent.diagnostics.configuration-state',
'codex.routing.unproven-native-model'];
@@ -45,6 +47,7 @@ export const routingWorkerRequired = ['routing.capabilities.candidate-vs-fixed',
'worker.installation.replace',
'worker.installation.latest-edit',
'qoder.installation.single-cli',
+ 'opencode.installation.single-cli',
'routing.protocol.pi-reselection',
'routing.protocol.qoder-reselection',
'routing.save.unobserved-editable',
diff --git a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs b/apps/desktop/tests/v3/visual/new-model-trial-active.mjs
index 1f535b63..fec0f219 100644
--- a/apps/desktop/tests/v3/visual/new-model-trial-active.mjs
+++ b/apps/desktop/tests/v3/visual/new-model-trial-active.mjs
@@ -290,6 +290,17 @@ try {
assert.equal(await evaluate(client,`divisionDraft.delegation_enabled&&divisionDraft.work.harness==='deepseek_harness'&&divisionDraft.branch_routing.branches.every(b=>b.primary_candidates.length===0&&b.candidates[0].binding_id==='binding/bailian/qwen-coder')`),true);
assert.equal(await evaluate(client,`trialTrace.filter(x=>x.command==='preview_plan_editor').length`),0);
await shot('division-worker-en-755');results.push({id:'division.optional-primary-and-explicit-executor.no-publication',status:'passed'});
+ for(const [lang,theme,width,height] of [['en','light',755,600],['zh','dark',755,600],['en','dark',1200,813],['zh','light',1200,813]]) {
+ await open(`lang=${lang}&theme=${theme}&view=editor&division=1`,width,height);
+ await click('[role="tab"]',lang==='zh'?'模型表现':'Model performance');await waitFor(client,`!!document.querySelector('.trust-suggestion.cyan')`);await click('.trust-suggestion button',lang==='zh'?'查看分工草稿':'Review division draft');
+ await click('[role="dialog"] button',lang==='zh'?'委派给执行 Agent':'Delegate to an agent');await waitFor(client,`!!document.querySelector('.division-executors')`);
+ await evaluate(client,`[...document.querySelectorAll('.division-executors label')].find(e=>e.textContent.includes('OpenCode')).querySelector('input').click();true`);await click('[role="dialog"] button',lang==='zh'?'在编辑器中查看草稿':'Review draft in editor');
+ await waitFor(client,`window.divisionDraft?.delegation_enabled&&divisionDraft.work?.harness==='opencode'&&divisionDraft.work.protocol==='responses'&&divisionDraft.branch_routing.branches.every(b=>b.primary_candidates.length===0&&b.candidates[0].binding_id==='binding/bailian/qwen-coder')`);
+ assert.equal(await evaluate(client,`trialTrace.filter(x=>x.command==='preview_plan_editor').length`),0);
+ await evaluate(client,`[...document.querySelectorAll('.division-executors label')].find(e=>e.textContent.includes('OpenCode')).scrollIntoView({block:'center'});true`);
+ assert.ok(await evaluate(client,`(()=>{const label=[...document.querySelectorAll('.division-executors label')].find(e=>e.textContent.includes('OpenCode')).getBoundingClientRect(),buttons=[...document.querySelectorAll('[role="dialog"] button')].filter(e=>e.textContent.includes(${JSON.stringify(lang==='zh'?'在编辑器中查看草稿':'Review draft in editor')}));return document.documentElement.scrollWidth<=innerWidth+1&&label.top>=0&&buttons.every(e=>{const b=e.getBoundingClientRect();return label.bottom<=b.top&&b.bottom<=innerHeight;})&&[...document.querySelectorAll('.division-executors label')].every(e=>e.scrollWidth<=e.clientWidth+1);})()`));
+ await shot(`division-opencode-${lang}-${theme}-${width}`);results.push({id:`division.opencode-explicit-executor.no-publication.${lang}.${theme}.${width}`,status:'passed'});
+ }
await open('lang=zh&view=attention&theme=dark');await shot('attention-zh-dark-755');await click('.trust-attention .btn-primary','打开调整草稿');assert.equal(await evaluate(client,`trialTrace.filter(x=>x.command==='review-trust-action').length`),1);await click('.trust-attention button','查看依据');assert.equal(await evaluate(client,`trialTrace.filter(x=>x.command==='review-trust').length`),1);results.push({id:'attention.optional-evidence-review',status:'passed'});
await open('lang=en&view=attention&empty=1');assert.ok(await evaluate(client,`document.querySelector('.trust-attention').textContent.includes('No routing adjustments are suggested')`));assert.equal(await evaluate(client,`document.querySelectorAll('.trust-attention button').length`),0);results.push({id:'attention.empty-is-normal',status:'passed'});
await open('lang=en&view=attention&error=1');assert.ok(await evaluate(client,`document.querySelector('.trust-attention [role=alert]').textContent.includes('retry before deciding')`));assert.equal(await evaluate(client,`[...document.querySelectorAll('.trust-attention button')].find(e=>e.textContent.includes('View evidence')).disabled`),true);await click('button','Retry');assert.equal(await evaluate(client,`trialTrace.filter(x=>x.command==='retry-suggestions').length`),1);results.push({id:'attention.failed-read-is-not-empty',status:'passed'});
diff --git a/apps/desktop/tests/worker-dependencies-state.test.mjs b/apps/desktop/tests/worker-dependencies-state.test.mjs
index 6e103003..a168c130 100644
--- a/apps/desktop/tests/worker-dependencies-state.test.mjs
+++ b/apps/desktop/tests/worker-dependencies-state.test.mjs
@@ -37,7 +37,7 @@ test('detection recommends but never invents a persisted selection', () => {
assert.deepEqual(detected.selected, []);
});
-for (const native of ['qoder_cli','deepseek_harness']) test(`${native} recommends and recognizes a saved native CLI without adapter or Node fields`, () => {
+for (const native of ['qoder_cli','deepseek_harness','opencode']) test(`${native} recommends and recognizes a saved native CLI without adapter or Node fields`, () => {
const selected = { harness: native, cli_path: '/bin/qodercli' };
const detected = view({
selection_revisions: [{ harness: native, revision: 7 }],
@@ -58,7 +58,7 @@ for (const native of ['qoder_cli','deepseek_harness']) test(`${native} recommend
assert.equal(workerDependencySelectionState(saved, native), 'configured');
});
-for (const native of ['qoder_cli','deepseek_harness']) test(`a missing selected ${native} CLI stays incomplete and does not fall back to a discovered installation`, () => {
+for (const native of ['qoder_cli','deepseek_harness','opencode']) test(`a missing selected ${native} CLI stays incomplete and does not fall back to a discovered installation`, () => {
const selected = { harness: native, cli_path: '/old/qoder' };
const detected = view({
selection_revisions: [{ harness: native, revision: 7 }],
diff --git a/assets/agent-profiles/current/profile-seed.json b/assets/agent-profiles/current/profile-seed.json
index 46d3606f..df3945c1 100644
--- a/assets/agent-profiles/current/profile-seed.json
+++ b/assets/agent-profiles/current/profile-seed.json
@@ -1 +1 @@
-{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"dsh-responses-v1","integration_profile_ref":"builtin/dsh-responses/v1","kind":"deepseek_harness","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"hermes-main-v1","integration_profile_ref":"builtin/hermes-main/v1","kind":"hermes","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"default_model","path":"model.default","write_layer":"user"},{"field_id":"provider","path":"model.provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}
+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"dsh-responses-v1","integration_profile_ref":"builtin/dsh-responses/v1","kind":"deepseek_harness","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"hermes-main-v1","integration_profile_ref":"builtin/hermes-main/v1","kind":"hermes","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"default_model","path":"model.default","write_layer":"user"},{"field_id":"provider","path":"model.provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"opencode-responses-v1","integration_profile_ref":"builtin/opencode-responses/v1","kind":"opencode","ingress_protocol":"responses","config_precedence":["managed","process","local","project","launch","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}
diff --git a/assets/release-facts/current/bundle/agent-profiles.json b/assets/release-facts/current/bundle/agent-profiles.json
index 46d3606f..df3945c1 100644
--- a/assets/release-facts/current/bundle/agent-profiles.json
+++ b/assets/release-facts/current/bundle/agent-profiles.json
@@ -1 +1 @@
-{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"dsh-responses-v1","integration_profile_ref":"builtin/dsh-responses/v1","kind":"deepseek_harness","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"hermes-main-v1","integration_profile_ref":"builtin/hermes-main/v1","kind":"hermes","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"default_model","path":"model.default","write_layer":"user"},{"field_id":"provider","path":"model.provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}
+{"schema":"hiroute.agent-profiles-artifact/v1","tool_version":"hiroute-release-facts/2","profiles":[{"schema":"hiroute.agent-profile/v1","profile_id":"claude-messages-v1","integration_profile_ref":"builtin/claude-messages/v1","kind":"claude_code","ingress_protocol":"messages","config_precedence":["managed","process","launch","project","user"],"owned_config_fields":[{"field_id":"base_endpoint","path":"env.ANTHROPIC_BASE_URL","write_layer":"user"},{"field_id":"default_model","path":"env.ANTHROPIC_MODEL","write_layer":"user"},{"field_id":"default_opus_model","path":"env.ANTHROPIC_DEFAULT_OPUS_MODEL","write_layer":"user"},{"field_id":"default_sonnet_model","path":"env.ANTHROPIC_DEFAULT_SONNET_MODEL","write_layer":"user"},{"field_id":"default_haiku_model","path":"env.ANTHROPIC_DEFAULT_HAIKU_MODEL","write_layer":"user"},{"field_id":"small_fast_model","path":"env.ANTHROPIC_SMALL_FAST_MODEL","write_layer":"user"},{"field_id":"auth_helper","path":"apiKeyHelper","write_layer":"user"},{"field_id":"auth_environment","path":"hiroute.auth_environment","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false,"managed_launch":{"settings_argument":"--settings","environment_removals":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX"],"caller_forbidden_options":["--anthropic-api-key","--anthropic-auth-token","--api-key","--api-key-helper","--auth-token","--base-url","--bedrock","--custom-headers","--foundry","--provider","--use-bedrock","--use-foundry","--use-vertex","--vertex"]}},{"schema":"hiroute.agent-profile/v1","profile_id":"codex-responses-v1","integration_profile_ref":"builtin/codex-responses/v1","kind":"codex","ingress_protocol":"responses","config_precedence":["process","launch","project","user","managed"],"owned_config_fields":[{"field_id":"provider","path":"model_provider","write_layer":"user"},{"field_id":"default_model","path":"model","write_layer":"user"},{"field_id":"base_endpoint","path":"model_providers.hiroute.base_url","write_layer":"user"},{"field_id":"wire_api","path":"model_providers.hiroute.wire_api","write_layer":"user"},{"field_id":"static_catalog","path":"model_catalog_json","write_layer":"user"}],"dynamic_catalog":true,"static_catalog_fallback":true,"native_subagent_routing":true,"spawn_guidance":{"tool_name":"spawn_agent","registration_id":"codex.builtin.spawn-agent.v1","begin_marker":"Available model overrides (optional; inherited parent model is preferred):","end_marker":"Spawn arguments:","expected_shape_digest":"sha256:e6fa92a60065816802f1048589e335a116799757bb16a27346b4c18756df8fde"}},{"schema":"hiroute.agent-profile/v1","profile_id":"dsh-responses-v1","integration_profile_ref":"builtin/dsh-responses/v1","kind":"deepseek_harness","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"hermes-main-v1","integration_profile_ref":"builtin/hermes-main/v1","kind":"hermes","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"default_model","path":"model.default","write_layer":"user"},{"field_id":"provider","path":"model.provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"opencode-responses-v1","integration_profile_ref":"builtin/opencode-responses/v1","kind":"opencode","ingress_protocol":"responses","config_precedence":["managed","process","local","project","launch","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"pi-responses-v1","integration_profile_ref":"builtin/pi-responses/v1","kind":"pi","ingress_protocol":"responses","config_precedence":["process","launch","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false},{"schema":"hiroute.agent-profile/v1","profile_id":"qoder-collaboration-v1","integration_profile_ref":"builtin/qoder-collaboration/v1","kind":"qoder","ingress_protocol":"responses","config_precedence":["process","local","project","user"],"owned_config_fields":[{"field_id":"additional_provider","path":"hiroute.additional_provider","write_layer":"user"}],"dynamic_catalog":false,"static_catalog_fallback":false,"native_subagent_routing":false}]}
diff --git a/contracts/cli/agent-plan-catalog-query.v2.schema.json b/contracts/cli/agent-plan-catalog-query.v2.schema.json
index c3ed240e..0df76e6e 100644
--- a/contracts/cli/agent-plan-catalog-query.v2.schema.json
+++ b/contracts/cli/agent-plan-catalog-query.v2.schema.json
@@ -798,7 +798,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"protocol": {
diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.json
index 5ac6443c..183cfede 100644
--- a/contracts/cli/contract-set.v1.json
+++ b/contracts/cli/contract-set.v1.json
@@ -1,16 +1,16 @@
{
- "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c",
+ "descriptor_digest": "sha256:599207be26345edcb2ca69333ea50fb0580337aeff58ed0afe8f1fe5e0eca30e",
"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:dc13704e5e2ff4b71ace74cd23f2558c08f9c658bfdcde543eaada5f0bf96052",
+ "agent-plan-catalog-query.v2.schema.json": "sha256:3e9ccab78eca526fb8e9ef3786ed9cb7a0eba284b63a5f0fcfd5f8dc7ef39948",
"agent-scan-request.v1.schema.json": "sha256:2112519120417189cfea67dbc23bcbbeabd573073df6a167fa774a5a766c6653",
"compute-connection-options-request.v1.schema.json": "sha256:4bc609ffeac30f22dbccb34b907b778722fb45c44d7d8d501afb0b74bf8b58ba",
"compute-scan-request.union.schema.json": "sha256:0b3fa6c790441aab8dc5a2f8002490ffbd19530fc6e7fd251dead24565d31159",
"console-launch-request.v1.schema.json": "sha256:bb201709ef64e99036a97d5879a32a8e4e3a9517010e1041def223e723e7f385",
"console-token-create.v1.schema.json": "sha256:10cc9b80ed0bec4a5ca80e098cf0ee94710eedd7dfce292cf4a8770a11be78ec",
"console-token-revoke.v1.schema.json": "sha256:fbec29753f6effd3c854bff57984b3c3932ac5b6f2345e52151e353c15933b36",
- "coverage-manifest.v1.json": "sha256:b7d3228b8de570eea6c816727cc379c9ad577469de302ea8ab9735332415d23b",
+ "coverage-manifest.v1.json": "sha256:bce2390a05bb800151b46dd5f5328f793320bcf48c6f0592f3519b396bd947be",
"delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878",
"delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93",
"delegation-get-request.v1.schema.json": "sha256:85b29839c1c508018ebe40e4b2bb5c1dce7c3a87c27efa30b196b2d1b6658471",
@@ -23,8 +23,8 @@
"historical-applicability-test.v1.schema.json": "sha256:be6def82922150897e39787c114745201ce43df3b157e475781ca62b73ca82ca",
"local-control-hello.v2.schema.json": "sha256:32fbce882152a886b79bd139d3b4e459b48d94e0634e56ccb189b2c9971ad772",
"local-control.v2.schema.json": "sha256:4b654de90cd6e333b3953379e5b2e1c5125f1dcbe307b7c7c73f12bb2032d18c",
- "machine-envelope.v2.schema.json": "sha256:23e019a3d024ae302a44105caff4ec95d3fb409a29f936dea1360e543ae6abd6",
- "manifest.v1.json": "sha256:eafe60bd52aa71ddc75f99fe7cb272486fdfe1fccb5c7f90bfd006db588867a8",
+ "machine-envelope.v2.schema.json": "sha256:6ca8fa1456681a063ede1d977df054572be3b01ce942d5ba7efce96d99150aa1",
+ "manifest.v1.json": "sha256:1bddeeedb76dfbab899bc74313e743588c05da69916f6f9803ebe73a1fd53f0f",
"model-availability.v1.schema.json": "sha256:5965a0360f17ef815a85eb924b65506f1e5b75471fb8170d234a8178c358b6ef",
"model-feed-removal-preview.v1.schema.json": "sha256:a78cc643d1f5b7b714209969ec8b4f748b9415da49331c0bf877b3bc94d8e971",
"model-feed-remove.v1.schema.json": "sha256:49a8fb7e2ba909141937cca4e73828706b0b67ea44622ae553c6da12fa8036cc",
@@ -32,13 +32,13 @@
"model-feed-status.v1.schema.json": "sha256:1941b9104ccf58d826e851387dbeeea56bd580496812c15337572b99339a0752",
"operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f",
"operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850",
- "plan-content-change.v2.schema.json": "sha256:b67a57ca076002e341c7a74a1b8d505819ed20ee6a028354c8e6d2c5ff475f47",
- "plan-draft-change.v1.schema.json": "sha256:cbf6f1ff62fbf04e659c69342a509bbf2b2acc21b3426c3a8e4e138e26cf58c3",
- "plan-editor.v2.schema.json": "sha256:85084c42de1e8d7be3b84401a47ec5e15406431dfad983cd3b48718e93533fe1",
- "plan-lifecycle-change.v1.schema.json": "sha256:23700c0ea1fbc9834e653c4edc8268e346912270c92be4904f9759426f641562",
- "planned-manifest.v1.json": "sha256:2cf3bfe6a618a2d867baca680721b63bf02753a2aed94993d964e0f18645b2b8",
+ "plan-content-change.v2.schema.json": "sha256:5ed68998d2f727cce49ee161cba4525ecabf40c9dba0b487f20120423cb315f8",
+ "plan-draft-change.v1.schema.json": "sha256:a2e4107486b1ab55fa82ac3067d3354a20b761f92d66802c9e59f85ddc52e37f",
+ "plan-editor.v2.schema.json": "sha256:f8a8ae18a3dc460483f67514fa152ed09b9c939059bf146af5c8a3ca84d4c8b5",
+ "plan-lifecycle-change.v1.schema.json": "sha256:387cb0af28823ba6dd3567a6a472d03b1c28eed27a1697a8b98c6479a0c22d13",
+ "planned-manifest.v1.json": "sha256:9b13e674fc3c5e459dc381fbb9dae932e7d23792c580d4da53ad425ad83e3cf8",
"prepare-discovered-model-connection-request.v1.schema.json": "sha256:4451d8d7d06160f399d683bc3987ac2bd458af09994e4e0d989687667f6af1bd",
- "publication-checkpoint-change.v1.schema.json": "sha256:b130577cdae0f1e5dc9f736b8b6f40f22555b4750b4604fdc76c4b65d5b96aa3",
+ "publication-checkpoint-change.v1.schema.json": "sha256:ef2b6500694e18f38797cf45e8073d5787e1ae4983515d165baf88527609ebd6",
"routing-timeline-selection.v1.schema.json": "sha256:6c508d2a463d993da29c325fdc14a63c4ca35444a07584760cd196f28485da70",
"session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44",
"session-lookup.v1.schema.json": "sha256:0c9e0ea31bdde7f720a9a17e8dc175902a20b3fb92abc21ce4bdae9fc3d97587",
@@ -50,8 +50,8 @@
"work-plan-list-request.v1.schema.json": "sha256:d50adc8e139cbed719fcec6412c796a7cf4d4f280dd7a56c525619f72c26c58d",
"worker-cancel-request.v1.schema.json": "sha256:425379b653e8c2e572b254baeabe572539ce5eb16200832411f0cbcf7aa08b0b",
"worker-continue-request.v1.schema.json": "sha256:cfe89487d3524061dd277a97b11291fcd0db4a0a0ca333118023628ab7d61b3b",
- "worker-dependencies-discover-request.v1.schema.json": "sha256:a585c2c179b5349a0491b63bebf41cd72308054fee6b9aa4f047a19847575423",
- "worker-dependencies-select-request.v1.schema.json": "sha256:72518d78c18877ac30360fa29ca4f510dca90e2603fc579dd0e037167b311795",
+ "worker-dependencies-discover-request.v1.schema.json": "sha256:f7ccbb94f6d828c329d256325919c0058bce4f1e6df3c430ccdf9af459c59135",
+ "worker-dependencies-select-request.v1.schema.json": "sha256:92251382f44be0dd8894d6b8f17dfb2fad95439c1e767975dca5ef9de6e4e786",
"worker-exec-request.v1.schema.json": "sha256:78bfea83b08e595ad4d4b5a5a20884ad9ebb34bb05e5ceed966f9e8e16f4d0fa",
"worker-list-request.v1.schema.json": "sha256:f1a2b5900b0412d8d561a5925a6f9489b495e74c41f386a3504175b2be3aff64",
"worker-plans-request.v1.schema.json": "sha256:a7f2d13869ab542223bf51eef4f0c1a05a4c8afef43f202165fd3025a2ab72c1",
diff --git a/contracts/cli/coverage-manifest.v1.json b/contracts/cli/coverage-manifest.v1.json
index 46c11bfc..4cb5b127 100644
--- a/contracts/cli/coverage-manifest.v1.json
+++ b/contracts/cli/coverage-manifest.v1.json
@@ -1471,7 +1471,7 @@
}
}
],
- "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c",
+ "descriptor_digest": "sha256:599207be26345edcb2ca69333ea50fb0580337aeff58ed0afe8f1fe5e0eca30e",
"schema_version": {
"major": 1,
"minor": 0
diff --git a/contracts/cli/machine-envelope.v2.schema.json b/contracts/cli/machine-envelope.v2.schema.json
index a222bf4b..6218ee7a 100644
--- a/contracts/cli/machine-envelope.v2.schema.json
+++ b/contracts/cli/machine-envelope.v2.schema.json
@@ -79,7 +79,8 @@
"enum": [
"qoder",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"context_id": {
diff --git a/contracts/cli/manifest.v1.json b/contracts/cli/manifest.v1.json
index 7b756692..5f4a6715 100644
--- a/contracts/cli/manifest.v1.json
+++ b/contracts/cli/manifest.v1.json
@@ -5,7 +5,7 @@
},
"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009",
"proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",
- "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c",
+ "descriptor_digest": "sha256:599207be26345edcb2ca69333ea50fb0580337aeff58ed0afe8f1fe5e0eca30e",
"visibility": "release",
"commands": [
{
@@ -1445,7 +1445,7 @@
"effects": "Read-only; no product side effect.",
"network_and_model_use": "No model use; any external dependency is declared by the typed Application operation.",
"automation": "Ready permits a managed launch attempt, not a promise of execution or authorization. Optional capabilities remain unknown until the actual ACP handshake; start, load and cancel report real outcomes.",
- "output": "Default text renders overall and scoped states for all five supported Harnesses. --output json emits the unchanged hiroute.machine-envelope/v2 object; --output quiet prints their stable wire names.",
+ "output": "Default text renders overall and scoped states for all six supported Harnesses. --output json emits the unchanged hiroute.machine-envelope/v2 object; --output quiet prints their stable wire names.",
"exit_status": "0 accepted/query/pending; final exec/continue failure is nonzero; 2 usage; 3 conflict/busy; 4 denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention; 1 execution failure. A result query may exit 0 while honestly reporting a failed run.",
"examples": [
"hiroute worker executors --output json"
@@ -1486,12 +1486,12 @@
"idempotency": "not_applicable",
"help": {
"purpose": "Discover and validate local Worker CLI, adapter, and Node candidates.",
- "usage": "hiroute worker dependencies discover [--harness <codex_cli|claude_code|qoder_cli|pi|deepseek_harness>] [--output <json|text|quiet>]",
+ "usage": "hiroute worker dependencies discover [--harness <codex_cli|claude_code|qoder_cli|pi|deepseek_harness|opencode>] [--output <json|text|quiet>]",
"arguments_and_options": "Optionally restrict discovery to one Harness. The query checks the selected path, PATH, common locations, npm globals and npx cache without installing or selecting anything.",
"effects": "Read-only; no product side effect.",
"network_and_model_use": "No model use; any external dependency is declared by the typed Application operation.",
"automation": "Automation must use --output json. For the chosen Harness, select only found candidates and copy that Harness's selection_revisions revision into expected_selection_revision; discovery never installs or selects anything.",
- "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), one per line, and is empty when nothing is selected.",
+ "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), one per line, and is empty when nothing is selected.",
"exit_status": "0 accepted/query/pending; final exec/continue failure is nonzero; 2 usage; 3 conflict/busy; 4 denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention; 1 execution failure. A result query may exit 0 while honestly reporting a failed run.",
"examples": [
"hiroute worker dependencies discover --harness codex_cli --output json"
@@ -1536,11 +1536,11 @@
"help": {
"purpose": "Select one validated Worker dependency tuple through same-UID local management.",
"usage": "hiroute worker dependencies select (--request-stdin | --request-file <PATH>) [--output <json|text|quiet>]",
- "arguments_and_options": "JSON input: choose exactly one of --request-stdin or --request-file <PATH>. Both read one bounded UTF-8 JSON request with the same strict typed parser; unknown fields, duplicate members, trailing JSON, repeated/mixed sources and human-option mixtures are rejected before Local Control. A file must be regular; relative paths resolve from the current directory (prefix option-shaped filenames with ./). Existing command byte limits and separate protected-input/capability channels remain unchanged. Same-UID local management only. --request-stdin reads one strict JSON object with harness (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), absolute cli_path, and expected_selection_revision copied from the matching selection_revisions entry returned by worker dependencies discover --output json. codex_cli and claude_code require absolute adapter_path and accept optional absolute node_path. pi requires absolute node_path and forbids adapter_path. qoder_cli and deepseek_harness accept only cli_path and forbid adapter_path and node_path. All paths and the revision are validated again before an atomic selection update; the command never installs software or accepts an Apply capability.",
+ "arguments_and_options": "JSON input: choose exactly one of --request-stdin or --request-file <PATH>. Both read one bounded UTF-8 JSON request with the same strict typed parser; unknown fields, duplicate members, trailing JSON, repeated/mixed sources and human-option mixtures are rejected before Local Control. A file must be regular; relative paths resolve from the current directory (prefix option-shaped filenames with ./). Existing command byte limits and separate protected-input/capability channels remain unchanged. Same-UID local management only. --request-stdin reads one strict JSON object with harness (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), absolute cli_path, and expected_selection_revision copied from the matching selection_revisions entry returned by worker dependencies discover --output json. codex_cli and claude_code require absolute adapter_path and accept optional absolute node_path. pi requires absolute node_path and forbids adapter_path. qoder_cli, deepseek_harness and opencode accept only cli_path and forbid adapter_path and node_path. All paths and the revision are validated again before an atomic selection update; the command never installs software or accepts an Apply capability.",
"effects": "Application-owned journaled operation after exact spec, digest, selection-revision CAS, and idempotency checks on owner-only Local Control.",
"network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",
"automation": "Preserve the submitted JSON document. If delivery may have succeeded but no response was received, replay that same document unchanged; its deterministic request identity returns the existing Operation instead of applying twice. Do not substitute paths or a newer revision until the server reports a conflict and discovery is run again.",
- "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), one per line, and is empty when nothing is selected.",
+ "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), one per line, and is empty when nothing is selected.",
"exit_status": "0 accepted/query/pending; final exec/continue failure is nonzero; 2 usage; 3 conflict/busy; 4 denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention; 1 execution failure. A result query may exit 0 while honestly reporting a failed run.",
"examples": [
"printf '%s\\n' '{\"harness\":\"codex_cli\",\"adapter_path\":\"/ABSOLUTE/PATH/TO/codex-acp\",\"cli_path\":\"/ABSOLUTE/PATH/TO/codex\",\"node_path\":\"/ABSOLUTE/PATH/TO/node\",\"expected_selection_revision\":0}' | hiroute worker dependencies select --request-stdin --output json"
diff --git a/contracts/cli/plan-content-change.v2.schema.json b/contracts/cli/plan-content-change.v2.schema.json
index f15bb70b..9405d7fb 100644
--- a/contracts/cli/plan-content-change.v2.schema.json
+++ b/contracts/cli/plan-content-change.v2.schema.json
@@ -798,7 +798,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"protocol": {
diff --git a/contracts/cli/plan-draft-change.v1.schema.json b/contracts/cli/plan-draft-change.v1.schema.json
index b8a3faee..26623356 100644
--- a/contracts/cli/plan-draft-change.v1.schema.json
+++ b/contracts/cli/plan-draft-change.v1.schema.json
@@ -798,7 +798,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"protocol": {
diff --git a/contracts/cli/plan-editor.v2.schema.json b/contracts/cli/plan-editor.v2.schema.json
index d38438ac..56e1f052 100644
--- a/contracts/cli/plan-editor.v2.schema.json
+++ b/contracts/cli/plan-editor.v2.schema.json
@@ -798,7 +798,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"protocol": {
diff --git a/contracts/cli/plan-lifecycle-change.v1.schema.json b/contracts/cli/plan-lifecycle-change.v1.schema.json
index 1bd7c2a2..c1fbf606 100644
--- a/contracts/cli/plan-lifecycle-change.v1.schema.json
+++ b/contracts/cli/plan-lifecycle-change.v1.schema.json
@@ -798,7 +798,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"protocol": {
diff --git a/contracts/cli/planned-manifest.v1.json b/contracts/cli/planned-manifest.v1.json
index 3a66bc6c..0c95bab8 100644
--- a/contracts/cli/planned-manifest.v1.json
+++ b/contracts/cli/planned-manifest.v1.json
@@ -5,7 +5,7 @@
},
"product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009",
"proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",
- "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c",
+ "descriptor_digest": "sha256:599207be26345edcb2ca69333ea50fb0580337aeff58ed0afe8f1fe5e0eca30e",
"visibility": "planned",
"commands": [
{
@@ -2262,7 +2262,7 @@
"effects": "Read-only; no product side effect.",
"network_and_model_use": "No model use; any external dependency is declared by the typed Application operation.",
"automation": "Ready permits a managed launch attempt, not a promise of execution or authorization. Optional capabilities remain unknown until the actual ACP handshake; start, load and cancel report real outcomes.",
- "output": "Default text renders overall and scoped states for all five supported Harnesses. --output json emits the unchanged hiroute.machine-envelope/v2 object; --output quiet prints their stable wire names.",
+ "output": "Default text renders overall and scoped states for all six supported Harnesses. --output json emits the unchanged hiroute.machine-envelope/v2 object; --output quiet prints their stable wire names.",
"exit_status": "0 accepted/query/pending; final exec/continue failure is nonzero; 2 usage; 3 conflict/busy; 4 denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention; 1 execution failure. A result query may exit 0 while honestly reporting a failed run.",
"examples": [
"hiroute worker executors --output json"
@@ -2303,12 +2303,12 @@
"idempotency": "not_applicable",
"help": {
"purpose": "Discover and validate local Worker CLI, adapter, and Node candidates.",
- "usage": "hiroute worker dependencies discover [--harness <codex_cli|claude_code|qoder_cli|pi|deepseek_harness>] [--output <json|text|quiet>]",
+ "usage": "hiroute worker dependencies discover [--harness <codex_cli|claude_code|qoder_cli|pi|deepseek_harness|opencode>] [--output <json|text|quiet>]",
"arguments_and_options": "Optionally restrict discovery to one Harness. The query checks the selected path, PATH, common locations, npm globals and npx cache without installing or selecting anything.",
"effects": "Read-only; no product side effect.",
"network_and_model_use": "No model use; any external dependency is declared by the typed Application operation.",
"automation": "Automation must use --output json. For the chosen Harness, select only found candidates and copy that Harness's selection_revisions revision into expected_selection_revision; discovery never installs or selects anything.",
- "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), one per line, and is empty when nothing is selected.",
+ "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), one per line, and is empty when nothing is selected.",
"exit_status": "0 accepted/query/pending; final exec/continue failure is nonzero; 2 usage; 3 conflict/busy; 4 denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention; 1 execution failure. A result query may exit 0 while honestly reporting a failed run.",
"examples": [
"hiroute worker dependencies discover --harness codex_cli --output json"
@@ -2353,11 +2353,11 @@
"help": {
"purpose": "Select one validated Worker dependency tuple through same-UID local management.",
"usage": "hiroute worker dependencies select (--request-stdin | --request-file <PATH>) [--output <json|text|quiet>]",
- "arguments_and_options": "JSON input: choose exactly one of --request-stdin or --request-file <PATH>. Both read one bounded UTF-8 JSON request with the same strict typed parser; unknown fields, duplicate members, trailing JSON, repeated/mixed sources and human-option mixtures are rejected before Local Control. A file must be regular; relative paths resolve from the current directory (prefix option-shaped filenames with ./). Existing command byte limits and separate protected-input/capability channels remain unchanged. Same-UID local management only. --request-stdin reads one strict JSON object with harness (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), absolute cli_path, and expected_selection_revision copied from the matching selection_revisions entry returned by worker dependencies discover --output json. codex_cli and claude_code require absolute adapter_path and accept optional absolute node_path. pi requires absolute node_path and forbids adapter_path. qoder_cli and deepseek_harness accept only cli_path and forbid adapter_path and node_path. All paths and the revision are validated again before an atomic selection update; the command never installs software or accepts an Apply capability.",
+ "arguments_and_options": "JSON input: choose exactly one of --request-stdin or --request-file <PATH>. Both read one bounded UTF-8 JSON request with the same strict typed parser; unknown fields, duplicate members, trailing JSON, repeated/mixed sources and human-option mixtures are rejected before Local Control. A file must be regular; relative paths resolve from the current directory (prefix option-shaped filenames with ./). Existing command byte limits and separate protected-input/capability channels remain unchanged. Same-UID local management only. --request-stdin reads one strict JSON object with harness (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), absolute cli_path, and expected_selection_revision copied from the matching selection_revisions entry returned by worker dependencies discover --output json. codex_cli and claude_code require absolute adapter_path and accept optional absolute node_path. pi requires absolute node_path and forbids adapter_path. qoder_cli, deepseek_harness and opencode accept only cli_path and forbid adapter_path and node_path. All paths and the revision are validated again before an atomic selection update; the command never installs software or accepts an Apply capability.",
"effects": "Application-owned journaled operation after exact spec, digest, selection-revision CAS, and idempotency checks on owner-only Local Control.",
"network_and_model_use": "No model inference; external access, when required, is limited to registered typed ports.",
"automation": "Preserve the submitted JSON document. If delivery may have succeeded but no response was received, replay that same document unchanged; its deterministic request identity returns the existing Operation instead of applying twice. Do not substitute paths or a newer revision until the server reports a conflict and discovery is run again.",
- "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), one per line, and is empty when nothing is selected.",
+ "output": "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), one per line, and is empty when nothing is selected.",
"exit_status": "0 accepted/query/pending; final exec/continue failure is nonzero; 2 usage; 3 conflict/busy; 4 denied; 5 not found; 6 unavailable; 7 action required; 8 needs attention; 1 execution failure. A result query may exit 0 while honestly reporting a failed run.",
"examples": [
"printf '%s\\n' '{\"harness\":\"codex_cli\",\"adapter_path\":\"/ABSOLUTE/PATH/TO/codex-acp\",\"cli_path\":\"/ABSOLUTE/PATH/TO/codex\",\"node_path\":\"/ABSOLUTE/PATH/TO/node\",\"expected_selection_revision\":0}' | hiroute worker dependencies select --request-stdin --output json"
diff --git a/contracts/cli/publication-checkpoint-change.v1.schema.json b/contracts/cli/publication-checkpoint-change.v1.schema.json
index b9fd7124..6f4e16f5 100644
--- a/contracts/cli/publication-checkpoint-change.v1.schema.json
+++ b/contracts/cli/publication-checkpoint-change.v1.schema.json
@@ -798,7 +798,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"protocol": {
diff --git a/contracts/cli/worker-dependencies-discover-request.v1.schema.json b/contracts/cli/worker-dependencies-discover-request.v1.schema.json
index c408d4ab..27842e48 100644
--- a/contracts/cli/worker-dependencies-discover-request.v1.schema.json
+++ b/contracts/cli/worker-dependencies-discover-request.v1.schema.json
@@ -9,7 +9,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
}
},
diff --git a/contracts/cli/worker-dependencies-select-request.v1.schema.json b/contracts/cli/worker-dependencies-select-request.v1.schema.json
index dc8eea37..c36aee48 100644
--- a/contracts/cli/worker-dependencies-select-request.v1.schema.json
+++ b/contracts/cli/worker-dependencies-select-request.v1.schema.json
@@ -29,7 +29,8 @@
"harness": {
"enum": [
"qoder_cli",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
}
}
@@ -56,7 +57,8 @@
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
},
"node_path": {
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index b379b1c7..2bd6683d 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -297,6 +297,9 @@
"hiroute.observation.serialization-failure/v1",
"hiroute.observation.valuation-summary/v2",
"hiroute.observation.value-report/v2",
+ "hiroute.opencode-additional-model/v1",
+ "hiroute.opencode-collaboration/v1",
+ "hiroute.opencode-native-restore/v2",
"hiroute.operation-cancel-request/v1",
"hiroute.operation-event/v1",
"hiroute.operation-idempotency-lookup/v1",
@@ -391,6 +394,7 @@
"hiroute.settings-hermes-plugin-file/v1",
"hiroute.settings-login-item/v1",
"hiroute.settings-model-publication/v1",
+ "hiroute.settings-opencode-model-file/v1",
"hiroute.settings-pi-model-file/v1",
"hiroute.settings-qoder-model-file/v1",
"hiroute.settings-service-completion/v2",
@@ -1226,6 +1230,16 @@
"hiroute.upgrade-source-backup/v2"
],
"legacy_support": []
+ },
+ {
+ "subject": "opencode_native_provider_restore",
+ "audited_prefixes": [
+ "hiroute.opencode-native-restore"
+ ],
+ "current_contracts": [
+ "hiroute.opencode-native-restore/v2"
+ ],
+ "legacy_support": []
}
],
"forbidden_contracts": [
@@ -1865,6 +1879,18 @@
"crates/daemon/src/control/runtime/history_cutover_tests.rs"
]
},
+ {
+ "contract": "hiroute.delegation-native-root/v1",
+ "field": "borrowed-native-context descriptor version 1 for existing native Harnesses; version 2 adds the complete OpenCode context",
+ "mode": "recovery_read_only",
+ "owner": "daemon/delegation/profile/native_history",
+ "reason": "Existing non-OpenCode task descriptor bytes and context digests retain their meaning. OpenCode requires version 2 with its HOME/XDG/config/database selectors; the reader never defaults a missing OpenCode descriptor or reconstructs it from current environment.",
+ "removal_condition": "Retire only when supported retained tasks and backups no longer contain version-1 descriptors, with exact-session continuation fixtures.",
+ "allowed_paths": [
+ "crates/daemon/src/delegation/profile/native_history.rs",
+ "crates/daemon/src/delegation/profile/native_history_tests.rs"
+ ]
+ },
{
"contract": "hiroute.observation.product-execution-envelope/v2",
"field": "AgentTurnFinished.opening_cause absent; pre-opening digest 7ff01a649de96b1f62e069b872b23609d64a3734b5ad42c337324d3eb7cfc9f2",
diff --git a/crates/application-api/src/agent_settings.rs b/crates/application-api/src/agent_settings.rs
index 5354d7cc..801e0cae 100644
--- a/crates/application-api/src/agent_settings.rs
+++ b/crates/application-api/src/agent_settings.rs
@@ -288,6 +288,9 @@ impl AgentModelSettingsStatusV2 {
*surface == AgentModelSurfaceV2::HermesCli
}
AgentModelSelectionV2::DshAdditional { .. } => *surface == AgentModelSurfaceV2::DshCli,
+ AgentModelSelectionV2::OpenCodeAdditional { .. } => {
+ *surface == AgentModelSurfaceV2::OpenCodeCli
+ }
AgentModelSelectionV2::PiAdditional { .. } => *surface == AgentModelSurfaceV2::PiCli,
AgentModelSelectionV2::QoderAdditional { .. } => {
*surface == AgentModelSurfaceV2::QoderCli
diff --git a/crates/application-api/src/commands/help.rs b/crates/application-api/src/commands/help.rs
index cab61efc..3938be68 100644
--- a/crates/application-api/src/commands/help.rs
+++ b/crates/application-api/src/commands/help.rs
@@ -93,12 +93,12 @@ pub(super) fn automation(command_id: &str) -> &'static str {
}
pub(super) fn output(command_id: &str) -> &'static str {
if command_id == "worker.executors" {
- "Default text renders overall and scoped states for all five supported Harnesses. --output json emits the unchanged hiroute.machine-envelope/v2 object; --output quiet prints their stable wire names."
+ "Default text renders overall and scoped states for all six supported Harnesses. --output json emits the unchanged hiroute.machine-envelope/v2 object; --output quiet prints their stable wire names."
} else if matches!(
command_id,
"worker.dependencies.discover" | "worker.dependencies.select"
) {
- "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), one per line, and is empty when nothing is selected."
+ "Default text renders selected tuples and discovered candidates but omits the CAS revisions, so automation must use --output json. --output quiet prints only selected Harness wire names (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), one per line, and is empty when nothing is selected."
} else if command_id == "worker.list" {
"Default text renders the instance task/state/title-or-ID/canonical-cwd page plus its next cursor. --output json emits the unchanged hiroute.machine-envelope/v2 object; --output quiet prints task IDs. A page length is never a total count."
} else if command_id.starts_with("worker.") {
diff --git a/crates/application-api/src/generated.rs b/crates/application-api/src/generated.rs
index 86eeb404..15486282 100644
--- a/crates/application-api/src/generated.rs
+++ b/crates/application-api/src/generated.rs
@@ -142,7 +142,7 @@ fn machine_envelope_v2_schema() -> Value {
"type": "object", "additionalProperties": false,
"required": ["agent_kind", "context_id", "plan_id", "model_alias", "reason", "declared", "proposed"],
"properties": {
- "agent_kind": { "enum": ["qoder", "pi", "deepseek_harness"] },
+ "agent_kind": { "enum": ["qoder", "pi", "deepseek_harness", "opencode"] },
"context_id": { "type": "string", "pattern": "^agent-context/[A-Za-z0-9/_:-]{1,242}$" },
"plan_id": { "type": "string", "minLength": 1, "maxLength": 256 },
"model_alias": { "type": "string", "pattern": "^(hiroute/[0-9a-f]{16}|[a-z0-9][a-z0-9._-]{0,63})$" },
@@ -608,6 +608,38 @@ pub fn generated_contract_files() -> Vec<GeneratedContractFile> {
mod tests {
use super::*;
+ #[test]
+ fn budget_schema_accepts_exactly_the_typed_installed_consumers() {
+ let schema = machine_envelope_v2_schema();
+ let kinds = schema["$defs"]["model_budget_blocker"]["properties"]["agent_kind"]["enum"]
+ .as_array()
+ .unwrap();
+ for kind in [
+ "codex",
+ "claude_code",
+ "qoder",
+ "pi",
+ "deepseek_harness",
+ "opencode",
+ ] {
+ let wire = json!({
+ "schema": "hiroute.agent-model-budget-conflict/v1",
+ "blockers": [{
+ "agent_kind": kind,
+ "context_id": "agent-context/native/sha256:abc",
+ "plan_id": "plan/free",
+ "model_alias": "free.plan",
+ "reason": "capacity_reduced",
+ "declared": {"context_window_tokens": 262144, "max_output_tokens": 235929},
+ "proposed": {"context_window_tokens": 262144, "max_output_tokens": 131072}
+ }]
+ });
+ let conflict: hiroute_domain::AgentModelBudgetConflictV1 =
+ serde_json::from_value(wire).unwrap();
+ assert_eq!(kinds.contains(&json!(kind)), conflict.is_valid(), "{kind}");
+ }
+ }
+
#[test]
fn generated_contract_set_is_complete_and_stably_ordered() {
let files = generated_contract_files();
diff --git a/crates/application-api/src/generated/plan_authoring.rs b/crates/application-api/src/generated/plan_authoring.rs
index f902163f..e72548b7 100644
--- a/crates/application-api/src/generated/plan_authoring.rs
+++ b/crates/application-api/src/generated/plan_authoring.rs
@@ -114,7 +114,7 @@ fn definitions() -> Value {
"schema":{"const":"hiroute.plan-editor/v2"},"display_name":{"type":"string","maxLength":128},"purpose":{"type":"string","maxLength":512},
"custom_alias":{"type":"string","maxLength":64},"mode":{"enum":["fixed_model","smart_saving","custom_branches","free_first"]},"branch_routing":{"oneOf":[{"type":"null"},routing]},
"candidates":reference("candidates"),"smart":smart,"free":free,"delegation_enabled":{"type":"boolean"},"requirements":requirements,"limits":limits,
- "work":object(&["harness","protocol"],json!({"harness":{"enum":["codex_cli","claude_code","qoder_cli","pi","deepseek_harness"]},"protocol":{"enum":["responses","messages"]}}))
+ "work":object(&["harness","protocol"],json!({"harness":{"enum":["codex_cli","claude_code","qoder_cli","pi","deepseek_harness","opencode"]},"protocol":{"enum":["responses","messages"]}}))
}),
);
let draft = object(
diff --git a/crates/application-api/src/generated/worker.rs b/crates/application-api/src/generated/worker.rs
index b17df0f0..7eb0ad62 100644
--- a/crates/application-api/src/generated/worker.rs
+++ b/crates/application-api/src/generated/worker.rs
@@ -244,7 +244,7 @@ pub(super) fn dependencies_discover() -> Value {
"$id": "hiroute://contracts/cli/worker-dependencies-discover-request.v1.schema.json",
"type": "object",
"additionalProperties": false,
- "properties": {"harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi", "deepseek_harness"]}}
+ "properties": {"harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi", "deepseek_harness","opencode"]}}
})
}
@@ -256,13 +256,13 @@ pub(super) fn dependencies_select() -> Value {
"additionalProperties": false,
"required": ["harness", "cli_path", "expected_selection_revision"],
"properties": {
- "harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi", "deepseek_harness"]},
+ "harness": {"enum": ["codex_cli", "claude_code", "qoder_cli", "pi", "deepseek_harness","opencode"]},
"adapter_path": {"type": "string", "minLength": 1, "maxLength": 4096},
"cli_path": {"type": "string", "minLength": 1, "maxLength": 4096},
"node_path": {"type": "string", "minLength": 1, "maxLength": 4096},
"expected_selection_revision": {"type": "integer", "minimum": 0, "maximum": u64::MAX}
},
- "if": {"properties": {"harness": {"enum": ["qoder_cli", "deepseek_harness"]}}},
+ "if": {"properties": {"harness": {"enum": ["qoder_cli", "deepseek_harness","opencode"]}}},
"then": {"properties": {"adapter_path": false, "node_path": false}},
"else": {"if": {"properties": {"harness": {"const": "pi"}}},
"then": {"required": ["node_path"], "properties": {"adapter_path": false}},
diff --git a/crates/application-api/src/protocol.rs b/crates/application-api/src/protocol.rs
index 83ce2de8..95ddfdee 100644
--- a/crates/application-api/src/protocol.rs
+++ b/crates/application-api/src/protocol.rs
@@ -1120,7 +1120,7 @@ pub(crate) fn command_usage(command_id: &str, joined_path: &str) -> String {
let usage: String = match command_id {
"worker.executors" => "hiroute worker executors [--output <json|text|quiet>]".into(),
- "worker.dependencies.discover" => "hiroute worker dependencies discover [--harness <codex_cli|claude_code|qoder_cli|pi|deepseek_harness>] [--output <json|text|quiet>]".into(),
+ "worker.dependencies.discover" => "hiroute worker dependencies discover [--harness <codex_cli|claude_code|qoder_cli|pi|deepseek_harness|opencode>] [--output <json|text|quiet>]".into(),
"worker.dependencies.select" => "hiroute worker dependencies select --request-stdin [--output <json|text|quiet>]".into(),
"worker.plans" => "hiroute worker plans [--output <json|text|quiet>]".into(),
"worker.list" => "hiroute worker list [--title <TITLE>] [--cursor <OPAQUE>] [--limit <1..200>] [--output <json|text|quiet>]".into(),
@@ -1189,7 +1189,7 @@ pub(crate) fn command_arguments(command_id: &str) -> String {
let arguments: String = match command_id {
"worker.executors" => "No Agent, Plan, allowlist, capability FD, or request body is accepted. The query checks configured entry metadata and executability, not program contents or compatibility. Ready allows a launch attempt; it does not prove optional capabilities, install, configure, authorize, or admit a run.".into(),
"worker.dependencies.discover" => "Optionally restrict discovery to one Harness. The query checks the selected path, PATH, common locations, npm globals and npx cache without installing or selecting anything.".into(),
- "worker.dependencies.select" => "Same-UID local management only. --request-stdin reads one strict JSON object with harness (codex_cli, claude_code, qoder_cli, pi, or deepseek_harness), absolute cli_path, and expected_selection_revision copied from the matching selection_revisions entry returned by worker dependencies discover --output json. codex_cli and claude_code require absolute adapter_path and accept optional absolute node_path. pi requires absolute node_path and forbids adapter_path. qoder_cli and deepseek_harness accept only cli_path and forbid adapter_path and node_path. All paths and the revision are validated again before an atomic selection update; the command never installs software or accepts an Apply capability.".into(),
+ "worker.dependencies.select" => "Same-UID local management only. --request-stdin reads one strict JSON object with harness (codex_cli, claude_code, qoder_cli, pi, deepseek_harness, or opencode), absolute cli_path, and expected_selection_revision copied from the matching selection_revisions entry returned by worker dependencies discover --output json. codex_cli and claude_code require absolute adapter_path and accept optional absolute node_path. pi requires absolute node_path and forbids adapter_path. qoder_cli, deepseek_harness and opencode accept only cli_path and forbid adapter_path and node_path. All paths and the revision are validated again before an atomic selection update; the command never installs software or accepts an Apply capability.".into(),
"worker.plans" => "Lists every currently published and delegation-enabled Worker Plan in this daemon instance; no main-Agent selector or allowlist participates.".into(),
"worker.list" => "Pages the daemon instance's durable tasks newest-first. --title is normalized exact matching; the signed opaque cursor is bound to that filter. Default 50, maximum 200, and no total count.".into(),
"worker.exec" => "Plan, cwd, and exactly one text source are required. Permission policy defaults to approve-all; approve-reads and deny-all are explicit run restrictions and fail unavailable unless the exact Harness mapping proves them. cwd is scheduling context, not directory authorization. Submits directly to the daemon without a local receipt. Choose a unique --submission-key before sending; after uncertain delivery, query or retry with that original key and the identical request.".into(),
diff --git a/crates/application-api/src/worker.rs b/crates/application-api/src/worker.rs
index c89612a2..6b8135ec 100644
--- a/crates/application-api/src/worker.rs
+++ b/crates/application-api/src/worker.rs
@@ -132,6 +132,7 @@ pub fn plan_worker_dependency_selection(
WorkerHarnessV1::ClaudeCode => "claude_code",
WorkerHarnessV1::QoderCli => "qoder_cli",
WorkerHarnessV1::Pi => "pi",
+ WorkerHarnessV1::OpenCode => "opencode",
WorkerHarnessV1::DeepseekHarness => "deepseek_harness",
};
let spec = ChangeSpecV1 {
@@ -257,7 +258,7 @@ impl WorkerDependenciesViewV1 {
.collect::<BTreeSet<_>>();
self.schema == WORKER_DEPENDENCIES_VIEW_SCHEMA_V1
&& !self.selection_revisions.is_empty()
- && self.selection_revisions.len() <= 5
+ && self.selection_revisions.len() <= 6
&& revisions.len() == self.selection_revisions.len()
&& selections.len() == self.selected.len()
&& self.selected.iter().all(|selection| {
@@ -269,7 +270,7 @@ impl WorkerDependenciesViewV1 {
)
.is_ok()
})
- && self.candidates.len() <= 5 * 64
+ && self.candidates.len() <= 6 * 64
&& self.candidates.iter().all(|candidate| {
absolute_path(&candidate.path)
&& candidate
@@ -378,12 +379,13 @@ pub struct WorkerExecutorAvailabilityListV1 {
impl WorkerExecutorAvailabilityListV1 {
pub fn valid(&self) -> bool {
self.schema == WORKER_EXECUTOR_AVAILABILITY_SCHEMA_V1
- && self.executors.len() == 5
+ && self.executors.len() == 6
&& self.executors[0].harness == WorkerHarnessV1::CodexCli
&& self.executors[1].harness == WorkerHarnessV1::ClaudeCode
&& self.executors[2].harness == WorkerHarnessV1::QoderCli
&& self.executors[3].harness == WorkerHarnessV1::Pi
&& self.executors[4].harness == WorkerHarnessV1::DeepseekHarness
+ && self.executors[5].harness == WorkerHarnessV1::OpenCode
&& self
.executors
.iter()
@@ -1196,6 +1198,7 @@ mod tests {
executor(WorkerHarnessV1::QoderCli),
executor(WorkerHarnessV1::Pi),
executor(WorkerHarnessV1::DeepseekHarness),
+ executor(WorkerHarnessV1::OpenCode),
],
};
assert!(response.valid());
diff --git a/crates/application-api/src/worker_selection_tests.rs b/crates/application-api/src/worker_selection_tests.rs
index 08ef555b..b9bfcdce 100644
--- a/crates/application-api/src/worker_selection_tests.rs
+++ b/crates/application-api/src/worker_selection_tests.rs
@@ -119,11 +119,13 @@ fn native_acp_requires_only_cli_and_rejects_cross_form_fields() {
let requests = [
r#"{"harness":"qoder_cli","cli_path":"/opt/bin/qodercli","expected_selection_revision":0}"#,
r#"{"harness":"deepseek_harness","cli_path":"/opt/bin/dsh","expected_selection_revision":0}"#,
+ r#"{"harness":"opencode","cli_path":"/opt/bin/opencode","expected_selection_revision":0}"#,
];
#[cfg(windows)]
let requests = [
r#"{"harness":"qoder_cli","cli_path":"C:/opt/bin/qodercli","expected_selection_revision":0}"#,
r#"{"harness":"deepseek_harness","cli_path":"C:/opt/bin/dsh","expected_selection_revision":0}"#,
+ r#"{"harness":"opencode","cli_path":"C:/opt/bin/opencode","expected_selection_revision":0}"#,
];
let (adapter, node) = if cfg!(windows) {
("C:/opt/adapter", "C:/opt/node")
@@ -194,7 +196,8 @@ fn published_worker_harnesses_match_typed_discovery_selection_and_plan_bindings(
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]);
for declared in [
&discover["properties"]["harness"]["enum"],
diff --git a/crates/application/src/agent_connection/additional_model_journal.rs b/crates/application/src/agent_connection/additional_model_journal.rs
index 9772945a..eba29471 100644
--- a/crates/application/src/agent_connection/additional_model_journal.rs
+++ b/crates/application/src/agent_connection/additional_model_journal.rs
@@ -16,6 +16,7 @@ pub fn additional_model_kind(intent: &ExternalEffectIntentV1) -> PortResult<Agen
Some("agent_qoder_default") => Ok(AgentKindV1::Qoder),
Some("agent_pi_default") => Ok(AgentKindV1::Pi),
Some("agent_dsh_default") => Ok(AgentKindV1::DeepseekHarness),
+ Some("agent_opencode_default") => Ok(AgentKindV1::OpenCode),
_ => Err(invalid()),
}
}
@@ -23,6 +24,7 @@ fn schema(kind: AgentKindV1) -> &'static str {
match kind {
AgentKindV1::Pi => PI_SCHEMA,
AgentKindV1::DeepseekHarness => "hiroute.settings-dsh-model-file/v1",
+ AgentKindV1::OpenCode => "hiroute.settings-opencode-model-file/v1",
_ => QODER_SCHEMA,
}
}
@@ -50,6 +52,8 @@ pub struct AdditionalModelFilePayload {
pub change: AdditionalModelFileAction,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pi_settings_content: Option<CanonicalDigest>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub additional_dependencies: Option<CanonicalDigest>,
}
/// A stable, context-owned namespace. It never adopts an existing unowned provider.
@@ -65,23 +69,29 @@ pub fn settings_additional_model_file_intent(
before_fingerprint: Option<CanonicalDigest>,
change: AdditionalModelFileAction,
pi_settings_content: Option<CanonicalDigest>,
+ additional_dependencies: Option<CanonicalDigest>,
) -> Result<ExternalEffectIntentV1, OperationValidationError> {
if control.transaction() != AgentConnectionTransactionKindV1::Settings {
return Err(OperationValidationError::UnregisteredEffectPlan);
}
let payload = AdditionalModelFilePayload {
- schema: schema(if control.subject().agent_id() == "agent_dsh_default" {
- AgentKindV1::DeepseekHarness
- } else if control.subject().agent_id() == "agent_pi_default" {
- AgentKindV1::Pi
- } else {
- AgentKindV1::Qoder
- })
+ schema: schema(
+ if control.subject().agent_id() == "agent_opencode_default" {
+ AgentKindV1::OpenCode
+ } else if control.subject().agent_id() == "agent_dsh_default" {
+ AgentKindV1::DeepseekHarness
+ } else if control.subject().agent_id() == "agent_pi_default" {
+ AgentKindV1::Pi
+ } else {
+ AgentKindV1::Qoder
+ },
+ )
.into(),
context_id: context_id.into(),
expected_content,
change,
pi_settings_content,
+ additional_dependencies,
};
let intent = ExternalEffectIntentV1::from_agent_connection_planner(
control,
@@ -111,6 +121,11 @@ pub fn decode_settings_additional_model_file(
let value = intent.desired();
let kind = additional_model_kind(intent)?;
let (agent, profile, integration) = match kind {
+ AgentKindV1::OpenCode => (
+ "agent_opencode_default",
+ "opencode-responses-v1",
+ "builtin/opencode-responses/v1",
+ ),
AgentKindV1::DeepseekHarness => (
"agent_dsh_default",
"dsh-responses-v1",
@@ -140,6 +155,7 @@ pub fn decode_settings_additional_model_file(
serde_json::from_value(value["payload"].clone()).map_err(|_| invalid())?;
if payload.schema != schema(kind)
|| (kind == AgentKindV1::Pi) != payload.pi_settings_content.is_some()
+ || (kind == AgentKindV1::OpenCode) != payload.additional_dependencies.is_some()
|| !super::settings::identity(&payload.context_id)
{
return Err(invalid());
@@ -156,7 +172,10 @@ pub fn decode_settings_additional_model_file(
|| models.is_empty()
|| models.len() > 256
|| models.iter().any(|model| {
- (if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {
+ (if matches!(
+ kind,
+ AgentKindV1::Pi | AgentKindV1::DeepseekHarness | AgentKindV1::OpenCode
+ ) {
model.validate_pi()
} else {
model.validate()
@@ -207,6 +226,9 @@ pub fn settings_additional_model_file_for_operation(
}
| AgentModelSelectionV2::DshAdditional {
allowed_plan_ids, ..
+ }
+ | AgentModelSelectionV2::OpenCodeAdditional {
+ allowed_plan_ids, ..
},
},
AdditionalModelFileAction::Configure {
@@ -227,6 +249,12 @@ pub fn settings_additional_model_file_for_operation(
settings: AgentModelSelectionV2::DshAdditional { .. }
}
) != (kind == AgentKindV1::DeepseekHarness)
+ || matches!(
+ &spec.model,
+ AgentFacetIntent::Configure {
+ settings: AgentModelSelectionV2::OpenCodeAdditional { .. }
+ }
+ ) != (kind == AgentKindV1::OpenCode)
{
return Err(invalid());
}
@@ -258,7 +286,10 @@ fn local_endpoint(value: &str, kind: AgentKindV1) -> bool {
.or_else(|| value.strip_prefix("http://[::1]:"))
.and_then(|rest| {
rest.strip_suffix(
- if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {
+ if matches!(
+ kind,
+ AgentKindV1::Pi | AgentKindV1::DeepseekHarness | AgentKindV1::OpenCode
+ ) {
"/v1"
} else {
hiroute_domain::QODER_MODEL_BASE_PATH
diff --git a/crates/application/src/agent_connection/previous_routing.rs b/crates/application/src/agent_connection/previous_routing.rs
index ab0792c8..137fadec 100644
--- a/crates/application/src/agent_connection/previous_routing.rs
+++ b/crates/application/src/agent_connection/previous_routing.rs
@@ -208,7 +208,8 @@ fn overlay(
(
a @ (AgentModelSelectionV2::QoderAdditional { .. }
| AgentModelSelectionV2::PiAdditional { .. }
- | AgentModelSelectionV2::DshAdditional { .. }),
+ | AgentModelSelectionV2::DshAdditional { .. }
+ | AgentModelSelectionV2::OpenCodeAdditional { .. }),
b,
) if preset == "models" && std::mem::discriminant(a) == std::mem::discriminant(b) => {
*a = b.clone();
@@ -278,6 +279,7 @@ pub fn previous_routing_targets(
"agent_dsh_default",
"agent_pi_default",
"agent_qoder_default",
+ "agent_opencode_default",
] {
let head = match connection.previous_routing_head(agent) {
Ok(head) => head,
@@ -345,6 +347,9 @@ fn mapped_presets(settings: &AgentModelSelectionV2, plan: &str) -> Vec<String> {
}
| AgentModelSelectionV2::QoderAdditional {
allowed_plan_ids, ..
+ }
+ | AgentModelSelectionV2::OpenCodeAdditional {
+ allowed_plan_ids, ..
} if allowed_plan_ids.iter().any(|id| id.as_str() == plan) => vec!["models".into()],
_ => Vec::new(),
}
diff --git a/crates/application/src/agent_connection/previous_routing/tests.rs b/crates/application/src/agent_connection/previous_routing/tests.rs
index 21ff7394..29d1ddab 100644
--- a/crates/application/src/agent_connection/previous_routing/tests.rs
+++ b/crates/application/src/agent_connection/previous_routing/tests.rs
@@ -175,3 +175,56 @@ fn recovery_targets_only_include_presets_currently_mapped_to_the_plan() {
);
assert!(mapped_presets(&value.settings, "plan/unmapped").is_empty());
}
+
+#[test]
+fn opencode_previous_routing_recovers_exact_additional_mapping() {
+ let entry = |id: &str, previous: Option<&str>, plan: &str, protocol: &str| {
+ let mut value = fixture(id, previous, "plan/opus", "plan/sonnet");
+ value.settings = serde_json::from_value(serde_json::json!({
+ "mode": "opencode_additional", "allowed_plan_ids": [plan],
+ "plan_protocols": BTreeMap::from([(plan, protocol)])
+ }))
+ .unwrap();
+ value.spec.model = AgentFacetIntent::Configure {
+ settings: value.settings.clone(),
+ };
+ value.resolved = BTreeMap::from([("models".into(), serde_json::json!([plan]))]);
+ value
+ };
+ let current = entry(
+ "op_00000000000000000000000000000002",
+ Some("op_00000000000000000000000000000001"),
+ "plan/trial",
+ "responses",
+ );
+ assert_eq!(mapped_presets(&current.settings, "plan/trial"), ["models"]);
+ assert!(mapped_presets(&current.settings, "plan/unmapped").is_empty());
+ let old = entry(
+ "op_00000000000000000000000000000001",
+ None,
+ "plan/original",
+ "messages",
+ );
+ let expected = old.settings.clone();
+ let mut chain = BTreeMap::from([(old.id.clone(), old)]);
+ let Preview::Available {
+ spec,
+ restored_from,
+ ..
+ } = recover(current, &BTreeSet::from(["models".into()]), |id| {
+ chain.remove(id).ok_or("history_missing")
+ })
+ else {
+ panic!("OpenCode must use the existing additional-model history path")
+ };
+ assert_eq!(
+ spec.model,
+ AgentFacetIntent::Configure { settings: expected }
+ );
+ assert_eq!(spec.collaboration, AgentFacetIntent::Keep);
+ assert_eq!(spec.access_token, AgentAccessTokenIntentV1::Keep);
+ assert_eq!(
+ restored_from["models"].as_str(),
+ "op_00000000000000000000000000000001"
+ );
+}
diff --git a/crates/application/src/agent_connection/settings.rs b/crates/application/src/agent_connection/settings.rs
index f5b68ebd..d1eb8cb6 100644
--- a/crates/application/src/agent_connection/settings.rs
+++ b/crates/application/src/agent_connection/settings.rs
@@ -171,6 +171,7 @@ pub fn preview_agent_settings(
| AgentModelSelectionV2::QoderAdditional { .. }
| AgentModelSelectionV2::PiAdditional { .. }
| AgentModelSelectionV2::DshAdditional { .. }
+ | AgentModelSelectionV2::OpenCodeAdditional { .. }
) {
// A short-lived isolated HTTP challenge diagnoses a native client; it is not
// authorization to write a safely observed Codex configuration. Actual client
@@ -225,6 +226,14 @@ pub fn preview_agent_settings(
{
return Err(SettingsPlanningError::InvalidSelection);
}
+ if matches!(settings, AgentModelSelectionV2::OpenCodeAdditional { .. })
+ && !model
+ .common
+ .available_surfaces
+ .contains(&hiroute_domain::AgentModelSurfaceV2::OpenCodeCli)
+ {
+ return Err(SettingsPlanningError::InvalidSelection);
+ }
if matches!(settings, AgentModelSelectionV2::HermesDefault { .. })
!= model
.common
@@ -645,7 +654,7 @@ fn validate_model_default(
.then_some(name.as_str())
}),
},
- AgentModelSelectionV2::QoderAdditional { .. } | AgentModelSelectionV2::PiAdditional { .. } | AgentModelSelectionV2::DshAdditional { .. } => return Ok(()),
+ AgentModelSelectionV2::QoderAdditional { .. } | AgentModelSelectionV2::PiAdditional { .. } | AgentModelSelectionV2::DshAdditional { .. } | AgentModelSelectionV2::OpenCodeAdditional { .. } => return Ok(()),
AgentModelSelectionV2::ClaudeLauncher { .. } => {
let facts = facts.claude().ok_or_else(invalid)?;
claude_presets = grant
diff --git a/crates/application/src/agent_connection/settings_input.rs b/crates/application/src/agent_connection/settings_input.rs
index f8c09649..3738bd71 100644
--- a/crates/application/src/agent_connection/settings_input.rs
+++ b/crates/application/src/agent_connection/settings_input.rs
@@ -54,6 +54,7 @@ pub enum SettingsModelTargetFacts {
Additional {
kind: hiroute_domain::AgentKindV1,
pi_settings_content: Option<CanonicalDigest>,
+ additional_dependencies: Option<CanonicalDigest>,
provider_id: String,
endpoint: String,
models: Vec<hiroute_domain::AdditionalAgentModelV1>,
@@ -142,6 +143,7 @@ impl AgentSettingsPlanningInput {
SettingsModelTargetFacts::Additional {
kind,
pi_settings_content,
+ additional_dependencies,
provider_id,
endpoint,
models,
@@ -151,15 +153,19 @@ impl AgentSettingsPlanningInput {
AgentModelSelectionV2::QoderAdditional { .. }
| AgentModelSelectionV2::PiAdditional { .. }
| AgentModelSelectionV2::DshAdditional { .. }
+ | AgentModelSelectionV2::OpenCodeAdditional { .. }
) || matches!(settings, AgentModelSelectionV2::PiAdditional { .. })
!= (*kind == hiroute_domain::AgentKindV1::Pi)
|| matches!(settings, AgentModelSelectionV2::DshAdditional { .. })
!= (*kind == hiroute_domain::AgentKindV1::DeepseekHarness)
+ || matches!(settings, AgentModelSelectionV2::OpenCodeAdditional { .. })
+ != (*kind == hiroute_domain::AgentKindV1::OpenCode)
{
return Err(invalid());
}
SettingsModelAction::Additional(
pi_settings_content.clone(),
+ additional_dependencies.clone(),
super::AdditionalModelFileAction::Configure {
previous_operation: file.active_configuration.clone(),
provider_id: provider_id.clone(),
@@ -244,9 +250,11 @@ impl AgentSettingsPlanningInput {
}
SettingsModelTargetFacts::Additional {
pi_settings_content,
+ additional_dependencies,
..
} => SettingsModelAction::Additional(
pi_settings_content.clone(),
+ additional_dependencies.clone(),
super::AdditionalModelFileAction::Restore {
original_operation: operation.clone(),
},
@@ -399,7 +407,11 @@ impl AgentSettingsPlanningInput {
change,
)?);
}
- SettingsModelAction::Additional(pi_settings_content, change) => {
+ SettingsModelAction::Additional(
+ pi_settings_content,
+ additional_dependencies,
+ change,
+ ) => {
external.push(super::settings_additional_model_file_intent(
control,
&self.facts.context_id,
@@ -407,6 +419,7 @@ impl AgentSettingsPlanningInput {
file.before_fingerprint.clone(),
change,
pi_settings_content,
+ additional_dependencies,
)?);
}
SettingsModelAction::Claude(change) => {
@@ -530,7 +543,11 @@ impl AgentSettingsPlanningInput {
enum SettingsModelAction {
Hermes(super::HermesModelFileAction),
- Additional(Option<CanonicalDigest>, super::AdditionalModelFileAction),
+ Additional(
+ Option<CanonicalDigest>,
+ Option<CanonicalDigest>,
+ super::AdditionalModelFileAction,
+ ),
Codex(CodexModelFileAction),
Claude(ClaudeModelFileAction),
}
diff --git a/crates/application/src/agent_connection/tests.rs b/crates/application/src/agent_connection/tests.rs
index 37992da5..f95ceef8 100644
--- a/crates/application/src/agent_connection/tests.rs
+++ b/crates/application/src/agent_connection/tests.rs
@@ -51,6 +51,7 @@ fn installation(kind: AgentKindV1) -> SupportedAgentInstallationV1 {
AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes => {
panic!("this fixture covers default-model replacement, not additional providers")
}
@@ -91,6 +92,7 @@ fn profile(kind: AgentKindV1) -> AgentProfileV1 {
AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes => {
panic!("this fixture covers default-model replacement, not additional providers")
}
@@ -261,6 +263,7 @@ fn spec(kind: AgentKindV1, native: bool, dynamic: bool) -> AgentConnectSpecV1 {
AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes => {
panic!("this fixture covers default-model replacement, not additional providers")
}
@@ -275,6 +278,7 @@ fn spec(kind: AgentKindV1, native: bool, dynamic: bool) -> AgentConnectSpecV1 {
AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes => {
panic!("this fixture covers default-model replacement, not additional providers")
}
diff --git a/crates/application/src/delegation/tasks.rs b/crates/application/src/delegation/tasks.rs
index 1e3f60dd..72f1411f 100644
--- a/crates/application/src/delegation/tasks.rs
+++ b/crates/application/src/delegation/tasks.rs
@@ -836,6 +836,7 @@ mod tests {
unavailable(hiroute_domain::delegation::WorkerHarnessV1::QoderCli),
unavailable(hiroute_domain::delegation::WorkerHarnessV1::Pi),
unavailable(hiroute_domain::delegation::WorkerHarnessV1::DeepseekHarness),
+ unavailable(hiroute_domain::delegation::WorkerHarnessV1::OpenCode),
],
})
}
@@ -908,7 +909,8 @@ mod tests {
"claude_code",
"qoder_cli",
"pi",
- "deepseek_harness"
+ "deepseek_harness",
+ "opencode"
]
);
diff --git a/crates/cli/src/worker/input.rs b/crates/cli/src/worker/input.rs
index 4a3712c6..4420fef9 100644
--- a/crates/cli/src/worker/input.rs
+++ b/crates/cli/src/worker/input.rs
@@ -27,6 +27,7 @@ pub(super) fn parse_dependencies_discover(
"claude_code" => WorkerHarnessV1::ClaudeCode,
"qoder_cli" => WorkerHarnessV1::QoderCli,
"pi" => WorkerHarnessV1::Pi,
+ "opencode" => WorkerHarnessV1::OpenCode,
"deepseek_harness" => WorkerHarnessV1::DeepseekHarness,
_ => return Err(ErrorCode::InvalidArguments),
};
diff --git a/crates/cli/src/worker/render.rs b/crates/cli/src/worker/render.rs
index eb01499a..41b27cbc 100644
--- a/crates/cli/src/worker/render.rs
+++ b/crates/cli/src/worker/render.rs
@@ -712,6 +712,7 @@ fn worker_harness_wire_name(harness: WorkerHarnessV1) -> &'static str {
WorkerHarnessV1::ClaudeCode => "claude_code",
WorkerHarnessV1::QoderCli => "qoder_cli",
WorkerHarnessV1::Pi => "pi",
+ WorkerHarnessV1::OpenCode => "opencode",
WorkerHarnessV1::DeepseekHarness => "deepseek_harness",
}
}
diff --git a/crates/cli/src/worker/selection_windows_tests.rs b/crates/cli/src/worker/selection_windows_tests.rs
index fd20ca7a..389cf4b3 100644
--- a/crates/cli/src/worker/selection_windows_tests.rs
+++ b/crates/cli/src/worker/selection_windows_tests.rs
@@ -122,6 +122,11 @@ fn ordinary_inputs_bind_the_same_native_files_and_canonical_digest_without_mutat
#[test]
fn canonical_completed_selection_replays_before_missing_file_inspection() {
+ canonical_selection_replays(WorkerHarnessV1::CodexCli);
+ canonical_selection_replays(WorkerHarnessV1::OpenCode);
+}
+
+fn canonical_selection_replays(harness: WorkerHarnessV1) {
use hiroute_application::ApplicationService;
use hiroute_daemon::control::{ProductionControlRuntime, start_control};
let fixture = Fixture::new();
@@ -129,9 +134,10 @@ fn canonical_completed_selection_replays_before_missing_file_inspection() {
let adapter = fixture.file("manual-adapter.js", b"export {};");
let node = fixture.file("manual-node.exe", b"metadata-only fixture");
let ordinary = WorkerDependenciesSelectRequestV1 {
- harness: WorkerHarnessV1::CodexCli,
- adapter_path: Some(adapter.to_str().unwrap().into()),
- node_path: Some(node.to_str().unwrap().into()),
+ harness,
+ adapter_path: (harness == WorkerHarnessV1::CodexCli)
+ .then(|| adapter.to_str().unwrap().into()),
+ node_path: (harness == WorkerHarnessV1::CodexCli).then(|| node.to_str().unwrap().into()),
expected_selection_revision: 0,
..request(&cli)
};
diff --git a/crates/cli/tests/contracts.rs b/crates/cli/tests/contracts.rs
index 4dc65d7b..8a7f4922 100644
--- a/crates/cli/tests/contracts.rs
+++ b/crates/cli/tests/contracts.rs
@@ -379,8 +379,8 @@ fn gateway_show_waits_for_native_discovery_and_honors_control_timeout() {
Err(error) => panic!("{error}"),
}
};
- // macOS accepts inherit O_NONBLOCK. Keep accept cancellable, but
- // let this connection's reads wait for the explicit deadline.
+ // BSD accept inherits the listener's nonblocking mode. This peer uses
+ // blocking reads with a deadline while the client starts its handshake.
stream.set_nonblocking(false).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
diff --git a/crates/client-core/tests/transport.rs b/crates/client-core/tests/transport.rs
index 458dc08f..775b4ef3 100644
--- a/crates/client-core/tests/transport.rs
+++ b/crates/client-core/tests/transport.rs
@@ -426,6 +426,15 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {
"continue_session": {"state":"unavailable","reason":"installation_not_configured"},
"restricted_policy": {"state":"unavailable","reason":"installation_not_configured"}
},
+ {
+ "harness": "opencode",
+ "state": "unavailable",
+ "reason": "installation_not_configured",
+ "start_approve_all": {"state":"unavailable","reason":"installation_not_configured"},
+ "cancel": {"state":"unavailable","reason":"installation_not_configured"},
+ "continue_session": {"state":"unavailable","reason":"installation_not_configured"},
+ "restricted_policy": {"state":"unavailable","reason":"installation_not_configured"}
+ },
]
}),
Some(request.request_id),
@@ -451,7 +460,8 @@ async fn worker_executor_availability_is_an_empty_local_trust_query() {
WorkerHarnessV1::ClaudeCode,
WorkerHarnessV1::QoderCli,
WorkerHarnessV1::Pi,
- WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::DeepseekHarness,
+ WorkerHarnessV1::OpenCode
]
);
server.await.unwrap();
diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rs
index 30988625..4a4db922 100644
--- a/crates/daemon/src/control/runtime.rs
+++ b/crates/daemon/src/control/runtime.rs
@@ -388,7 +388,7 @@ impl ProductionControlRuntime {
.map_err(|error| error.to_string())?;
let home = native_agent_home()?;
let project = std::env::current_dir().map_err(|error| error.to_string())?;
- let scanner = match overrides.scanner {
+ let mut scanner = match overrides.scanner {
Some(scanner) => scanner,
None => {
use hiroute_domain::delegation::WorkerHarnessV1;
@@ -397,6 +397,7 @@ impl ProductionControlRuntime {
(AgentKindV1::ClaudeCode, WorkerHarnessV1::ClaudeCode),
(AgentKindV1::Qoder, WorkerHarnessV1::QoderCli),
(AgentKindV1::Pi, WorkerHarnessV1::Pi),
+ (AgentKindV1::OpenCode, WorkerHarnessV1::OpenCode),
(
AgentKindV1::DeepseekHarness,
WorkerHarnessV1::DeepseekHarness,
@@ -464,6 +465,15 @@ impl ProductionControlRuntime {
hiroute_integrations::DSH_INTEGRATION_PROFILE_REF_V1,
)
.map_err(|e| e.to_string())?;
+ let opencode_subject = AgentConnectionTransactionSubjectV1::from_registered_profile(
+ "agent_opencode_default",
+ hiroute_integrations::OPENCODE_PROFILE_ID_V1,
+ hiroute_integrations::OPENCODE_INTEGRATION_PROFILE_REF_V1,
+ )
+ .map_err(|e| e.to_string())?;
+ let opencode_model_target = AgentConnectionEffectRoleV1::ManagedConfiguration
+ .target_for(&opencode_subject)
+ .map_err(|e| e.to_string())?;
let mut scoped_targets = Vec::new();
let mut hermes_scan_targets = BTreeMap::new();
for target in stores
@@ -493,7 +503,11 @@ impl ProductionControlRuntime {
(&qoder_subject, scanner.qoder_user_skill_target()),
(&pi_subject, scanner.pi_user_skill_target()),
(&dsh_subject, scanner.dsh_user_skill_target()),
- ] {
+ (&opencode_subject, scanner.opencode_user_skill_target()),
+ ]
+ .into_iter()
+ .filter(|(_, collaboration)| collaboration.is_absolute())
+ {
let root = collaboration
.parent()
.and_then(|p| p.parent())
@@ -505,72 +519,105 @@ impl ProductionControlRuntime {
root.join("hiroute-management/SKILL.md"),
));
}
- let artifacts = stores
- .open_managed_artifacts_with_external_targets(
+ let mut external_targets = [
+ (
+ opencode_model_target.clone(),
+ scanner.opencode_user_models_target(),
+ ),
+ (
+ AgentConnectionEffectRoleV1::RoutingSkill
+ .target_for(&opencode_subject)
+ .map_err(|e| e.to_string())?,
+ scanner.opencode_user_skill_target(),
+ ),
+ (
+ AgentConnectionEffectRoleV1::ManagedConfiguration
+ .target_for(&dsh_subject)
+ .map_err(|e| e.to_string())?,
+ scanner.dsh_user_models_target(),
+ ),
+ (
+ AgentConnectionEffectRoleV1::RoutingSkill
+ .target_for(&dsh_subject)
+ .map_err(|e| e.to_string())?,
+ scanner.dsh_user_skill_target(),
+ ),
+ (
+ AgentConnectionEffectRoleV1::ManagedConfiguration
+ .target_for(&pi_subject)
+ .map_err(|error| error.to_string())?,
+ scanner.pi_user_models_target(),
+ ),
+ (
+ AgentConnectionEffectRoleV1::RoutingSkill
+ .target_for(&pi_subject)
+ .map_err(|error| error.to_string())?,
+ scanner.pi_user_skill_target(),
+ ),
+ (
+ AgentConnectionEffectRoleV1::ManagedConfiguration
+ .target_for(&qoder_subject)
+ .map_err(|error| error.to_string())?,
+ scanner.qoder_user_config_target(),
+ ),
+ (claude_managed_target, scanner.claude_user_settings_target()),
+ (codex_managed_target, scanner.codex_user_config_target()),
+ (profile_target, scanner.codex_profile_config_target()),
+ (
+ AgentConnectionEffectRoleV1::RoutingSkill
+ .target_for(&codex_subject)
+ .map_err(|error| error.to_string())?,
+ home.join(".agents/skills/hiroute-collaboration/SKILL.md"),
+ ),
+ (
+ AgentConnectionEffectRoleV1::RoutingSkill
+ .target_for(&claude_subject)
+ .map_err(|error| error.to_string())?,
+ home.join(".claude/skills/hiroute-collaboration/SKILL.md"),
+ ),
+ (
+ AgentConnectionEffectRoleV1::RoutingSkill
+ .target_for(&qoder_subject)
+ .map_err(|error| error.to_string())?,
+ scanner.qoder_user_skill_target(),
+ ),
+ ]
+ .into_iter()
+ .chain(scoped_targets)
+ .filter(|(_, path)| path.is_absolute())
+ .collect::<Vec<_>>();
+ let mut alternatives = scanner
+ .opencode_model_target_candidates()
+ .into_iter()
+ .skip(1);
+ let artifacts = loop {
+ match stores.open_managed_artifacts_with_external_targets(
storage_root.join("managed-artifacts"),
storage_root.join("artifact-restores"),
- [
- (
- AgentConnectionEffectRoleV1::ManagedConfiguration
- .target_for(&dsh_subject)
- .map_err(|e| e.to_string())?,
- scanner.dsh_user_models_target(),
- ),
- (
- AgentConnectionEffectRoleV1::RoutingSkill
- .target_for(&dsh_subject)
- .map_err(|e| e.to_string())?,
- scanner.dsh_user_skill_target(),
- ),
- (
- AgentConnectionEffectRoleV1::ManagedConfiguration
- .target_for(&pi_subject)
- .map_err(|error| error.to_string())?,
- scanner.pi_user_models_target(),
- ),
- (
- AgentConnectionEffectRoleV1::RoutingSkill
- .target_for(&pi_subject)
- .map_err(|error| error.to_string())?,
- scanner.pi_user_skill_target(),
- ),
- (
- AgentConnectionEffectRoleV1::ManagedConfiguration
- .target_for(&qoder_subject)
- .map_err(|error| error.to_string())?,
- scanner.qoder_user_config_target(),
- ),
- (claude_managed_target, scanner.claude_user_settings_target()),
- (codex_managed_target, scanner.codex_user_config_target()),
- (profile_target, scanner.codex_profile_config_target()),
- (
- AgentConnectionEffectRoleV1::RoutingSkill
- .target_for(&codex_subject)
- .map_err(|error| error.to_string())?,
- home.join(".agents/skills/hiroute-collaboration/SKILL.md"),
- ),
- (
- AgentConnectionEffectRoleV1::RoutingSkill
- .target_for(&claude_subject)
- .map_err(|error| error.to_string())?,
- home.join(".claude/skills/hiroute-collaboration/SKILL.md"),
- ),
- (
- AgentConnectionEffectRoleV1::RoutingSkill
- .target_for(&qoder_subject)
- .map_err(|error| error.to_string())?,
- scanner.qoder_user_skill_target(),
- ),
- ]
- .into_iter()
- .chain(scoped_targets),
- )
- .map_err(|error| error.to_string())?;
- if startup.preserve_observation_source
- && let Some(progress) = &startup.upgrade_progress
- {
- let _ = progress.send(hiroute_host_runtime::StorageUpgradePhase::Conversion);
- }
+ external_targets.clone(),
+ ) {
+ Ok(artifacts) => break artifacts,
+ Err(error) => {
+ // An added JSONC layer must not redirect an existing JSON recovery target.
+ // The same store validates every marker against the exact candidate path;
+ // no new binding metadata or permissive recovery reader is introduced.
+ if matches!(&error, hiroute_local_storage::LocalStorageError::Locked)
+ && let Some(path) = alternatives.next()
+ {
+ let target = external_targets
+ .iter_mut()
+ .find(|(target, _)| target == &opencode_model_target)
+ .ok_or_else(|| error.to_string())?;
+ target.1 = path.clone();
+ scanner
+ .bind_opencode_model_target(path)
+ .map_err(|e| e.to_string())?;
+ continue;
+ }
+ return Err(error.to_string());
+ }
+ }
+ };
let observation_workspace_key = observation_workspace_key(storage_root)?;
let digest_authority = DigestAuthority::new(*observation_workspace_key);
let observation_root = storage_root.join("observation");
@@ -1689,6 +1736,7 @@ fn release_agent_scanner(
AgentKindV1::Qoder => &mut layout.qoder_executable,
AgentKindV1::Pi => &mut layout.pi_executable,
AgentKindV1::DeepseekHarness => &mut layout.dsh_executable,
+ AgentKindV1::OpenCode => &mut layout.opencode_executable,
AgentKindV1::Hermes => continue,
};
*target = executable.clone();
@@ -1725,6 +1773,7 @@ fn discovered_agent(
AgentKindV1::Qoder => QODER_PROFILE_ID_V1,
AgentKindV1::Pi => hiroute_integrations::PI_PROFILE_ID_V1,
AgentKindV1::DeepseekHarness => hiroute_integrations::DSH_PROFILE_ID_V1,
+ AgentKindV1::OpenCode => hiroute_integrations::OPENCODE_PROFILE_ID_V1,
AgentKindV1::Hermes => hiroute_integrations::HERMES_PROFILE_ID_V1,
}
.to_owned(),
diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rs
index 9386724d..67fe4459 100644
--- a/crates/daemon/src/control/runtime/agent_connection.rs
+++ b/crates/daemon/src/control/runtime/agent_connection.rs
@@ -361,6 +361,20 @@ impl AgentConnectionControlPort for LocalControlAdapter {
} else {
"hiroute"
});
+ if agent_id == "agent_opencode_default" {
+ return self
+ .scanner
+ .check_opencode_collaboration(
+ &cli,
+ self.additional_collaboration_probe_target(
+ super::settings_facts::SettingsAgentClass::OpenCode,
+ )?,
+ )
+ .map_err(|error| {
+ eprintln!("native OpenCode collaboration check: {}", error.stage);
+ collaboration_check::qoder_failure(error)
+ });
+ }
if agent_id == "agent_dsh_default" {
return self
.scanner
diff --git a/crates/daemon/src/control/runtime/agent_live_check.rs b/crates/daemon/src/control/runtime/agent_live_check.rs
index 119595cf..cb9366ed 100644
--- a/crates/daemon/src/control/runtime/agent_live_check.rs
+++ b/crates/daemon/src/control/runtime/agent_live_check.rs
@@ -142,6 +142,7 @@ impl LocalControlAdapter {
let result = match target.surface {
AgentModelSurfaceV2::PiCli
| AgentModelSurfaceV2::DshCli
+ | AgentModelSurfaceV2::OpenCodeCli
| AgentModelSurfaceV2::HermesCli => {
return Err(ControlReadError::Denied);
}
diff --git a/crates/daemon/src/control/runtime/collaboration_installation.rs b/crates/daemon/src/control/runtime/collaboration_installation.rs
index 4c08d26f..251b2054 100644
--- a/crates/daemon/src/control/runtime/collaboration_installation.rs
+++ b/crates/daemon/src/control/runtime/collaboration_installation.rs
@@ -92,7 +92,10 @@ impl LocalControlAdapter {
// Only historical clients ever owned sealed collaboration credentials.
if matches!(
class,
- SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh
+ SettingsAgentClass::Qoder
+ | SettingsAgentClass::Pi
+ | SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
) {
return Ok(());
}
@@ -124,6 +127,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Qoder
| SettingsAgentClass::Pi
| SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
| SettingsAgentClass::Hermes => {
return Err(error());
}
@@ -141,6 +145,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Qoder
| SettingsAgentClass::Pi
| SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
| SettingsAgentClass::Hermes => {
return Err(error());
}
diff --git a/crates/daemon/src/control/runtime/compute_routing.rs b/crates/daemon/src/control/runtime/compute_routing.rs
index b446eb78..410fea22 100644
--- a/crates/daemon/src/control/runtime/compute_routing.rs
+++ b/crates/daemon/src/control/runtime/compute_routing.rs
@@ -112,16 +112,13 @@ impl LocalControlAdapter {
return Ok(());
}
}
- if matches!(
- descriptor.field_selector.as_str(),
- "pi.api-key" | "dsh.api-key"
- ) {
- let sources = if descriptor.field_selector == "dsh.api-key" {
- self.scanner.dsh_api_sources()
- } else {
- self.scanner.pi_api_sources()
- }
- .map_err(|_| ControlReadError::SnapshotChanged)?;
+ if let Some(ecosystem) =
+ hiroute_integrations::NativeApiEcosystem::from_selector(&descriptor.field_selector)
+ {
+ let sources = self
+ .scanner
+ .native_api_sources(ecosystem)
+ .map_err(|_| ControlReadError::SnapshotChanged)?;
if hiroute_integrations::native_api_connection_points(sources)
.iter()
.any(|point| {
@@ -140,19 +137,17 @@ impl LocalControlAdapter {
{
return Ok(());
}
- return (if descriptor.field_selector == "dsh.api-key" {
- self.scanner.dsh_api_sources()
- } else {
- self.scanner.pi_api_sources()
- })
- .map_err(|_| ControlReadError::SnapshotChanged)?
- .iter()
- .any(|source| {
- source.credential.as_ref() == Some(&descriptor)
- && &source.evidence_digest == expected_evidence
- })
- .then_some(())
- .ok_or(ControlReadError::SnapshotChanged);
+ return self
+ .scanner
+ .native_api_sources(ecosystem)
+ .map_err(|_| ControlReadError::SnapshotChanged)?
+ .iter()
+ .any(|source| {
+ source.credential.as_ref() == Some(&descriptor)
+ && &source.evidence_digest == expected_evidence
+ })
+ .then_some(())
+ .ok_or(ControlReadError::SnapshotChanged);
}
let catalog = self
.current_catalog()
@@ -362,8 +357,9 @@ impl ComputeFactsPort for LocalControlAdapter {
.iter()
.map(|discovery| scan_item(&catalog, discovery))
.collect::<Result<Vec<_>, _>>()?;
- items.extend(self.native_compute_scan_items(false)?);
- items.extend(self.native_compute_scan_items(true)?);
+ for ecosystem in hiroute_integrations::NativeApiEcosystem::ALL {
+ items.extend(self.native_compute_scan_items(ecosystem)?);
+ }
// Subscription discovery has its own metadata-only API. Generic ScanCompute must not
// start CPA or materialize OAuth state merely because a screen was opened.
items.sort_by(|left, right| left.agent_id.cmp(&right.agent_id));
diff --git a/crates/daemon/src/control/runtime/delegation_task_queries.rs b/crates/daemon/src/control/runtime/delegation_task_queries.rs
index 727df065..c653467e 100644
--- a/crates/daemon/src/control/runtime/delegation_task_queries.rs
+++ b/crates/daemon/src/control/runtime/delegation_task_queries.rs
@@ -259,6 +259,7 @@ pub(super) fn run_view(task: &DelegationTaskV1, run: &DelegationRunV1) -> Delega
hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "Qoder",
hiroute_domain::delegation::WorkerHarnessV1::Pi => "Pi",
hiroute_domain::delegation::WorkerHarnessV1::DeepseekHarness => "DeepSeek Harness",
+ hiroute_domain::delegation::WorkerHarnessV1::OpenCode => "OpenCode",
};
DelegationRunViewV1 {
task_id: run.task_id.clone(),
diff --git a/crates/daemon/src/control/runtime/model_connections/discovered.rs b/crates/daemon/src/control/runtime/model_connections/discovered.rs
index 1d067684..19375aaa 100644
--- a/crates/daemon/src/control/runtime/model_connections/discovered.rs
+++ b/crates/daemon/src/control/runtime/model_connections/discovered.rs
@@ -135,6 +135,7 @@ impl LocalControlAdapter {
.unwrap_or_default()
.into_iter()
.chain(self.scanner.dsh_api_sources().unwrap_or_default())
+ .chain(self.scanner.opencode_api_sources().unwrap_or_default())
.collect();
let mut sources = sources;
sources.extend(self.claude_api_point_sources(&catalog).unwrap_or_default());
@@ -159,6 +160,7 @@ impl LocalControlAdapter {
.unwrap_or_default()
.into_iter()
.chain(self.scanner.dsh_api_sources().unwrap_or_default())
+ .chain(self.scanner.opencode_api_sources().unwrap_or_default())
.find(|source| super::pi_discovered::pi_discovery(source) == request.discovery)
{
return self.prepare_native_api_candidate(source, &request.prepare_id);
diff --git a/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs b/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs
index bfc011b9..2bf2f491 100644
--- a/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs
+++ b/crates/daemon/src/control/runtime/model_connections/pi_discovered.rs
@@ -1,7 +1,7 @@
//! Pi sources use the same closed prepare/save transaction as other native API discoveries.
use super::*;
use hiroute_application_api::{ComputeDiscoveryRefV1, ComputeScanItemV1};
-use hiroute_integrations::{DiscoveredAuthSource, PiApiSource};
+use hiroute_integrations::{DiscoveredAuthSource, NativeApiEcosystem, PiApiSource};
#[cfg(all(test, unix))]
#[path = "pi_discovered_tests.rs"]
@@ -16,18 +16,10 @@ pub(super) fn pi_discovery(source: &PiApiSource) -> ComputeDiscoveryRefV1 {
impl LocalControlAdapter {
pub(in crate::control::runtime) fn native_compute_scan_items(
&self,
- dsh: bool,
+ ecosystem: NativeApiEcosystem,
) -> Result<Vec<ComputeScanItemV1>, hiroute_application::control::ControlReadError> {
- let agent_id = if dsh {
- "agent_dsh_default"
- } else {
- "agent_pi_default"
- };
- let sources = match if dsh {
- self.scanner.dsh_api_sources()
- } else {
- self.scanner.pi_api_sources()
- } {
+ let agent_id = ecosystem.agent_id();
+ let sources = match self.scanner.native_api_sources(ecosystem) {
Ok(sources) => sources,
Err(_) => {
return Ok(vec![ComputeScanItemV1 {
@@ -44,10 +36,10 @@ impl LocalControlAdapter {
inventory_eligible: false,
discovery: None,
actions_required: vec![
- if dsh {
- "check_dsh_configuration"
- } else {
- "check_pi_configuration"
+ match ecosystem {
+ NativeApiEcosystem::Pi => "check_pi_configuration",
+ NativeApiEcosystem::Dsh => "check_dsh_configuration",
+ NativeApiEcosystem::OpenCode => "check_opencode_configuration",
}
.into(),
],
@@ -90,7 +82,7 @@ impl LocalControlAdapter {
connection_option_id: None,
endpoint_profile_id: None,
registered_base_url: None,
- observed_model_id: Some(source.model_id),
+ observed_model_id: (!source.model_id.is_empty()).then_some(source.model_id),
model_configuration_id: None,
inventory_eligible: ready,
discovery,
@@ -165,7 +157,7 @@ impl LocalControlAdapter {
.protocol
.ok_or(ComputeManagementControlError::DiscoveryNotImportable)?;
use hiroute_application::ProtectedInputPort;
- let dsh = source.source_ref.starts_with("dsh-source/");
+
let (base_url, secret) = (if source.source_ref.starts_with("hermes-source/") {
self.read_hermes_source(&source)
.map_err(|_| hiroute_integrations::AgentFilesystemScanError::SourceChanged)
@@ -195,10 +187,8 @@ impl LocalControlAdapter {
)
})
.map_err(|_| hiroute_integrations::AgentFilesystemScanError::SourceChanged)
- } else if dsh {
- self.scanner.read_dsh_api_source(&source)
} else {
- self.scanner.read_pi_api_source(&source)
+ self.scanner.read_native_api_source(&source)
})
.map_err(|_| ComputeManagementControlError::DiscoveryChanged)?;
let credential = source
@@ -219,10 +209,11 @@ impl LocalControlAdapter {
.map_err(|_| ComputeManagementControlError::Unavailable)?
.insert(input_slot.clone(), credential.clone());
let candidate_digest = hiroute_domain::CanonicalDigest::of(&(
- if dsh {
- "dsh-discovered-candidate/v1"
- } else {
- "pi-discovered-candidate/v1"
+ match NativeApiEcosystem::from_source(&source) {
+ Some(NativeApiEcosystem::Dsh) => "dsh-discovered-candidate/v1",
+ Some(NativeApiEcosystem::OpenCode) => "opencode-discovered-candidate/v1",
+ // Hermes/Claude retain the shared candidate identity used on main.
+ _ => "pi-discovered-candidate/v1",
},
&evidence,
prepare_id,
@@ -267,12 +258,10 @@ impl LocalControlAdapter {
.is_some_and(|c| c.field_selector == "env.ANTHROPIC_AUTH_TOKEN")
{
"Claude Code"
- } else if dsh {
- "DSH"
- } else if source.source_ref.starts_with("hermes-source/") {
- "Hermes"
} else {
- "Pi"
+ NativeApiEcosystem::from_source(&source)
+ .ok_or(ComputeManagementControlError::DiscoveryNotImportable)?
+ .label()
},
source.provider_id
),
diff --git a/crates/daemon/src/control/runtime/model_connections/points.rs b/crates/daemon/src/control/runtime/model_connections/points.rs
index cfc968c6..99450b05 100644
--- a/crates/daemon/src/control/runtime/model_connections/points.rs
+++ b/crates/daemon/src/control/runtime/model_connections/points.rs
@@ -142,6 +142,10 @@ impl LocalControlAdapter {
"agent_claude_default",
self.claude_api_point_sources(&catalog).map_err(|_| ()),
),
+ (
+ "agent_opencode_default",
+ self.scanner.opencode_api_sources().map_err(|_| ()),
+ ),
("agent_hermes_default", hermes_sources),
] {
let sources = match sources {
diff --git a/crates/daemon/src/control/runtime/mutation.rs b/crates/daemon/src/control/runtime/mutation.rs
index 2a40997c..e7eee8d7 100644
--- a/crates/daemon/src/control/runtime/mutation.rs
+++ b/crates/daemon/src/control/runtime/mutation.rs
@@ -159,6 +159,7 @@ impl LocalControlAdapter {
.unwrap_or_default()
.into_iter()
.chain(self.scanner.dsh_api_sources().unwrap_or_default())
+ .chain(self.scanner.opencode_api_sources().unwrap_or_default())
.chain(
self.hermes_source_facts()
.map(|facts| facts.sources)
diff --git a/crates/daemon/src/control/runtime/native_additional_model.rs b/crates/daemon/src/control/runtime/native_additional_model.rs
index 3c210235..1c89ea50 100644
--- a/crates/daemon/src/control/runtime/native_additional_model.rs
+++ b/crates/daemon/src/control/runtime/native_additional_model.rs
@@ -15,7 +15,12 @@ pub(super) fn is_settings_additional_model(intent: &ExternalEffectIntentV1) -> b
&& intent.desired()["transaction"] == "settings"
&& matches!(
intent.desired()["subject"]["agent_id"].as_str(),
- Some("agent_qoder_default" | "agent_pi_default" | "agent_dsh_default")
+ Some(
+ "agent_qoder_default"
+ | "agent_pi_default"
+ | "agent_dsh_default"
+ | "agent_opencode_default"
+ )
)
}
@@ -25,7 +30,10 @@ pub(super) fn additional_model_endpoint(
) -> PortResult<String> {
if matches!(
kind,
- AgentKindV1::Pi | AgentKindV1::DeepseekHarness | AgentKindV1::Hermes
+ AgentKindV1::Pi
+ | AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
+ | AgentKindV1::Hermes
) {
return Ok(gateway_base_url.to_owned());
}
@@ -68,7 +76,10 @@ pub(super) fn additional_models_for_grant(
}
let budget = (if matches!(
kind,
- AgentKindV1::Pi | AgentKindV1::DeepseekHarness | AgentKindV1::Hermes
+ AgentKindV1::Pi
+ | AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
+ | AgentKindV1::Hermes
) {
hiroute_integrations::pi_plan_token_budget(&plan.body.materialized)
} else {
@@ -111,6 +122,24 @@ impl LocalControlAdapter {
return Err(conflict("dsh.settings.default.changed"));
}
}
+ if let Some(expected) = &payload.additional_dependencies {
+ let models = match &payload.change {
+ AdditionalModelFileAction::Configure { models, .. } => models.as_slice(),
+ _ => &[],
+ };
+ let observed = self
+ .scanner
+ .opencode_model_dependencies(
+ &hiroute_application::agent_connection::additional_model_provider_id(
+ &payload.context_id,
+ ),
+ models,
+ )
+ .map_err(|_| conflict("opencode.settings.dependencies"))?;
+ if &observed != expected {
+ return Err(conflict("opencode.settings.dependencies.changed"));
+ }
+ }
if let Some(expected) = &payload.pi_settings_content {
let settings = self
.scanner
diff --git a/crates/daemon/src/control/runtime/settings_entry_opencode_tests.rs b/crates/daemon/src/control/runtime/settings_entry_opencode_tests.rs
new file mode 100644
index 00000000..c9f6b475
--- /dev/null
+++ b/crates/daemon/src/control/runtime/settings_entry_opencode_tests.rs
@@ -0,0 +1,372 @@
+//! Shared public settings transactions with OpenCode's loaded user layers and real recovery.
+use super::models::{model_spec, model_status, restore_spec};
+use super::*;
+
+fn configure_models(fixture: &QoderFixture) {
+ let mut spec = model_spec(fixture);
+ spec["model"]["settings"]["mode"] = json!("opencode_additional");
+ apply(&fixture.service, &fixture.runtime, spec, "opencode-models");
+}
+
+fn selector(fixture: &QoderFixture) -> String {
+ let value: serde_json::Value =
+ serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();
+ let (provider, declaration) = value["provider"]
+ .as_object()
+ .unwrap()
+ .iter()
+ .next()
+ .unwrap();
+ format!(
+ "{provider}/{}",
+ declaration["models"]
+ .as_object()
+ .unwrap()
+ .keys()
+ .next()
+ .unwrap()
+ )
+}
+
+#[test]
+fn opencode_markdown_references_block_restore_but_keep_rotation_and_user_resources() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::opencode::opencode_markdown_references_block_restore_but_keep_rotation_and_user_resources",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_kind(true, AgentKindV1::OpenCode);
+ configure_models(&fixture);
+ for directory in ["agent/nested", "agents", "mode", "modes"] {
+ let path = fixture
+ .native_config
+ .parent()
+ .unwrap()
+ .join(directory)
+ .join("reviewer.md");
+ let content = format!(
+ "---\nmodel: '{}'\n---\nKeep this native prompt.\n",
+ selector(&fixture)
+ );
+ private_file(&path, content.as_bytes());
+ let before = fs::read(&fixture.native_config).unwrap();
+ let status = model_status(&fixture);
+ let preview = fixture.service.dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":restore_spec(&fixture, &status)}),
+ None,
+ ));
+ assert!(preview.error.is_none(), "{preview:?}");
+ let preview = preview.data.unwrap();
+ assert_eq!(preview["applicable"], false, "{preview}");
+ assert!(
+ preview["blockers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|row| row["reason"] == "additional_default_in_use")
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), before);
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ let mut rotation = model_spec(&fixture);
+ rotation["model"]["settings"]["mode"] = json!("opencode_additional");
+ rotation["access_token"] = json!({"intent":"regenerate"});
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ rotation,
+ &format!("markdown-rotation-{}", directory.replace('/', "-")),
+ );
+ assert_eq!(fs::read(&path).unwrap(), content.as_bytes());
+ fs::remove_file(path).unwrap();
+ }
+ // Unknown frontmatter has the same removal boundary, without blocking rotation.
+ let path = fixture
+ .native_config
+ .parent()
+ .unwrap()
+ .join("agents/unknown.md");
+ private_file(&path, b"---\n<<: {model: hidden/route}\n---\nKeep\n");
+ let status = model_status(&fixture);
+ let preview = fixture
+ .service
+ .dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":restore_spec(&fixture, &status)}),
+ None,
+ ))
+ .data
+ .unwrap();
+ assert_eq!(preview["applicable"], false);
+ let mut rotation = model_spec(&fixture);
+ rotation["model"]["settings"]["mode"] = json!("opencode_additional");
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ rotation,
+ "markdown-unknown-retained",
+ );
+ fs::remove_file(path).unwrap();
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ restore_spec(&fixture, &model_status(&fixture)),
+ "markdown-safe-restore",
+ );
+ assert_eq!(model_status(&fixture)["state"], "not_configured");
+}
+
+#[test]
+fn opencode_markdown_added_or_changed_after_preview_rejects_stale_restore() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::opencode::opencode_markdown_added_or_changed_after_preview_rejects_stale_restore",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_kind(true, AgentKindV1::OpenCode);
+ configure_models(&fixture);
+ let path = fixture
+ .native_config
+ .parent()
+ .unwrap()
+ .join("agents/reviewer.md");
+ let reference = format!("---\nmodel: '{}'\n---\nNative prompt\n", selector(&fixture));
+ for existed in [false, true] {
+ if existed {
+ private_file(&path, b"---\nmodel: daily/default\n---\nNative prompt\n");
+ }
+ let spec = restore_spec(&fixture, &model_status(&fixture));
+ let preview = fixture
+ .service
+ .dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":spec}),
+ None,
+ ))
+ .data
+ .unwrap();
+ assert_eq!(preview["applicable"], true);
+ let before = fs::read(&fixture.native_config).unwrap();
+ private_file(&path, reference.as_bytes());
+ let response = fixture.service.dispatch_wire(request("ApplyAgentConnectionRestore", json!({"spec":spec,
+ "accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],
+ "expected_revisions":preview["expected_revisions"],"idempotency_key":format!("markdown-stale-{existed}")}), None));
+ assert_eq!(
+ response.error.unwrap().code,
+ api::ErrorCode::ChangePreviewStale
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), before);
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ fs::remove_file(&path).unwrap();
+ }
+}
+
+#[test]
+fn opencode_markdown_reference_added_during_staging_preserves_the_active_route() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::opencode::opencode_markdown_reference_added_during_staging_preserves_the_active_route",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_kind(true, AgentKindV1::OpenCode);
+ configure_models(&fixture);
+ let path = fixture
+ .native_config
+ .parent()
+ .unwrap()
+ .join("agents/reviewer.md");
+ private_file(&path, b"Native prompt without a model\n");
+ let reference = format!("---\nmodel: '{}'\n---\nNative prompt\n", selector(&fixture));
+ let spec = restore_spec(&fixture, &model_status(&fixture));
+ let before = fs::read(&fixture.native_config).unwrap();
+ let mut ports = fixture.runtime.application_ports();
+ ports.mutation = Some(Arc::new(fault::FileRace {
+ adapter: fixture.runtime.adapter.clone(),
+ path: path.clone(),
+ fail_after_file: false,
+ replacement: Some(reference.as_bytes().to_vec()),
+ }));
+ let racing = LocalControlDaemon::new(ApplicationService::new(ports));
+ let preview = racing
+ .dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":spec}),
+ None,
+ ))
+ .data
+ .unwrap();
+ assert_eq!(preview["applicable"], true);
+ let response = racing.dispatch_wire(request("ApplyAgentConnectionRestore", json!({"spec":spec,
+ "accept_digest":preview["accept_digest"],"dependency_digest":preview["dependency_digest"],
+ "expected_revisions":preview["expected_revisions"],"idempotency_key":"markdown-staging-race"}), None));
+ assert!(response.error.is_none(), "{response:?}");
+ assert_eq!(response.data.unwrap()["state"], "rolled_back");
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), before);
+ assert_eq!(fs::read(path).unwrap(), reference.as_bytes());
+ assert_eq!(model_status(&fixture)["state"], "configured");
+}
+
+#[test]
+fn opencode_pending_file_tail_retries_the_original_context_bound_operation() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::opencode::opencode_pending_file_tail_retries_the_original_context_bound_operation",
+ ) {
+ return;
+ }
+ super::models::pending_file_tail_retries_exact_operation(AgentKindV1::OpenCode);
+}
+
+#[test]
+fn opencode_selected_native_default_blocks_restore_with_an_actionable_preview() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::opencode::opencode_selected_native_default_blocks_restore_with_an_actionable_preview",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_kind(true, AgentKindV1::OpenCode);
+ configure_models(&fixture);
+ let status = model_status(&fixture);
+ let mut value: serde_json::Value =
+ serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();
+ let (provider, declaration) = value["provider"]
+ .as_object()
+ .unwrap()
+ .iter()
+ .next()
+ .unwrap();
+ let model = declaration["models"]
+ .as_object()
+ .unwrap()
+ .keys()
+ .next()
+ .unwrap();
+ value["model"] = json!(format!("{provider}/{model}"));
+ private_file(&fixture.native_config, &serde_json::to_vec(&value).unwrap());
+ let before = fs::read(&fixture.native_config).unwrap();
+ let preview = fixture.service.dispatch_wire(request(
+ "PreviewAgentConnectionRestore",
+ json!({"spec":restore_spec(&fixture, &status)}),
+ None,
+ ));
+ assert!(preview.error.is_none(), "{preview:?}");
+ let preview = preview.data.unwrap();
+ assert_eq!(preview["applicable"], false, "{preview:?}");
+ assert!(
+ preview["blockers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|row| row["reason"] == "additional_default_in_use"),
+ "{preview:?}"
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), before);
+}
+
+#[test]
+fn opencode_review_new_jsonc_keeps_managed_json_binding_after_restart_and_restore() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::opencode::opencode_review_new_jsonc_keeps_managed_json_binding_after_restart_and_restore",
+ ) {
+ return;
+ }
+ let mut fixture = QoderFixture::with_kind(true, AgentKindV1::OpenCode);
+ let original = fs::read(&fixture.native_config).unwrap();
+ configure_models(&fixture);
+ let status = model_status(&fixture);
+ let managed = fs::read(&fixture.native_config).unwrap();
+ let added = fixture.native_config.with_extension("jsonc");
+ let unrelated = br#"{"$schema":"https://opencode.ai/config.json","instructions":["new.md"]}"#;
+ private_file(&added, unrelated);
+ let storage = fixture._root.path().join("storage");
+ let home = PathBuf::from(std::env::var_os("HOME").unwrap());
+ let mut layout = AgentFilesystemLayoutV1::from_process(&home, fixture._root.path());
+ layout.opencode_context =
+ Some(hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap());
+ let registry = serde_json::from_slice(include_bytes!(
+ "../../../../../assets/connector-registry/current/registry-seed.json"
+ ))
+ .unwrap();
+ let model_data: hiroute_domain::ReleaseModelDataBundleV2 = serde_json::from_slice(
+ include_bytes!("../../../../../assets/release-facts/current/bundle/model-data.json"),
+ )
+ .unwrap();
+ let scanner = FilesystemAgentScannerV1::new(
+ layout,
+ ClaudeRegistrationIndexV1::from_verified_model_data(&registry, &model_data.data).unwrap(),
+ );
+ drop(fixture.service);
+ drop(fixture.runtime);
+ fixture.runtime = open_with_scanner(&storage, scanner);
+ fixture
+ .runtime
+ .adapter
+ .reconcile_startup_and_open()
+ .unwrap();
+ fixture.service = LocalControlDaemon::new(ApplicationService::new(
+ fixture
+ .runtime
+ .application_ports()
+ .with_agent_connection(Arc::new(FixtureFacts::collaboration(
+ fixture.runtime.adapter.clone(),
+ ))),
+ ));
+ assert_eq!(
+ fixture
+ .runtime
+ .adapter
+ .scanner
+ .opencode_user_models_target(),
+ fixture.native_config
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), managed);
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ restore_spec(&fixture, &status),
+ "opencode-restarted-restore",
+ );
+ assert_eq!(model_status(&fixture)["state"], "not_configured");
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), original);
+ assert_eq!(fs::read(added).unwrap(), unrelated);
+}
+
+#[test]
+fn opencode_review_status_reports_relevant_user_layer_drift_only() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::opencode::opencode_review_status_reports_relevant_user_layer_drift_only",
+ ) {
+ return;
+ }
+ let fixture = QoderFixture::with_kind(true, AgentKindV1::OpenCode);
+ configure_models(&fixture);
+ let original_status = model_status(&fixture);
+ let managed = fs::read(&fixture.native_config).unwrap();
+ let value: serde_json::Value = serde_json::from_slice(&managed).unwrap();
+ let provider = value["provider"]
+ .as_object()
+ .unwrap()
+ .keys()
+ .next()
+ .unwrap();
+ let overlay = PathBuf::from(std::env::var_os("HOME").unwrap()).join(".opencode/opencode.jsonc");
+ let unrelated = br#"{"$schema":"https://opencode.ai/config.json","instructions":["other.md"],"provider":{"daily":{}}}"#;
+ for conflict in [
+ json!({"provider":{(provider):{"options":{"baseURL":"https://example.invalid/v1"}}}}),
+ json!({"enabled_providers":["daily"]}),
+ json!({"disabled_providers":[provider]}),
+ ] {
+ private_file(&overlay, unrelated);
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ private_file(&overlay, &serde_json::to_vec(&conflict).unwrap());
+ let status = model_status(&fixture);
+ assert_eq!(status["state"], "drift", "{conflict}");
+ assert_eq!(
+ status["restore_point_ref"],
+ original_status["restore_point_ref"]
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), managed);
+ }
+ private_file(&overlay, unrelated);
+ assert_eq!(model_status(&fixture)["state"], "configured");
+}
diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
index b430c736..288dc0aa 100644
--- a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
@@ -1,7 +1,7 @@
//! Additive model settings through the public transaction and real native artifact store.
use super::*;
-fn model_spec(fixture: &QoderFixture) -> serde_json::Value {
+pub(super) fn model_spec(fixture: &QoderFixture) -> serde_json::Value {
let publication = fixture
.runtime
.adapter
@@ -26,7 +26,7 @@ fn model_spec(fixture: &QoderFixture) -> serde_json::Value {
.unwrap();
json!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context,"model":{"intent":"configure","settings":{"mode":"qoder_additional","allowed_plan_ids":[plan.agent_plan_id]}}})
}
-fn model_status(fixture: &QoderFixture) -> serde_json::Value {
+pub(super) fn model_status(fixture: &QoderFixture) -> serde_json::Value {
let result = fixture.service.dispatch_wire(request(
"GetAgentConnectionStatus",
json!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context}),
@@ -35,7 +35,10 @@ fn model_status(fixture: &QoderFixture) -> serde_json::Value {
assert!(result.error.is_none(), "{result:?}");
result.data.unwrap()
}
-fn restore_spec(fixture: &QoderFixture, status: &serde_json::Value) -> serde_json::Value {
+pub(super) fn restore_spec(
+ fixture: &QoderFixture,
+ status: &serde_json::Value,
+) -> serde_json::Value {
json!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context,"model":{"intent":"restore","restore_point_ref":status["restore_point_ref"]}})
}
@@ -638,9 +641,16 @@ fn qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_e
) {
return;
}
- let fixture = QoderFixture::with_models(true);
+ pending_file_tail_retries_exact_operation(AgentKindV1::Qoder);
+}
+
+pub(super) fn pending_file_tail_retries_exact_operation(kind: AgentKindV1) {
+ let fixture = QoderFixture::with_kind(true, kind);
let before = fs::read(&fixture.native_config).unwrap();
- let spec = model_spec(&fixture);
+ let mut spec = model_spec(&fixture);
+ if kind == AgentKindV1::OpenCode {
+ spec["model"]["settings"]["mode"] = json!("opencode_additional");
+ }
let mut ports = fixture
.runtime
.application_ports()
@@ -747,6 +757,33 @@ fn qoder_pending_file_tail_keeps_collaboration_preview_independent_and_retries_e
assert_eq!(model_status(&fixture)["state"], "pending");
private_file(&fixture.native_config, &before);
let request_body = json!({"schema":"hiroute.agent-settings-retry/v1","context_id":fixture.context,"operation_id":id});
+ if kind == AgentKindV1::OpenCode {
+ let resource = fixture
+ .native_config
+ .parent()
+ .unwrap()
+ .join("agents/late.md");
+ private_file(
+ &resource,
+ b"---\nmodel: daily/default\n---\nConcurrent native resource\n",
+ );
+ let resumed = fixture.service.dispatch_wire(request(
+ "ApplyAgentConnectionChange",
+ request_body.clone(),
+ None,
+ ));
+ assert!(
+ resumed.error.is_some()
+ || resumed
+ .data
+ .as_ref()
+ .is_some_and(|data| data["state"] != "succeeded"),
+ "{resumed:?}"
+ );
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), before);
+ assert_eq!(model_status(&fixture)["state"], "pending");
+ fs::remove_file(resource).unwrap();
+ }
for _ in 0..2 {
let resumed = fixture.service.dispatch_wire(request(
"ApplyAgentConnectionChange",
diff --git a/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs
index 7a1e9b29..7ac1171f 100644
--- a/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_tests.rs
@@ -34,10 +34,17 @@ impl QoderFixture {
fn with_agents(models: bool, kind: AgentKindV1, all: bool) -> Self {
let pi = kind == AgentKindV1::Pi;
+ let opencode = kind == AgentKindV1::OpenCode;
let root = tempfile::tempdir().unwrap();
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
let home = PathBuf::from(std::env::var_os("HOME").unwrap());
- let config_root = home.join(if pi { "selected-pi" } else { "selected-qoder" });
+ let config_root = home.join(if opencode {
+ ".config/opencode"
+ } else if pi {
+ "selected-pi"
+ } else {
+ "selected-qoder"
+ });
private_file(
&config_root.join("settings.json"),
b"native settings are opaque to HiRoute\n",
@@ -74,6 +81,18 @@ impl QoderFixture {
} else {
layout.qoder_executable = root.path().join("missing-qoder");
}
+ if opencode {
+ layout.opencode_executable = layout.qoder_executable.clone();
+ layout.qoder_config_root = home.join("selected-qoder");
+ layout.opencode_context = Some(
+ hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap(),
+ );
+ // Exercise the existing JSON target before a higher JSONC layer appears.
+ private_file(
+ &config_root.join("opencode.json"),
+ br#"{"$schema":"https://opencode.ai/config.json","instructions":["keep.md"]}"#,
+ );
+ }
if all {
let package = root.path().join("all-pi-package");
private_file(&package.join("package.json"), br#"{"name":"@earendil-works/pi-coding-agent","version":"1.0.2","bin":{"pi":"dist/bundle/cli.js"}}"#);
@@ -113,12 +132,16 @@ impl QoderFixture {
private_file(&scanner.pi_user_models_target(), br#"{"providers":{}}"#);
private_file(&scanner.dsh_user_models_target(), b"[]\n");
}
- let native_config = if pi {
+ let native_config = if opencode {
+ scanner.opencode_user_models_target()
+ } else if pi {
scanner.pi_user_models_target()
} else {
scanner.qoder_user_config_target()
};
- let skill = if pi {
+ let skill = if opencode {
+ scanner.opencode_user_skill_target()
+ } else if pi {
scanner.pi_user_skill_target()
} else {
scanner.qoder_user_skill_target()
@@ -141,7 +164,9 @@ impl QoderFixture {
if models {
private_file(
&native_config,
- if pi {
+ if opencode {
+ br#"{"$schema":"https://opencode.ai/config.json","instructions":["keep.md"]}"#
+ } else if pi {
br#"{"providers":{"native":{"user":"preserved"}},"unknown":{"keep":true}}"#
} else {
br#"{"model":{"name":"native/default"},"providers":{"native":{"user":"preserved"}},"unknown":{"keep":true}}"#
@@ -151,7 +176,9 @@ impl QoderFixture {
runtime.adapter.reconcile_startup_and_open().unwrap();
let context = runtime
.adapter
- .settings_context_for_agent(if pi {
+ .settings_context_for_agent(if opencode {
+ "agent_opencode_default"
+ } else if pi {
"agent_pi_default"
} else {
"agent_qoder_default"
@@ -698,5 +725,8 @@ fn qoder_borrowed_skill_restore_releases_only_the_reference_after_user_edits() {
#[path = "settings_entry_qoder_model_tests.rs"]
mod models;
+#[path = "settings_entry_opencode_tests.rs"]
+mod opencode;
+
#[path = "settings_entry_model_budget_tests.rs"]
mod budget_tests;
diff --git a/crates/daemon/src/control/runtime/settings_entry_shared_skills_tests.rs b/crates/daemon/src/control/runtime/settings_entry_shared_skills_tests.rs
index 00c8513c..f0c722c1 100644
--- a/crates/daemon/src/control/runtime/settings_entry_shared_skills_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_shared_skills_tests.rs
@@ -27,7 +27,10 @@ fn shared_management_and_collaboration_coexist_for_all_existing_agent_families()
layout.codex_executable = executable.clone();
layout.claude_executable = executable.clone();
layout.qoder_executable = executable.clone();
- layout.dsh_executable = executable;
+ layout.dsh_executable = executable.clone();
+ layout.opencode_executable = executable;
+ layout.opencode_context =
+ Some(hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap());
let package = root.path().join("pi-package");
private_file(&package.join("package.json"),br#"{"name":"@earendil-works/pi-coding-agent","version":"1.0.2","bin":{"pi":"dist/bundle/cli.js"}}"#);
private_file(&package.join("dist/index.js"), b"fixture resource SDK");
@@ -71,6 +74,7 @@ fn shared_management_and_collaboration_coexist_for_all_existing_agent_families()
SettingsAgentClass::Qoder,
SettingsAgentClass::Pi,
SettingsAgentClass::Dsh,
+ SettingsAgentClass::OpenCode,
] {
let context = runtime.adapter.settings_context(class);
let model = class.native_path(&runtime.adapter.scanner).unwrap();
diff --git a/crates/daemon/src/control/runtime/settings_facts.rs b/crates/daemon/src/control/runtime/settings_facts.rs
index aa6eddf0..4296c28f 100644
--- a/crates/daemon/src/control/runtime/settings_facts.rs
+++ b/crates/daemon/src/control/runtime/settings_facts.rs
@@ -64,6 +64,7 @@ impl LocalControlAdapter {
"agent_qoder_default" => SettingsAgentClass::Qoder,
"agent_pi_default" => SettingsAgentClass::Pi,
"agent_dsh_default" => SettingsAgentClass::Dsh,
+ "agent_opencode_default" => SettingsAgentClass::OpenCode,
_ => return None,
};
Some(self.settings_context(class))
@@ -88,6 +89,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Qoder,
SettingsAgentClass::Pi,
SettingsAgentClass::Dsh,
+ SettingsAgentClass::OpenCode,
]
.into_iter()
.find(|class| context == self.settings_context(*class))
@@ -128,7 +130,10 @@ impl LocalControlAdapter {
) -> Result<AgentSettingsPlanningInput, ControlReadError> {
if matches!(
class,
- SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh
+ SettingsAgentClass::Qoder
+ | SettingsAgentClass::Pi
+ | SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
) {
return self.attach_additional_model_facts(
spec,
@@ -345,6 +350,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Qoder
| SettingsAgentClass::Pi
| SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
| SettingsAgentClass::Hermes => {
return Err(ControlReadError::Denied);
}
@@ -413,7 +419,7 @@ impl LocalControlAdapter {
selected_collaboration_restore = Some(original.operation_id.clone());
}
let model = match class {
- SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh | SettingsAgentClass::Hermes => return Err(ControlReadError::Denied),
+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh | SettingsAgentClass::Hermes | SettingsAgentClass::OpenCode => return Err(ControlReadError::Denied),
SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => original
.plan
.external()
@@ -562,6 +568,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Qoder
| SettingsAgentClass::Pi
| SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
| SettingsAgentClass::Hermes => {
return Err(ControlReadError::Denied);
}
@@ -855,6 +862,7 @@ impl LocalControlAdapter {
SettingsAgentClass::Qoder
| SettingsAgentClass::Pi
| SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
| SettingsAgentClass::Hermes => {
return Err(ControlReadError::Denied);
}
diff --git a/crates/daemon/src/control/runtime/settings_facts/additional_model.rs b/crates/daemon/src/control/runtime/settings_facts/additional_model.rs
index e97ab81f..b0eb254f 100644
--- a/crates/daemon/src/control/runtime/settings_facts/additional_model.rs
+++ b/crates/daemon/src/control/runtime/settings_facts/additional_model.rs
@@ -30,11 +30,14 @@ impl LocalControlAdapter {
AgentModelSelectionV2::QoderAdditional { .. }
| AgentModelSelectionV2::PiAdditional { .. }
| AgentModelSelectionV2::DshAdditional { .. }
+ | AgentModelSelectionV2::OpenCodeAdditional { .. }
)
{
return Ok(input);
}
- let kind = if class == SettingsAgentClass::Dsh {
+ let kind = if class == SettingsAgentClass::OpenCode {
+ hiroute_domain::AgentKindV1::OpenCode
+ } else if class == SettingsAgentClass::Dsh {
hiroute_domain::AgentKindV1::DeepseekHarness
} else if class == SettingsAgentClass::Pi {
hiroute_domain::AgentKindV1::Pi
@@ -251,12 +254,22 @@ impl LocalControlAdapter {
}
AgentFacetIntent::Keep => unreachable!(),
};
+ let (additional_dependencies, opencode_default_in_use) =
+ if kind == hiroute_domain::AgentKindV1::OpenCode {
+ let (digest, in_use) = self
+ .scanner
+ .opencode_model_facts(&provider_id, &models)
+ .map_err(|_| ControlReadError::SnapshotChanged)?;
+ (Some(digest), in_use)
+ } else {
+ (None, false)
+ };
let dsh_default_in_use = kind == hiroute_domain::AgentKindV1::DeepseekHarness
&& self
.scanner
.dsh_web_default_in_use(&provider_id, &models)
.map_err(|_| ControlReadError::Denied)?;
- let qoder_model_conflict = if dsh_default_in_use
+ let qoder_model_conflict = if opencode_default_in_use || dsh_default_in_use
|| pi_settings
.as_ref()
.is_some_and(|settings| settings.removes_default(&provider_id, &models))
@@ -274,7 +287,7 @@ impl LocalControlAdapter {
"schema":"qoder-model-facts/v1", "collaboration":input.facts.dependency_digest,
"content":expected_content,"fingerprint":before_fingerprint,"publication":publication.digest,
"grant":current_grant,"token":token_input_fingerprint,"provider":provider_id,"endpoint":endpoint,
- "conflict":qoder_model_conflict,"models":models,"kind":kind,"pi_settings":pi_settings,"previous":previous.as_ref().map(|(op,_)| &op.operation_id),"restore":restore,
+ "conflict":qoder_model_conflict,"models":models,"additional_dependencies":additional_dependencies,"kind":kind,"pi_settings":pi_settings,"previous":previous.as_ref().map(|(op,_)| &op.operation_id),"restore":restore,
})).map_err(|_| ControlReadError::Corrupt)?;
let old_digest = input.facts.dependency_digest.clone();
let mut capabilities = [
@@ -305,6 +318,7 @@ impl LocalControlAdapter {
state: CapabilityState::Proven,
adapter_contract: match kind {
hiroute_domain::AgentKindV1::Pi => "hiroute.pi-additional-model/v1",
+ hiroute_domain::AgentKindV1::OpenCode => "hiroute.opencode-additional-model/v1",
hiroute_domain::AgentKindV1::DeepseekHarness => {
"hiroute.dsh-additional-model/v1"
}
@@ -322,7 +336,9 @@ impl LocalControlAdapter {
input.facts.model = Some(SettingsModelFacts {
common: SettingsModelCommonFacts {
ingress: protocol,
- available_surfaces: [if kind == hiroute_domain::AgentKindV1::DeepseekHarness {
+ available_surfaces: [if kind == hiroute_domain::AgentKindV1::OpenCode {
+ AgentModelSurfaceV2::OpenCodeCli
+ } else if kind == hiroute_domain::AgentKindV1::DeepseekHarness {
AgentModelSurfaceV2::DshCli
} else if kind == hiroute_domain::AgentKindV1::Pi {
AgentModelSurfaceV2::PiCli
@@ -350,6 +366,7 @@ impl LocalControlAdapter {
target: SettingsModelTargetFacts::Additional {
kind,
pi_settings_content: pi_settings.map(|settings| settings.content_digest),
+ additional_dependencies,
provider_id,
endpoint,
models,
diff --git a/crates/daemon/src/control/runtime/settings_facts/class.rs b/crates/daemon/src/control/runtime/settings_facts/class.rs
index f4f0a32b..09500d34 100644
--- a/crates/daemon/src/control/runtime/settings_facts/class.rs
+++ b/crates/daemon/src/control/runtime/settings_facts/class.rs
@@ -10,6 +10,7 @@ pub(in crate::control::runtime) enum SettingsAgentClass {
Pi,
Dsh,
Hermes,
+ OpenCode,
}
impl SettingsAgentClass {
@@ -24,6 +25,7 @@ impl SettingsAgentClass {
Self::Qoder => "agent_qoder_default",
Self::Pi => "agent_pi_default",
Self::Dsh => "agent_dsh_default",
+ Self::OpenCode => "agent_opencode_default",
Self::Hermes => "agent_hermes_default",
}
}
@@ -35,6 +37,7 @@ impl SettingsAgentClass {
Self::Qoder => "qoder",
Self::Pi => "pi",
Self::Dsh => "dsh",
+ Self::OpenCode => "opencode",
Self::Hermes => "hermes",
}
}
@@ -50,6 +53,7 @@ impl SettingsAgentClass {
Self::Qoder => scanner.qoder_user_config_target(),
Self::Pi => scanner.pi_user_models_target(),
Self::Dsh => scanner.dsh_user_models_target(),
+ Self::OpenCode => scanner.opencode_user_models_target(),
Self::Hermes => return None,
})
}
@@ -61,6 +65,7 @@ impl SettingsAgentClass {
Self::Qoder => "skill-root/agent_qoder_default",
Self::Pi => "skill-root/agent_pi_default",
Self::Dsh => "skill-root/agent_dsh_default",
+ Self::OpenCode => "skill-root/agent_opencode_default",
Self::Hermes => "skill-root/hermes-explicit-target-required",
}
}
@@ -94,6 +99,10 @@ impl SettingsAgentClass {
Self::Hermes => {
return Err(hiroute_domain::OperationValidationError::UnregisteredEffectPlan);
}
+ Self::OpenCode => (
+ hiroute_integrations::OPENCODE_PROFILE_ID_V1,
+ hiroute_integrations::OPENCODE_INTEGRATION_PROFILE_REF_V1,
+ ),
Self::Dsh => (
hiroute_integrations::DSH_PROFILE_ID_V1,
hiroute_integrations::DSH_INTEGRATION_PROFILE_REF_V1,
diff --git a/crates/daemon/src/control/runtime/settings_facts/qoder.rs b/crates/daemon/src/control/runtime/settings_facts/qoder.rs
index 82928892..6f0da804 100644
--- a/crates/daemon/src/control/runtime/settings_facts/qoder.rs
+++ b/crates/daemon/src/control/runtime/settings_facts/qoder.rs
@@ -8,7 +8,9 @@ impl LocalControlAdapter {
spec: &AgentSettingsSpecV2,
class: SettingsAgentClass,
) -> Result<AgentSettingsPlanningInput, ControlReadError> {
- let discovery = if class == SettingsAgentClass::Dsh {
+ let discovery = if class == SettingsAgentClass::OpenCode {
+ self.scanner.opencode_settings_discovery()
+ } else if class == SettingsAgentClass::Dsh {
self.scanner.dsh_settings_discovery()
} else if class == SettingsAgentClass::Pi {
self.scanner.pi_settings_discovery()
@@ -190,7 +192,13 @@ impl LocalControlAdapter {
pub(in crate::control::runtime) fn qoder_collaboration_probe_target(
&self,
) -> Result<QoderCollaborationProbeTarget, ControlReadError> {
- let class = SettingsAgentClass::Qoder;
+ self.additional_collaboration_probe_target(SettingsAgentClass::Qoder)
+ }
+
+ pub(in crate::control::runtime) fn additional_collaboration_probe_target(
+ &self,
+ class: SettingsAgentClass,
+ ) -> Result<QoderCollaborationProbeTarget, ControlReadError> {
let context = self.settings_context(class);
let record = self
.stores_lock()
diff --git a/crates/daemon/src/control/runtime/settings_facts/skills.rs b/crates/daemon/src/control/runtime/settings_facts/skills.rs
index e2118d5b..fab3bc28 100644
--- a/crates/daemon/src/control/runtime/settings_facts/skills.rs
+++ b/crates/daemon/src/control/runtime/settings_facts/skills.rs
@@ -169,6 +169,7 @@ impl LocalControlAdapter {
let discovery = match class {
SettingsAgentClass::Pi => self.scanner.pi_settings_discovery(),
SettingsAgentClass::Dsh => self.scanner.dsh_settings_discovery(),
+ SettingsAgentClass::OpenCode => self.scanner.opencode_settings_discovery(),
_ => self.scanner.qoder_settings_discovery(true),
};
let AgentDiscoveryOutcomeV1::Supported { installation } = discovery.outcome else {
diff --git a/crates/daemon/src/control/runtime/settings_retry.rs b/crates/daemon/src/control/runtime/settings_retry.rs
index 60d08b0e..9befe672 100644
--- a/crates/daemon/src/control/runtime/settings_retry.rs
+++ b/crates/daemon/src/control/runtime/settings_retry.rs
@@ -19,6 +19,7 @@ impl LocalControlAdapter {
| SettingsAgentClass::Qoder
| SettingsAgentClass::Pi
| SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
| SettingsAgentClass::Hermes
)
})
@@ -46,7 +47,12 @@ impl LocalControlAdapter {
if !matches!(spec.model, AgentFacetIntent::Keep)
&& matches!(
self.settings_agent_for_context(&request.context_id),
- Some(SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh)
+ Some(
+ SettingsAgentClass::Qoder
+ | SettingsAgentClass::Pi
+ | SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
+ )
)
{
let intent = op
diff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rs
index d89ca8c1..3a19456c 100644
--- a/crates/daemon/src/control/runtime/settings_status.rs
+++ b/crates/daemon/src/control/runtime/settings_status.rs
@@ -258,7 +258,10 @@ impl LocalControlAdapter {
ModelAction::Configure => {
let file_applied = if matches!(
class,
- SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh
+ SettingsAgentClass::Qoder
+ | SettingsAgentClass::Pi
+ | SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode
) {
hiroute_integrations::additional_native_configuration_is_applied(
&self.artifacts,
@@ -306,6 +309,27 @@ impl LocalControlAdapter {
)
.map_err(super::map_port)?
};
+ let file_applied = file_applied
+ && (class != SettingsAgentClass::OpenCode || {
+ use hiroute_application::agent_connection::{
+ AdditionalModelFileAction, decode_settings_additional_model_file,
+ };
+ let payload = decode_settings_additional_model_file(intent)
+ .map_err(super::map_port)?;
+ let AdditionalModelFileAction::Configure {
+ provider_id,
+ models,
+ ..
+ } = payload.change
+ else {
+ return Err(ControlReadError::Corrupt);
+ };
+ // Recheck effective ownership/allowlists, without treating unrelated
+ // document changes as drift or rejecting a retained default selector.
+ self.scanner
+ .opencode_model_facts(&provider_id, &models)
+ .is_ok()
+ });
let [mutation] = operation.plan.agent_access_grants() else {
return Err(ControlReadError::Corrupt);
};
@@ -423,6 +447,10 @@ impl LocalControlAdapter {
hiroute_domain::AgentModelSelectionV2::PiAdditional { .. },
SettingsAgentClass::Pi,
) => [hiroute_domain::AgentModelSurfaceV2::PiCli].into(),
+ (
+ hiroute_domain::AgentModelSelectionV2::OpenCodeAdditional { .. },
+ SettingsAgentClass::OpenCode,
+ ) => [hiroute_domain::AgentModelSurfaceV2::OpenCodeCli].into(),
(
hiroute_domain::AgentModelSelectionV2::DshAdditional { .. },
SettingsAgentClass::Dsh,
@@ -569,7 +597,8 @@ fn model_intent(
}
super::settings_facts::SettingsAgentClass::Qoder
| super::settings_facts::SettingsAgentClass::Pi
- | super::settings_facts::SettingsAgentClass::Dsh => {
+ | super::settings_facts::SettingsAgentClass::Dsh
+ | super::settings_facts::SettingsAgentClass::OpenCode => {
super::native_additional_model::is_settings_additional_model(intent)
}
})
@@ -585,7 +614,7 @@ fn model_action(
hiroute_application::agent_connection::HermesModelFileAction::Configure { .. } => Ok(ModelAction::Configure),
hiroute_application::agent_connection::HermesModelFileAction::Restore { .. } => Ok(ModelAction::Restore),
},
- super::settings_facts::SettingsAgentClass::Qoder | super::settings_facts::SettingsAgentClass::Pi | super::settings_facts::SettingsAgentClass::Dsh => {
+ super::settings_facts::SettingsAgentClass::Qoder | super::settings_facts::SettingsAgentClass::Pi | super::settings_facts::SettingsAgentClass::Dsh | super::settings_facts::SettingsAgentClass::OpenCode => {
match hiroute_application::agent_connection::settings_additional_model_file_for_operation(
operation, intent,
)?
@@ -640,7 +669,10 @@ fn model_endpoint_matches_runtime(
ClaudeModelFileAction::Configure { gateway_base_url: endpoint, .. }
if endpoint == gateway_base_url
)),
- SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => {
+ SettingsAgentClass::Qoder
+ | SettingsAgentClass::Pi
+ | SettingsAgentClass::Dsh
+ | SettingsAgentClass::OpenCode => {
let endpoint = super::native_additional_model::additional_model_endpoint(
additional_model_kind(intent)?,
gateway_base_url,
diff --git a/crates/daemon/src/control/runtime_worker_dependencies_tests.rs b/crates/daemon/src/control/runtime_worker_dependencies_tests.rs
index 40241484..28d9de27 100644
--- a/crates/daemon/src/control/runtime_worker_dependencies_tests.rs
+++ b/crates/daemon/src/control/runtime_worker_dependencies_tests.rs
@@ -146,3 +146,104 @@ fn collaboration_grant_cannot_select_worker_dependencies() {
));
assert_eq!(denied.error.unwrap().code, ErrorCode::CapabilityDenied);
}
+
+#[test]
+fn unavailable_opencode_context_does_not_block_other_agents_or_control_startup() {
+ #[cfg(unix)]
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::worker_dependencies_tests::unavailable_opencode_context_does_not_block_other_agents_or_control_startup",
+ ) {
+ return;
+ }
+ let root = crate::test_support::private_tempdir();
+ let home = root.path().join("home");
+ std::fs::create_dir(&home).unwrap();
+ private_root(&home);
+ let mut layout =
+ hiroute_integrations::AgentFilesystemLayoutV1::from_process(&home, root.path());
+ layout.opencode_context = None;
+ let registry = serde_json::from_slice(include_bytes!(
+ "../../../../assets/connector-registry/current/registry-seed.json"
+ ))
+ .unwrap();
+ let models: hiroute_domain::ReleaseModelDataBundleV2 = serde_json::from_slice(include_bytes!(
+ "../../../../assets/release-facts/current/bundle/model-data.json"
+ ))
+ .unwrap();
+ let scanner = hiroute_integrations::FilesystemAgentScannerV1::new(
+ layout,
+ hiroute_integrations::ClaudeRegistrationIndexV1::from_verified_model_data(
+ &registry,
+ &models.data,
+ )
+ .unwrap(),
+ );
+ let runtime = ProductionControlRuntime::prepare_for_role_all_with_scanner(
+ &root.path().join("storage"),
+ crate::release_catalog::fixture_catalog(),
+ None,
+ scanner,
+ )
+ .unwrap();
+ runtime.adapter.reconcile_startup_and_open().unwrap();
+ assert!(runtime.adapter.scanner.opencode_native_context().is_err());
+ let daemon =
+ super::super::LocalControlDaemon::new(ApplicationService::new(runtime.application_ports()))
+ .with_released_commands_only();
+ let selected = daemon.dispatch_wire(wire(&select_request(root.path(), "codex"), None));
+ assert!(selected.error.is_none(), "{selected:?}");
+}
+
+#[test]
+fn opencode_selected_entry_is_discovered_after_restart() {
+ #[cfg(unix)]
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::worker_dependencies_tests::opencode_selected_entry_is_discovered_after_restart",
+ ) {
+ return;
+ }
+ let directory = tempfile::tempdir().unwrap();
+ private_root(directory.path());
+ let root = directory.path().canonicalize().unwrap();
+ let cli = root.join("opencode");
+ executable(&cli);
+ let storage = root.join("storage");
+ {
+ let runtime = ProductionControlRuntime::open_with_release_catalog(
+ &storage,
+ crate::release_catalog::fixture_catalog(),
+ )
+ .unwrap();
+ let daemon = super::super::LocalControlDaemon::new(ApplicationService::new(
+ runtime.application_ports(),
+ ))
+ .with_released_commands_only();
+ let request = WorkerDependenciesSelectRequestV1 {
+ harness: WorkerHarnessV1::OpenCode,
+ cli_path: cli.to_string_lossy().into_owned(),
+ adapter_path: None,
+ node_path: None,
+ expected_selection_revision: 0,
+ };
+ let applied = daemon.dispatch_wire(wire(&request, None));
+ assert!(applied.error.is_none(), "{applied:?}");
+ assert_eq!(applied.operation.as_ref().unwrap().state, "succeeded");
+ }
+ let reopened = ProductionControlRuntime::open_with_release_catalog(
+ &storage,
+ crate::release_catalog::fixture_catalog(),
+ )
+ .unwrap();
+ assert_eq!(
+ reopened.adapter.scanner.opencode_executable_target(),
+ Some(cli)
+ );
+ let agents = reopened.adapter.discover().unwrap();
+ assert!(agents.iter().any(|agent| {
+ agent.agent_id == "agent_opencode_default"
+ && agent.supported
+ && agent
+ .available_surfaces
+ .contains(&hiroute_application_api::AgentModelSurfaceV2::OpenCodeCli)
+ }));
+}
diff --git a/crates/daemon/src/delegation/acp/identity.rs b/crates/daemon/src/delegation/acp/identity.rs
index e7655860..88f79732 100644
--- a/crates/daemon/src/delegation/acp/identity.rs
+++ b/crates/daemon/src/delegation/acp/identity.rs
@@ -12,6 +12,7 @@ pub enum AcpNativeIdentityContract {
ClaudeSessionV1,
QoderSessionV1,
DshSessionV1,
+ OpenCodeSessionV1,
}
impl AcpNativeIdentityContract {
@@ -26,7 +27,8 @@ impl AcpNativeIdentityContract {
Self::CodexThreadV1
| Self::ClaudeSessionV1
| Self::QoderSessionV1
- | Self::DshSessionV1 => {
+ | Self::DshSessionV1
+ | Self::OpenCodeSessionV1 => {
if !valid_id(acp_id) {
return Err(DelegationErrorV1::ProtocolFailed);
}
@@ -44,7 +46,8 @@ impl AcpNativeIdentityContract {
Self::CodexThreadV1
| Self::ClaudeSessionV1
| Self::QoderSessionV1
- | Self::DshSessionV1 => {
+ | Self::DshSessionV1
+ | Self::OpenCodeSessionV1 => {
valid_id(&binding.acp_session_id)
&& binding.native_session_id.as_deref() == Some(binding.acp_session_id.as_str())
}
diff --git a/crates/daemon/src/delegation/acp/mod.rs b/crates/daemon/src/delegation/acp/mod.rs
index 2ad46c83..3b3f1c7e 100644
--- a/crates/daemon/src/delegation/acp/mod.rs
+++ b/crates/daemon/src/delegation/acp/mod.rs
@@ -411,6 +411,26 @@ async fn run_session(
updates.lock().unwrap_or_else(|e| e.into_inner()).session =
Some(binding.acp_session_id.clone());
journal.session_bound(&binding)?;
+ let typed_mode = input.identity_contract == AcpNativeIdentityContract::OpenCodeSessionV1;
+ let config_options = if typed_mode {
+ let expected = input
+ .native_session_mode
+ .as_deref()
+ .ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ Some(
+ model::ensure_mode(
+ &connection,
+ &binding.acp_session_id,
+ config_options.as_deref(),
+ expected,
+ &input.cancellation,
+ input.deadline,
+ )
+ .await?,
+ )
+ } else {
+ config_options
+ };
if let Some(expected_model) = input.expected_model.as_deref() {
model::ensure_model(
&connection,
@@ -422,7 +442,7 @@ async fn run_session(
)
.await?;
}
- if let Some(native_session_mode) = input.native_session_mode {
+ if let Some(native_session_mode) = input.native_session_mode.filter(|_| !typed_mode) {
let mode_available = modes.as_ref().is_some_and(|modes| {
modes
.available_modes
@@ -651,3 +671,6 @@ mod notification_tests;
mod security_tests;
#[cfg(test)]
mod tests;
+
+#[cfg(test)]
+mod opencode_tests;
diff --git a/crates/daemon/src/delegation/acp/model.rs b/crates/daemon/src/delegation/acp/model.rs
index 47b48805..ddafc70e 100644
--- a/crates/daemon/src/delegation/acp/model.rs
+++ b/crates/daemon/src/delegation/acp/model.rs
@@ -19,19 +19,61 @@ pub(super) async fn ensure_model(
cancellation: &CancellationToken,
deadline: Instant,
) -> Result<(), DelegationErrorV1> {
- let model = model_selector(config_options)?;
- if model.current_value.to_string() == expected_model {
- return Ok(());
+ ensure_select(
+ connection,
+ session_id,
+ config_options,
+ "model",
+ expected_model,
+ cancellation,
+ deadline,
+ )
+ .await
+ .map(|_| ())
+}
+
+pub(super) async fn ensure_mode(
+ connection: &ConnectionTo<Agent>,
+ session_id: &str,
+ config_options: Option<&[SessionConfigOption]>,
+ expected_mode: &str,
+ cancellation: &CancellationToken,
+ deadline: Instant,
+) -> Result<Vec<SessionConfigOption>, DelegationErrorV1> {
+ ensure_select(
+ connection,
+ session_id,
+ config_options,
+ "mode",
+ expected_mode,
+ cancellation,
+ deadline,
+ )
+ .await
+}
+
+async fn ensure_select(
+ connection: &ConnectionTo<Agent>,
+ session_id: &str,
+ config_options: Option<&[SessionConfigOption]>,
+ id: &str,
+ expected: &str,
+ cancellation: &CancellationToken,
+ deadline: Instant,
+) -> Result<Vec<SessionConfigOption>, DelegationErrorV1> {
+ let model = selector(config_options, id)?;
+ if model.current_value.to_string() == expected {
+ return Ok(config_options.unwrap_or_default().to_vec());
}
let available = match &model.options {
SessionConfigSelectOptions::Ungrouped(options) => options
.iter()
- .any(|option| option.value.to_string() == expected_model),
+ .any(|option| option.value.to_string() == expected),
SessionConfigSelectOptions::Grouped(groups) => groups.iter().any(|group| {
group
.options
.iter()
- .any(|option| option.value.to_string() == expected_model)
+ .any(|option| option.value.to_string() == expected)
}),
_ => false,
};
@@ -39,14 +81,18 @@ pub(super) async fn ensure_model(
return Err(DelegationErrorV1::CapabilityUnavailable);
}
let response = super::phase(
- "set-model",
+ if id == "mode" {
+ "set-mode"
+ } else {
+ "set-model"
+ },
cancellation,
deadline,
connection
.send_request(SetSessionConfigOptionRequest::new(
session_id.to_owned(),
- "model",
- expected_model,
+ id.to_owned(),
+ expected,
))
.block_task(),
)
@@ -55,23 +101,24 @@ pub(super) async fn ensure_model(
DelegationErrorV1::ProtocolFailed => DelegationErrorV1::CapabilityUnavailable,
error => error,
})?;
- if model_selector(Some(&response.config_options))?
+ if selector(Some(&response.config_options), id)?
.current_value
.to_string()
- != expected_model
+ != expected
{
return Err(DelegationErrorV1::CapabilityUnavailable);
}
- Ok(())
+ Ok(response.config_options)
}
-fn model_selector(
- options: Option<&[SessionConfigOption]>,
-) -> Result<&SessionConfigSelect, DelegationErrorV1> {
+fn selector<'a>(
+ options: Option<&'a [SessionConfigOption]>,
+ id: &str,
+) -> Result<&'a SessionConfigSelect, DelegationErrorV1> {
let mut models = options
.unwrap_or_default()
.iter()
- .filter(|option| option.id.to_string() == "model");
+ .filter(|option| option.id.to_string() == id);
let Some(option) = models.next() else {
return Err(DelegationErrorV1::CapabilityUnavailable);
};
diff --git a/crates/daemon/src/delegation/acp/opencode_tests.rs b/crates/daemon/src/delegation/acp/opencode_tests.rs
new file mode 100644
index 00000000..e543b335
--- /dev/null
+++ b/crates/daemon/src/delegation/acp/opencode_tests.rs
@@ -0,0 +1,110 @@
+use super::tests::{Journal, input};
+use super::*;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+fn options(mode: &str, model: &str) -> Vec<Value> {
+ vec![
+ json!({"id":"mode","name":"Mode","type":"select","currentValue":mode,"options":[{"value":"owned","name":"Owned"}]}),
+ json!({"id":"model","name":"Model","type":"select","currentValue":model,"options":[{"value":"provider/route","name":"Route"}]}),
+ ]
+}
+
+async fn fixture(
+ start: AcpSessionStart,
+ invalid: Option<&str>,
+) -> (Result<AcpRunOutcome, DelegationErrorV1>, Vec<String>) {
+ let invalid = invalid.map(str::to_owned);
+ let (client, server) = tokio::io::duplex(16_384);
+ let server = tokio::spawn(async move {
+ let (reader, mut writer) = tokio::io::split(server);
+ let mut lines = BufReader::new(reader).lines();
+ let mut calls = vec![];
+ while let Some(line) = lines.next_line().await.unwrap() {
+ let request: Value = serde_json::from_str(&line).unwrap();
+ let method = request["method"].as_str().unwrap();
+ calls.push(if method == "session/set_config_option" {
+ format!("set:{}", request["params"]["configId"].as_str().unwrap())
+ } else {
+ method.into()
+ });
+ let result = match method {
+ "initialize" => {
+ json!({"protocolVersion":1,"agentCapabilities":{"loadSession":true}})
+ }
+ "session/new" | "session/load" => {
+ let mut opts = options("daily", "daily/model");
+ match invalid.as_deref() {
+ Some("missing") => {
+ opts.remove(0);
+ }
+ Some("duplicate") => opts.push(opts[0].clone()),
+ Some("wrong_type") => opts[0]["type"] = json!("boolean"),
+ _ => {}
+ }
+ if method == "session/new" {
+ json!({"sessionId":"native-a","configOptions":opts})
+ } else {
+ json!({"configOptions":opts})
+ }
+ }
+ "session/set_config_option" if request["params"]["configId"] == "mode" => {
+ assert_eq!(request["params"]["value"], "owned");
+ json!({"configOptions":options(if invalid.as_deref()==Some("mismatch") {"daily"} else {"owned"},"changed-by-mode")})
+ }
+ "session/set_config_option" => {
+ assert_eq!(request["params"]["configId"], "model");
+ assert_eq!(request["params"]["value"], "provider/route");
+ json!({"configOptions":options("owned","provider/route")})
+ }
+ "session/prompt" => json!({"stopReason":"end_turn"}),
+ other => panic!("unexpected {other}"),
+ };
+ if writer
+ .write_all(
+ format!(
+ "{}\n",
+ json!({"jsonrpc":"2.0","id":request["id"],"result":result})
+ )
+ .as_bytes(),
+ )
+ .await
+ .is_err()
+ {
+ break;
+ }
+ }
+ calls
+ });
+ let (read, write) = tokio::io::split(client);
+ let mut request = input();
+ request.session = start;
+ request.identity_contract = AcpNativeIdentityContract::OpenCodeSessionV1;
+ request.native_session_mode = Some("owned".into());
+ request.expected_model = Some("provider/route".into());
+ let result = run_acp(read, write, request, Arc::new(Journal::default())).await;
+ (result, server.await.unwrap())
+}
+
+#[tokio::test]
+async fn opencode_typed_mode_then_final_model_before_new_or_load_prompt() {
+ for start in [
+ AcpSessionStart::New,
+ AcpSessionStart::Load(AcpSessionBinding {
+ acp_session_id: "native-a".into(),
+ native_session_id: Some("native-a".into()),
+ }),
+ ] {
+ let (result, calls) = fixture(start, None).await;
+ assert!(result.is_ok(), "{:?}", result.err());
+ assert_eq!(&calls[2..], ["set:mode", "set:model", "session/prompt"]);
+ }
+}
+
+#[tokio::test]
+async fn invalid_opencode_mode_never_sends_prompt() {
+ for failure in ["missing", "duplicate", "wrong_type", "mismatch"] {
+ let (result, calls) = fixture(AcpSessionStart::New, Some(failure)).await;
+ assert!(result.is_err(), "{failure}");
+ assert!(!calls.iter().any(|c| c == "session/prompt"), "{failure}");
+ }
+}
diff --git a/crates/daemon/src/delegation/installation.rs b/crates/daemon/src/delegation/installation.rs
index e386e23c..38fa48cf 100644
--- a/crates/daemon/src/delegation/installation.rs
+++ b/crates/daemon/src/delegation/installation.rs
@@ -33,12 +33,13 @@ pub(crate) use discovery::{
validate_selection,
};
-const WORKER_HARNESSES: [WorkerHarnessV1; 5] = [
+const WORKER_HARNESSES: [WorkerHarnessV1; 6] = [
WorkerHarnessV1::CodexCli,
WorkerHarnessV1::ClaudeCode,
WorkerHarnessV1::QoderCli,
WorkerHarnessV1::Pi,
WorkerHarnessV1::DeepseekHarness,
+ WorkerHarnessV1::OpenCode,
];
#[derive(Clone, Debug)]
@@ -308,7 +309,10 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
)?;
if matches!(
installation.harness,
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
) && input.run.configuration.permission_policy
!= hiroute_domain::delegation::WorkerPermissionPolicyV1::ApproveAll
{
@@ -384,11 +388,15 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
}
let identity = match (|| {
let context = NativeWorkerContext::from_environment(installation.harness)?;
- session.bind_borrowed_context(
- context.home(),
- context.config_root(),
- &input.workspace_path,
- )?;
+ if let Some(opencode) = context.opencode() {
+ session.bind_opencode_context(opencode, &input.workspace_path)?;
+ } else {
+ session.bind_borrowed_context(
+ context.home(),
+ context.config_root(),
+ &input.workspace_path,
+ )?;
+ }
session.create_ownership_marker(&roots.sessions, &native.root)
})() {
Ok(identity) => identity,
@@ -471,13 +479,20 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
session.verify_native_session(native_session_id)?;
}
(
- NativeWorkerContext::borrowed(&context.home, &context.config_root)?,
+ if let Some(opencode) = context.opencode {
+ NativeWorkerContext::from_opencode(opencode)?
+ } else {
+ NativeWorkerContext::borrowed(&context.home, &context.config_root)?
+ },
context.workspace,
)
}
None if matches!(
installation.harness,
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
) =>
{
return Err(DelegationErrorV1::ResumeUnavailable);
@@ -510,12 +525,15 @@ impl WorkerProfileSource for ManagedWorkerProfileSource {
}
let qoder_budget = (matches!(
installation.harness,
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
))
.then(|| {
if matches!(
installation.harness,
- WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness | WorkerHarnessV1::OpenCode
) {
hiroute_integrations::agents::pi_plan_token_budget(
&input.compiled_plan.body.materialized,
diff --git a/crates/daemon/src/delegation/installation/availability.rs b/crates/daemon/src/delegation/installation/availability.rs
index 7de956eb..d2e8e875 100644
--- a/crates/daemon/src/delegation/installation/availability.rs
+++ b/crates/daemon/src/delegation/installation/availability.rs
@@ -65,6 +65,12 @@ impl WorkerExecutorAvailabilityRegistry {
if check_installation(&selection.config).is_err() {
return unavailable(harness, State::Unavailable, Reason::ArtifactUnavailable);
}
+ if harness == WorkerHarnessV1::OpenCode
+ && hiroute_integrations::opencode_native_format(&selection.config.harness_binary)
+ .is_err()
+ {
+ return unavailable(harness, State::Unavailable, Reason::CapabilityUnverified);
+ }
let ready = WorkerExecutorCapabilityAvailabilityV1 {
state: State::Ready,
reason: None,
diff --git a/crates/daemon/src/delegation/installation/discovery.rs b/crates/daemon/src/delegation/installation/discovery.rs
index 2e37b928..6547966b 100644
--- a/crates/daemon/src/delegation/installation/discovery.rs
+++ b/crates/daemon/src/delegation/installation/discovery.rs
@@ -124,7 +124,18 @@ fn validate_selection_for(
.as_deref()
.map(|path| normalize_required(Path::new(path), request.node_path.is_none()))
.transpose()?;
- let cli = normalize_required(Path::new(&request.cli_path), true)?;
+ let cli = if request.harness == WorkerHarnessV1::OpenCode {
+ let native = hiroute_integrations::opencode_native_executable(Path::new(&request.cli_path))
+ .map_err(|_| DelegationErrorV1::DependenciesInvalid)?
+ .ok_or(DelegationErrorV1::DependenciesMissing)?;
+ // Native launch uses an ordinary Windows drive path; selection binds the
+ // same canonical tuple as discovery and every other Worker harness.
+ #[cfg(windows)]
+ let native = normalize_required(&native, true)?;
+ native
+ } else {
+ normalize_required(Path::new(&request.cli_path), true)?
+ };
#[cfg(windows)]
let (adapter, cli) = {
let mut adapter = adapter;
@@ -282,6 +293,9 @@ impl HarnessScan {
if self.harness == WorkerHarnessV1::QoderCli {
directories.push(home.join(".qoder/bin"));
}
+ if self.harness == WorkerHarnessV1::OpenCode {
+ directories.push(home.join(".opencode/bin"));
+ }
}
#[cfg(windows)]
if let Some(appdata) = std::env::var_os("APPDATA") {
@@ -528,7 +542,9 @@ impl HarnessScan {
package_root: &Path,
source: WorkerDependencyCandidateSourceV1,
) {
- let adapter = if self.harness == WorkerHarnessV1::DeepseekHarness {
+ let adapter = if self.harness == WorkerHarnessV1::OpenCode {
+ "opencode"
+ } else if self.harness == WorkerHarnessV1::DeepseekHarness {
"dsh"
} else if self.harness == WorkerHarnessV1::Pi {
"pi"
@@ -552,7 +568,7 @@ impl HarnessScan {
self.add_discovered(
if matches!(
self.harness,
- WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness | WorkerHarnessV1::OpenCode
) {
WorkerDependencyComponentV1::Cli
} else {
@@ -624,7 +640,9 @@ impl HarnessScan {
] {
if (matches!(
self.harness,
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
) && component != WorkerDependencyComponentV1::Cli)
|| (self.harness == WorkerHarnessV1::Pi
&& component == WorkerDependencyComponentV1::Adapter)
@@ -655,7 +673,12 @@ impl HarnessScan {
if self.incomplete {
hints.push(WorkerDependencyInstallHintV1 {
harness: self.harness,
- component: if self.harness == WorkerHarnessV1::QoderCli {
+ component: if matches!(
+ self.harness,
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
+ ) {
WorkerDependencyComponentV1::Cli
} else {
WorkerDependencyComponentV1::Adapter
@@ -783,6 +806,7 @@ fn names(harness: WorkerHarnessV1) -> (&'static [&'static str], Option<&'static
WorkerHarnessV1::QoderCli => (&["qoder", "qodercli"], None),
WorkerHarnessV1::Pi => (&["pi"], None),
WorkerHarnessV1::DeepseekHarness => (&["dsh"], None),
+ WorkerHarnessV1::OpenCode => (&["opencode"], None),
}
}
@@ -793,6 +817,7 @@ fn package_name(harness: WorkerHarnessV1) -> Option<&'static Path> {
WorkerHarnessV1::QoderCli => None,
WorkerHarnessV1::Pi => Some(Path::new("@earendil-works/pi-coding-agent")),
WorkerHarnessV1::DeepseekHarness => Some(Path::new("@deepseek-ai/dsh")),
+ WorkerHarnessV1::OpenCode => Some(Path::new("opencode-ai")),
}
}
diff --git a/crates/daemon/src/delegation/installation/discovery/tests.rs b/crates/daemon/src/delegation/installation/discovery/tests.rs
index 2ea0e5f8..5fc787d8 100644
--- a/crates/daemon/src/delegation/installation/discovery/tests.rs
+++ b/crates/daemon/src/delegation/installation/discovery/tests.rs
@@ -66,6 +66,48 @@ fn pi_discovers_path_node_without_an_adapter() {
assert!(view.selected.is_empty());
}
+#[test]
+fn opencode_discovers_the_official_home_entry_without_selecting_or_executing_it() {
+ let root = tempfile::tempdir().unwrap();
+ let home = fs::canonicalize(root.path()).unwrap();
+ let cli = home.join(".opencode/bin/opencode");
+ make_file(&cli, 0o700);
+ let missing = home.join("explicitly-selected-but-missing");
+ let source = StaticSelection(Some(WorkerInstallationSelection {
+ config: WorkerInstallationConfig {
+ harness: WorkerHarnessV1::OpenCode,
+ harness_binary: missing.clone(),
+ adapter: None,
+ node_binary: None,
+ },
+ revision: 4,
+ }));
+ let view = discover_with_environment(
+ &source,
+ &WorkerDependenciesDiscoverRequestV1 {
+ harness: Some(WorkerHarnessV1::OpenCode),
+ },
+ &ScanEnvironment {
+ path: Some(OsString::new()),
+ home: Some(home),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert!(view.candidates.iter().any(|candidate| {
+ candidate.path == cli.to_string_lossy()
+ && candidate.state == WorkerDependencyCandidateStateV1::Found
+ && candidate.source == WorkerDependencyCandidateSourceV1::Common
+ }));
+ assert!(
+ view.candidates
+ .iter()
+ .all(|candidate| { candidate.component == WorkerDependencyComponentV1::Cli })
+ );
+ assert_eq!(view.selected[0].cli_path, missing.to_string_lossy());
+ assert_eq!(view.selection_revisions[0].revision, 4);
+}
+
#[test]
#[cfg(unix)]
fn pi_resume_checks_its_own_capability_instead_of_new_session_admission() {
@@ -356,24 +398,37 @@ fn shared_scan_budget_marks_the_view_incomplete() {
for index in 0..=MAX_DIRECTORY_ENTRIES {
fs::create_dir_all(npx.join(format!("entry-{index:03}"))).unwrap();
}
- let view = discover_with_environment(
- &StaticSelection(None),
- &WorkerDependenciesDiscoverRequestV1 {
- harness: Some(WorkerHarnessV1::CodexCli),
- },
- &ScanEnvironment {
- path: None,
- home: Some(root.path().join("home")),
- npm_prefix: None,
- npm_cache: Some(root.path().join("cache")),
- },
- )
- .unwrap();
- assert!(
- view.install_hints
+ for (harness, component) in [
+ (
+ WorkerHarnessV1::CodexCli,
+ WorkerDependencyComponentV1::Adapter,
+ ),
+ (WorkerHarnessV1::OpenCode, WorkerDependencyComponentV1::Cli),
+ (
+ WorkerHarnessV1::DeepseekHarness,
+ WorkerDependencyComponentV1::Cli,
+ ),
+ ] {
+ let view = discover_with_environment(
+ &StaticSelection(None),
+ &WorkerDependenciesDiscoverRequestV1 {
+ harness: Some(harness),
+ },
+ &ScanEnvironment {
+ path: None,
+ home: Some(root.path().join("home")),
+ npm_prefix: None,
+ npm_cache: Some(root.path().join("cache")),
+ },
+ )
+ .unwrap();
+ let hint = view
+ .install_hints
.iter()
- .any(|hint| hint.reason_code == "worker.dependencies.scan_incomplete")
- );
+ .find(|hint| hint.reason_code == "worker.dependencies.scan_incomplete")
+ .unwrap();
+ assert_eq!(hint.component, component, "{harness:?}");
+ }
}
#[test]
diff --git a/crates/daemon/src/delegation/installation/installation_probe.rs b/crates/daemon/src/delegation/installation/installation_probe.rs
index eb1e10a1..3828c0d2 100644
--- a/crates/daemon/src/delegation/installation/installation_probe.rs
+++ b/crates/daemon/src/delegation/installation/installation_probe.rs
@@ -258,9 +258,10 @@ fn harness_kind(harness: WorkerHarnessV1) -> HarnessKind {
WorkerHarnessV1::CodexCli => HarnessKind::Codex,
WorkerHarnessV1::ClaudeCode => HarnessKind::Claude,
// This historical adapter-only, private-HOME probe is not Qoder acceptance.
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness => {
- HarnessKind::Unknown
- }
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode => HarnessKind::Unknown,
}
}
diff --git a/crates/daemon/src/delegation/installation/native_tools_probe.rs b/crates/daemon/src/delegation/installation/native_tools_probe.rs
index ee5a418e..ec04d12c 100644
--- a/crates/daemon/src/delegation/installation/native_tools_probe.rs
+++ b/crates/daemon/src/delegation/installation/native_tools_probe.rs
@@ -86,6 +86,7 @@ impl ToolsFixture {
WorkerHarnessV1::QoderCli => ".qoder",
WorkerHarnessV1::Pi => ".pi",
WorkerHarnessV1::DeepseekHarness => ".dsh",
+ WorkerHarnessV1::OpenCode => ".opencode",
};
// Codex's .agents user root is the actual KnownFolder on Windows, not an
// environment-selected probe HOME. Use its supported private CODEX_HOME user root.
diff --git a/crates/daemon/src/delegation/installation/probe_server.rs b/crates/daemon/src/delegation/installation/probe_server.rs
index ca2550a2..8b12eeaf 100644
--- a/crates/daemon/src/delegation/installation/probe_server.rs
+++ b/crates/daemon/src/delegation/installation/probe_server.rs
@@ -379,7 +379,8 @@ fn serve_probe_request(
WorkerHarnessV1::CodexCli
| WorkerHarnessV1::QoderCli
| WorkerHarnessV1::Pi
- | WorkerHarnessV1::DeepseekHarness => responses_stream(endpoint.model),
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode => responses_stream(endpoint.model),
WorkerHarnessV1::ClaudeCode => messages_stream(endpoint.model),
}
};
diff --git a/crates/daemon/src/delegation/lifecycle.rs b/crates/daemon/src/delegation/lifecycle.rs
index 039353ec..978343ed 100644
--- a/crates/daemon/src/delegation/lifecycle.rs
+++ b/crates/daemon/src/delegation/lifecycle.rs
@@ -215,7 +215,7 @@ pub(crate) async fn execute(
let terminal_checkpoint = ClaudeHistoryCheckpoint::capture(&request.profile, &input)
.map(|history| Arc::new(LiveTerminalCheckpoint::new(journal.clone(), history)));
let startup = match startup::StartupPermit::acquire(
- request.profile.codex_initialization_root(),
+ request.profile.native_initialization_root(),
input.deadline,
&input.cancellation,
)
@@ -229,6 +229,13 @@ pub(crate) async fn execute(
};
// Waiting for another native initializer does not preserve stale launch authority.
journal.before_launch()?;
+ if let Err(error) = request
+ .profile
+ .validate_native_initialization(matches!(&input.session, super::acp::AcpSessionStart::New))
+ {
+ let _ = journal.execution_failed(error);
+ return Err(error);
+ }
// Dropped launch futures must finitely release acquired resources in the platform backend.
let launch_nonce = request.launch_nonce.clone();
let worker = tokio::select! {
diff --git a/crates/daemon/src/delegation/lifecycle/startup.rs b/crates/daemon/src/delegation/lifecycle/startup.rs
index 7fa7337f..9bb048c5 100644
--- a/crates/daemon/src/delegation/lifecycle/startup.rs
+++ b/crates/daemon/src/delegation/lifecycle/startup.rs
@@ -1,4 +1,4 @@
-//! In-memory startup ownership for a borrowed Codex root, never a task concurrency limit.
+//! In-memory native initialization ownership, never a task concurrency limit.
use super::*;
use crate::delegation::acp::AcpSessionBinding;
use std::collections::BTreeMap;
diff --git a/crates/daemon/src/delegation/profile/README.md b/crates/daemon/src/delegation/profile/README.md
index dcae9b9f..2ebb80b3 100644
--- a/crates/daemon/src/delegation/profile/README.md
+++ b/crates/daemon/src/delegation/profile/README.md
@@ -17,7 +17,7 @@ environment; preserving command search paths does not import upstream credential
New tasks bind their effective home, native config root and canonical workspace
once in the task-owned metadata directory. Continue reads that descriptor instead
of resolving today's environment. Only Codex/Claude accept the registered legacy
-private-root path when the descriptor is absent; Qoder requires it. A damaged
+private-root path when the descriptor is absent; Qoder/OpenCode require it. A damaged
descriptor must fail rather than fall back.
`TaskSessionRoot` still owns HiRoute metadata and the frozen Codex alias catalog.
The borrowed native config/history tree is never a launcher material or cleanup
@@ -148,6 +148,57 @@ add ecosystem scanning/import, general Agent launch, a new execution backend or
plugin framework. ACP model/session verification remains in [ACP](../acp/mod.rs),
and the OS launcher owns executable material permissions and process cleanup.
+## OpenCode native ACP and opaque history
+
+[OpenCode rendering](opencode.rs) launches the selected native executable with
+`acp --cwd`, an explicit loopback hostname and an ephemeral authenticated listener.
+Stdio ACP, its listener and native tools share the existing process-group/Job owner;
+there is no separately managed server. No Node runtime or ACP adapter is selected.
+
+The context descriptor additionally freezes OpenCode's XDG config/data/cache/state
+roots, optional absolute config file, additive config directory and exact database
+path. Canonical XDG roots must retain the `opencode` leaf used by the child's XDG
+projection. A link resolving to another leaf name is refused on New and Continue,
+so admission and the child cannot address different directories. Extra config
+directories use their explicit selector and are not subject to this leaf rule.
+Existing borrowed history is checked read-only against the audited native
+migration-ID set before launch. Initial format admission uses adjacent official
+npm platform-package metadata for 1.19.3; it does not run a shim, fingerprint a
+binary, decode sessions or migrate history. A new absent database may be initialized
+by OpenCode, while Continue requires the existing bound database and exact ACP ID.
+Other installation forms can retain independent configuration/Skill capabilities.
+
+OpenCode shares the existing daemon-local native initialization permit, keyed by
+the frozen database path. Final database/composition admission runs after waiting;
+the captured configuration digest must still match. The permit ends at successful
+ACP initialize, before New/Load or prompt, so cold schema creation cannot race
+between participating Workers while their tasks can still execute concurrently.
+Cancellation, deadline, fresh authority and uncertain-stop handling stay shared.
+There is no native database prewarming, repair or persistent lock file.
+
+One task provider supplies the frozen raw Plan alias, protocol and context/output
+bounds through a final native overlay. Main, small, title, summary and compaction
+models share that selector, with a fresh run token and stateless Responses.
+The shared typed ACP helper confirms the primary mode first, then confirms the
+model from the latest typed config options before New/Load prompt intent.
+
+The supported static composition preserves native project rules and user/project
+Skills. Approve-all admits native read/search/edit/shell/Skill; nested tasks, external
+MCP, plugins and custom executable tools are excluded. Existing nonempty tool/agent
+directories, late remote/organization/managed settings or unsupported agent overrides
+fail before launch. Native LSP/formatter execution is disabled. The bounded reader
+rechecks dependencies without rewriting daily configuration or copying credentials.
+Project inspection stops at a Git root only after bounded native `rev-parse` checks
+in the same filtered HOME/XDG/PATH as the Worker. Invalid `.git`/worktree pointers,
+unavailable or rejecting Git, and unconfirmed roots make this Worker unavailable;
+they cannot hide ancestor configuration or custom tools. Final admission rechecks
+the boundary after waiting for native initialization, using the captured child PATH.
+This permission boundary is not an OS sandbox for approve-all shell commands.
+
+The [native acceptance guide](../../../../../tools/product-e2e/tests/OPENCODE_INTEGRATION.md)
+separates saved ordinary model use, the installed shared Skill, frozen Worker
+execution, real compaction/auxiliary requests, cancellation and exact Continue.
+
## Pi resources and SDK transport
[Pi rendering](pi.rs) binds the selected official npm CLI, its SDK export and the
diff --git a/crates/daemon/src/delegation/profile/capabilities.rs b/crates/daemon/src/delegation/profile/capabilities.rs
index 650def80..cd617981 100644
--- a/crates/daemon/src/delegation/profile/capabilities.rs
+++ b/crates/daemon/src/delegation/profile/capabilities.rs
@@ -5,7 +5,10 @@ pub(super) fn identity_contract(
) -> Result<AcpNativeIdentityContract, DelegationErrorV1> {
if matches!(
input.harness,
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
) && !input.native_context.is_borrowed()
{
return Err(DelegationErrorV1::CapabilityUnavailable);
@@ -18,6 +21,7 @@ pub(super) fn identity_contract(
| WorkerHarnessV1::QoderCli
| WorkerHarnessV1::Pi
| WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
) && input.permission_policy != WorkerPermissionPolicyV1::ApproveAll
{
return Err(DelegationErrorV1::CapabilityUnavailable);
@@ -28,5 +32,6 @@ pub(super) fn identity_contract(
WorkerHarnessV1::QoderCli => AcpNativeIdentityContract::QoderSessionV1,
WorkerHarnessV1::Pi => AcpNativeIdentityContract::ExplicitResponseMetadata,
WorkerHarnessV1::DeepseekHarness => AcpNativeIdentityContract::DshSessionV1,
+ WorkerHarnessV1::OpenCode => AcpNativeIdentityContract::OpenCodeSessionV1,
})
}
diff --git a/crates/daemon/src/delegation/profile/materials.rs b/crates/daemon/src/delegation/profile/materials.rs
index 43643cd5..7f759c0e 100644
--- a/crates/daemon/src/delegation/profile/materials.rs
+++ b/crates/daemon/src/delegation/profile/materials.rs
@@ -359,7 +359,10 @@ fn legacy_native_history(
// Qoder has only the borrowed-context contract, never a private legacy reader.
if matches!(
harness,
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
) {
return Err(DelegationErrorV1::ResumeUnavailable);
}
@@ -379,7 +382,10 @@ fn legacy_native_history(
let durable_root = root.join(match harness {
WorkerHarnessV1::CodexCli => "sessions",
WorkerHarnessV1::ClaudeCode => "projects",
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness => {
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode => {
return Err(DelegationErrorV1::ResumeUnavailable);
}
});
@@ -424,7 +430,8 @@ fn legacy_native_history(
WorkerHarnessV1::ClaudeCode => file_name == claude_name,
WorkerHarnessV1::QoderCli
| WorkerHarnessV1::Pi
- | WorkerHarnessV1::DeepseekHarness => {
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode => {
return Err(DelegationErrorV1::ResumeUnavailable);
}
};
diff --git a/crates/daemon/src/delegation/profile/mod.rs b/crates/daemon/src/delegation/profile/mod.rs
index abeda2ac..64a1efaa 100644
--- a/crates/daemon/src/delegation/profile/mod.rs
+++ b/crates/daemon/src/delegation/profile/mod.rs
@@ -19,6 +19,7 @@ mod claude_runtime;
mod codex;
mod dsh;
mod native_context;
+mod opencode;
mod pi;
mod qoder;
pub use native_context::NativeWorkerContext;
@@ -75,7 +76,8 @@ pub struct CandidateWorkerProfile {
permission_policy: WorkerPermissionPolicyV1,
native_session_mode: String,
native_selected_model_id: String,
- codex_initialization_root: Option<PathBuf>,
+ native_initialization_root: Option<PathBuf>,
+ opencode_startup: Option<opencode::StartupAdmission>,
}
pub use super::platform::WorkerPlatformCapabilities;
@@ -166,6 +168,8 @@ impl CandidateWorkerProfile {
(WorkerHarnessV1::QoderCli, WorkerPermissionPolicyV1::ApproveAll) => "yolo",
(WorkerHarnessV1::Pi, WorkerPermissionPolicyV1::ApproveAll) => "approve-all",
(WorkerHarnessV1::Pi, _) => return Err(DelegationErrorV1::CapabilityUnavailable),
+ (WorkerHarnessV1::OpenCode, WorkerPermissionPolicyV1::ApproveAll) => opencode::MODE,
+ (WorkerHarnessV1::OpenCode, _) => return Err(DelegationErrorV1::CapabilityUnavailable),
(WorkerHarnessV1::DeepseekHarness, WorkerPermissionPolicyV1::ApproveAll) => "",
(WorkerHarnessV1::DeepseekHarness, _) => {
return Err(DelegationErrorV1::CapabilityUnavailable);
@@ -250,6 +254,7 @@ impl CandidateWorkerProfile {
WorkerHarnessV1::QoderCli => qoder::render(&input, &private_root)?,
WorkerHarnessV1::Pi => pi::render(&input)?,
WorkerHarnessV1::DeepseekHarness => dsh::render(&input)?,
+ WorkerHarnessV1::OpenCode => opencode::render(&input, env["PATH"].as_str())?,
};
env.extend(rendered.env);
let (executable, args) = match launch {
@@ -305,9 +310,16 @@ impl CandidateWorkerProfile {
permission_policy: input.permission_policy,
native_session_mode: native_session_mode.to_owned(),
native_selected_model_id: rendered.native_model_id,
- codex_initialization_root: (input.harness == WorkerHarnessV1::CodexCli
- && input.native_context.is_borrowed())
- .then(|| input.native_context.config_root().to_owned()),
+ native_initialization_root: rendered
+ .opencode_startup
+ .as_ref()
+ .map(|admission| admission.root().to_owned())
+ .or_else(|| {
+ (input.harness == WorkerHarnessV1::CodexCli
+ && input.native_context.is_borrowed())
+ .then(|| input.native_context.config_root().to_owned())
+ }),
+ opencode_startup: rendered.opencode_startup,
})
}
@@ -333,8 +345,18 @@ impl CandidateWorkerProfile {
/// The installation owner has already bound the canonical effective native root.
/// Never derive this coordination key from cwd, a model alias, or mutable child env.
- pub(crate) fn codex_initialization_root(&self) -> Option<&Path> {
- self.codex_initialization_root.as_deref()
+ pub(crate) fn native_initialization_root(&self) -> Option<&Path> {
+ self.native_initialization_root.as_deref()
+ }
+
+ pub(crate) fn validate_native_initialization(
+ &self,
+ new_session: bool,
+ ) -> Result<(), DelegationErrorV1> {
+ if let Some(admission) = &self.opencode_startup {
+ admission.validate(&self.cwd, new_session)?;
+ }
+ Ok(())
}
/// Compatibility check for callers that require a native Harness profile. Restricted
@@ -394,6 +416,7 @@ struct RenderedHarnessProfile {
adapter_bootstrap: Option<PathBuf>,
native_args: Vec<PathBuf>,
native_model_id: String,
+ opencode_startup: Option<opencode::StartupAdmission>,
}
fn secret_str(secret: &ProtectedSecret) -> Result<&str, DelegationErrorV1> {
diff --git a/crates/daemon/src/delegation/profile/native_context.rs b/crates/daemon/src/delegation/profile/native_context.rs
index 67287fff..74b5ef32 100644
--- a/crates/daemon/src/delegation/profile/native_context.rs
+++ b/crates/daemon/src/delegation/profile/native_context.rs
@@ -7,6 +7,7 @@ pub struct NativeWorkerContext {
home: PathBuf,
config_root: PathBuf,
borrowed: bool,
+ opencode: Option<hiroute_integrations::OpenCodeNativeContext>,
}
impl NativeWorkerContext {
@@ -57,11 +58,17 @@ impl NativeWorkerContext {
let home = home
.map(PathBuf::from)
.ok_or(DelegationErrorV1::CapabilityUnavailable)?;
+ if harness == WorkerHarnessV1::OpenCode {
+ let context = hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, lookup)
+ .map_err(|_| DelegationErrorV1::CapabilityUnavailable)?;
+ return Self::from_opencode(context);
+ }
let (variable, default) = match harness {
WorkerHarnessV1::CodexCli => ("CODEX_HOME", ".codex"),
WorkerHarnessV1::ClaudeCode => ("CLAUDE_CONFIG_DIR", ".claude"),
WorkerHarnessV1::Pi => ("PI_CODING_AGENT_DIR", ".pi/agent"),
WorkerHarnessV1::DeepseekHarness => ("DSH_HOME", ".dsh"),
+ WorkerHarnessV1::OpenCode => return Err(DelegationErrorV1::CapabilityUnavailable),
WorkerHarnessV1::QoderCli => {
let selected = lookup("QODER_CONFIG_DIR").map(PathBuf::from);
let context = hiroute_integrations::agents::QoderNativeContext::from_selected(
@@ -105,9 +112,24 @@ impl NativeWorkerContext {
home,
config_root,
borrowed,
+ opencode: None,
})
}
+ pub fn from_opencode(
+ context: hiroute_integrations::OpenCodeNativeContext,
+ ) -> Result<Self, DelegationErrorV1> {
+ context
+ .validate()
+ .map_err(|_| DelegationErrorV1::InvalidArguments)?;
+ let mut native = Self::borrowed(&context.home, &context.config_root)?;
+ native.opencode = Some(context);
+ Ok(native)
+ }
+ pub fn opencode(&self) -> Option<&hiroute_integrations::OpenCodeNativeContext> {
+ self.opencode.as_ref()
+ }
+
pub fn home(&self) -> &Path {
&self.home
}
diff --git a/crates/daemon/src/delegation/profile/native_history.rs b/crates/daemon/src/delegation/profile/native_history.rs
index 4c4d214e..920584c7 100644
--- a/crates/daemon/src/delegation/profile/native_history.rs
+++ b/crates/daemon/src/delegation/profile/native_history.rs
@@ -17,6 +17,8 @@ pub struct BorrowedNativeContext {
pub home: PathBuf,
pub config_root: PathBuf,
pub workspace: PathBuf,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub opencode: Option<hiroute_integrations::OpenCodeNativeContext>,
}
#[derive(Eq, PartialEq, Serialize, Deserialize)]
@@ -50,6 +52,7 @@ impl TaskSessionRoot {
home: canonical_context_path(home, false)?,
config_root: canonical_context_path(config_root, true)?,
workspace: canonical_context_path(workspace, false)?,
+ opencode: None,
};
if context.config_root.starts_with(&self.path) {
return Err(DelegationErrorV1::InvalidArguments);
@@ -71,6 +74,60 @@ impl TaskSessionRoot {
read_context(&self.path, self.harness).map(|value| value.map(|value| value.context))
}
+ pub fn bind_opencode_context(
+ &self,
+ native: &hiroute_integrations::OpenCodeNativeContext,
+ workspace: &Path,
+ ) -> Result<(), DelegationErrorV1> {
+ if !self.newly_created || self.harness != WorkerHarnessV1::OpenCode {
+ return Err(DelegationErrorV1::Conflict);
+ }
+ let mut native = native.clone();
+ native.home = canonical_context_path(&native.home, false)?;
+ for root in [
+ &mut native.config_root,
+ &mut native.data_root,
+ &mut native.cache_root,
+ &mut native.state_root,
+ ] {
+ *root = canonical_context_path(root, true)?;
+ }
+ if let Some(root) = &mut native.extra_config_root {
+ *root = canonical_context_path(root, true)?;
+ }
+ // Files are selectors, not directories. Resolve their existing parent prefix only.
+ for file in std::iter::once(&mut native.database).chain(native.config_file.iter_mut()) {
+ let name = file
+ .file_name()
+ .ok_or(DelegationErrorV1::InvalidArguments)?
+ .to_owned();
+ *file = canonical_context_path(
+ file.parent().ok_or(DelegationErrorV1::InvalidArguments)?,
+ true,
+ )?
+ .join(name);
+ }
+ validate_opencode_paths(&native, &self.path)?;
+ let context = BorrowedNativeContext {
+ home: native.home.clone(),
+ config_root: native.config_root.clone(),
+ workspace: canonical_context_path(workspace, false)?,
+ opencode: Some(native),
+ };
+ if context.config_root.starts_with(&self.path) {
+ return Err(DelegationErrorV1::InvalidArguments);
+ }
+ write_owned_json(
+ &self.path,
+ CONTEXT_FILE,
+ &ContextDescriptor {
+ version: 2,
+ harness: self.harness,
+ context,
+ },
+ )
+ }
+
/// Match the task's persisted ACP identity before attempting Continue. For borrowed Codex/Qoder,
/// this proves only the retained binding: session/load must still confirm native history.
pub fn verify_native_session(&self, native_session_id: &str) -> Result<(), DelegationErrorV1> {
@@ -122,6 +179,7 @@ pub(super) fn read_context(
WorkerHarnessV1::QoderCli
| WorkerHarnessV1::Pi
| WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
) =>
{
Ok(None)
@@ -133,10 +191,22 @@ pub(super) fn read_context(
Ok(_) => {}
}
let descriptor: ContextDescriptor = read_owned_json(root, CONTEXT_FILE)?;
- if descriptor.version != 1 || descriptor.harness != harness {
+ if descriptor.harness != harness
+ || if harness == WorkerHarnessV1::OpenCode {
+ descriptor.version != 2 || descriptor.context.opencode.is_none()
+ } else {
+ descriptor.version != 1 || descriptor.context.opencode.is_some()
+ }
+ {
return Err(DelegationErrorV1::ResumeUnavailable);
}
let context = &descriptor.context;
+ if let Some(native) = &context.opencode {
+ if native.home != context.home || native.config_root != context.config_root {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ validate_opencode_paths(native, root)?;
+ }
for (path, missing) in [
(&context.home, false),
(&context.config_root, true),
@@ -223,6 +293,18 @@ fn verify_borrowed_history(
native_session_id: &str,
) -> Result<(), DelegationErrorV1> {
validate_session_id(native_session_id)?;
+ if context.harness == WorkerHarnessV1::OpenCode {
+ let native = context
+ .context
+ .opencode
+ .as_ref()
+ .ok_or(DelegationErrorV1::ResumeUnavailable)?;
+ let metadata = std::fs::symlink_metadata(&native.database)
+ .map_err(|_| DelegationErrorV1::ResumeUnavailable)?;
+ if !metadata.is_file() || metadata.file_type().is_symlink() {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ }
if context.harness == WorkerHarnessV1::Pi {
pi_transcript(root, context, native_session_id)?;
}
@@ -418,3 +500,58 @@ fn write_owned_json<T: Serialize + DeserializeOwned + PartialEq>(
#[cfg(test)]
#[path = "native_history_tests.rs"]
mod tests;
+
+fn validate_opencode_paths(
+ native: &hiroute_integrations::OpenCodeNativeContext,
+ root: &Path,
+) -> Result<(), DelegationErrorV1> {
+ let invalid = || DelegationErrorV1::ResumeUnavailable;
+ native.validate().map_err(|_| invalid())?;
+ // The child appends `opencode` to each XDG selector. A canonical leaf with another name
+ // cannot be reconstructed by taking its parent; reject it on New and persisted Continue.
+ for path in [
+ &native.config_root,
+ &native.data_root,
+ &native.cache_root,
+ &native.state_root,
+ ] {
+ if path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .is_none_or(|name| {
+ if cfg!(windows) {
+ !name.eq_ignore_ascii_case("opencode")
+ } else {
+ name != "opencode"
+ }
+ })
+ {
+ return Err(invalid());
+ }
+ }
+ for path in [
+ &native.home,
+ &native.config_root,
+ &native.data_root,
+ &native.cache_root,
+ &native.state_root,
+ ]
+ .into_iter()
+ .chain(native.extra_config_root.iter())
+ {
+ if path.starts_with(root)
+ || canonical_context_path(path, true).map_err(|_| invalid())? != *path
+ {
+ return Err(invalid());
+ }
+ }
+ for path in std::iter::once(&native.database).chain(native.config_file.iter()) {
+ let parent = path.parent().ok_or_else(invalid)?;
+ if path.starts_with(root)
+ || canonical_context_path(parent, true).map_err(|_| invalid())? != parent
+ {
+ return Err(invalid());
+ }
+ }
+ Ok(())
+}
diff --git a/crates/daemon/src/delegation/profile/native_history_tests.rs b/crates/daemon/src/delegation/profile/native_history_tests.rs
index 137a22f9..eb8c7f82 100644
--- a/crates/daemon/src/delegation/profile/native_history_tests.rs
+++ b/crates/daemon/src/delegation/profile/native_history_tests.rs
@@ -2,6 +2,130 @@ use super::*;
const SESSION: &str = "71a2b020-312e-49cd-b084-924cbb3642ad";
+#[cfg(unix)]
+#[test]
+fn opencode_review_rejects_unprojectable_xdg_roots_for_new_and_continue() {
+ use std::os::unix::fs::symlink;
+ for index in 0..4 {
+ let storage = crate::test_support::private_tempdir();
+ let home = storage.path().canonicalize().unwrap().join("home");
+ let workspace = storage.path().canonicalize().unwrap().join("workspace");
+ fs::create_dir_all(&home).unwrap();
+ fs::create_dir_all(&workspace).unwrap();
+ let mut native =
+ hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap();
+ let selected = [
+ &mut native.config_root,
+ &mut native.data_root,
+ &mut native.cache_root,
+ &mut native.state_root,
+ ]
+ .into_iter()
+ .nth(index)
+ .unwrap();
+ let borrowed = home.join("borrowed-root");
+ fs::create_dir_all(&borrowed).unwrap();
+ fs::create_dir_all(selected.parent().unwrap()).unwrap();
+ symlink(&borrowed, &*selected).unwrap();
+ let session = TaskSessionRoot::prepare(
+ storage.path(),
+ &WorkspaceId::default(),
+ "root",
+ "task",
+ WorkerHarnessV1::OpenCode,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ assert!(
+ session.bind_opencode_context(&native, &workspace).is_err(),
+ "XDG root {index}"
+ );
+
+ // A descriptor produced by the old binding code must also fail before a Continue launch.
+ *[
+ &mut native.config_root,
+ &mut native.data_root,
+ &mut native.cache_root,
+ &mut native.state_root,
+ ][index] = borrowed.clone();
+ if index == 1 {
+ native.database = borrowed.join("opencode.db");
+ }
+ write_owned_json(
+ session.path(),
+ CONTEXT_FILE,
+ &ContextDescriptor {
+ version: 2,
+ harness: WorkerHarnessV1::OpenCode,
+ context: BorrowedNativeContext {
+ home: home.clone(),
+ config_root: native.config_root.clone(),
+ workspace,
+ opencode: Some(native),
+ },
+ },
+ )
+ .unwrap();
+ assert!(
+ session.borrowed_context().is_err(),
+ "Continue XDG root {index}"
+ );
+ assert!(borrowed.is_dir());
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn opencode_xdg_directory_links_preserve_the_admitted_child_roots() {
+ use std::os::unix::fs::symlink;
+ let storage = crate::test_support::private_tempdir();
+ let base = storage.path().canonicalize().unwrap();
+ let home = base.join("home");
+ let workspace = base.join("workspace");
+ fs::create_dir_all(&home).unwrap();
+ fs::create_dir_all(&workspace).unwrap();
+ let native = hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap();
+ for (index, path) in [
+ &native.config_root,
+ &native.data_root,
+ &native.cache_root,
+ &native.state_root,
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let actual = base.join(format!("selected-{index}/opencode"));
+ fs::create_dir_all(&actual).unwrap();
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ symlink(&actual, path).unwrap();
+ }
+ let session = TaskSessionRoot::prepare(
+ &base,
+ &WorkspaceId::default(),
+ "root",
+ "task",
+ WorkerHarnessV1::OpenCode,
+ SessionRootUse::New,
+ )
+ .unwrap();
+ session.bind_opencode_context(&native, &workspace).unwrap();
+ let bound = session
+ .borrowed_context()
+ .unwrap()
+ .unwrap()
+ .opencode
+ .unwrap();
+ for (source, admitted) in [
+ (&native.config_root, &bound.config_root),
+ (&native.data_root, &bound.data_root),
+ (&native.cache_root, &bound.cache_root),
+ (&native.state_root, &bound.state_root),
+ ] {
+ assert_eq!(&fs::canonicalize(source).unwrap(), admitted);
+ assert_eq!(admitted.parent().unwrap().join("opencode"), *admitted);
+ }
+}
+
fn canonical(path: &Path) -> PathBuf {
super::super::super::native_context::native_path(&fs::canonicalize(path).unwrap())
}
diff --git a/crates/daemon/src/delegation/profile/opencode.rs b/crates/daemon/src/delegation/profile/opencode.rs
new file mode 100644
index 00000000..bcd19791
--- /dev/null
+++ b/crates/daemon/src/delegation/profile/opencode.rs
@@ -0,0 +1,479 @@
+//! OpenCode native ACP leaf; the shared executor owns authority, transport and process cleanup.
+use super::*;
+use std::collections::BTreeSet;
+
+pub(super) const MODE: &str = "hiroute-worker";
+
+/// Final admission runs under the existing initialization permit. In particular,
+/// another first Worker may still be creating this native database during rendering.
+pub(super) struct StartupAdmission {
+ native: hiroute_integrations::OpenCodeNativeContext,
+ config_digest: hiroute_domain::CanonicalDigest,
+ migrations: &'static [&'static str],
+ search_path: String,
+}
+
+impl StartupAdmission {
+ pub(super) fn root(&self) -> &Path {
+ &self.native.database
+ }
+
+ pub(super) fn validate(
+ &self,
+ workspace: &Path,
+ new_session: bool,
+ ) -> Result<(), DelegationErrorV1> {
+ let unavailable = || DelegationErrorV1::CapabilityUnavailable;
+ if !new_session
+ && !self
+ .native
+ .database
+ .try_exists()
+ .map_err(|_| unavailable())?
+ {
+ return Err(DelegationErrorV1::ResumeUnavailable);
+ }
+ validate_database(&self.native.database, self.migrations)?;
+ let config = self
+ .native
+ .read_config(Some((workspace, &self.search_path)))
+ .map_err(|_| unavailable())?;
+ if config.digest != self.config_digest {
+ return Err(unavailable());
+ }
+ hiroute_integrations::validate_opencode_composition(
+ &self.native,
+ &config,
+ workspace,
+ &self.search_path,
+ )
+ .map_err(|_| unavailable())
+ }
+}
+
+pub(super) fn render(
+ input: &ProfileInput<'_>,
+ search_path: &str,
+) -> Result<RenderedHarnessProfile, DelegationErrorV1> {
+ let unavailable = || DelegationErrorV1::CapabilityUnavailable;
+ let native = input.native_context.opencode().ok_or_else(unavailable)?;
+ let ids = hiroute_integrations::opencode_native_format(input.harness_binary)
+ .map_err(|_| unavailable())?;
+ let config = native
+ .read_config(Some((input.workspace, search_path)))
+ .map_err(|_| unavailable())?;
+ let task = input
+ .session_root
+ .path()
+ .file_name()
+ .and_then(|n| n.to_str())
+ .ok_or_else(unavailable)?;
+ let provider = format!("hiroute-worker-{task}");
+ if config.value["provider"].get(&provider).is_some()
+ || config.value["agent"].get(MODE).is_some()
+ {
+ return Err(unavailable());
+ }
+ let model = hiroute_domain::AdditionalAgentModelV1 {
+ alias: input.alias.into(),
+ protocol: input.protocol,
+ context_window_tokens: input.context_window_tokens.ok_or_else(unavailable)?,
+ max_output_tokens: input.max_output_tokens.ok_or_else(unavailable)?,
+ };
+ let declaration = hiroute_integrations::opencode_provider(
+ &format!("http://{}/v1", input.gateway),
+ &model,
+ "{env:HIROUTE_RUN_TOKEN}",
+ None,
+ )
+ .map_err(|_| unavailable())?;
+ let selector = format!("{provider}/{}", input.alias);
+ let permission = json!({"*":"deny","read":"allow","edit":"allow","bash":"allow","glob":"allow","grep":"allow","skill":"allow","external_directory":"allow","doom_loop":"allow"});
+ let mut agents = serde_json::Map::new();
+ for key in ["build", "plan", "general", "explore"].into_iter().chain(
+ config.value["agent"]
+ .as_object()
+ .into_iter()
+ .flat_map(|v| v.keys().map(String::as_str)),
+ ) {
+ agents.insert(key.into(), json!({"disable":true}));
+ }
+ for key in ["title", "summary", "compaction"] {
+ agents.insert(
+ key.into(),
+ json!({"model":selector,"disable":false,"permission":{"*":"deny"}}),
+ );
+ }
+ agents.insert(
+ MODE.into(),
+ json!({"mode":"primary","model":selector,"permission":permission}),
+ );
+ let mcp = config.value["mcp"]
+ .as_object()
+ .into_iter()
+ .flat_map(|v| v.keys())
+ .map(|k| (k.clone(), json!({"enabled":false})))
+ .collect::<serde_json::Map<_, _>>();
+ let overlay = json!({"$schema":"https://opencode.ai/config.json","model":selector,"small_model":selector,"default_agent":MODE,
+ "enabled_providers":[provider],"provider":{(provider):declaration},"agent":agents,"permission":permission,"mcp":mcp,
+ "share":"disabled","autoupdate":false,"lsp":false,"formatter":false,"compaction":{"auto":true}});
+ let mut listener_entropy = [0u8; 32];
+ getrandom::fill(&mut listener_entropy).map_err(|_| unavailable())?;
+ let listener_password = Zeroizing::new(
+ listener_entropy
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect::<String>(),
+ );
+ use zeroize::Zeroize;
+ listener_entropy.zeroize();
+ let mut rendered = RenderedHarnessProfile {
+ opencode_startup: Some(StartupAdmission {
+ native: native.clone(),
+ config_digest: config.digest.clone(),
+ migrations: ids,
+ search_path: search_path.into(),
+ }),
+ native_model_id: selector,
+ native_args: vec![
+ "acp".into(),
+ "--cwd".into(),
+ input.workspace.into(),
+ "--hostname".into(),
+ "127.0.0.1".into(),
+ "--port".into(),
+ "0".into(),
+ "--mdns=false".into(),
+ ],
+ ..Default::default()
+ };
+ for (key, value) in [
+ (
+ "OPENCODE_CONFIG_CONTENT",
+ serde_json::to_string(&overlay).map_err(|_| unavailable())?,
+ ),
+ ("HIROUTE_RUN_TOKEN", secret_string(&input.token)?),
+ ("OPENCODE_SERVER_PASSWORD", listener_password.to_string()),
+ ("OPENCODE_SERVER_USERNAME", "hiroute-worker".into()),
+ ("OPENCODE_PURE", "true".into()),
+ ("OPENCODE_DISABLE_DEFAULT_PLUGINS", "true".into()),
+ ("OPENCODE_DISABLE_AUTOUPDATE", "true".into()),
+ ("OPENCODE_DISABLE_MODELS_FETCH", "true".into()),
+ ("OPENCODE_DISABLE_LSP_DOWNLOAD", "true".into()),
+ ("OPENCODE_DISABLE_FFF", "true".into()),
+ (
+ "OPENCODE_PERMISSION",
+ serde_json::to_string(&permission).map_err(|_| unavailable())?,
+ ),
+ ("OPENCODE_DB", path_string(&native.database)?),
+ (
+ "XDG_CONFIG_HOME",
+ path_string(native.config_root.parent().ok_or_else(unavailable)?)?,
+ ),
+ (
+ "XDG_DATA_HOME",
+ path_string(native.data_root.parent().ok_or_else(unavailable)?)?,
+ ),
+ (
+ "XDG_CACHE_HOME",
+ path_string(native.cache_root.parent().ok_or_else(unavailable)?)?,
+ ),
+ (
+ "XDG_STATE_HOME",
+ path_string(native.state_root.parent().ok_or_else(unavailable)?)?,
+ ),
+ ] {
+ rendered.env.insert(key.into(), Zeroizing::new(value));
+ }
+ for (key, path) in [
+ ("OPENCODE_CONFIG", native.config_file.as_ref()),
+ ("OPENCODE_CONFIG_DIR", native.extra_config_root.as_ref()),
+ ] {
+ if let Some(path) = path {
+ rendered
+ .env
+ .insert(key.into(), Zeroizing::new(path_string(path)?));
+ }
+ }
+ Ok(rendered)
+}
+
+fn validate_database(path: &Path, expected: &[&str]) -> Result<(), DelegationErrorV1> {
+ let unavailable = || DelegationErrorV1::CapabilityUnavailable;
+ match std::fs::symlink_metadata(path) {
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => {}
+ _ => return Err(unavailable()),
+ }
+ let db = rusqlite::Connection::open_with_flags(
+ path,
+ rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )
+ .map_err(|_| unavailable())?;
+ db.busy_timeout(std::time::Duration::from_millis(100))
+ .map_err(|_| unavailable())?;
+ let kind: String = db
+ .query_row(
+ "SELECT type FROM sqlite_schema WHERE name='migration'",
+ [],
+ |r| r.get(0),
+ )
+ .map_err(|_| unavailable())?;
+ if kind != "table" {
+ return Err(unavailable());
+ }
+ let mut query = db
+ .prepare(
+ "SELECT CASE WHEN length(CAST(id AS BLOB)) <= 256 THEN id END FROM migration LIMIT 129",
+ )
+ .map_err(|_| unavailable())?;
+ let rows = query
+ .query_map([], |r| r.get::<_, String>(0))
+ .map_err(|_| unavailable())?
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|_| unavailable())?;
+ if rows.len() > 128 || rows.iter().any(|x| x.len() > 256) {
+ return Err(unavailable());
+ }
+ let actual = rows.iter().map(String::as_str).collect::<BTreeSet<_>>();
+ if actual.len() != rows.len() || actual != expected.iter().copied().collect() {
+ return Err(unavailable());
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn git_workspace(home: &Path) -> String {
+ let path = worker_path(&home.join("opencode"), None, None).unwrap();
+ let status = std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(home)
+ .env_clear()
+ .env("HOME", home)
+ .env("PATH", &path)
+ .status()
+ .unwrap();
+ assert!(status.success());
+ path
+ }
+
+ #[test]
+ fn opencode_startup_rejects_rewritable_schema_without_touching_borrowed_files() {
+ let root = tempfile::tempdir().unwrap();
+ let home = root.path().canonicalize().unwrap();
+ let native =
+ hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap();
+ std::fs::create_dir_all(&native.config_root).unwrap();
+ let search_path = git_workspace(&home);
+ for schema in [
+ "",
+ "{env:HIROUTE_UNSET_SCHEMA}",
+ "{file:schema.txt}",
+ "https://opencode.ai/config.json",
+ ] {
+ let bytes = serde_json::to_vec(&json!({"$schema":schema})).unwrap();
+ std::fs::write(native.model_target(), &bytes).unwrap();
+ let config = native.read_config(Some((&home, &search_path))).unwrap();
+ let admission = StartupAdmission {
+ native: native.clone(),
+ config_digest: config.digest.clone(),
+ migrations: &["known"],
+ search_path: search_path.clone(),
+ };
+ assert_eq!(
+ admission.validate(&home, true).is_ok(),
+ schema == "https://opencode.ai/config.json",
+ "{schema}"
+ );
+ assert_eq!(std::fs::read(native.model_target()).unwrap(), bytes);
+ assert!(!native.database.exists());
+ }
+ }
+
+ #[test]
+ fn opencode_startup_refuses_incomplete_ancestry_before_native_tool_loading() {
+ for git in [true, false] {
+ let root = tempfile::tempdir().unwrap();
+ let home = root.path().canonicalize().unwrap();
+ let project = home.join("project");
+ std::fs::create_dir_all(project.join(".opencode/tools")).unwrap();
+ if git {
+ std::fs::create_dir(project.join(".git")).unwrap();
+ }
+ let tool = project.join(".opencode/tools/custom.ts");
+ let content = b"throw new Error('must never be imported')";
+ std::fs::write(&tool, content).unwrap();
+ let native =
+ hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap();
+ let search_path = git_workspace(&home);
+ let config = native.read_config(Some((&home, &search_path))).unwrap();
+ let admission = StartupAdmission {
+ native: native.clone(),
+ config_digest: config.digest.clone(),
+ migrations: &["known"],
+ search_path: search_path.clone(),
+ };
+ let deep = (0..65).fold(project, |path, _| path.join("d"));
+ std::fs::create_dir_all(&deep).unwrap();
+ assert_eq!(
+ admission.validate(&deep, true),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ );
+ assert_eq!(std::fs::read(tool).unwrap(), content);
+ assert!(!native.database.exists());
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn opencode_startup_refuses_false_git_stops_and_rechecks_late_boundary_changes() {
+ for kind in [
+ "empty",
+ "corrupt",
+ "broken-worktree",
+ "missing-git",
+ "rejected-git",
+ "late-corruption",
+ ] {
+ let root = tempfile::tempdir().unwrap();
+ let base = root.path().canonicalize().unwrap();
+ let home = base.join("home");
+ let ancestor = base.join("ancestor");
+ let project = ancestor.join("project");
+ std::fs::create_dir(&home).unwrap();
+ std::fs::create_dir_all(&project).unwrap();
+ let native =
+ hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap();
+ let path = worker_path(&home.join("opencode"), None, None).unwrap();
+ let marker = project.join(".git");
+ if matches!(kind, "missing-git" | "rejected-git" | "late-corruption") {
+ let status = std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(&project)
+ .env_clear()
+ .env("HOME", &home)
+ .env("PATH", &path)
+ .status()
+ .unwrap();
+ assert!(status.success());
+ } else if kind == "empty" {
+ std::fs::create_dir(&marker).unwrap();
+ } else {
+ std::fs::write(
+ &marker,
+ if kind == "corrupt" {
+ "not a gitdir"
+ } else {
+ "gitdir: missing-worktree\n"
+ },
+ )
+ .unwrap();
+ }
+ let config_bytes = br#"{"$schema":""}"#;
+ let config_path = ancestor.join("opencode.json");
+ std::fs::write(&config_path, config_bytes).unwrap();
+ std::fs::create_dir_all(ancestor.join(".opencode/tools")).unwrap();
+ let tool = ancestor.join(".opencode/tools/custom.ts");
+ let tool_bytes = b"throw new Error('must never be imported')";
+ std::fs::write(&tool, tool_bytes).unwrap();
+ let config = native.read_config(None).unwrap();
+ let mut admission = StartupAdmission {
+ native: native.clone(),
+ config_digest: config.digest.clone(),
+ migrations: &["known"],
+ search_path: path.clone(),
+ };
+ if kind == "late-corruption" {
+ assert!(admission.validate(&project, true).is_ok());
+ std::fs::write(marker.join("config"), b"[invalid git config").unwrap();
+ }
+ if kind == "missing-git" {
+ admission.search_path = home.to_str().unwrap().into();
+ }
+ if kind == "rejected-git" {
+ // A real Git rejection, without changing process-global test environment.
+ std::fs::write(marker.join("config"), b"[invalid git config").unwrap();
+ }
+ assert_eq!(
+ admission.validate(&project, true),
+ Err(DelegationErrorV1::CapabilityUnavailable),
+ "{kind}"
+ );
+ assert!(
+ native
+ .read_config(Some((&project, &admission.search_path)))
+ .is_err(),
+ "{kind}"
+ );
+ assert_eq!(std::fs::read(&config_path).unwrap(), config_bytes);
+ assert_eq!(std::fs::read(&tool).unwrap(), tool_bytes);
+ assert!(!native.database.exists());
+ }
+ }
+
+ #[test]
+ fn opencode_startup_rechecks_configuration_and_missing_continue_history() {
+ let root = tempfile::tempdir().unwrap();
+ let home = root.path().canonicalize().unwrap();
+ let native =
+ hiroute_integrations::OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap();
+ let search_path = git_workspace(&home);
+ let config = native.read_config(Some((&home, &search_path))).unwrap();
+ let admission = StartupAdmission {
+ native: native.clone(),
+ config_digest: config.digest.clone(),
+ migrations: &["known"],
+ search_path: search_path.clone(),
+ };
+ assert_eq!(admission.root(), native.database);
+ assert!(admission.validate(&home, true).is_ok());
+ assert_eq!(
+ admission.validate(&home, false),
+ Err(DelegationErrorV1::ResumeUnavailable)
+ );
+ assert!(!native.database.exists());
+
+ std::fs::create_dir_all(&native.config_root).unwrap();
+ std::fs::write(
+ native.model_target(),
+ br#"{"$schema":"https://opencode.ai/config.json","mcp":{"late":{"enabled":true}}}"#,
+ )
+ .unwrap();
+ assert_eq!(
+ admission.validate(&home, true),
+ Err(DelegationErrorV1::CapabilityUnavailable)
+ );
+ assert!(!native.database.exists());
+ }
+
+ #[test]
+ fn opencode_database_admission_refuses_pending_unknown_and_legacy_without_writes() {
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("native.db");
+ assert!(validate_database(&path, &["known"]).is_ok());
+ assert!(!path.exists());
+ let db = rusqlite::Connection::open(&path).unwrap();
+ db.execute_batch("CREATE TABLE migration(id TEXT PRIMARY KEY);CREATE TABLE session(id TEXT PRIMARY KEY,content TEXT);INSERT INTO session VALUES('native-exact','opaque-must-survive')").unwrap();
+ drop(db);
+ let before = std::fs::read(&path).unwrap();
+ assert!(validate_database(&path, &["known"]).is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ let db = rusqlite::Connection::open(&path).unwrap();
+ db.execute("INSERT INTO migration VALUES('known')", [])
+ .unwrap();
+ drop(db);
+ let before = std::fs::read(&path).unwrap();
+ assert!(validate_database(&path, &["known"]).is_ok());
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ let db = rusqlite::Connection::open(&path).unwrap();
+ db.execute("INSERT INTO migration VALUES('future')", [])
+ .unwrap();
+ drop(db);
+ let before = std::fs::read(&path).unwrap();
+ assert!(validate_database(&path, &["known"]).is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), before);
+ }
+}
diff --git a/crates/daemon/src/delegation/profile/tests.rs b/crates/daemon/src/delegation/profile/tests.rs
index b4c371ab..cd0a04ec 100644
--- a/crates/daemon/src/delegation/profile/tests.rs
+++ b/crates/daemon/src/delegation/profile/tests.rs
@@ -40,7 +40,7 @@ fn isolated_worker_profiles_can_resolve_standard_tools() {
profile.native_selected_model_id(),
"hiroute/1234567890abcdef"
);
- assert!(profile.codex_initialization_root().is_none());
+ assert!(profile.native_initialization_root().is_none());
let path = profile.env.get("PATH").expect("worker PATH");
let entries: Vec<_> = std::env::split_paths(path.as_str()).collect();
assert!(entries.iter().all(|entry| entry.is_absolute()));
@@ -207,9 +207,10 @@ fn try_request_in_context(
WorkerHarnessV1::CodexCli | WorkerHarnessV1::ClaudeCode => {
Some(Path::new("/trusted/adapter"))
}
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::Pi | WorkerHarnessV1::DeepseekHarness => {
- None
- }
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::Pi
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode => None,
},
harness_binary,
node_binary,
@@ -477,11 +478,11 @@ fn borrowed_codex_keeps_daily_config_and_routes_before_startup_with_task_owned_m
.unwrap();
assert_eq!(first.env["HOME"].as_str(), daily_home.to_str().unwrap());
assert_eq!(
- first.codex_initialization_root(),
+ first.native_initialization_root(),
Some(config_root.as_path())
);
assert_eq!(
- continued.codex_initialization_root(),
+ continued.native_initialization_root(),
Some(config_root.as_path())
);
assert_eq!(
@@ -619,7 +620,7 @@ fn borrowed_claude_enables_skills_without_expanding_restricted_permissions() {
)
.unwrap();
assert_eq!(profile.env["HOME"].as_str(), "/instance-home");
- assert!(profile.codex_initialization_root().is_none());
+ assert!(profile.native_initialization_root().is_none());
assert_eq!(profile.env["CLAUDE_CONFIG_DIR"].as_str(), "/native-claude");
assert_eq!(
profile.env["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST"].as_str(),
diff --git a/crates/daemon/src/delegation/profile/tests/qoder.rs b/crates/daemon/src/delegation/profile/tests/qoder.rs
index 23dd295e..37a7d0ab 100644
--- a/crates/daemon/src/delegation/profile/tests/qoder.rs
+++ b/crates/daemon/src/delegation/profile/tests/qoder.rs
@@ -81,7 +81,7 @@ fn native_qoder_uses_selected_cli_shared_resources_and_only_transient_managed_ro
profile.identity_contract,
AcpNativeIdentityContract::QoderSessionV1
);
- assert!(profile.codex_initialization_root().is_none());
+ assert!(profile.native_initialization_root().is_none());
assert!(profile.session_meta.is_empty());
assert_eq!(
profile.native_selected_model_id(),
diff --git a/crates/daemon/src/delegation/run_authority.rs b/crates/daemon/src/delegation/run_authority.rs
index 2afbd47b..45a31b5f 100644
--- a/crates/daemon/src/delegation/run_authority.rs
+++ b/crates/daemon/src/delegation/run_authority.rs
@@ -282,6 +282,7 @@ fn build_entry(
hiroute_domain::delegation::WorkerHarnessV1::QoderCli => "qoder",
hiroute_domain::delegation::WorkerHarnessV1::Pi => "pi",
hiroute_domain::delegation::WorkerHarnessV1::DeepseekHarness => "dsh",
+ hiroute_domain::delegation::WorkerHarnessV1::OpenCode => "opencode",
},
task.session
.as_ref()
diff --git a/crates/daemon/src/test_support.rs b/crates/daemon/src/test_support.rs
index a4b826a1..cd70b9b6 100644
--- a/crates/daemon/src/test_support.rs
+++ b/crates/daemon/src/test_support.rs
@@ -104,7 +104,20 @@ fn isolated_agent_home_inner(
hiroute_domain::CLAUDE_CONTEXT_CONFLICT_ENVIRONMENT
.iter()
.copied(),
- ) {
+ )
+ // OpenCode selectors must follow this child's private HOME, rather than the
+ // host agent's XDG roots, inline configuration or nonresumable database.
+ .chain([
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_STATE_HOME",
+ "OPENCODE_CONFIG",
+ "OPENCODE_CONFIG_DIR",
+ "OPENCODE_CONFIG_CONTENT",
+ "OPENCODE_DB",
+ "OPENCODE_TEST_MANAGED_CONFIG_DIR",
+ ]) {
command.env_remove(name);
}
let status = command.status().unwrap();
diff --git a/crates/daemon/tests/subscription_management_product.rs b/crates/daemon/tests/subscription_management_product.rs
index 3e835ebc..027b62d4 100644
--- a/crates/daemon/tests/subscription_management_product.rs
+++ b/crates/daemon/tests/subscription_management_product.rs
@@ -338,7 +338,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
proxy.set_nonblocking(true).unwrap();
let proxy_address = proxy.local_addr().unwrap();
let mut daemon =
- ProductDaemon::start_with_cpa(directory.path(), proxy_address, &binary, &sha256);
+ ProductDaemon::start_with_codex_cpa(directory.path(), proxy_address, &binary, &sha256);
let candidates = succeeded(
daemon
@@ -633,7 +633,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
drop(stores);
let restarted =
- ProductDaemon::start_with_cpa(directory.path(), proxy_address, &binary, &sha256);
+ ProductDaemon::start_with_codex_cpa(directory.path(), proxy_address, &binary, &sha256);
let restarted_snapshot = succeeded(
restarted
.client
@@ -878,7 +878,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
fs::set_permissions(&binary, fs::Permissions::from_mode(0o600)).unwrap();
let runtime_unavailable =
- ProductDaemon::start_with_cpa(directory.path(), proxy_address, &binary, &sha256);
+ ProductDaemon::start_with_codex_cpa(directory.path(), proxy_address, &binary, &sha256);
let runtime_snapshot = succeeded(
runtime_unavailable
.client
@@ -910,7 +910,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
fs::write(&auth_path, br#"{"auth_mode":"chatgpt"}"#).unwrap();
fs::set_permissions(&auth_path, fs::Permissions::from_mode(0o600)).unwrap();
let invalid_auth =
- ProductDaemon::start_with_cpa(directory.path(), proxy_address, &binary, &sha256);
+ ProductDaemon::start_with_codex_cpa(directory.path(), proxy_address, &binary, &sha256);
let invalid_auth_snapshot = succeeded(
invalid_auth
.client
@@ -935,7 +935,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
let unavailable_auth_path = directory.path().join("home/.codex/auth.unavailable");
fs::rename(&auth_path, &unavailable_auth_path).unwrap();
let needs_auth =
- ProductDaemon::start_with_cpa(directory.path(), proxy_address, &binary, &sha256);
+ ProductDaemon::start_with_codex_cpa(directory.path(), proxy_address, &binary, &sha256);
let auth_snapshot = succeeded(
needs_auth
.client
@@ -958,7 +958,7 @@ async fn hirouted_client_core_subscription_save_snapshot_and_restart_are_closed(
fs::rename(unavailable_auth_path, auth_path).unwrap();
corrupt_saved_display_name(directory.path(), &source_id);
let mismatched =
- ProductDaemon::start_with_cpa(directory.path(), proxy_address, &binary, &sha256);
+ ProductDaemon::start_with_codex_cpa(directory.path(), proxy_address, &binary, &sha256);
let mismatch_snapshot = succeeded(
mismatched
.client
diff --git a/crates/daemon/tests/support/additional_model_fixture.py b/crates/daemon/tests/support/additional_model_fixture.py
index f85c22ed..746b44f2 100644
--- a/crates/daemon/tests/support/additional_model_fixture.py
+++ b/crates/daemon/tests/support/additional_model_fixture.py
@@ -22,6 +22,9 @@ LIVE_PROMPT = 'Reply with exactly HIROUTE_LIVE_CHECK_OK. Do not use tools or per
def select_model_context(product, harness="qoder"):
product.additional_harness = harness
+ if harness == "opencode":
+ from opencode_native_context import select_context
+ return select_context(product)
if harness == "pi":
config = Path(product.env["HOME"]) / ".pi/agent"
config.mkdir(mode=0o700, parents=True)
@@ -41,6 +44,9 @@ def select_model_context(product, harness="qoder"):
class OwnedModelSettings:
def __new__(cls, config, foreign_endpoint, harness="qoder"):
+ if harness == 'opencode':
+ from opencode_native_context import OpenCodeModelSettings
+ return OpenCodeModelSettings(config,foreign_endpoint)
if harness == 'dsh':
from dsh_native_context import DshModelSettings
return DshModelSettings(config, foreign_endpoint)
@@ -194,6 +200,8 @@ class PersistedRouteOracle:
def native_command(product, binary, selector, prompt):
# Ordinary settings precedence remains active. In particular, no --settings,
# --setting-sources or credential environment can hide a persistence defect.
+ if getattr(product,'additional_harness','qoder')=='opencode':
+ return [str(binary),'run','--format','json','--model',selector,prompt]
if getattr(product, 'additional_harness', 'qoder') == 'pi':
provider, model = selector.split('/',1)
return [os.environ['HIROUTE_WORKER_NODE'], str(binary), '--provider', provider, '--model', model,
@@ -205,6 +213,13 @@ def native_command(product, binary, selector, prompt):
def successful_native_result(stdout, receipt, harness='qoder'):
+ if harness=='opencode':
+ rows=[json.loads(line) for line in stdout.decode().splitlines() if line.startswith('{')]
+ assert not any(r.get('type')=='error' for r in rows),'native OpenCode returned an error'
+ texts=[r for r in rows if r.get('type')=='text']
+ assert len(texts)==1 and texts[0]['part']['text'].strip()==receipt,'native OpenCode receipt mismatch'
+ assert any(r.get('type')=='step_finish' for r in rows),'native OpenCode did not finish'
+ return texts[0]['sessionID']
if harness == 'pi':
rows = [json.loads(line) for line in stdout.decode().splitlines() if line.startswith('{')]
headers = [r for r in rows if r.get('type') == 'session']
diff --git a/crates/daemon/tests/support/additional_model_product.py b/crates/daemon/tests/support/additional_model_product.py
index e13a71cf..36fa5413 100644
--- a/crates/daemon/tests/support/additional_model_product.py
+++ b/crates/daemon/tests/support/additional_model_product.py
@@ -80,7 +80,7 @@ def assert_saved_aliases(settings, provider, aliases):
models = [model for name, value in settings.read()['providers'].items() if name == provider or name.startswith(provider + '-') for model in value['models']]
for alias in aliases:
assert len(settings.read()['providers'][persisted_plan_provider(settings, provider, alias)]['models']) == 1
- assert len(models) == len(aliases) and {item['id' if HARNESS in ('pi','dsh') else 'model'] for item in models} == set(aliases), \
+ assert len(models) == len(aliases) and {item['id' if HARNESS in ('pi','dsh','opencode') else 'model'] for item in models} == set(aliases), \
'persisted native choices do not match the selected routes'
@@ -111,7 +111,7 @@ def reject_gateway_request(product, token, alias, protocol, sources, expected_co
if protocol == 'responses' else {'model': alias, 'messages': [{'role':'user','content':'Untrusted removed route'}],
'max_tokens':16, 'stream':True})
client.request('POST', TAIL + '/' + protocol, body=encoded(body),
- headers={'Content-Type': 'application/json', **({'X-HiRoute-Token':token} if HARNESS in ('pi','dsh')
+ headers={'Content-Type': 'application/json', **({'X-HiRoute-Token':token} if HARNESS in ('pi','dsh','opencode')
else {'Authorization':'Bearer ' + token})})
response = client.getresponse()
error = json.loads(response.read())
@@ -134,7 +134,7 @@ def assert_default_blocks_removal(product, context, settings, provider, plans, s
command = 'agents restore' if spec['model']['intent'] == 'restore' else 'agents connect'
preview = product.preview(command + ' preview', {'spec': spec})
assert not preview['applicable'] and any(
- item['reason'] == ('additional_default_in_use' if HARNESS in ('pi','dsh') else 'qoder_default_in_use') for item in preview['blockers']), \
+ item['reason'] == ('additional_default_in_use' if HARNESS in ('pi','dsh','opencode') else 'qoder_default_in_use') for item in preview['blockers']), \
'removing the selected native default must fail closed'
assert digest(settings.path) == before and digest(skill) == skill_before, 'blocked removal changed files'
assert settings_status(product, context) == status, 'blocked removal changed settings authority'
@@ -159,10 +159,10 @@ def run(repository, candidate):
global HARNESS, AGENT, MODE, TAIL
PLAN_PROTOCOLS.clear()
HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS', 'qoder')
- assert HARNESS in ('qoder', 'pi', 'dsh')
+ assert HARNESS in ('qoder', 'pi', 'dsh', 'opencode')
AGENT = 'agent_' + HARNESS + '_default'
MODE = HARNESS + '_additional'
- TAIL = '/v1' if HARNESS in ('pi','dsh') else '/_hiroute/qoder/v1'
+ TAIL = '/v1' if HARNESS in ('pi','dsh','opencode') else '/_hiroute/qoder/v1'
repo = Path(repository).resolve()
assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
product = Product(repo)
@@ -237,7 +237,7 @@ def run(repository, candidate):
stage = 'independent-model-and-skill'
(config / 'skills').mkdir(mode=0o700, exist_ok=True)
- skill = (config / 'skills/hiroute-collaboration/SKILL.md' if HARNESS in ('pi','dsh') else
+ skill = (config / 'skills/hiroute-collaboration/SKILL.md' if HARNESS in ('pi','dsh','opencode') else
qoder_native_context.prepare_collaboration_target(product))
before_skill = skill.read_bytes() if skill.exists() else None
check_collaboration(product, 'model-skill-preflight')
diff --git a/crates/daemon/tests/support/agent_product_support.py b/crates/daemon/tests/support/agent_product_support.py
index 1308b1d7..2b418af8 100644
--- a/crates/daemon/tests/support/agent_product_support.py
+++ b/crates/daemon/tests/support/agent_product_support.py
@@ -7,15 +7,20 @@ from pathlib import Path
def expose_native_installation(product, harness, binary, node=None):
"""Expose selected native entries in the fixture's private PATH, never the host PATH."""
- assert harness in ('pi', 'qoder', 'dsh')
+ assert harness in ('pi', 'qoder', 'dsh', 'opencode')
assert harness != 'pi' or node is not None, 'Pi fixture requires its selected Node'
- entries = [({'pi':'pi','qoder':'qodercli','dsh':'dsh'}[harness], binary)]
+ entries = [({'pi':'pi','qoder':'qodercli','dsh':'dsh','opencode':'opencode'}[harness], binary)]
if harness == 'dsh':
import shutil
runtime = Path(shutil.which('node')).resolve(strict=True)
entries.append(('node',runtime))
if harness == 'pi':
entries.append(('node', node))
+ if harness == 'opencode':
+ import shutil
+ ripgrep = shutil.which('rg')
+ assert ripgrep is not None, 'OpenCode product fixtures require installed ripgrep'
+ entries.append(('rg', Path(ripgrep).resolve(strict=True)))
for name, path in entries:
(product.root / 'bin' / name).symlink_to(Path(path).resolve(strict=True))
diff --git a/crates/daemon/tests/support/collaboration_fixture.py b/crates/daemon/tests/support/collaboration_fixture.py
index 631a083a..fa794bd9 100644
--- a/crates/daemon/tests/support/collaboration_fixture.py
+++ b/crates/daemon/tests/support/collaboration_fixture.py
@@ -54,8 +54,8 @@ def worker_decision(fixture, body):
if fixture.get('harness') == 'dsh':
return dict(kind='tool',id='delegated_artifact',name='bash',
arguments={'command':command,'description':'Write delegated receipt','timeoutMs':10000})
- return dict(kind='tool', id='delegated_artifact', name='bash' if fixture.get('harness') == 'pi' else 'Bash',
- arguments={'command': command, 'timeout': 10 if fixture.get('harness') == 'pi' else 10000})
+ return dict(kind='tool', id='delegated_artifact', name='bash' if fixture.get('harness') in ('pi','opencode') else 'Bash',
+ arguments={'command': command, 'description':'Write delegated receipt', 'timeout': 10 if fixture.get('harness') == 'pi' else 10000})
class MainAgentOracle:
@@ -78,7 +78,7 @@ class MainAgentOracle:
assert self.fixture['main_marker'] in rendered, 'Worker request reached the main Agent source'
results = tool_results(body, self.fixture.get('harness', 'qoder'))
names = {item.get('name') for item in body.get('tools', [])}
- if self.fixture.get('harness') == 'dsh':
+ if self.fixture.get('harness') in ('dsh','opencode'):
assert {'skill','bash'} <= names, 'native DSH Skill/bash tools unavailable'
if 'main_skill' not in results:
assert 'hiroute-collaboration' in rendered, 'installed user collaboration Skill not discovered'
@@ -108,7 +108,7 @@ class MainAgentOracle:
return self.bash('main_plans', shlex.quote(self.cli) + ' worker plans --output json')
directory = output_envelope(results['main_plans'])
plans = [plan for plan in directory['plans'] if plan['agent_plan_id'] == self.fixture['plan_id']]
- assert len(plans) == 1 and plans[0]['harness'] == {'pi':'pi','dsh':'deepseek_harness','qoder':'qoder_cli'}[self.fixture.get('harness','qoder')] and plans[0]['availability'] == 'ready', \
+ assert len(plans) == 1 and plans[0]['harness'] == {'pi':'pi','dsh':'deepseek_harness','qoder':'qoder_cli','opencode':'opencode'}[self.fixture.get('harness','qoder')] and plans[0]['availability'] == 'ready', \
'the public directory did not offer the published Qoder Worker Plan'
if 'main_exec' not in results:
prompt = 'Use ' + ' and '.join(item['name'] for item in self.fixture['skills']) + \
@@ -169,6 +169,8 @@ class MainAgentOracle:
if self.fixture.get("harness") == "dsh":
return dict(kind="tool",id=call_id,name="bash",
arguments={"command":command,"description":"Use public HiRoute CLI","timeoutMs":timeout})
+ if self.fixture.get("harness")=="opencode":
+ return dict(kind="tool",id=call_id,name="bash",arguments={"command":command,"description":"Use public HiRoute CLI","timeout":timeout})
pi = self.fixture.get("harness") == "pi"
return dict(kind="tool", id=call_id, name="bash" if pi else "Bash",
arguments={"command":command,"timeout":timeout / 1000 if pi else timeout})
diff --git a/crates/daemon/tests/support/collaboration_product.py b/crates/daemon/tests/support/collaboration_product.py
index 2c2ae56b..66f4ac23 100644
--- a/crates/daemon/tests/support/collaboration_product.py
+++ b/crates/daemon/tests/support/collaboration_product.py
@@ -43,6 +43,14 @@ def apply_collaboration(product, context, intent, key):
def run_main_agent(product, binary, upstream, fixture):
+ if HARNESS=='opencode':
+ from opencode_native_context import main_route
+ selector=main_route(product,upstream.base_url,upstream.model,upstream.token,fixture)
+ stdout=run_native_command(product,[str(binary),'run','--format','json','--model',selector,
+ fixture['main_marker']+': Read hiroute-collaboration and delegate the native receipt task.'],timeout=190,label='native OpenCode main Agent')
+ from additional_model_fixture import successful_native_result
+ successful_native_result(stdout,'MAIN-AGENT-COMPLETED-'+fixture['artifact']['receipt'],'opencode')
+ return
if HARNESS == 'dsh':
from dsh_native_context import main_route_patch
from native_acp_client import prompt
@@ -142,7 +150,7 @@ def finish_collaboration(product, sources, restore, report, stage, primary_failu
def run(repository, candidate):
global HARNESS, AGENT
HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','qoder')
- assert HARNESS in ('qoder','pi','dsh')
+ assert HARNESS in ('qoder','pi','dsh','opencode')
AGENT = 'agent_' + HARNESS + '_default'
repo = Path(repository).resolve()
assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
@@ -167,7 +175,7 @@ def run(repository, candidate):
fixture, worker_source = prepare_product(product, HARNESS)
report['source_context_tokens'] = fixture['source_context_tokens']
sources.append(worker_source)
- configure_worker_installation(product, {'pi':'pi','qoder':'qoder_cli','dsh':'deepseek_harness'}[HARNESS], None, binary, node)
+ configure_worker_installation(product, {'pi':'pi','qoder':'qoder_cli','dsh':'deepseek_harness','opencode':'opencode'}[HARNESS], None, binary, node)
if HARNESS == 'pi':
# Main CLI follows native auth behavior; the Worker-only helper trap is
# covered by the core journey, not executed by the main Agent fixture.
@@ -180,7 +188,7 @@ def run(repository, candidate):
receipt='QODER-WORKER-' + secrets.token_hex(16))
(product.root / 'native-context.json').write_text(json.dumps(fixture))
worker_source.reply = worker_decision
- skill = (Path(fixture['config']) / 'skills/hiroute-collaboration/SKILL.md' if HARNESS in ('pi','dsh') else
+ skill = (Path(fixture['config']) / 'skills/hiroute-collaboration/SKILL.md' if HARNESS in ('pi','dsh','opencode') else
qoder_native_context.prepare_collaboration_target(product))
assert not skill.is_symlink(), 'user collaboration Skill is a symlink'
before_skill = skill.read_bytes() if skill.exists() else None
@@ -217,6 +225,7 @@ def run(repository, candidate):
wait_for_resumable_task(product, oracle.accepted['task_id'], oracle.accepted['run_id'])
report.update(task_id=oracle.accepted['task_id'], run_id=oracle.accepted['run_id'],
native_session_id=(__import__('pi_native_context').exact_history(dict(fixture, receipt=fixture['artifact']['receipt']))[1] if HARNESS == 'pi'
+ else __import__('opencode_native_context').exact_history(fixture)[1] if HARNESS=='opencode'
else __import__('dsh_native_context').exact_history(dict(fixture,receipt=fixture['artifact']['receipt']))[1] if HARNESS == 'dsh' else qoder_native_context.task_binding(fixture)),
main_requests=len(source_events(main_source)), worker_requests=len(source_events(worker_source)),
actual_user_skill_sha256=digest(skill), artifact_sha256=digest(fixture['artifact']['path']),
diff --git a/crates/daemon/tests/support/discovered_model_product_support.rs b/crates/daemon/tests/support/discovered_model_product_support.rs
index be2e9d8a..c1017d28 100644
--- a/crates/daemon/tests/support/discovered_model_product_support.rs
+++ b/crates/daemon/tests/support/discovered_model_product_support.rs
@@ -63,7 +63,12 @@ impl ProductDaemon {
Self::start_inner(root, proxy, None)
}
- pub fn start_with_cpa(root: &Path, proxy: SocketAddr, binary: &Path, sha256_hex: &str) -> Self {
+ pub fn start_with_codex_cpa(
+ root: &Path,
+ proxy: SocketAddr,
+ binary: &Path,
+ sha256_hex: &str,
+ ) -> Self {
Self::start_inner(root, proxy, Some((binary, sha256_hex)))
}
@@ -116,6 +121,13 @@ impl ProductDaemon {
.stderr(Stdio::piped());
if let Some((binary, sha256_hex)) = cpa {
command
+ // This fixture exposes a Codex subscription only. Keep Claude's
+ // passive Keychain-source anchor absent even though model fixtures
+ // have a separate, existing Claude settings directory.
+ .env(
+ "CLAUDE_SECURESTORAGE_CONFIG_DIR",
+ root.join("home/unconfigured-claude-secure-store"),
+ )
.arg("--cpa-binary")
.arg(binary)
.arg("--cpa-sha256")
diff --git a/crates/daemon/tests/support/isolated_agent_environment.rs b/crates/daemon/tests/support/isolated_agent_environment.rs
index 2e103182..fdcb6097 100644
--- a/crates/daemon/tests/support/isolated_agent_environment.rs
+++ b/crates/daemon/tests/support/isolated_agent_environment.rs
@@ -20,6 +20,7 @@ pub fn configure(command: &mut Command, home: &Path) {
"QODER_",
"PI_",
"DSH_",
+ "OPENCODE_",
"XDG_",
]
.iter()
diff --git a/crates/daemon/tests/support/native_compaction_product.py b/crates/daemon/tests/support/native_compaction_product.py
index 0a907ebd..59d5f8ea 100644
--- a/crates/daemon/tests/support/native_compaction_product.py
+++ b/crates/daemon/tests/support/native_compaction_product.py
@@ -70,6 +70,32 @@ class CompactionOracle:
text='compacted-' + self.fixture['receipt'])
+class OpenCodeCompactionOracle(CompactionOracle):
+ def __init__(self,fixture,model):
+ super().__init__(fixture,model)
+ self.title_requests=0
+ def reply(self,_fixture,body):
+ assert body.get('model')==self.model,'OpenCode auxiliary request changed the frozen model'
+ text=native_text(body)
+ if any(signature in text.lower() for signature in ('title generator','generate a concise title','generate a short title')):
+ self.title_requests+=1
+ return dict(kind='text',request_kind='title',text='Native compaction receipt',input_tokens=30)
+ # Pinned native agent system instruction, independent of call order.
+ if 'You are a context summarization agent.' in text:
+ assert self.compact_requests==0 and self.main_requests==1
+ assert self.tool_receipt in text,'compaction lost the independently executed tool receipt'
+ self.compact_requests+=1
+ return dict(kind='text',request_kind='compact',text=self.summary_receipt+': Executed '+self.tool_receipt,input_tokens=30)
+ self.main_requests+=1
+ assert self.main_requests<=3
+ if self.main_requests==1:
+ assert self.fixture['compaction_prompt'] in text
+ return dict(kind='tool',request_kind='main',id='native_compaction_tool',name='bash',
+ arguments={'command':'/bin/sh '+shlex.quote(self.fixture['compaction_script']),'description':'Execute compaction receipt tool','timeout':10000},input_tokens=31000)
+ assert self.compact_requests==1 and self.summary_receipt in text,'native continuation did not consume its summary'
+ return dict(kind='text',request_kind='main',input_tokens=30,text='compacted-'+self.fixture['receipt'])
+
+
def assert_native_compaction(path, summary_receipt):
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line]
boundaries = [row.get('compactMetadata', {}) for row in rows if row.get('subtype') == 'compact_boundary']
@@ -144,7 +170,7 @@ def run(repository, candidate):
harness = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','qoder')
recovery = os.environ.get('HIROUTE_PRODUCT_PI_RECOVERY') == '1'
assert not recovery or harness == 'pi'
- assert harness in ('qoder','pi')
+ assert harness in ('qoder','pi','opencode')
cases = CASES if harness == 'qoder' else (CASES[1],)
repo = Path(repository).resolve()
assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
@@ -156,10 +182,10 @@ def run(repository, candidate):
required_cases=list(cases), selected_cases=list(cases), cases=[],
evidence_limit='Real Plan/admission/profile/native Worker/Gateway; controlled upstream; no Desktop verdict')
try:
- fixture, upstream = prepare_product(product, harness, context_tokens=32768 if harness == 'pi' else CONTEXT_TOKENS)
+ fixture, upstream = prepare_product(product, harness, context_tokens=32768 if harness in ('pi','opencode') else CONTEXT_TOKENS)
report['source_context_tokens'] = fixture['source_context_tokens']
binary, _, node = selected_installation(harness)
- configure_worker_installation(product, 'pi' if harness == 'pi' else 'qoder_cli', None, binary, node)
+ configure_worker_installation(product, {'pi':'pi','qoder':'qoder_cli','opencode':'opencode'}[harness], None, binary, node)
if harness == 'qoder':
project_settings = product.project / '.qoder/settings.json'
settings = json.loads(project_settings.read_text())
@@ -170,7 +196,7 @@ def run(repository, candidate):
fixture['recovery'] = recovery
fixture['compaction_prompt'] = 'QODER-COMPACTION-' + secrets.token_hex(12)
fixture['compaction_script'] = str(product.project / 'native-compaction-receipt.sh')
- oracle = (PiCompactionOracle if harness == 'pi' else CompactionOracle)(fixture, upstream.model)
+ oracle = ({'pi':PiCompactionOracle,'qoder':CompactionOracle,'opencode':OpenCodeCompactionOracle}[harness])(fixture, upstream.model)
script = Path(fixture['compaction_script'])
# Pi's compactor estimates actual recent messages as well as provider usage.
# Two genuine large tool outputs leave an older receipt to summarize and
@@ -196,7 +222,7 @@ def run(repository, candidate):
assert 'compacted-' + fixture['receipt'] in result['result'], 'missing compacted Worker result'
wait_for_resumable_task(product, first['task_id'], first['run_id'])
history = exact_history(fixture)
- report['native_compaction_boundaries'] = (assert_pi_compaction(history[0], oracle.summary_receipt, recovery) if harness == 'pi' else assert_native_compaction(history[0], oracle.summary_receipt))
+ report['native_compaction_boundaries'] = ({'native_summary_received':oracle.compact_requests==1} if harness=='opencode' else assert_pi_compaction(history[0], oracle.summary_receipt, recovery) if harness == 'pi' else assert_native_compaction(history[0], oracle.summary_receipt))
report['recovery_context_edit'] = recovery
if recovery:
assert fixture.get('length_prefix_observed'), 'length stop was not an accepted Worker stream'
@@ -204,16 +230,24 @@ def run(repository, candidate):
stage = 'continue-native-compacted-history'
command = ('worker continue --task ' + first['task_id'] + ' --expected-latest-run ' + first['run_id'] +
' --run-timeout 120 --no-wait --submission-key qoder-compaction-continue --file - --output json')
+ if harness=='opencode':
+ product.stop();product.start()
_, accepted = worker_cli(product, command, 'Continue the same native task using its compacted summary.')
continued = accepted['data']
result = wait_for_worker_result(product, continued['run_id'], timeout=150)
assert 'compacted-' + fixture['receipt'] in result['result']
wait_for_resumable_task(product, first['task_id'], continued['run_id'])
assert exact_history(fixture) == history, 'compacted Continue changed the exact native session'
- assert oracle.main_requests == ((5 if recovery else 4) if harness == 'pi' else 3) and oracle.compact_requests == 1 and oracle.tool_summary_requests == (0 if harness == "pi" else 1), \
- 'required native request kinds missing'
attempts = source_events(upstream)
- assert [event.get('request_kind') for event in attempts] == ((['main','main','length','compact','main','main'] if recovery else ['main','main','compact','main','main']) if harness == 'pi' else ['main', 'tool_summary', 'compact', 'main', 'main']), attempts
+ if harness=='opencode':
+ assert oracle.main_requests==3 and oracle.compact_requests==1
+ assert [e.get('request_kind') for e in attempts if e.get('request_kind')!='title']==['main','compact','main','main']
+ assert oracle.title_requests>0,'no actual auxiliary title request was observed'
+ report['native_compaction_boundaries']['summary_consumed_after_restart']=True
+ report['title_requests']=oracle.title_requests
+ else:
+ assert oracle.main_requests == ((5 if recovery else 4) if harness == 'pi' else 3) and oracle.compact_requests == 1 and oracle.tool_summary_requests == (0 if harness == "pi" else 1), 'required native request kinds missing'
+ assert [event.get('request_kind') for event in attempts] == ((['main','main','length','compact','main','main'] if recovery else ['main','main','compact','main','main']) if harness == 'pi' else ['main', 'tool_summary', 'compact', 'main', 'main']), attempts
assert all(event['state'] == 'green' and event['model'] == upstream.model for event in attempts)
assert_preserved(fixture)
if harness == 'qoder':
diff --git a/crates/daemon/tests/support/native_context_boundaries.py b/crates/daemon/tests/support/native_context_boundaries.py
index ff484b20..4fa0bbdc 100644
--- a/crates/daemon/tests/support/native_context_boundaries.py
+++ b/crates/daemon/tests/support/native_context_boundaries.py
@@ -6,6 +6,7 @@ edits, deletion API, or private execution port. This entry never builds binaries
import qoder_native_context
import pi_native_context
import dsh_native_context
+import opencode_native_context
import argparse
from concurrent.futures import ThreadPoolExecutor
import copy
@@ -59,6 +60,9 @@ def prepare_heartbeat(fixture, role):
'printf "%s\\n" ' + shlex.quote(receipt) + ' > ' + shlex.quote(paths['done']),
'printf "%s\\n" ' + shlex.quote(receipt), '',
)), True)
+ if fixture['harness']=='opencode':
+ fixture['edit']=dict(fixture['edit'],path=str(root/'native-edit.txt'),after=role+'-'+fixture['edit']['after'])
+ write_new(Path(fixture['edit']['path']),fixture['edit']['before']+'\n')
fixture['receipt'] = receipt
fixture['boundary'] = dict(paths, role=role, script=str(script),
marker='NATIVE-CONTEXT-WORKER-' + role)
@@ -67,6 +71,10 @@ def prepare_heartbeat(fixture, role):
def boundary_decision(fixture, body):
"""Two source oracles reject cross-routing and execute actual native shell children."""
+ if fixture['harness']=='opencode':
+ from native_context_fixture import native_text
+ if any(signature in native_text(body).lower() for signature in ('title generator','generate a concise title','generate a short title')):
+ return decision(fixture,body)
state = fixture['boundary']
assert state['marker'] in json.dumps(body), 'task reached the other task source'
results = tool_results(body, fixture['harness'])
@@ -86,6 +94,9 @@ def boundary_decision(fixture, body):
if fixture['harness'] in ('claude', 'qoder'):
assert 'Bash' in names, 'native Bash tool unavailable'
name, arguments = 'Bash', {'command': command, 'timeout': 120000}
+ elif fixture['harness']=='opencode':
+ assert 'bash' in names
+ name,arguments='bash',{'command':command,'description':'Run owned heartbeat script','timeout':120000}
elif fixture['harness'] == 'dsh':
assert 'bash' in names
name,arguments='bash',{'command':command,'description':'Run the owned heartbeat script','timeoutMs':120000}
@@ -147,6 +158,9 @@ def assert_source_routing(upstream):
def transcript_snapshot(fixture):
+ if fixture['harness']=='opencode':
+ root=Path(fixture['database']).parent
+ return {str(p):digest(p) for p in root.glob('opencode.db*') if p.is_file() and not p.is_symlink()}
root = (qoder_native_context.history_directory(fixture) if fixture['harness'] == 'qoder'
else dsh_native_context.history_directory(fixture) if fixture['harness'] == 'dsh' else pi_native_context.history_directory(fixture) if fixture['harness'] == 'pi' else Path(fixture['config']) / ('sessions' if fixture['harness'] == 'codex' else 'projects'))
paths = list(root.rglob('*.jsonl'))
@@ -245,7 +259,7 @@ def run(repository, candidate, harness):
install_oracle(neighbor_source, neighbor)
neighbor_plan = publish_neighbor(product, neighbor_source)
binary, adapter, node = selected_installation(harness)
- if harness=='dsh':
+ if harness in ('dsh','opencode'):
from agent_product_support import expose_native_installation
expose_native_installation(product,harness,binary)
configure_worker_installation(product, product.worker_work['harness'], adapter, binary, node)
@@ -283,14 +297,15 @@ def run(repository, candidate, harness):
assert_preserved(fixture)
cancelled = dict(target, receipt=target['boundary']['marker'])
target_history = (qoder_native_context.cancelled_history(cancelled, runs[0]['run_id'])
- if harness == 'qoder' else dsh_native_context.cancelled_history(cancelled,runs[0]['run_id'])
+ if harness == 'qoder' else opencode_native_context.cancelled_history(cancelled,runs[0]['run_id'])
+ if harness=='opencode' else dsh_native_context.cancelled_history(cancelled,runs[0]['run_id'])
if harness == 'dsh' else exact_history(cancelled))
wait_for_resumable_task(product, runs[1]['task_id'], runs[1]['run_id'])
neighbor_history = exact_history(neighbor)
assert target_history[1] != neighbor_history[1], 'concurrent tasks shared a native session'
report['native_session_ids'] = [target_history[1], neighbor_history[1]]
for history in (target_history, neighbor_history):
- text = Path(history[0]).read_text()
+ text = (Path(history[0]).read_bytes().decode('utf-8',errors='replace') if harness=='opencode' else Path(history[0]).read_text())
assert all(source.token not in text for source in upstreams), 'source credential entered native history'
report['cases'].append({'id': CASES[1], 'state': 'green'})
report['task_ids'] = [run['task_id'] for run in runs]
@@ -329,6 +344,6 @@ if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('repository')
parser.add_argument('candidate')
- parser.add_argument('--harness', choices=('codex', 'claude', 'qoder', 'pi', 'dsh'), required=True)
+ parser.add_argument('--harness', choices=('codex', 'claude', 'qoder', 'pi', 'dsh', 'opencode'), required=True)
args = parser.parse_args()
run(args.repository, args.candidate, args.harness)
diff --git a/crates/daemon/tests/support/native_context_fixture.py b/crates/daemon/tests/support/native_context_fixture.py
index 3111f4b7..1b96589d 100644
--- a/crates/daemon/tests/support/native_context_fixture.py
+++ b/crates/daemon/tests/support/native_context_fixture.py
@@ -54,7 +54,7 @@ def prepare_skill(parent, name, scope, writer=write_new):
def prepare(home, config, project, harness, suffix='', owned_files=None):
"""Add only new fixture-owned skills and neighbors; never replace existing files."""
- assert harness in ('codex', 'claude', 'qoder', 'pi', 'dsh')
+ assert harness in ('codex', 'claude', 'qoder', 'pi', 'dsh', 'opencode')
home, config, project = map(lambda path: Path(path).resolve(), (home, config, project))
def owned_write(path, text, executable=False):
write_new(path, text, executable)
@@ -64,7 +64,7 @@ def prepare(home, config, project, harness, suffix='', owned_files=None):
skills = []
for scope, parent in (
('user', home / '.agents/skills' if harness == 'codex' else config / 'skills'),
- ('project', project / {'codex': '.agents/skills', 'claude': '.claude/skills', 'qoder': '.qoder/skills', 'pi': '.pi/skills', 'dsh': '.dsh/skills'}[harness]),
+ ('project', project / {'codex': '.agents/skills', 'claude': '.claude/skills', 'qoder': '.qoder/skills', 'pi': '.pi/skills', 'dsh': '.dsh/skills', 'opencode':'.opencode/skills'}[harness]),
):
skills.append(prepare_skill(parent, 'native-context-' + scope + suffix, scope, owned_write))
neighbor = config / ('native-context-neighbor' + suffix + '.txt')
@@ -151,6 +151,8 @@ def decision(fixture, body):
assert harness != 'qoder' or not is_native_compaction(body), \
'unexpected Qoder compaction in the ordinary Skill journey; check the native context budget'
rendered = json.dumps(body)
+ if harness=='opencode' and any(signature in native_text(body).lower() for signature in ('title generator','generate a concise title','generate a short title')):
+ return dict(kind='text',text='Native context receipt',request_kind='title',continued=False)
results = tool_results(body, harness)
result_text = json.dumps(results.get('native_context_execute', ''))
if CONTINUE_PROMPT in rendered:
@@ -182,8 +184,26 @@ def decision(fixture, body):
'expected native Skill directory was not loaded'
assert 'Bash' in names, 'native Bash tool unavailable'
name = 'Bash'
+ elif harness == 'opencode':
+ assert {'skill','bash'} <= names,'native OpenCode tools unavailable'
+ for skill in fixture['skills']:
+ call_id='native_context_skill_'+skill['scope']
+ if call_id not in results:
+ return dict(kind='tool',id=call_id,name='skill',arguments={'name':skill['name']})
+ loaded=results[call_id]
+ assert loaded.startswith('<skill_content name="'+skill['name']+'">')
+ assert '\nBase directory for this skill: '+str(Path(skill['skill']).parent)+'\n' in loaded
+ assert skill['contents'] in loaded,'native OpenCode Skill body mismatch'
+ edit=fixture['edit']
+ if 'native_context_read' not in results:
+ return dict(kind='tool',id='native_context_read',name='read',arguments={'filePath':edit['path']})
+ if 'native_context_edit' not in results:
+ assert edit['before'] in results['native_context_read'],'native read lost original edit content'
+ return dict(kind='tool',id='native_context_edit',name='edit',arguments={'filePath':edit['path'],'oldString':edit['before'],'newString':edit['after']})
+ assert Path(edit['path']).read_text().strip()==edit['after'],'native edit did not change the owned file'
+ name='bash'
elif harness == 'dsh':
- assert 'bash' in names and 'read' in names, 'native DSH tools unavailable'
+ assert 'bash' in names and 'read' in names, 'native DSH tools unavailable'
return dict(kind='tool',id='native_context_execute',name='bash', arguments={'command':' && '.join('/bin/cat '+shlex.quote(skill['skill'])+' && /bin/sh '+shlex.quote(skill['script']) for skill in fixture['skills']), 'description':'Read native Skills and run receipt scripts','timeoutMs':10000})
elif harness == 'pi':
assert 'bash' in names and 'read' in names, 'native Pi tools unavailable'
@@ -195,7 +215,7 @@ def decision(fixture, body):
+ shlex.quote(skill['script']) for skill in fixture['skills'])
arguments = ({'cmd': command, 'max_output_tokens': 2000, 'yield_time_ms': 1000}
if name == 'exec_command' else {'command': command, 'timeout_ms': 10000}
- if name == 'shell_command' else {'command': command, 'timeout': 10 if harness == 'pi' else 10000})
+ if name == 'shell_command' else {'command': command, 'description':'Read Skills and execute receipt scripts', 'timeout': 10 if harness == 'pi' else 10000})
return dict(kind='tool', id='native_context_execute', name=name, arguments=arguments)
@@ -211,7 +231,7 @@ def events(body, action, protocol):
return [
('message_start', {'message': {'id': 'msg_native_context', 'type': 'message',
'role': 'assistant', 'model': body['model'], 'content': [], 'stop_reason': None,
- 'stop_sequence': None, 'usage': {'input_tokens': 1, 'output_tokens': 0}}}),
+ 'stop_sequence': None, 'usage': {'input_tokens': action.get('input_tokens',1), 'output_tokens': 0}}}),
('content_block_start', {'index': 0, 'content_block': initial}),
('content_block_delta', {'index': 0, 'delta': delta}),
('content_block_stop', {'index': 0}),
diff --git a/crates/daemon/tests/support/native_context_product.py b/crates/daemon/tests/support/native_context_product.py
index 258947b5..ec836262 100644
--- a/crates/daemon/tests/support/native_context_product.py
+++ b/crates/daemon/tests/support/native_context_product.py
@@ -24,6 +24,7 @@ from publication_process import plan_change
import qoder_native_context
import pi_native_context
import dsh_native_context
+import opencode_native_context
def save_context_source(product, upstream, variant='', context_tokens=None, protocol=None):
@@ -45,7 +46,7 @@ def native_context_budget(product):
def selected_installation(harness):
binary = Path(os.environ['HIROUTE_WORKER_' + harness.upper() + '_BINARY']).resolve(strict=True)
- if harness in ('qoder','dsh'):
+ if harness in ('qoder','dsh','opencode'):
return binary, None, None
if harness == 'pi':
return binary, None, Path(os.environ['HIROUTE_WORKER_NODE']).resolve(strict=True)
@@ -58,7 +59,11 @@ def prepare_product(product, harness, context_tokens=None):
"""Prepare a normal API source/Plan; Desktop can take over after product.stop()."""
product.enable_debug_diagnostics()
roots = {'codex': 'CODEX_HOME', 'claude': 'CLAUDE_CONFIG_DIR', 'qoder': 'QODER_CONFIG_DIR', 'pi': 'PI_CODING_AGENT_DIR', 'dsh':'DSH_HOME'}
- if harness == 'qoder':
+ if harness == 'opencode':
+ native=opencode_native_context.select_context(product)
+ fixture=prepare(Path(product.env['HOME']),native,product.project,harness)
+ opencode_native_context.prepare_context(product,fixture)
+ elif harness == 'qoder':
qoder_native_context.select_context(product)
fixture = qoder_native_context.prepare_context(product)
else:
@@ -68,10 +73,10 @@ def prepare_product(product, harness, context_tokens=None):
dsh_native_context.prepare_context(product,fixture)
if harness == 'pi':
pi_native_context.prepare_context(product, fixture)
- native = Path(product.env[roots[harness]])
+ native = Path(fixture['config'])
product.worker_work = {'harness': {'codex': 'codex_cli', 'claude': 'claude_code',
- 'qoder': 'qoder_cli', 'pi': 'pi', 'dsh':'deepseek_harness'}[harness],
- 'protocol': 'messages' if harness == 'claude' else (os.environ.get('HIROUTE_PRODUCT_AGENT_PROTOCOL', 'responses') if harness in ('pi', 'qoder', 'dsh') else 'responses')}
+ 'qoder': 'qoder_cli', 'pi': 'pi', 'dsh':'deepseek_harness','opencode':'opencode'}[harness],
+ 'protocol': 'messages' if harness == 'claude' else (os.environ.get('HIROUTE_PRODUCT_AGENT_PROTOCOL', 'responses') if harness in ('pi', 'qoder', 'dsh', 'opencode') else 'responses')}
assert product.worker_work['protocol'] in ('responses', 'messages')
fixture['source_context_tokens'] = (context_tokens if context_tokens is not None
else native_context_budget(product))
@@ -95,7 +100,7 @@ def prepare_product(product, harness, context_tokens=None):
product.apply('routing apply', 'ApplyAgentPlanChange', preview, {'change': change}, 'native-worker-plan')
product.plan_id = preview['plan_head']['reference']['plan_id']
product.model_alias = preview['plan_head']['model_alias']
- configuration = native / ('config.toml' if harness == 'codex' else 'cordis.patch.yml' if harness == 'dsh' else 'settings.json')
+ configuration = native / ('config.toml' if harness == 'codex' else 'cordis.patch.yml' if harness == 'dsh' else 'opencode.json' if harness=='opencode' else 'settings.json')
if harness == 'codex':
configuration.write_text('model = "gpt-5.5"\nmodel_provider = "native_context_ambient"\n'
'[model_providers.native_context_ambient]\nname = "Unreachable synthetic source"\n'
@@ -103,7 +108,7 @@ def prepare_product(product, harness, context_tokens=None):
'env_key = "NATIVE_CONTEXT_UNUSED_TOKEN"\nrequires_openai_auth = false\n')
elif harness == 'qoder':
qoder_native_context.install_project_conflict(fixture, upstream)
- elif harness in ('pi','dsh'):
+ elif harness in ('pi','dsh','opencode'):
pass # Pi's conflict files and package resource receipt are prepared by its leaf.
elif harness == 'claude':
configuration.write_text(json.dumps({'env': {'ANTHROPIC_BASE_URL': 'http://127.0.0.1:9',
@@ -165,6 +170,8 @@ def assert_frozen_route(original_events, before, replacement, protocol=None):
def exact_history(fixture):
"""Inspect only this synthetic context's native transcript directory, never auth."""
+ if fixture['harness'] == 'opencode':
+ return opencode_native_context.exact_history(fixture)
if fixture['harness'] == 'dsh':
return dsh_native_context.exact_history(fixture)
if fixture['harness'] == 'pi':
@@ -240,11 +247,11 @@ def run(repository, candidate):
repo = Path(repository).resolve()
assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
harness = os.environ['HIROUTE_PRODUCT_WORKER_HARNESS']
- assert harness in ('codex', 'claude', 'qoder', 'pi', 'dsh')
+ assert harness in ('codex', 'claude', 'qoder', 'pi', 'dsh', 'opencode')
product = Product(repo)
# Headless services may explicitly select a non-default native configuration.
# Mac Pilot intentionally uses its documented HOME/.codex and HOME/.claude roots.
- if harness != 'qoder':
+ if harness not in ('qoder','opencode'):
product.env['CODEX_HOME' if harness == 'codex' else 'PI_CODING_AGENT_DIR' if harness == 'pi' else 'DSH_HOME' if harness == 'dsh' else 'CLAUDE_CONFIG_DIR'] = str(
Path(product.env['HOME']) / ('selected-' + harness + '-config'))
upstream = replacement = None
@@ -256,9 +263,11 @@ def run(repository, candidate):
for case in BUSINESS_CASES if case not in CORE_CASES])
try:
binary, adapter, node = selected_installation(harness)
- if harness=='dsh':
+ if harness in ('dsh','opencode'):
from agent_product_support import expose_native_installation
expose_native_installation(product,harness,binary)
+ if harness == 'opencode':
+ project_boundary = opencode_native_context.prepare_project_boundary(product)
stage = 'real-daemon-and-plan'
fixture, upstream = prepare_product(product, harness,
context_tokens=16_384 if harness == 'pi' else 32_768 if harness == 'qoder' else None)
@@ -268,6 +277,10 @@ def run(repository, candidate):
report['source_output_tokens'] = 4096
(product.root / 'native-context.json').write_text(json.dumps(fixture))
configure_worker_installation(product, product.worker_work['harness'], adapter, binary, node)
+ if harness == 'opencode':
+ stage = 'opencode-project-admission'
+ report['project_ancestry_admission'] = opencode_native_context.assert_project_admission(
+ product, fixture, upstream, project_boundary)
if harness == 'qoder':
stage = 'unsupported-qoder-permissions'
report['rejected_permission_modes'] = qoder_native_context.assert_restricted_modes_unavailable(product, upstream)
@@ -330,6 +343,10 @@ def run(repository, candidate):
'Continue replay sent another model request'
report['cases'].append({'id': CORE_CASES[1], 'state': 'green'})
attempts = events(product)
+ if harness == 'opencode':
+ assert not Path(project_boundary['imported']).exists(), 'native crossed its confirmed Git stop'
+ for path, original in project_boundary['protected'].items():
+ assert Path(path).read_bytes() == original, 'native changed foreign ancestor configuration/tool'
if fixture.get('proxy_trap_events'):
report['native_proxy_requests'] = len(Path(fixture['proxy_trap_events']).read_text().splitlines())
assert report['native_proxy_requests'] == 0, 'native Worker used the user-configured proxy'
diff --git a/crates/daemon/tests/support/opencode_native_context.py b/crates/daemon/tests/support/opencode_native_context.py
new file mode 100644
index 00000000..46cb348f
--- /dev/null
+++ b/crates/daemon/tests/support/opencode_native_context.py
@@ -0,0 +1,183 @@
+"""OpenCode native locations/records; shared product journeys own business assertions."""
+from copy import deepcopy
+import json
+from pathlib import Path
+from native_context_fixture import write_new, protect_configuration
+
+def prepare_project_boundary(product):
+ """Real Git stop, with unsafe foreign ancestors that native must not load."""
+ import subprocess
+ def git(cwd, *args):
+ subprocess.run(['git', *args], cwd=cwd, env=product.env, check=True,
+ capture_output=True, timeout=10)
+ import os
+ linked = os.environ.get('HIROUTE_PRODUCT_AGENT_PROTOCOL', 'responses') == 'responses'
+ repository = product.root / 'git-repository' if linked else product.project
+ repository.mkdir(mode=0o700, exist_ok=True)
+ git(repository, 'init', '-q')
+ if linked:
+ git(repository, '-c', 'user.name=Fixture', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'fixture')
+ # Product has not installed any project fixtures yet; keep all later
+ # user/Skill paths unchanged while making cwd an actual linked worktree.
+ product.project.rmdir()
+ git(repository, 'worktree', 'add', '--detach', str(product.project), 'HEAD')
+ foreign_config = product.root / 'opencode.json'
+ write_new(foreign_config, '{"$schema":""}\n')
+ imported = product.root / 'foreign-tool-imported'
+ tool = product.root / '.opencode/tools/foreign.ts'
+ tool.parent.mkdir(mode=0o700, parents=True)
+ write_new(tool, 'import { writeFileSync } from "node:fs";\nwriteFileSync(' +
+ json.dumps(str(imported)) + ', "imported");\nthrow new Error("foreign tool imported");\n')
+ return dict(kind='linked-worktree' if linked else 'repository', imported=str(imported),
+ protected={str(path): path.read_bytes() for path in (foreign_config, tool)})
+
+def assert_project_admission(product, fixture, upstream, boundary):
+ """False stops fail through public Worker admission before DB/tool/model work."""
+ import shutil
+ from delegation_product import worker_cli, wait_for_worker_result
+ marker = product.project / '.git'
+ saved = product.project / '.git-confirmed-fixture'
+ marker.rename(saved)
+ shadow_git = product.root / 'bin/git'
+ assert not shadow_git.exists()
+ events = upstream.controls / 'native-context-events.jsonl'
+ before = events.read_bytes() if events.exists() else b''
+ results = []
+ try:
+ for kind in ('empty', 'corrupt', 'broken-worktree', 'unavailable-git'):
+ if kind == 'empty':
+ marker.mkdir(mode=0o700)
+ elif kind == 'unavailable-git':
+ saved.rename(marker)
+ write_new(shadow_git, '#!/bin/sh\nexit 127\n', executable=True)
+ else:
+ write_new(marker, 'not a gitdir\n' if kind == 'corrupt' else 'gitdir: missing-worktree\n')
+ try:
+ command = ('worker exec --plan ' + product.plan_id + ' --cwd ' + str(product.project) +
+ ' --run-timeout 30 --no-wait --submission-key opencode-false-git-' +
+ kind + ' --file - --output json')
+ status, response = worker_cli(product, command, 'Return done.', success=False)
+ if status == 0:
+ try:
+ result = wait_for_worker_result(product, response['data']['run_id'], expected='failed', timeout=40)
+ finally:
+ # Even a different terminal error must not hide native
+ # startup side effects in this pre-launch refusal case.
+ assert not Path(fixture['database']).exists(), 'unconfirmed Git stop launched native database initialization'
+ assert not result.get('result'), 'unconfirmed Git stop returned a result'
+ else:
+ assert response.get('error', {}).get('code') == 'CAPABILITY_UNAVAILABLE', response
+ assert not Path(fixture['database']).exists(), 'unconfirmed Git stop launched native database initialization'
+ assert not Path(boundary['imported']).exists(), 'unconfirmed Git stop imported a foreign tool'
+ assert (events.read_bytes() if events.exists() else b'') == before, 'unconfirmed Git stop made a model request'
+ for path, original in boundary['protected'].items():
+ assert Path(path).read_bytes() == original, 'unconfirmed Git stop rewrote borrowed configuration/tool'
+ results.append(kind)
+ finally:
+ if kind == 'unavailable-git':
+ shadow_git.unlink()
+ marker.rename(saved)
+ elif marker.is_dir():
+ shutil.rmtree(marker)
+ else:
+ marker.unlink()
+ finally:
+ saved.rename(marker)
+ return dict(positive=boundary['kind'], rejected=results,
+ foreign_tool_imported=False, native_database_created=False, model_requests=0)
+
+def select_context(product):
+ home=Path(product.env['HOME'])
+ for key,folder in [('XDG_CONFIG_HOME','.config'),('XDG_DATA_HOME','.local/share'),('XDG_CACHE_HOME','.cache'),('XDG_STATE_HOME','.local/state')]:
+ root=home/folder
+ root.mkdir(mode=0o700,parents=True,exist_ok=True)
+ product.env[key]=str(root)
+ root=Path(product.env['XDG_CONFIG_HOME'])/'opencode'
+ root.mkdir(mode=0o700,exist_ok=True)
+ product.env.update(OPENCODE_DISABLE_MODELS_FETCH='true',OPENCODE_DISABLE_AUTOUPDATE='true',OPENCODE_DISABLE_LSP_DOWNLOAD='true',OPENCODE_DISABLE_FFF='true',OPENCODE_PURE='true',OPENCODE_DISABLE_DEFAULT_PLUGINS='true')
+ product.env['OPENCODE_DB']=str(Path(product.env['XDG_DATA_HOME'])/'opencode/opencode.db')
+ return root
+
+def prepare_context(product,fixture):
+ root=Path(fixture['config'])
+ fixture['product_storage']=str(product.storage)
+ fixture['database']=product.env['OPENCODE_DB']
+ import secrets
+ nonce=secrets.token_hex(10)
+ fixture['edit']={'path':str(product.project/'opencode-owned-edit.txt'),'before':'before-'+nonce,'after':'edited-'+nonce}
+ write_new(Path(fixture['edit']['path']),fixture['edit']['before']+'\n')
+ write_new(root/'opencode.json',json.dumps({'$schema':'https://opencode.ai/config.json','model':'ambient/wrong-native-model','small_model':'ambient/wrong-native-model','provider':{'ambient':{'npm':'@ai-sdk/openai','options':{'baseURL':'http://127.0.0.1:9/v1','apiKey':'wrong-native-key'},'models':{'wrong-native-model':{'limit':{'context':32768,'output':4096}}}}},'share':'disabled','autoupdate':False}))
+ protect_configuration(fixture,[root/'opencode.json'])
+
+def exact_history(fixture,cancelled_session_id=None):
+ import sqlite3
+ matches=[]
+ for marker in (Path(fixture['product_storage'])/'delegation-workers/sessions').glob('*/.hiroute-native-root-v1.json'):
+ value=json.loads(marker.read_text())
+ if value['task_id']!=fixture['task_id']: continue
+ assert value['harness']=='opencode'
+ binding={'native_session_id':cancelled_session_id} if cancelled_session_id else json.loads((marker.parent/'native-session-binding.json').read_text())
+ database=Path(fixture['database'])
+ assert database.is_file() and not database.is_symlink()
+ # Only the selected synthetic session's existence/identity; production never parses its history.
+ with sqlite3.connect(database.as_uri()+'?mode=ro',uri=True) as db:
+ assert db.execute('SELECT id FROM session WHERE id=?',(binding['native_session_id'],)).fetchone()==(binding['native_session_id'],)
+ matches.append((str(database),binding['native_session_id']))
+ assert len(matches)==1,'expected exactly one bound OpenCode task'
+ return matches[0]
+
+class OpenCodeModelSettings:
+ def __init__(self,config,foreign_endpoint):
+ self.harness,self.auth_owned='opencode',None
+ self.path=Path(config)/'opencode.json'
+ assert not self.path.exists(),'model journey requires its dedicated empty context'
+ self.original=None
+ self.native_default='fixture-native/native-default'
+ self.path.write_text(json.dumps({'$schema':'https://opencode.ai/config.json','model':self.native_default,'small_model':self.native_default,'provider':{'fixture-native':{'npm':'@ai-sdk/openai','options':{'baseURL':foreign_endpoint,'apiKey':'synthetic-unselected-native-key'},'models':{'native-default':{'limit':{'context':100000,'output':4096}}}}},'share':'disabled','autoupdate':False,'compaction':{'auto':False},'agent':{'title':{'disable':True},'summary':{'disable':True}}}))
+ self.path.chmod(0o600)
+ self.baseline=self.read()
+ def read(self):
+ assert self.path.is_file() and not self.path.is_symlink()
+ value=json.loads(self.path.read_text())
+ value['providers']=value.pop('provider',{})
+ for provider in value['providers'].values():
+ provider['models']=[dict(model,id=key) for key,model in provider['models'].items()]
+ value['model']={'name':value['model']}
+ return value
+ def assert_preserved(self,provider_id,selected_default=None):
+ actual=self.read()
+ for name in list(actual['providers']):
+ if name==provider_id or name.startswith(provider_id+'-'): actual['providers'].pop(name)
+ expected=deepcopy(self.baseline)
+ if selected_default: expected['model']['name']=selected_default
+ assert actual==expected,'OpenCode save changed daily defaults/unowned fields'
+ def add_user_edit(self,provider_id):
+ self.assert_preserved(provider_id)
+ text=self.path.read_text();end=text.rfind('}')
+ self.path.write_text(text[:end].rstrip()+',"instructions":["./user-rule.md"]'+text[end:])
+ self.baseline['instructions']=['./user-rule.md']
+ def select_default(self,expected,replacement):
+ text=self.path.read_text();needle=json.dumps(expected)
+ assert self.read()['model']['name']==expected
+ # Only the root value is replaced; owned provider bytes stay unchanged.
+ start=text.index('"model"');at=text.index(needle,start)
+ self.path.write_text(text[:at]+json.dumps(replacement)+text[at+len(needle):])
+ def close(self):
+ assert self.read()==self.baseline
+ self.path.unlink()
+
+def main_route(product,endpoint,model,token,fixture):
+ config=Path(fixture['config'])/'opencode.json'
+ value=json.loads(config.read_text())
+ value['provider']['hiroute-main-acceptance']={'npm':'@ai-sdk/openai','options':{'baseURL':endpoint,'apiKey':token,'store':False},'models':{model:{'limit':{'context':100000,'output':4096}}}}
+ value['model']=value['small_model']='hiroute-main-acceptance/'+model
+ value['permission']={'*':'allow'}
+ value['agent']={'title':{'disable':True},'summary':{'disable':True}}
+ config.write_text(json.dumps(value));config.chmod(0o600)
+ protect_configuration(fixture,[config])
+ return 'hiroute-main-acceptance/'+model
+
+def cancelled_history(fixture,run_id):
+ from native_task_witness import cancelled_session
+ return exact_history(fixture,cancelled_session(fixture,run_id,'opencode'))
diff --git a/crates/daemon/tests/support/pi_discovery_product.py b/crates/daemon/tests/support/pi_discovery_product.py
index 06c04301..5b5f3140 100644
--- a/crates/daemon/tests/support/pi_discovery_product.py
+++ b/crates/daemon/tests/support/pi_discovery_product.py
@@ -54,7 +54,10 @@ def use_imported_route(product, binary, source, saved):
source.reply = oracle.reply
try:
namespace = configured['model_effect']['provider_id']
- if HARNESS=='dsh':
+ if HARNESS=='opencode':
+ providers=json.loads((Path(product.env['XDG_CONFIG_HOME'])/'opencode/opencode.json').read_text())['provider']
+ providers={name:dict(p,models=[dict(m,id=k) for k,m in p['models'].items()]) for name,p in providers.items()}
+ elif HARNESS=='dsh':
from dsh_native_context import read_patch
providers = next(r['config']['providers'] for r in read_patch(
Path(product.env['DSH_HOME'])/'profiles/web/cordis.patch.yml') if r['id']=='llm-pi-ai')
@@ -88,10 +91,30 @@ def scan(product):
return sources[0]['discovery']
+def opencode_local_credential_failures(models_path, controls):
+ """Native-readable keys outside the protected import reader's supported subset."""
+ value = json.loads(models_path.read_text())
+ template = value['provider']['native-source']
+ linked = controls / 'linked.key'
+ target = controls / 'link-target.key'
+ hardlinked = controls / 'hardlinked.key'
+ oversized = controls / 'oversized.key'
+ write_new(target, 'synthetic-linked-key')
+ linked.symlink_to(target)
+ os.link(target, hardlinked)
+ write_new(oversized, 'x' * (1024 * 1024 + 1))
+ for name, key in [('linked', linked), ('hardlinked', hardlinked), ('oversized', oversized)]:
+ provider = json.loads(json.dumps(template))
+ provider['options']['apiKey'] = '{file:' + str(key) + '}'
+ value['provider']['a-broken-' + name] = provider
+ models_path.write_text(json.dumps(value))
+ return (linked, target, hardlinked, oversized)
+
+
def run(repository, candidate):
global HARNESS
HARNESS = os.environ.get('HIROUTE_PRODUCT_WORKER_HARNESS','pi')
- assert HARNESS in ('pi','dsh')
+ assert HARNESS in ('pi','dsh','opencode')
repo = Path(repository).resolve()
assert subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip() == candidate
product = Product(repo)
@@ -104,15 +127,29 @@ def run(repository, candidate):
product.enable_debug_diagnostics()
binary, _, node = selected_installation(HARNESS)
expose_native_installation(product, HARNESS, binary, node)
- config = Path(product.env['HOME']) / ('selected-'+HARNESS+'-config')
- config.mkdir(mode=0o700)
- product.env['DSH_HOME' if HARNESS=='dsh' else 'PI_CODING_AGENT_DIR'] = str(config)
+ if HARNESS=='opencode':
+ from opencode_native_context import select_context
+ config=select_context(product)
+ else:
+ config = Path(product.env['HOME']) / ('selected-'+HARNESS+'-config')
+ config.mkdir(mode=0o700)
+ if HARNESS!='opencode':
+ product.env['DSH_HOME' if HARNESS=='dsh' else 'PI_CODING_AGENT_DIR'] = str(config)
controls = product.root / 'source'
controls.mkdir(mode=0o700)
write_new(controls / 'native-context.json', '{}')
source = NativeContextUpstream(controls)
credential_context_paths = ()
- if HARNESS=='dsh':
+ if HARNESS=='opencode':
+ models_path=config/'opencode.json'
+ auth_path=Path(product.env['XDG_DATA_HOME'])/'opencode/auth.json'
+ # This journey counts one ordinary model call. Worker auxiliary routing
+ # is exercised independently with the native title/compaction agents enabled.
+ write_new(models_path,json.dumps({'$schema':'https://opencode.ai/config.json','agent':{'title':{'disable':True},'summary':{'disable':True}},'provider':{'native-source':{'npm':'@ai-sdk/openai','options':{'baseURL':source.base_url},'models':{source.model:{'limit':{'context':16384,'output':4096}}}}}}))
+ write_new(auth_path,json.dumps({'native-source':{'type':'api','key':source.token}}))
+ changed_auth=json.dumps({'native-source':{'type':'api','key':'changed-native-key'}})
+ credential_context_paths = opencode_local_credential_failures(models_path, controls)
+ elif HARNESS=='dsh':
from dsh_native_context import encode_patch, source_credentials
models_path = config/'profiles/web/cordis.patch.yml'
provider = {'api':'openai-responses','baseURL':source.base_url,'apiKeyEnv':'IMPORT_KEY',
@@ -133,6 +170,12 @@ def run(repository, candidate):
product.secrets.update((source.token, 'provider-fallback'))
product.start()
stage = 'public-scan-prepare-save'
+ if HARNESS == 'opencode':
+ items = control(product, 'ScanCompute', {})['data']['items']
+ blocked = [item for item in items if item['agent_id']=='agent_opencode_default'
+ and str(item.get('native_provider_id','')).startswith('a-broken-')]
+ assert len(blocked) == 3 and all(not row['inventory_eligible'] and not row.get('discovery') for row in blocked), 'one credential failure hid independent native sources'
+ report['provider_local_credential_failures_isolated'] = ['symlink', 'hardlink', 'oversized']
discovery = scan(product)
candidate_view = prepare(product, discovery, 'pi-source-prepare')
assert prepare(product, discovery, 'pi-source-prepare') == candidate_view, 'prepare retry changed its candidate'
diff --git a/crates/daemon/tests/support/publication_product.py b/crates/daemon/tests/support/publication_product.py
index 8e185fb6..d9c8b72a 100644
--- a/crates/daemon/tests/support/publication_product.py
+++ b/crates/daemon/tests/support/publication_product.py
@@ -179,10 +179,14 @@ finally:
self.diagnostics_args = []
self.env = {k: v for k, v in os.environ.items()
if not k.startswith(('ANTHROPIC_', 'HIROUTE_', 'OPENAI_', 'AWS_', 'AZURE_',
- 'GOOGLE_', 'VERTEX_', 'QODER_'))
+ 'GOOGLE_', 'VERTEX_', 'QODER_', 'OPENCODE_'))
and k not in ('CODEX_CONFIG', 'CODEX_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN',
'GEMINI_API_KEY', 'OPENROUTER_API_KEY', 'CLAUDE_CODE_USE_BEDROCK',
'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',
+ 'CLAUDE_CODE_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',
'DEEPSEEK_API_KEY', 'GROQ_API_KEY', 'MISTRAL_API_KEY',
'XAI_API_KEY', 'CEREBRAS_API_KEY')}
self.env.update(HOME=str(home), CODEX_HOME=str(home / '.codex'),
diff --git a/crates/daemon/tests/support/standalone_headless_product.py b/crates/daemon/tests/support/standalone_headless_product.py
index badf4f6c..e37ce6eb 100644
--- a/crates/daemon/tests/support/standalone_headless_product.py
+++ b/crates/daemon/tests/support/standalone_headless_product.py
@@ -975,7 +975,7 @@ def run(repository):
stage = 'worker-selection-submit-wait-result-replay'
discovered = product.cli('worker', 'dependencies', 'discover')['data']
assert {item['harness'] for item in discovered['selection_revisions']} == {
- 'codex_cli', 'claude_code', 'qoder_cli', 'pi', 'deepseek_harness'}, discovered
+ 'codex_cli', 'claude_code', 'qoder_cli', 'pi', 'deepseek_harness', 'opencode'}, discovered
revision = next(item['revision'] for item in discovered['selection_revisions']
if item['harness'] == 'codex_cli')
selected = product.cli(
diff --git a/crates/daemon/tests/support/subscription_cache_regression.rs b/crates/daemon/tests/support/subscription_cache_regression.rs
index d1779968..d2910269 100644
--- a/crates/daemon/tests/support/subscription_cache_regression.rs
+++ b/crates/daemon/tests/support/subscription_cache_regression.rs
@@ -10,7 +10,7 @@ fn cache_fixture() -> (tempfile::TempDir, TcpListener, ProductDaemon) {
let (binary, sha256) = install_subscription_fixture(directory.path());
let proxy = TcpListener::bind("127.0.0.1:0").unwrap();
proxy.set_nonblocking(true).unwrap();
- let daemon = ProductDaemon::start_with_cpa(
+ let daemon = ProductDaemon::start_with_codex_cpa(
directory.path(),
proxy.local_addr().unwrap(),
&binary,
diff --git a/crates/daemon/tests/support/windows_opencode_business.rs b/crates/daemon/tests/support/windows_opencode_business.rs
new file mode 100644
index 00000000..3c6d5bff
--- /dev/null
+++ b/crates/daemon/tests/support/windows_opencode_business.rs
@@ -0,0 +1,207 @@
+//! OpenCode's native Windows leaves reuse public routing, Worker receipts and Job checks.
+use super::InstalledProduct;
+use super::windows_headless_business::{Business, cli};
+use super::windows_routing_business::Plan;
+use super::windows_worker_business::{
+ cancel, command, exec_args, oracle, select_native, selected, wait_result, write_new,
+};
+use hiroute_application_api::WorkerHarnessV1;
+use hiroute_platform::windows::security;
+use serde_json::{Value, json};
+use std::ffi::OsString;
+use std::path::PathBuf;
+use std::time::Duration;
+
+pub struct Context {
+ variables: Vec<(OsString, OsString)>,
+ configuration: PathBuf,
+ original: Vec<u8>,
+}
+impl Context {
+ pub fn prepare(product: &InstalledProduct) -> Self {
+ let root = product.root.join("OpenCode native 中文 roots");
+ security::create_owner_only_directory(&root).unwrap();
+ let mut variables = Vec::new();
+ let mut config = PathBuf::new();
+ for (variable, directory) in [
+ ("XDG_CONFIG_HOME", "config"),
+ ("XDG_DATA_HOME", "data"),
+ ("XDG_CACHE_HOME", "cache"),
+ ("XDG_STATE_HOME", "state"),
+ ] {
+ let parent = root.join(directory);
+ security::create_owner_only_directory(&parent).unwrap();
+ let native = parent.join("opencode");
+ security::create_owner_only_directory(&native).unwrap();
+ if variable == "XDG_CONFIG_HOME" {
+ config = native;
+ }
+ variables.push((variable.into(), parent.into_os_string()));
+ }
+ let configuration = config.join("opencode.json");
+ let original = br#"{"$schema":"https://opencode.ai/config.json","instructions":[],"autoupdate":false,"share":"disabled"}"#.to_vec();
+ write_new(&configuration, &original);
+ Self {
+ variables,
+ configuration,
+ original,
+ }
+ }
+ pub fn variables(&self) -> &[(OsString, OsString)] {
+ &self.variables
+ }
+ pub fn preserved(&self) {
+ assert_eq!(std::fs::read(&self.configuration).unwrap(), self.original);
+ }
+}
+
+pub struct Journey {
+ workspace: PathBuf,
+ prompt: PathBuf,
+ continued_prompt: PathBuf,
+ receipt: String,
+ plan: Plan,
+ _source: Business,
+ worker: oracle::Oracle,
+ original: Value,
+}
+impl Journey {
+ pub fn run(product: &InstalledProduct) -> Self {
+ let binary = selected("HIROUTE_WORKER_OPENCODE_BINARY");
+ let workspace = product.root.join("OpenCode public Worker 中文 % ! ' &");
+ security::create_owner_only_directory(&workspace).unwrap();
+ let mut entropy = [0u8; 16];
+ getrandom::fill(&mut entropy).unwrap();
+ let nonce: String = entropy.iter().map(|b| format!("{b:02x}")).collect();
+ let receipt = format!("worker-direct-{nonce}");
+ let project = workspace.join(".opencode");
+ let skills = project.join("skills");
+ let skill = skills.join("windows-worker-receipt");
+ for path in [&project, &skills, &skill] {
+ security::create_owner_only_directory(path).unwrap();
+ }
+ let skill = skill.join("SKILL.md");
+ let contents = format!(
+ "---\nname: windows-worker-receipt\ndescription: Complete native receipt skill-discovery-{nonce}\n---\n\nRead this actual Skill and use native write/read tools.\nContent receipt: skill-contents-{nonce}\n"
+ );
+ write_new(&skill, contents.as_bytes());
+ let worker = oracle::Oracle::worker(&workspace, skill.clone(), contents.clone(), &nonce);
+ let source = Business::save_on(
+ product,
+ "candidate/native/windows-opencode",
+ "windows-opencode-source",
+ worker.address(),
+ );
+ let editor = json!({"schema":"hiroute.plan-editor/v2","display_name":"Windows OpenCode Worker",
+ "purpose":"Use actual native Skills, tools and exact history","mode":"fixed_model",
+ "candidates":[{"binding_id":source.binding_id()}],
+ "smart":{"economy":[],"primary":[],"judgment":super::windows_routing_business::judgment(),
+ "reselect_on_user_message":false,"classifier":{"kind":"local_rules"},"complex_keywords":[]},
+ "free":{"candidates":[],"primary":[],"primary_fallback":false},
+ "delegation_enabled":true,"work":{"harness":"opencode","protocol":"responses"},"requirements":{},
+ "limits":{"maximum_attempts":1,"request_timeout_ms":30000,"attempt_timeout_ms":30000}});
+ let plan = Plan::create_with_editor(product, editor, "windows-opencode-plan");
+ let discovered = cli(
+ product,
+ &[
+ "worker",
+ "dependencies",
+ "discover",
+ "--harness",
+ "opencode",
+ ],
+ None,
+ );
+ select_native(product, &discovered, WorkerHarnessV1::OpenCode, &binary);
+ let prompt = workspace.join("direct.txt");
+ let continued_prompt = workspace.join("continue.txt");
+ write_new(&prompt, format!("{}: Load the windows-worker-receipt Skill and complete its bounded tool receipt.\n", oracle::DIRECT).as_bytes());
+ write_new(
+ &continued_prompt,
+ format!(
+ "{} {}: Continue the original task with its original successful read receipt.\n",
+ oracle::CONTINUE,
+ oracle::DIRECT
+ )
+ .as_bytes(),
+ );
+ let accepted = command(
+ product,
+ &exec_args(
+ &plan.plan_id,
+ &workspace,
+ &prompt,
+ "windows-opencode-direct",
+ ),
+ None,
+ Duration::from_secs(180),
+ );
+ let result = wait_result(product, accepted, &worker);
+ assert!(result["result"].as_str().unwrap().contains(&receipt));
+ assert_eq!(
+ std::fs::read_to_string(workspace.join("direct 中文 % ! ' &.txt"))
+ .unwrap()
+ .trim(),
+ receipt
+ );
+ assert_eq!(std::fs::read(&skill).unwrap(), contents.as_bytes());
+ cancel::verify_opencode(product, &workspace, &plan.plan_id, &nonce);
+ Self {
+ workspace,
+ prompt,
+ continued_prompt,
+ receipt,
+ plan,
+ _source: source,
+ worker,
+ original: result,
+ }
+ }
+
+ pub fn recovered(&self, product: &InstalledProduct) {
+ let replay = command(
+ product,
+ &exec_args(
+ &self.plan.plan_id,
+ &self.workspace,
+ &self.prompt,
+ "windows-opencode-direct",
+ ),
+ None,
+ Duration::from_secs(180),
+ );
+ assert_eq!(replay["data"]["task_id"], self.original["task_id"]);
+ assert_eq!(replay["data"]["run_id"], self.original["run_id"]);
+ assert_eq!(replay["data"]["replayed"], true);
+ let accepted = command(
+ product,
+ &[
+ "worker",
+ "continue",
+ "--task",
+ self.original["task_id"].as_str().unwrap(),
+ "--expected-latest-run",
+ self.original["run_id"].as_str().unwrap(),
+ "--file",
+ self.continued_prompt.to_str().unwrap(),
+ "--no-wait",
+ "--run-timeout",
+ "120",
+ "--submission-key",
+ "windows-opencode-continue",
+ ],
+ None,
+ Duration::from_secs(180),
+ );
+ let result = wait_result(product, accepted, &self.worker);
+ assert_eq!(result["task_id"], self.original["task_id"]);
+ assert_ne!(result["run_id"], self.original["run_id"]);
+ assert!(
+ result["result"]
+ .as_str()
+ .unwrap()
+ .contains(&format!("continued-{}", self.receipt))
+ );
+ assert!(self.worker.ledger.lock().unwrap().continued > 0);
+ }
+}
diff --git a/crates/daemon/tests/support/windows_worker_business.rs b/crates/daemon/tests/support/windows_worker_business.rs
index ff87accc..58049109 100644
--- a/crates/daemon/tests/support/windows_worker_business.rs
+++ b/crates/daemon/tests/support/windows_worker_business.rs
@@ -2,13 +2,13 @@
//! The fixture shares the calling gate's one disposable installed Windows product and
//! uses public management throughout. Only the independent model endpoints are controlled.
#[path = "windows_worker_cancel.rs"]
-mod cancel;
+pub(super) mod cancel;
#[path = "windows_worker_dependency_selection.rs"]
mod dependency_selection;
#[path = "windows_worker_failure_diagnostics.rs"]
mod failure_diagnostics;
#[path = "windows_worker_oracle.rs"]
-mod oracle;
+pub(super) mod oracle;
pub(crate) use dependency_selection::discovery_environment;
@@ -446,16 +446,31 @@ fn read_optional(path: &Path) -> Option<Vec<u8>> {
}
}
-fn write_new(path: &Path, bytes: &[u8]) {
+pub(super) fn write_new(path: &Path, bytes: &[u8]) {
hiroute_platform::durable::write_private_new(path, bytes).unwrap();
security::verify_owner_only(path, false).unwrap();
}
-fn selected(variable: &str) -> PathBuf {
+pub(super) fn selected(variable: &str) -> PathBuf {
std::env::var_os(variable)
.map(PathBuf::from)
.filter(|path| path.is_absolute() && path.is_file())
.unwrap_or_else(|| panic!("{variable} must select the fixed actual native client"))
}
+pub(super) fn select_native(
+ product: &InstalledProduct,
+ discovered: &Value,
+ harness: hiroute_application_api::WorkerHarnessV1,
+ binary: &Path,
+) {
+ let selection = dependency_selection::select_native(discovered, harness, binary);
+ command(
+ product,
+ &["worker", "dependencies", "select"],
+ Some(&serde_json::to_value(&selection.request).unwrap()),
+ Duration::from_secs(120),
+ );
+}
+
fn select_pi(product: &InstalledProduct) {
let discovered = cli(
product,
@@ -548,7 +563,7 @@ fn select_pi(product: &InstalledProduct) {
);
assert_eq!(replay["data"]["selected"], selected["data"]["selected"]);
}
-fn exec_args<'a>(
+pub(crate) fn exec_args<'a>(
plan: &'a str,
workspace: &'a Path,
prompt: &'a Path,
@@ -575,7 +590,11 @@ fn same_identity(current: &Value, expected: &Value) {
assert_eq!(current[field], expected[field]);
}
}
-fn wait_result(product: &InstalledProduct, accepted: Value, worker: &oracle::Oracle) -> Value {
+pub(super) fn wait_result(
+ product: &InstalledProduct,
+ accepted: Value,
+ worker: &oracle::Oracle,
+) -> Value {
let task = accepted["data"]["task_id"].as_str().unwrap();
let run = accepted["data"]["run_id"].as_str().unwrap();
let deadline = Instant::now() + Duration::from_secs(180);
@@ -697,7 +716,7 @@ fn apply_settings(product: &InstalledProduct, verb: &str, spec: &Value, key: &st
operation
);
}
-fn command(
+pub(super) fn command(
product: &InstalledProduct,
args: &[&str],
payload: Option<&Value>,
diff --git a/crates/daemon/tests/support/windows_worker_cancel.rs b/crates/daemon/tests/support/windows_worker_cancel.rs
index 0b4c09b4..afd7f0fa 100644
--- a/crates/daemon/tests/support/windows_worker_cancel.rs
+++ b/crates/daemon/tests/support/windows_worker_cancel.rs
@@ -19,6 +19,26 @@ use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, WaitForSingleObject,
};
+pub(super) fn opencode_command(workspace: &Path, nonce: &str) -> String {
+ use base64::Engine;
+ let literal = |text: &str| {
+ format!(
+ "Buffer.from('{}','base64').toString('utf8')",
+ base64::engine::general_purpose::STANDARD.encode(text)
+ )
+ };
+ // OpenCode exposes its Windows shell as bash even when it selects PowerShell
+ // or cmd. Reuse the runner's pinned Node in PATH; encode user paths so this
+ // one native command crosses all three shells without interpreting them.
+ format!(
+ "node.exe -e \"const fs=require('fs');fs.writeFileSync({},{});setTimeout(()=>fs.writeFileSync({},{}),60000)\"",
+ literal(workspace.join("cancel-started.txt").to_str().unwrap()),
+ literal(&format!("started-{nonce}")),
+ literal(workspace.join("cancel-late.txt").to_str().unwrap()),
+ literal(&format!("late-{nonce}")),
+ )
+}
+
pub(super) struct CancellationReceipts {
pub late: Vec<PathBuf>,
pub residual_task: String,
@@ -29,6 +49,25 @@ pub(super) fn verify(
workspace: &Path,
plan: &str,
nonce: &str,
+) -> CancellationReceipts {
+ verify_for(product, workspace, plan, nonce, "pi")
+}
+
+pub(crate) fn verify_opencode(
+ product: &InstalledProduct,
+ workspace: &Path,
+ plan: &str,
+ nonce: &str,
+) {
+ let _ = verify_for(product, workspace, plan, nonce, "opencode");
+}
+
+fn verify_for(
+ product: &InstalledProduct,
+ workspace: &Path,
+ plan: &str,
+ nonce: &str,
+ harness: &str,
) -> CancellationReceipts {
let executors = command(
product,
@@ -40,12 +79,14 @@ pub(super) fn verify(
.as_array()
.unwrap()
.iter()
- .find(|executor| executor["harness"] == "pi")
+ .find(|executor| executor["harness"] == harness)
.unwrap();
assert_eq!(pi["start_approve_all"]["state"], "ready");
assert_eq!(pi["cancel"]["state"], "ready");
- assert_eq!(pi["continue_session"]["state"], "unknown");
- assert_eq!(pi["continue_session"]["reason"], "capability_unverified");
+ if harness == "pi" {
+ assert_eq!(pi["continue_session"]["state"], "unknown");
+ assert_eq!(pi["continue_session"]["reason"], "capability_unverified");
+ }
let prompt = workspace.join("cancel-task.txt");
write_new(
&prompt,
@@ -174,6 +215,12 @@ pub(super) fn verify(
);
assert_eq!(rejected["error"]["code"], "REVISION_CONFLICT");
assert_eq!(rejected["status"], json!("conflict"));
+ if harness == "opencode" {
+ return CancellationReceipts {
+ late: vec![late],
+ residual_task: String::new(),
+ };
+ }
let (residual_late, residual_task) = residual(product, workspace, plan, nonce);
CancellationReceipts {
late: vec![late, residual_late],
diff --git a/crates/daemon/tests/support/windows_worker_dependency_selection.rs b/crates/daemon/tests/support/windows_worker_dependency_selection.rs
index 74ada0e0..71b0fc85 100644
--- a/crates/daemon/tests/support/windows_worker_dependency_selection.rs
+++ b/crates/daemon/tests/support/windows_worker_dependency_selection.rs
@@ -124,8 +124,20 @@ pub(super) fn select(discovered: &Value, cli: &Path, node: &Path) -> Selection {
.expect("actual discovery must report the Pi selection revision")
.revision;
let mut held = Vec::new();
- let cli_path = candidate(&view, WorkerDependencyComponentV1::Cli, cli, &mut held);
- let node_path = candidate(&view, WorkerDependencyComponentV1::Node, node, &mut held);
+ let cli_path = candidate(
+ &view,
+ WorkerHarnessV1::Pi,
+ WorkerDependencyComponentV1::Cli,
+ cli,
+ &mut held,
+ );
+ let node_path = candidate(
+ &view,
+ WorkerHarnessV1::Pi,
+ WorkerDependencyComponentV1::Node,
+ node,
+ &mut held,
+ );
let request = WorkerDependenciesSelectRequestV1 {
harness: WorkerHarnessV1::Pi,
adapter_path: None,
@@ -158,8 +170,45 @@ pub(super) fn select(discovered: &Value, cli: &Path, node: &Path) -> Selection {
}
}
+pub(super) fn select_native(discovered: &Value, harness: WorkerHarnessV1, cli: &Path) -> Selection {
+ let view: WorkerDependenciesViewV1 =
+ serde_json::from_value(discovered["data"].clone()).unwrap();
+ assert!(view.valid());
+ let revision = view
+ .selection_revisions
+ .iter()
+ .find(|row| row.harness == harness)
+ .unwrap()
+ .revision;
+ let mut held = Vec::new();
+ let request = WorkerDependenciesSelectRequestV1 {
+ harness,
+ cli_path: candidate(
+ &view,
+ harness,
+ WorkerDependencyComponentV1::Cli,
+ cli,
+ &mut held,
+ ),
+ adapter_path: None,
+ node_path: None,
+ expected_selection_revision: revision,
+ };
+ assert!(request.valid());
+ let ordinary = WorkerDependenciesSelectRequestV1 {
+ cli_path: cli.to_str().unwrap().to_owned(),
+ ..request.clone()
+ };
+ Selection {
+ request,
+ ordinary,
+ _held: held,
+ }
+}
+
fn candidate(
view: &WorkerDependenciesViewV1,
+ harness: WorkerHarnessV1,
component: WorkerDependencyComponentV1,
pinned: &Path,
held: &mut Vec<File>,
@@ -170,7 +219,7 @@ fn candidate(
held.push(pin);
let mut matches = Vec::new();
for row in &view.candidates {
- if row.harness != WorkerHarnessV1::Pi
+ if row.harness != harness
|| row.component != component
|| row.state != WorkerDependencyCandidateStateV1::Found
{
diff --git a/crates/daemon/tests/support/windows_worker_oracle.rs b/crates/daemon/tests/support/windows_worker_oracle.rs
index ff70a3ea..776400f0 100644
--- a/crates/daemon/tests/support/windows_worker_oracle.rs
+++ b/crates/daemon/tests/support/windows_worker_oracle.rs
@@ -65,6 +65,16 @@ impl Oracle {
Self::start(move |body, ledger| {
ledger.worker_stage = Some(WorkerStage::ModelRequest);
let text = native_text(body);
+ if [
+ "title generator",
+ "generate a concise title",
+ "generate a short title",
+ ]
+ .iter()
+ .any(|part| text.to_lowercase().contains(part))
+ {
+ return text_reply(body, "Native task receipt");
+ }
if text.contains(RESIDUAL) {
ledger.worker_stage = Some(WorkerStage::ResidualRequest);
println!("Windows public residual checkpoint: stage=oracle-request-observed");
@@ -113,13 +123,17 @@ impl Oracle {
let quote = |text: &str| format!("'{}'", text.replace('\'', "'\\''"));
let path =
|name: &str| quote(&workspace.join(name).to_string_lossy().replace('\\', "/"));
- let command = format!(
- "printf '%s\\n' {} > {} && sleep 60 && printf '%s\\n' {} > {}",
- quote(&format!("started-{nonce}")),
- path("cancel-started.txt"),
- quote(&format!("late-{nonce}")),
- path("cancel-late.txt")
- );
+ let command = if shell_timeout_is_millis(body) {
+ super::cancel::opencode_command(&workspace, &nonce)
+ } else {
+ format!(
+ "printf '%s\\n' {} > {} && sleep 60 && printf '%s\\n' {} > {}",
+ quote(&format!("started-{nonce}")),
+ path("cancel-started.txt"),
+ quote(&format!("late-{nonce}")),
+ path("cancel-late.txt")
+ )
+ };
return function_reply(
body,
"worker_cancel",
@@ -170,13 +184,20 @@ impl Oracle {
if let Some(output) = correlated(body, "worker_skill") {
ledger.worker_stage = Some(WorkerStage::SkillResult);
ledger.worker_skill_results += 1;
- assert!(
- contents
- .lines()
- .filter(|line| !line.trim().is_empty())
- .all(|line| output.contains(line)),
- "Worker must load the actual project Skill, not a prompt copy"
- );
+ if tool(body, "skill").is_some() {
+ assert!(
+ output.contains(&format!("skill-contents-{nonce}")),
+ "OpenCode must load the actual native project Skill body"
+ );
+ } else {
+ assert!(
+ contents
+ .lines()
+ .filter(|line| !line.trim().is_empty())
+ .all(|line| output.contains(line)),
+ "Worker must load the actual project Skill, not a prompt copy"
+ );
+ }
return function_reply(
body,
"worker_write",
@@ -184,11 +205,26 @@ impl Oracle {
json!({"path":artifact,"content":format!("{receipt}\n")}),
);
}
- assert!(
- text.contains(&format!("skill-discovery-{nonce}")),
- "native project Skill discovery receipt is absent"
- );
- function_reply(body, "worker_skill", "read", json!({"path":skill}))
+ if tool(body, "skill").is_some() {
+ // OpenCode 1.19.3 advertises Skills in model context while the
+ // tool's description stays static. Match the shared native oracle.
+ assert!(
+ text.contains(&format!("skill-discovery-{nonce}")),
+ "native OpenCode Skill discovery receipt is absent"
+ );
+ function_reply(
+ body,
+ "worker_skill",
+ "skill",
+ json!({"name":"windows-worker-receipt"}),
+ )
+ } else {
+ assert!(
+ text.contains(&format!("skill-discovery-{nonce}")),
+ "native project Skill discovery receipt is absent"
+ );
+ function_reply(body, "worker_skill", "read", json!({"path":skill}))
+ }
})
}
@@ -571,7 +607,17 @@ fn tool<'a>(body: &'a Value, name: &str) -> Option<&'a Value> {
.iter()
.find(|tool| tool["name"] == name || tool["function"]["name"] == name)
}
-fn function_reply(body: &Value, id: &str, name: &str, arguments: Value) -> http::Reply {
+fn shell_timeout_is_millis(body: &Value) -> bool {
+ let Some(declaration) = tool(body, "bash") else {
+ return false;
+ };
+ declaration
+ .get("parameters")
+ .or_else(|| declaration["function"].get("parameters"))
+ .and_then(|schema| schema["properties"]["timeout"]["description"].as_str())
+ .is_some_and(|description| description.to_ascii_lowercase().contains("milliseconds"))
+}
+fn function_reply(body: &Value, id: &str, name: &str, mut arguments: Value) -> http::Reply {
let declaration =
tool(body, name).expect("actual native client must declare the selected tool");
assert_ne!(
@@ -581,6 +627,22 @@ fn function_reply(body: &Value, id: &str, name: &str, arguments: Value) -> http:
let parameters = declaration
.get("parameters")
.or_else(|| declaration["function"].get("parameters"));
+ // Follow the actual native declaration; Pi uses path, OpenCode uses filePath.
+ if parameters.is_some_and(|schema| schema["properties"].get("filePath").is_some())
+ && let Some(path) = arguments.as_object_mut().unwrap().remove("path")
+ {
+ arguments["filePath"] = path;
+ }
+ if name == "bash"
+ && parameters.is_some_and(|schema| schema["properties"].get("description").is_some())
+ {
+ arguments["description"] = json!("Produce the bounded native acceptance receipt");
+ }
+ // OpenCode 1.19.3 no longer declares a description argument; its timeout
+ // still uses milliseconds. Pi's timeout remains in seconds.
+ if name == "bash" && shell_timeout_is_millis(body) {
+ arguments["timeout"] = json!(120000);
+ }
if let Some(required) = parameters.and_then(|schema| schema["required"].as_array()) {
assert!(
required
@@ -663,6 +725,36 @@ fn stream(body: &Value, id: &str, item: Value) -> http::Reply {
mod tests {
use super::*;
+ #[test]
+ fn shell_timeout_follows_declared_units_without_a_description_argument() {
+ for (description, expected) in [
+ ("Optional timeout in milliseconds", 120000),
+ ("Optional timeout in seconds", 120),
+ ] {
+ let body = json!({"tools":[{"type":"function","name":"bash","parameters":{
+ "type":"object","properties":{"command":{"type":"string"},
+ "timeout":{"type":"number","description":description}},
+ "required":["command"]}}]});
+ let reply = function_reply(
+ &body,
+ "worker_cancel",
+ "bash",
+ json!({"command":"native-receipt","timeout":120}),
+ );
+ let event: Value = String::from_utf8(reply.body)
+ .unwrap()
+ .lines()
+ .filter_map(|line| line.strip_prefix("data: "))
+ .map(|line| serde_json::from_str::<Value>(line).unwrap())
+ .find(|event| event["type"] == "response.output_item.done")
+ .unwrap();
+ let arguments: Value =
+ serde_json::from_str(event["item"]["arguments"].as_str().unwrap()).unwrap();
+ assert_eq!(arguments["timeout"], expected);
+ assert!(arguments.get("description").is_none());
+ }
+ }
+
#[test]
fn a_prompt_or_unrelated_or_error_tool_result_cannot_supply_a_native_receipt() {
let mut body = json!({"input":[{"type":"message","content":"native-receipt"},
diff --git a/crates/daemon/tests/windows_headless.rs b/crates/daemon/tests/windows_headless.rs
index ba3f78a5..8c4aa048 100644
--- a/crates/daemon/tests/windows_headless.rs
+++ b/crates/daemon/tests/windows_headless.rs
@@ -23,6 +23,8 @@ mod windows_management_business;
mod windows_model_ratings;
#[path = "support/windows_native_protocols.rs"]
mod windows_native_protocols;
+#[path = "support/windows_opencode_business.rs"]
+mod windows_opencode_business;
#[path = "support/windows_packaged_foreground.rs"]
mod windows_packaged_foreground;
#[path = "support/windows_qoder_daemon_diagnostic.rs"]
@@ -90,9 +92,12 @@ impl InstalledProduct {
"product gate must not replace an existing stable entry"
);
security::ensure_private_directory(&layout.data_root).unwrap();
+ let mut entropy = [0u8; 16];
+ getrandom::fill(&mut entropy).unwrap();
+ let nonce: String = entropy.iter().map(|byte| format!("{byte:02x}")).collect();
let root = layout
.data_root
- .join(format!("Windows headless 测试 {}", std::process::id()));
+ .join(format!("Windows headless 测试 {nonce}"));
security::create_owner_only_directory(&root).unwrap();
if windows_execution_host::selected() {
assert!(
@@ -1142,3 +1147,36 @@ fn actual_windows_installed_management_commands() {
fn actual_windows_packaged_foreground_subscription_lifecycle() {
windows_packaged_foreground::run();
}
+
+/// Focused native OpenCode coverage; the standard Windows runner owns execution.
+#[test]
+#[ignore = "requires the pinned official OpenCode Windows native package"]
+fn actual_windows_opencode_worker_native_history_and_cancellation() {
+ let product = InstalledProduct::create();
+ let context = windows_opencode_business::Context::prepare(&product);
+ let mut first = product.start_with_environment(false, context.variables());
+ gateway_ready(first.listen);
+ let journey = windows_opencode_business::Journey::run(&product);
+ context.preserved();
+ lifecycle::stop(
+ &product.layout.lifecycle_endpoint(),
+ &product.daemon,
+ Duration::from_secs(30),
+ )
+ .unwrap();
+ first.wait(true);
+ let mut recovered = product.start_with_environment(true, context.variables());
+ gateway_ready(recovered.listen);
+ journey.recovered(&product);
+ context.preserved();
+ lifecycle::stop(
+ &product.layout.lifecycle_endpoint(),
+ &product.daemon,
+ Duration::from_secs(30),
+ )
+ .unwrap();
+ recovered.wait(true);
+ println!(
+ "Windows native OpenCode: public Plan and installation selection, actual Skill/tool receipts, Job cancellation, daemon restart and exact Continue; borrowed native configuration preserved"
+ );
+}
diff --git a/crates/domain/src/agents/model_budget_conflict.rs b/crates/domain/src/agents/model_budget_conflict.rs
index 5831ec49..5c59cb87 100644
--- a/crates/domain/src/agents/model_budget_conflict.rs
+++ b/crates/domain/src/agents/model_budget_conflict.rs
@@ -75,6 +75,7 @@ impl AgentModelBudgetConflictV1 {
AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes
) && blocker.context_id.starts_with("agent-context/")
&& blocker.context_id.len() <= 256
diff --git a/crates/domain/src/agents/model_grant.rs b/crates/domain/src/agents/model_grant.rs
index f193720f..abb71fb1 100644
--- a/crates/domain/src/agents/model_grant.rs
+++ b/crates/domain/src/agents/model_grant.rs
@@ -95,7 +95,8 @@ impl AgentModelGrantV2 {
AgentModelSelectionV2::CodexDefault { .. }
| AgentModelSelectionV2::QoderAdditional { .. }
| AgentModelSelectionV2::PiAdditional { .. }
- | AgentModelSelectionV2::DshAdditional { .. },
+ | AgentModelSelectionV2::DshAdditional { .. }
+ | AgentModelSelectionV2::OpenCodeAdditional { .. },
AgentIngressProtocolV1::Responses
) | (
AgentModelSelectionV2::ClaudeLauncher { .. },
@@ -369,7 +370,8 @@ impl AgentModelGrantV2 {
AgentModelSelectionV2::CodexDefault { .. }
| AgentModelSelectionV2::QoderAdditional { .. }
| AgentModelSelectionV2::PiAdditional { .. }
- | AgentModelSelectionV2::DshAdditional { .. },
+ | AgentModelSelectionV2::DshAdditional { .. }
+ | AgentModelSelectionV2::OpenCodeAdditional { .. },
AgentIngressProtocolV1::Responses
) | (
AgentModelSelectionV2::ClaudeLauncher { .. },
diff --git a/crates/domain/src/agents/profile.rs b/crates/domain/src/agents/profile.rs
index 0520b69a..b88cb63a 100644
--- a/crates/domain/src/agents/profile.rs
+++ b/crates/domain/src/agents/profile.rs
@@ -18,6 +18,8 @@ pub enum AgentKindV1 {
Qoder,
Pi,
DeepseekHarness,
+ #[serde(rename = "opencode")]
+ OpenCode,
Hermes,
}
@@ -40,6 +42,14 @@ impl AgentKindV1 {
ConfigLayerV1::Project,
ConfigLayerV1::User,
],
+ Self::OpenCode => &[
+ ConfigLayerV1::Managed,
+ ConfigLayerV1::Process,
+ ConfigLayerV1::Local,
+ ConfigLayerV1::Project,
+ ConfigLayerV1::Launch,
+ ConfigLayerV1::User,
+ ],
Self::Pi | Self::DeepseekHarness | Self::Hermes => &[
ConfigLayerV1::Process,
ConfigLayerV1::Launch,
@@ -62,6 +72,7 @@ impl AgentKindV1 {
Self::Qoder => "qoder",
Self::Pi => "pi",
Self::DeepseekHarness => "deepseek_harness",
+ Self::OpenCode => "opencode",
Self::Hermes => "hermes",
}
}
@@ -227,6 +238,7 @@ impl AgentProfileV1 {
AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes
) && (self.dynamic_catalog
|| self.static_catalog_fallback
@@ -273,6 +285,7 @@ impl AgentProfileV1 {
| AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes,
Some(AgentIngressProtocolV1::Responses),
)
diff --git a/crates/domain/src/agents/settings.rs b/crates/domain/src/agents/settings.rs
index d264546b..8bd70c80 100644
--- a/crates/domain/src/agents/settings.rs
+++ b/crates/domain/src/agents/settings.rs
@@ -20,6 +20,12 @@ pub enum AgentFacetIntent<T> {
#[derive(schemars::JsonSchema, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum AgentModelSelectionV2 {
+ #[serde(rename = "opencode_additional")]
+ OpenCodeAdditional {
+ allowed_plan_ids: BTreeSet<AgentPlanId>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ plan_protocols: BTreeMap<AgentPlanId, crate::AgentIngressProtocolV1>,
+ },
HermesDefault {
plan_id: AgentPlanId,
protocol: crate::AgentIngressProtocolV1,
@@ -70,6 +76,8 @@ pub enum AgentModelSurfaceV2 {
QoderCli,
PiCli,
DshCli,
+ #[serde(rename = "opencode_cli")]
+ OpenCodeCli,
HermesCli,
}
@@ -123,7 +131,8 @@ impl AgentModelSelectionV2 {
| Self::PiAdditional { plan_protocols, .. } => {
plan_protocols.get(id).copied().unwrap_or(fallback)
}
- Self::DshAdditional { plan_protocols, .. } => {
+ Self::DshAdditional { plan_protocols, .. }
+ | Self::OpenCodeAdditional { plan_protocols, .. } => {
plan_protocols.get(id).copied().unwrap_or(fallback)
}
_ => fallback,
@@ -138,6 +147,7 @@ impl AgentModelSelectionV2 {
Self::QoderAdditional { .. }
| Self::PiAdditional { .. }
| Self::DshAdditional { .. }
+ | Self::OpenCodeAdditional { .. }
| Self::HermesDefault { .. } => &[],
}
}
@@ -156,6 +166,9 @@ impl AgentModelSelectionV2 {
}
| Self::DshAdditional {
allowed_plan_ids, ..
+ }
+ | Self::OpenCodeAdditional {
+ allowed_plan_ids, ..
} => allowed_plan_ids.clone(),
Self::ClaudeLauncher {
preset_mappings, ..
@@ -207,7 +220,8 @@ impl AgentModelSelectionV2 {
},
Self::QoderAdditional { plan_protocols, .. }
| Self::PiAdditional { plan_protocols, .. }
- | Self::DshAdditional { plan_protocols, .. } => {
+ | Self::DshAdditional { plan_protocols, .. }
+ | Self::OpenCodeAdditional { plan_protocols, .. } => {
if plan_protocols.keys().any(|id| !plans.contains(id))
|| plan_protocols
.values()
diff --git a/crates/domain/src/delegation/installation.rs b/crates/domain/src/delegation/installation.rs
index b648f7d2..1b1af1ab 100644
--- a/crates/domain/src/delegation/installation.rs
+++ b/crates/domain/src/delegation/installation.rs
@@ -39,12 +39,16 @@ impl<'a> WorkerLaunchFormV1<'a> {
cli,
node,
}),
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::DeepseekHarness
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode
if adapter.is_none() && node.is_none() =>
{
Ok(Self::NativeAcp { cli })
}
- WorkerHarnessV1::QoderCli | WorkerHarnessV1::DeepseekHarness => Err(invalid()),
+ WorkerHarnessV1::QoderCli
+ | WorkerHarnessV1::DeepseekHarness
+ | WorkerHarnessV1::OpenCode => Err(invalid()),
WorkerHarnessV1::Pi if adapter.is_none() => Ok(Self::NativeSdk {
cli,
node: node.ok_or_else(invalid)?,
diff --git a/crates/domain/src/delegation/mod.rs b/crates/domain/src/delegation/mod.rs
index 771b0652..05055668 100644
--- a/crates/domain/src/delegation/mod.rs
+++ b/crates/domain/src/delegation/mod.rs
@@ -54,6 +54,8 @@ pub enum WorkerHarnessV1 {
QoderCli,
Pi,
DeepseekHarness,
+ #[serde(rename = "opencode")]
+ OpenCode,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
diff --git a/crates/domain/src/operation/mod.rs b/crates/domain/src/operation/mod.rs
index cf196c99..f6a03cbc 100644
--- a/crates/domain/src/operation/mod.rs
+++ b/crates/domain/src/operation/mod.rs
@@ -857,6 +857,7 @@ impl TransactionPlanV1 {
change.after_selection.validated_launch()?;
let harness = change.after_selection.harness;
let resource = match harness {
+ crate::delegation::WorkerHarnessV1::OpenCode => "worker-dependency-selection/opencode",
crate::delegation::WorkerHarnessV1::QoderCli => "worker-dependency-selection/qoder_cli",
crate::delegation::WorkerHarnessV1::Pi => "worker-dependency-selection/pi",
crate::delegation::WorkerHarnessV1::DeepseekHarness => {
diff --git a/crates/gateway/src/dispatch/run.rs b/crates/gateway/src/dispatch/run.rs
index 8038d46b..3ced4e58 100644
--- a/crates/gateway/src/dispatch/run.rs
+++ b/crates/gateway/src/dispatch/run.rs
@@ -64,7 +64,7 @@ impl RunObservationMetadata {
|| !valid_observation_reference(&value.publication_ref)
|| !matches!(
value.harness_id.as_str(),
- "codex" | "claude" | "qoder" | "pi" | "dsh"
+ "codex" | "claude" | "qoder" | "pi" | "dsh" | "opencode"
)
|| [
&value.native_session_id,
@@ -463,7 +463,7 @@ mod tests {
}
}
- for harness in ["codex", "claude", "qoder"] {
+ for harness in ["codex", "claude", "qoder", "pi", "dsh", "opencode"] {
let authority = GatewayRequestAuthority::new(empty_global())
.with_run_request_authority(Arc::new(Authority(verified_for_harness(
Arc::new(Safety(AtomicUsize::new(0))),
diff --git a/crates/integrations/Cargo.toml b/crates/integrations/Cargo.toml
index 6ca424c4..47e247d0 100644
--- a/crates/integrations/Cargo.toml
+++ b/crates/integrations/Cargo.toml
@@ -15,6 +15,7 @@ hiroute-gateway = { path = "../gateway" }
hiroute-platform = { path = "../platform" }
http.workspace = true
reqwest = { version = "=0.13.4", features = ["blocking"] }
+rusqlite.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_yaml.workspace = true
diff --git a/crates/integrations/src/agents/additional_native.rs b/crates/integrations/src/agents/additional_native.rs
index 1dc32dfc..300094a5 100644
--- a/crates/integrations/src/agents/additional_native.rs
+++ b/crates/integrations/src/agents/additional_native.rs
@@ -18,6 +18,12 @@ pub(super) fn parse_native_jsonc(bytes: &[u8]) -> Result<Value, QoderNativeError
Ok(Document::parse(bytes)?.root.value)
}
+pub(super) fn parse_opencode_jsonc(bytes: &[u8]) -> Result<Value, QoderNativeError> {
+ Ok(Document::parse_with_trailing_commas(bytes, true)?
+ .root
+ .value)
+}
+
// This structure is serialized only into NativeAgentArtifactPort's encrypted restore envelope.
// It deliberately has no Debug implementation or public JSON conversion.
#[derive(Deserialize, Serialize)]
@@ -54,8 +60,10 @@ pub(super) fn validate_declaration(
) -> Result<(), QoderNativeError> {
if kind == AgentKindV1::Qoder {
qoder_provider::validate_model_route(provider_id, endpoint)?;
- } else if !matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness)
- || !endpoint.starts_with("http://")
+ } else if !matches!(
+ kind,
+ AgentKindV1::Pi | AgentKindV1::DeepseekHarness | AgentKindV1::OpenCode
+ ) || !endpoint.starts_with("http://")
|| !endpoint.ends_with("/v1")
{
return Err(qoder_error("additional endpoint"));
@@ -76,7 +84,10 @@ pub(super) fn validate_declaration(
return Err(qoder_error("additional models"));
}
for model in models {
- (if matches!(kind, AgentKindV1::Pi | AgentKindV1::DeepseekHarness) {
+ (if matches!(
+ kind,
+ AgentKindV1::Pi | AgentKindV1::DeepseekHarness | AgentKindV1::OpenCode
+ ) {
model.validate_pi()
} else {
model.validate()
@@ -96,6 +107,18 @@ fn document(current: Option<&[u8]>) -> Result<Document<'_>, QoderNativeError> {
fn native_root(kind: AgentKindV1, current: Option<&[u8]>) -> Result<Value, QoderNativeError> {
if kind == AgentKindV1::DeepseekHarness {
super::dsh_config::Patch::parse(current)?.model_root()
+ } else if kind == AgentKindV1::OpenCode {
+ let mut root = parse_opencode_jsonc(current.unwrap_or(b"{}"))?;
+ let object = root
+ .as_object_mut()
+ .ok_or_else(|| qoder_error("OpenCode root"))?;
+ if object.contains_key("providers") {
+ return Err(qoder_error("OpenCode provider layout"));
+ }
+ if let Some(providers) = object.remove("provider") {
+ object.insert("providers".into(), providers);
+ }
+ Ok(root)
} else {
Ok(document(current)?.root.value)
}
@@ -118,13 +141,22 @@ fn edit_provider(
if kind == AgentKindV1::DeepseekHarness {
return super::dsh_config::Patch::parse(Some(bytes))?.edit_provider(id, provider);
}
- let document = document(Some(bytes))?;
- if let Some(providers) = document.object(&document.root, "providers")? {
+ let document = if kind == AgentKindV1::OpenCode {
+ Document::parse_with_trailing_commas(bytes, true)?
+ } else {
+ document(Some(bytes))?
+ };
+ let key = if kind == AgentKindV1::OpenCode {
+ "provider"
+ } else {
+ "providers"
+ };
+ if let Some(providers) = document.object(&document.root, key)? {
document.edit(&providers, id, provider)
} else {
document.edit(
&document.root,
- "providers",
+ key,
Some(&serde_json::json!({(id):provider})),
)
}
@@ -140,6 +172,9 @@ pub(super) fn validate_configuration(
) -> Result<(), QoderNativeError> {
validate_declaration(kind, provider_id, endpoint, models)?;
let document = native_root(kind, current)?;
+ if kind == AgentKindV1::OpenCode && super::opencode::dynamic_keys(&document) {
+ return Err(qoder_error("OpenCode dynamic configuration keys"));
+ }
let desired: BTreeSet<_> = models
.iter()
.map(|m| hiroute_domain::additional_model_provider_for(provider_id, models, m))
@@ -162,7 +197,7 @@ pub(super) fn validate_configuration(
})
.collect();
for id in previous.owned_providers().keys() {
- default_not_removed(&document, id, &retain)?;
+ default_not_removed(kind, &document, id, &retain)?;
}
}
for id in desired {
@@ -176,10 +211,20 @@ pub(super) fn validate_configuration(
}
fn default_not_removed(
+ kind: AgentKindV1,
document: &Value,
provider: &str,
retain: &BTreeSet<String>,
) -> Result<(), QoderNativeError> {
+ if kind == AgentKindV1::OpenCode {
+ return super::opencode::validate_references(
+ document,
+ provider,
+ &document["providers"][provider],
+ retain,
+ Some(&[]),
+ );
+ }
let Some(model) = document.get("model") else {
return Ok(());
};
@@ -230,6 +275,8 @@ pub(super) fn configure(
|| {
Zeroizing::new(if kind == AgentKindV1::DeepseekHarness {
b"[]\n".to_vec()
+ } else if kind == AgentKindV1::OpenCode {
+ br#"{"$schema":"https://opencode.ai/config.json"}"#.to_vec()
} else {
b"{}".to_vec()
})
@@ -243,7 +290,9 @@ pub(super) fn configure(
bytes = edit_provider(kind, &bytes, &id, Some(&provider))?;
}
let restore = Restore {
- schema: if kind == AgentKindV1::DeepseekHarness {
+ schema: if kind == AgentKindV1::OpenCode {
+ "hiroute.opencode-native-restore/v2"
+ } else if kind == AgentKindV1::DeepseekHarness {
"hiroute.dsh-native-restore/v2"
} else if kind == AgentKindV1::Pi {
"hiroute.pi-native-restore/v2"
@@ -283,6 +332,11 @@ fn render_provider(
})
.collect::<Result<Vec<_>, _>>()?;
qoder_provider::provider(endpoint, credential, models, protocol)?
+ } else if kind == AgentKindV1::OpenCode {
+ if models.len() != 1 {
+ return Err(qoder_error("OpenCode per-plan provider"));
+ }
+ super::opencode_provider(endpoint, &models[0], "hiroute-local", Some(credential))?
} else {
let models = models
.iter()
@@ -317,6 +371,7 @@ impl Restore {
}
"hiroute.pi-native-restore/v1" | "hiroute.pi-native-restore/v2" => Ok(AgentKindV1::Pi),
"hiroute.dsh-native-restore/v2" => Ok(AgentKindV1::DeepseekHarness),
+ "hiroute.opencode-native-restore/v2" => Ok(AgentKindV1::OpenCode),
_ => Err(qoder_error("restore schema")),
}
}
@@ -433,7 +488,7 @@ impl Restore {
let document = native_root(self.kind()?, current)?;
if check_default {
for id in self.owned_providers().keys() {
- default_not_removed(&document, id, &BTreeSet::new())?;
+ default_not_removed(self.kind()?, &document, id, &BTreeSet::new())?;
}
}
if current.is_none() && !self.original_exists {
diff --git a/crates/integrations/src/agents/additional_native/README.md b/crates/integrations/src/agents/additional_native/README.md
index e8e480b5..4194f67a 100644
--- a/crates/integrations/src/agents/additional_native/README.md
+++ b/crates/integrations/src/agents/additional_native/README.md
@@ -6,13 +6,13 @@ application owns authorization, grants, publication and restore ordering; native
leaves own effective configuration, model budgets and result interpretation.
See the [Agent map](../../../../../docs/code-map/README.md) before changing owners.
-| Native boundary | Qoder | Pi | DSH |
-| --- | --- | --- | --- |
-| Selected user target | `QODER_CONFIG_DIR/settings.json` | `PI_CODING_AGENT_DIR/models.json` (effective HOME fallback) | `DSH_HOME/profiles/web/cordis.patch.yml` |
-| Model declaration / budget | [Qoder provider](../qoder_provider.rs), [Plan budget](../qoder_budget.rs) | [Shared provider renderer](../additional_native.rs), [Pi Plan budget](../qoder_budget.rs) | [Public YAML leaf](../dsh_config.rs), [shared budget](../qoder_budget.rs) |
-| Separate default dependency | `model.name` in the target file | `defaultProvider/defaultModel` in user `settings.json` | `agent-default-model` in Web and home patches; home provider shadowing is refused |
-| Ordinary Gateway authentication | Dedicated `/_hiroute/qoder/v1` bearer channel | `/v1`, fixed `X-HiRoute-Token` header; saved native auth may override ordinary Bearer | Fixed `X-HiRoute-Token` header; Responses base ends in `/v1`, Messages base does not |
-| Actual native acceptance | [Qoder journeys](../../../../../tools/product-e2e/tests/QODER_DELEGATION.md) | [Pi journeys](../../../../../tools/product-e2e/tests/PI_INTEGRATION.md) | [DSH journeys](../../../../../tools/product-e2e/tests/DSH_INTEGRATION.md) |
+| Native boundary | Qoder | Pi | DSH | OpenCode |
+| --- | --- | --- | --- | --- |
+| Selected user target | `QODER_CONFIG_DIR/settings.json` | `PI_CODING_AGENT_DIR/models.json` (effective HOME fallback) | `DSH_HOME/profiles/web/cordis.patch.yml` | Absolute `OPENCODE_CONFIG`, otherwise additive config directory or XDG config root; existing JSONC/JSON target |
+| Model declaration / budget | [Qoder provider](../qoder_provider.rs), [Plan budget](../qoder_budget.rs) | [Shared provider renderer](../additional_native.rs), [Pi Plan budget](../qoder_budget.rs) | [Public YAML leaf](../dsh_config.rs), [shared budget](../qoder_budget.rs) | [Singular provider renderer/context](../opencode.rs), shared Pi numeric budget policy |
+| Separate default dependency | `model.name` in the target file | `defaultProvider/defaultModel` in user `settings.json` | `agent-default-model` in Web and home patches; home provider shadowing is refused | Effective user-layer `model`, `small_model`, agent/mode models, provider overrides and allow/deny lists |
+| Ordinary Gateway authentication | Dedicated `/_hiroute/qoder/v1` bearer channel | `/v1`, fixed `X-HiRoute-Token` header; saved native auth may override ordinary Bearer | Fixed `X-HiRoute-Token` header; Responses base ends in `/v1`, Messages base does not | Both SDKs use `/v1` and fixed `X-HiRoute-Token`; inert SDK API-key placeholder |
+| Actual native acceptance | [Qoder journeys](../../../../../tools/product-e2e/tests/QODER_DELEGATION.md) | [Pi journeys](../../../../../tools/product-e2e/tests/PI_INTEGRATION.md) | [DSH journeys](../../../../../tools/product-e2e/tests/DSH_INTEGRATION.md) | [OpenCode journeys](../../../../../tools/product-e2e/tests/OPENCODE_INTEGRATION.md) |
Main-Agent configuration adds only selected Plan aliases. It leaves native defaults,
purpose routing, extensions, hooks, MCP and Skills to their existing owners. The
@@ -24,8 +24,8 @@ A native provider name alone never grants ownership of an existing user entry.
- [Native edits](../additional_native.rs) enforce the independent namespace,
semantic ownership, default reference and encrypted restore binding.
- [JSONC edits](../qoder_jsonc.rs) preserve unrelated bytes and comments. The name
- is historical; it is the single bounded parser/editor for Qoder/Pi. DSH uses
- its static YAML leaf below.
+ is historical; it is the single bounded parser/editor for Qoder/Pi/OpenCode. Only
+ OpenCode enables native object/array trailing commas. DSH uses its static YAML leaf below.
Ambiguous duplicate keys, invalid JSON and oversized files fail closed. Line
comments accept LF/CRLF; standalone CR and Unicode line separators are rejected
because native readers disagree about where such comments end.
@@ -43,7 +43,7 @@ A native provider name alone never grants ownership of an existing user entry.
keeps installed declarations compatible with publication changes and blocks a
second mutation while the original operation has a pending tail. Only the exact active
grant generation retained in the next publication owns a declaration. All affected
- Qoder/Pi/DSH contexts are reported with their Plan ID/alias, declared/proposed context
+ Qoder/Pi/DSH/OpenCode contexts are reported with their Plan ID/alias, declared/proposed context
and output, or a distinct missing/uncomputable reason. Sharing an upstream binding
does not establish a Plan dependency.
@@ -60,7 +60,7 @@ retain the released closed error shape. This presentation flag is outside the
change spec and confirmation digest and never grants write authority. `operations.find` emits
these facts only when `include_model_budget_conflict=true`; omitted/false requests
retain the old strict response shape. Existing operation inputs, grant formats,
-SQL schema and native settings formats are unchanged.
+SQL schema and existing native settings formats are unchanged by this diagnostic.
The prepared local grant is written only to the private native provider, mode
0600. Public journals contain no bearer or original native settings. Status reads
@@ -68,7 +68,8 @@ use the protected artifact port; restoration can still remove an owned secret
following permission drift. Preserve existing Qoder journal/restore wire strings
as registered recovery contracts; Pi/DSH use their current closed kinds. Current
multi-provider writes produce V2 restore records; V1 remains a registered reader
-for historical single-provider writes.
+for historical single-provider writes. OpenCode has its own current V2 restore
+discriminator, retaining the same protected ownership and recovery engine.
## Adjustment and recovery
diff --git a/crates/integrations/src/agents/additional_native_effects.rs b/crates/integrations/src/agents/additional_native_effects.rs
index d89277a7..047c47eb 100644
--- a/crates/integrations/src/agents/additional_native_effects.rs
+++ b/crates/integrations/src/agents/additional_native_effects.rs
@@ -145,6 +145,7 @@ fn stage(
Some("agent_qoder_default") => AgentKindV1::Qoder,
Some("agent_pi_default") => AgentKindV1::Pi,
Some("agent_dsh_default") => AgentKindV1::DeepseekHarness,
+ Some("agent_opencode_default") => AgentKindV1::OpenCode,
_ => return Err(error(PortErrorCode::InvalidData, "additional.native.kind")),
};
let edit = additional_native::configure(
diff --git a/crates/integrations/src/agents/filesystem.rs b/crates/integrations/src/agents/filesystem.rs
index 67747087..b9088a46 100644
--- a/crates/integrations/src/agents/filesystem.rs
+++ b/crates/integrations/src/agents/filesystem.rs
@@ -35,6 +35,8 @@ mod claude_settings;
mod dsh_native;
#[path = "claude_observation.rs"]
mod main_observation;
+#[path = "opencode_scanner.rs"]
+mod opencode_scanner;
#[path = "pi_native.rs"]
mod pi_native;
#[path = "qoder_discovery.rs"]
@@ -130,6 +132,8 @@ pub struct AgentFilesystemLayoutV1 {
pub qoder_executable: PathBuf,
pub pi_executable: PathBuf,
pub pi_config_root: PathBuf,
+ pub opencode_executable: PathBuf,
+ pub opencode_context: Option<super::OpenCodeNativeContext>,
pub dsh_executable: PathBuf,
pub dsh_config_root: PathBuf,
pub qoder_home: PathBuf,
@@ -179,6 +183,8 @@ impl AgentFilesystemLayoutV1 {
qoder_executable: PathBuf::from("qoder"),
pi_executable: PathBuf::from("pi"),
dsh_executable: PathBuf::from("dsh"),
+ opencode_executable: PathBuf::from("opencode"),
+ opencode_context: super::OpenCodeNativeContext::from_environment(home).ok(),
dsh_config_root: std::env::var_os("DSH_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
@@ -222,6 +228,7 @@ pub struct FilesystemAgentScannerV1 {
std::sync::Arc<std::sync::Mutex<Option<(PathBuf, hiroute_domain::CanonicalDigest)>>>,
dsh_collaboration_cli: std::sync::Arc<std::sync::Mutex<Option<(PathBuf, CanonicalDigest)>>>,
pub(super) layout: AgentFilesystemLayoutV1,
+ opencode_model_target: PathBuf,
registry: ClaudeRegistrationIndexV1,
legacy_recovery_version: Option<String>,
legacy_process_format: bool,
@@ -230,6 +237,8 @@ pub struct FilesystemAgentScannerV1 {
#[cfg(any(unix, windows))]
claude_ingress: std::sync::Arc<std::sync::Mutex<Option<super::ClaudeIngressEvidence>>>,
#[cfg(any(unix, windows))]
+ opencode_collaboration: std::sync::Arc<std::sync::Mutex<super::opencode_probe::ProofCache>>,
+ #[cfg(any(unix, windows))]
qoder_collaboration: std::sync::Arc<std::sync::Mutex<super::qoder_probe::QoderProofCache>>,
}
@@ -277,8 +286,14 @@ impl FilesystemAgentScannerV1 {
pub fn new(mut layout: AgentFilesystemLayoutV1, registry: ClaudeRegistrationIndexV1) -> Self {
layout.codex_user_config = super::canonical_codex_config_path(&layout.codex_user_config);
+ let opencode_model_target = layout
+ .opencode_context
+ .as_ref()
+ .map(|context| context.model_target())
+ .unwrap_or_default();
Self {
layout,
+ opencode_model_target,
registry,
legacy_recovery_version: None,
legacy_process_format: false,
@@ -288,6 +303,8 @@ impl FilesystemAgentScannerV1 {
claude_ingress: Default::default(),
#[cfg(any(unix, windows))]
qoder_collaboration: Default::default(),
+ #[cfg(any(unix, windows))]
+ opencode_collaboration: Default::default(),
pi_collaboration_cli: Default::default(),
dsh_collaboration_cli: Default::default(),
}
@@ -398,6 +415,7 @@ impl FilesystemAgentScannerV1 {
self.qoder_settings_discovery(false),
self.pi_settings_discovery(),
self.dsh_settings_discovery(),
+ self.opencode_settings_discovery(),
];
match executable_probe(&self.layout.claude_executable) {
ExecutableProbe::Installed(executable) => {
@@ -435,6 +453,7 @@ impl FilesystemAgentScannerV1 {
AgentKindV1::Qoder
| AgentKindV1::Pi
| AgentKindV1::DeepseekHarness
+ | AgentKindV1::OpenCode
| AgentKindV1::Hermes => continue,
};
#[cfg(any(unix, windows))]
@@ -503,6 +522,9 @@ impl FilesystemAgentScannerV1 {
&self,
descriptor: &DiscoveredCredentialRefV1,
) -> Result<ProtectedSecret, AgentFilesystemScanError> {
+ if descriptor.field_selector == "opencode.api-key" {
+ return self.read_opencode_secret(descriptor);
+ }
if descriptor.field_selector == "pi.api-key" {
return self.read_pi_secret(descriptor);
}
@@ -575,6 +597,7 @@ impl FilesystemAgentScannerV1 {
| hiroute_domain::AgentModelSurfaceV2::QoderCli
| hiroute_domain::AgentModelSurfaceV2::PiCli
| hiroute_domain::AgentModelSurfaceV2::DshCli
+ | hiroute_domain::AgentModelSurfaceV2::OpenCodeCli
| hiroute_domain::AgentModelSurfaceV2::HermesCli => None,
}
}
@@ -607,6 +630,9 @@ impl FilesystemAgentScannerV1 {
.into_iter()
.collect()
}
+ "agent_opencode_default" if self.opencode_executable_target().is_some() => {
+ [hiroute_domain::AgentModelSurfaceV2::OpenCodeCli].into()
+ }
"agent_dsh_default" if self.dsh_executable_target().is_some() => {
[hiroute_domain::AgentModelSurfaceV2::DshCli].into()
}
diff --git a/crates/integrations/src/agents/filesystem_tests.rs b/crates/integrations/src/agents/filesystem_tests.rs
index adccdc6b..39d3796a 100644
--- a/crates/integrations/src/agents/filesystem_tests.rs
+++ b/crates/integrations/src/agents/filesystem_tests.rs
@@ -81,6 +81,10 @@ fn layout_with_claude_version(root: &Path, claude_version: &str) -> AgentFilesys
write_executable(&codex, "codex-cli diagnostic-build");
write_executable(&claude, &format!("{claude_version} (Claude Code)"));
AgentFilesystemLayoutV1 {
+ opencode_context: Some(
+ crate::agents::OpenCodeNativeContext::from_lookup(root, |_| None).unwrap(),
+ ),
+ opencode_executable: root.join("missing-opencode"),
codex_executable: codex,
codex_desktop_executable: None,
claude_executable: claude,
@@ -1053,3 +1057,6 @@ mod layer_tests;
#[path = "filesystem_tests/managed_launch.rs"]
mod managed_launch_tests;
+
+#[path = "filesystem_tests/opencode.rs"]
+mod opencode_tests;
diff --git a/crates/integrations/src/agents/filesystem_tests/opencode.rs b/crates/integrations/src/agents/filesystem_tests/opencode.rs
new file mode 100644
index 00000000..a8b68ee6
--- /dev/null
+++ b/crates/integrations/src/agents/filesystem_tests/opencode.rs
@@ -0,0 +1,401 @@
+use super::*;
+fn scanner(root: &Path) -> FilesystemAgentScannerV1 {
+ let mut layout = layout(root);
+ layout.opencode_context =
+ Some(crate::agents::OpenCodeNativeContext::from_lookup(root, |_| None).unwrap());
+ FilesystemAgentScannerV1::new(layout, registry())
+}
+fn declaration() -> serde_json::Value {
+ json!({"$schema":"https://opencode.ai/config.json","provider":{"ordinary":{"npm":"@ai-sdk/openai","options":{"baseURL":"http://127.0.0.1:4222/v1","apiKey":"static-only"},"models":{"explicit":{"limit":{"context":16384,"output":4096}}}}}})
+}
+
+#[test]
+fn opencode_provider_credential_failures_do_not_hide_independent_sources_or_relax_stale_reads() {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ let secret = root.path().join("broken.key");
+ let mut value = declaration();
+ let mut broken = value["provider"]["ordinary"].clone();
+ broken["options"]["apiKey"] = json!(format!("{{file:{}}}", secret.display()));
+ value["provider"]["a-broken"] = broken;
+ write_secret_settings(&scanner.opencode_user_models_target(), value.clone());
+ for bytes in [vec![0xff], vec![b'x'; 1024 * 1024 + 1]] {
+ std::fs::write(&secret, bytes).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o600)).unwrap();
+ }
+ assert_independent_source(&scanner);
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{PermissionsExt, symlink};
+ std::fs::write(&secret, b"native-public-key").unwrap();
+ std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o000)).unwrap();
+ if std::fs::read(&secret).is_err() {
+ // Root may bypass POSIX read permissions; exercise a real read denial.
+ assert_independent_source(&scanner);
+ }
+ std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o600)).unwrap();
+ std::fs::remove_file(&secret).unwrap();
+ let target = root.path().join("target.key");
+ std::fs::write(&target, b"native-linked-key").unwrap();
+ symlink(target, &secret).unwrap();
+ assert_independent_source(&scanner);
+ }
+ let selected = scanner
+ .opencode_api_sources()
+ .unwrap()
+ .into_iter()
+ .find(|s| s.provider_id == "ordinary")
+ .unwrap();
+ value["provider"]["ordinary"]["options"]["apiKey"] = json!("changed-independent-key");
+ write_secret_settings(&scanner.opencode_user_models_target(), value);
+ assert!(scanner.read_opencode_api_source(&selected).is_err());
+}
+
+fn assert_independent_source(scanner: &FilesystemAgentScannerV1) {
+ let sources = scanner.opencode_api_sources().unwrap();
+ assert_eq!(sources.len(), 2);
+ let broken = sources
+ .iter()
+ .find(|s| s.provider_id == "a-broken")
+ .unwrap();
+ assert!(!broken.supported_auth && broken.credential.is_none());
+ assert!(scanner.read_opencode_api_source(broken).is_err());
+ let valid = sources
+ .iter()
+ .find(|s| s.provider_id == "ordinary")
+ .unwrap();
+ assert!(valid.supported_auth && valid.credential.is_some());
+ assert_eq!(
+ scanner.read_opencode_api_source(valid).unwrap().1.expose(),
+ b"static-only"
+ );
+}
+
+#[test]
+fn opencode_discovers_the_official_home_entry_without_executing_or_replacing_a_selection() {
+ let root = tempfile::tempdir().unwrap();
+ let mut scanner = scanner(root.path());
+ let entry = root.path().join(".opencode/bin/opencode");
+ std::fs::create_dir_all(entry.parent().unwrap()).unwrap();
+ // Invalid process bytes are intentional: passive discovery must not execute them.
+ std::fs::write(&entry, b"metadata-only discovery fixture").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ scanner.layout.opencode_executable = "opencode".into();
+ let primary =
+ crate::agents::opencode_native_executable(std::path::Path::new("opencode")).unwrap();
+ assert_eq!(
+ scanner.opencode_executable_target(),
+ primary.or_else(|| Some(std::fs::canonicalize(&entry).unwrap()))
+ );
+ assert!(matches!(
+ scanner.opencode_settings_discovery().outcome,
+ AgentDiscoveryOutcomeV1::Supported { .. }
+ ));
+ // Losing a saved installation cannot switch the user's Agent to this fallback.
+ scanner.layout.opencode_executable = root.path().join("explicitly-selected-but-missing");
+ assert!(scanner.opencode_executable_target().is_none());
+}
+
+#[test]
+fn opencode_dynamic_configuration_keys_are_scoped_out_of_models_workers_and_import() {
+ let root = tempfile::tempdir().unwrap();
+ let search_path = crate::agents::native_ingress_probe::native_probe_path();
+ assert!(
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(root.path())
+ .env_clear()
+ .env("HOME", root.path())
+ .env("PATH", &search_path)
+ .status()
+ .unwrap()
+ .success()
+ );
+ let scanner = scanner(root.path());
+ for (section, dynamic_key) in [
+ ("root", "{env:CONFIG_SECTION}"),
+ ("provider", "{file:provider-name.txt}"),
+ ("agent", "{env:AGENT_NAME}"),
+ ] {
+ let mut value = declaration();
+ if section == "root" {
+ value[dynamic_key] = json!([]);
+ } else {
+ value[section][dynamic_key] = json!({});
+ }
+ write_secret_settings(&scanner.opencode_user_models_target(), value);
+ let model_rejected = scanner
+ .opencode_model_dependencies("hiroute-main-test", &[])
+ .is_err();
+ let native = scanner.opencode_native_context().unwrap();
+ let config = native.read_config(None).unwrap();
+ let worker_rejected = crate::agents::validate_opencode_composition(
+ native,
+ &config,
+ root.path(),
+ search_path.to_str().unwrap(),
+ )
+ .is_err();
+ let sources = scanner.opencode_api_sources().unwrap();
+ let import_rejected = !sources.is_empty()
+ && sources
+ .iter()
+ .all(|source| !source.supported_auth && source.credential.is_none());
+ assert_eq!(
+ (model_rejected, worker_rejected, import_rejected),
+ (true, true, true),
+ "{section}"
+ );
+ }
+}
+#[test]
+fn opencode_static_import_is_secret_free_and_rejects_stale_credential_reads() {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ write_secret_settings(&scanner.opencode_user_models_target(), declaration());
+ let sources = scanner.opencode_api_sources().unwrap();
+ assert_eq!(sources.len(), 1);
+ let source = &sources[0];
+ assert!(source.supported_auth);
+ assert!(
+ !serde_json::to_string(source)
+ .unwrap()
+ .contains("static-only")
+ );
+ let (endpoint, key) = scanner.read_opencode_api_source(source).unwrap();
+ assert_eq!(endpoint.as_str(), "http://127.0.0.1:4222/v1");
+ assert_eq!(key.expose(), b"static-only");
+ let mut changed = declaration();
+ changed["provider"]["ordinary"]["options"]["apiKey"] = "rotated".into();
+ write_secret_settings(&scanner.opencode_user_models_target(), changed);
+ assert!(scanner.read_opencode_api_source(source).is_err());
+}
+#[test]
+fn opencode_dynamic_options_and_oauth_remain_non_importable() {
+ for option in ["headers", "fetch", "region"] {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ let mut value = declaration();
+ value["provider"]["ordinary"]["options"][option] = json!({"unsafe":"must-not-run"});
+ write_secret_settings(&scanner.opencode_user_models_target(), value);
+ assert!(
+ scanner.opencode_api_sources().unwrap()[0]
+ .credential
+ .is_none()
+ );
+ }
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ write_secret_settings(&scanner.opencode_user_models_target(), declaration());
+ let native = scanner.opencode_native_context().unwrap();
+ write_secret_settings(
+ &native.data_root.join("auth.json"),
+ json!({"ordinary":{"type":"oauth","access":"never-copy"}}),
+ );
+ assert!(
+ scanner.opencode_api_sources().unwrap()[0]
+ .credential
+ .is_none()
+ );
+}
+
+#[test]
+fn opencode_review_substituted_model_ids_cannot_be_imported_as_literals() {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ for id in [
+ "{env:UPSTREAM_MODEL}",
+ "{file:model-id.txt}",
+ "prefix-{env:UPSTREAM_MODEL}",
+ ] {
+ let mut value = declaration();
+ value["provider"]["ordinary"]["models"]["explicit"]["id"] = json!(id);
+ write_secret_settings(&scanner.opencode_user_models_target(), value);
+ let sources = scanner.opencode_api_sources().unwrap();
+ assert_eq!(sources.len(), 1);
+ assert!(!sources[0].supported_auth, "{id}");
+ assert!(sources[0].credential.is_none());
+ assert!(scanner.read_opencode_api_source(&sources[0]).is_err());
+ }
+ write_secret_settings(&scanner.opencode_user_models_target(), declaration());
+ let sources = scanner.opencode_api_sources().unwrap();
+ assert!(sources[0].supported_auth);
+ assert!(scanner.read_opencode_api_source(&sources[0]).is_ok());
+}
+
+#[test]
+fn opencode_model_target_stays_bound_and_explicit_selectors_have_no_alternative() {
+ let root = tempfile::tempdir().unwrap();
+ let native = crate::agents::OpenCodeNativeContext::from_lookup(root.path(), |_| None).unwrap();
+ let json = native.config_root.join("opencode.json");
+ write_secret_settings(&json, declaration());
+ let scanner = scanner(root.path());
+ write_secret_settings(&json.with_extension("jsonc"), json!({}));
+ assert_eq!(scanner.opencode_user_models_target(), json);
+ assert_eq!(
+ scanner.opencode_model_target_candidates(),
+ vec![json.clone(), json.with_extension("jsonc")]
+ );
+
+ let explicit_root = tempfile::tempdir().unwrap();
+ let mut layout = layout(explicit_root.path());
+ let selected = explicit_root.path().join("explicit.json");
+ layout.opencode_context = Some(
+ crate::agents::OpenCodeNativeContext::from_lookup(explicit_root.path(), |key| {
+ (key == "OPENCODE_CONFIG").then(|| selected.clone().into_os_string())
+ })
+ .unwrap(),
+ );
+ let mut explicit = FilesystemAgentScannerV1::new(layout, registry());
+ assert_eq!(explicit.opencode_model_target_candidates(), vec![selected]);
+ let unselected_sibling = explicit
+ .opencode_native_context()
+ .unwrap()
+ .config_root
+ .join("opencode.jsonc");
+ assert!(
+ explicit
+ .bind_opencode_model_target(unselected_sibling)
+ .is_err()
+ );
+}
+#[test]
+fn opencode_settings_dependencies_detect_layer_changes_and_owned_provider_shadowing() {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ let native = scanner.opencode_native_context().unwrap();
+ let a = scanner
+ .opencode_model_dependencies("hiroute-main-test", &[])
+ .unwrap();
+ write_secret_settings(
+ &native.config_root.join("config.json"),
+ json!({"small_model":"daily/small"}),
+ );
+ let b = scanner
+ .opencode_model_dependencies("hiroute-main-test", &[])
+ .unwrap();
+ assert_ne!(a, b);
+ write_secret_settings(
+ &native.config_root.join("config.json"),
+ json!({"provider":{"hiroute-main-test":{"options":{"apiKey":"foreign"}}}}),
+ );
+ assert!(
+ scanner
+ .opencode_model_dependencies("hiroute-main-test", &[])
+ .is_err()
+ );
+}
+
+#[test]
+fn opencode_default_reference_conflict_is_a_preview_fact_and_a_stage_rejection() {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ let native = scanner.opencode_native_context().unwrap();
+ write_secret_settings(
+ &scanner.opencode_user_models_target(),
+ json!({"provider":{"hiroute-main-test":{"models":{"route":{}}}}}),
+ );
+ write_secret_settings(
+ &native.config_root.join("config.json"),
+ json!({"small_model":"hiroute-main-test/route"}),
+ );
+ let (_, in_use) = scanner
+ .opencode_model_facts("hiroute-main-test", &[])
+ .unwrap();
+ assert!(
+ in_use,
+ "Preview must retain a closed, actionable reference conflict"
+ );
+ assert!(
+ scanner
+ .opencode_model_dependencies("hiroute-main-test", &[])
+ .is_err(),
+ "staging must reject the dangling reference"
+ );
+}
+
+#[test]
+fn opencode_restore_file_capabilities_survive_a_missing_executable_and_bad_model_json() {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ write_secret_settings(
+ &scanner.opencode_user_models_target(),
+ json!({"provider":{}}),
+ );
+ std::fs::write(
+ scanner.opencode_user_models_target(),
+ b"malformed daily model configuration",
+ )
+ .unwrap();
+ let discovery = scanner.opencode_settings_discovery();
+ let AgentDiscoveryOutcomeV1::Supported { installation } = discovery.outcome else {
+ panic!("existing files must remain recoverable");
+ };
+ assert!(installation.capability_evidence.iter().any(|p| p.capability
+ == hiroute_domain::AgentCapability::AtomicManagedReplace
+ && p.state == hiroute_domain::CapabilityState::Proven));
+ assert!(scanner.opencode_executable_target().is_none());
+}
+
+#[test]
+fn opencode_connection_points_group_native_bindings_and_recheck_rotated_secrets() {
+ let root = tempfile::tempdir().unwrap();
+ let scanner = scanner(root.path());
+ let mut value = declaration();
+ value["model"] = json!("ordinary/explicit");
+ value["provider"]["ordinary"]["models"]["second"] =
+ json!({"limit":{"context":16384,"output":4096}});
+ value["provider"]["ordinary"]["models"]["messages"] =
+ json!({"provider":{"npm":"@ai-sdk/anthropic"}});
+ write_secret_settings(&scanner.opencode_user_models_target(), value.clone());
+ let sources = scanner.opencode_api_sources().unwrap();
+ let points = crate::agents::native_api_connection_points(sources);
+ assert_eq!(points.len(), 2);
+ let responses = points
+ .iter()
+ .find(|p| p.protocol() == Some(hiroute_domain::UpstreamProtocol::Responses))
+ .unwrap();
+ assert_eq!(responses.sources.len(), 2);
+ assert_eq!(
+ responses.sources[0]
+ .point_binding
+ .as_ref()
+ .unwrap()
+ .configured_default_model_id
+ .as_deref(),
+ Some("explicit")
+ );
+ assert!(points.iter().any(|p| p.protocol()
+ == Some(hiroute_domain::UpstreamProtocol::Messages)
+ && p.sources.len() == 1));
+ value["provider"]["ordinary"]["options"]["apiKey"] = json!("rotated-point-key");
+ write_secret_settings(&scanner.opencode_user_models_target(), value);
+ let fresh =
+ crate::agents::native_api_connection_points(scanner.opencode_api_sources().unwrap());
+ let updated = fresh
+ .iter()
+ .find(|p| p.key_digest == responses.key_digest)
+ .unwrap();
+ assert_ne!(updated.snapshot_digest, responses.snapshot_digest);
+ assert!(
+ scanner
+ .read_opencode_api_source(&responses.sources[0])
+ .is_err()
+ );
+ assert_eq!(
+ scanner
+ .read_opencode_api_source(&updated.sources[0])
+ .unwrap()
+ .1
+ .expose(),
+ b"rotated-point-key"
+ );
+}
diff --git a/crates/integrations/src/agents/mod.rs b/crates/integrations/src/agents/mod.rs
index 6053ddd5..2edeec3d 100644
--- a/crates/integrations/src/agents/mod.rs
+++ b/crates/integrations/src/agents/mod.rs
@@ -61,10 +61,22 @@ mod dsh_sources;
mod dsh_tests;
mod native_points;
mod observed_capabilities;
+mod opencode;
+mod opencode_installation;
+mod opencode_migrations;
+mod opencode_project;
+mod opencode_resources;
+mod opencode_sources;
+#[cfg(test)]
+mod opencode_tests;
+pub use opencode::{
+ OpenCodeConfig, OpenCodeNativeContext, opencode_provider, validate_opencode_composition,
+};
+pub use opencode_installation::{opencode_native_executable, opencode_native_format};
mod pi_runtime;
mod pi_sources;
pub use native_points::*;
-pub use pi_sources::{NativeApiSource, PiApiSource};
+pub use pi_sources::{NativeApiEcosystem, NativeApiSource, PiApiSource};
mod qoder;
pub use pi_runtime::*;
mod additional_native;
@@ -72,7 +84,13 @@ mod additional_native_effects;
mod qoder_provider;
pub use additional_native_effects::*;
#[cfg(any(unix, windows))]
+mod native_responses_probe;
+#[cfg(any(unix, windows))]
+mod opencode_probe;
+#[cfg(any(unix, windows))]
mod qoder_probe;
+#[cfg(any(unix, windows))]
+pub use opencode_probe::OpenCodeCollaborationProbe;
mod registration;
mod registry;
mod source_candidates;
diff --git a/crates/integrations/src/agents/native_probe_process.rs b/crates/integrations/src/agents/native_probe_process.rs
index 44884151..9fa4c2d3 100644
--- a/crates/integrations/src/agents/native_probe_process.rs
+++ b/crates/integrations/src/agents/native_probe_process.rs
@@ -13,6 +13,8 @@ use std::path::Path;
use std::process::Child;
use std::time::{Duration, Instant};
+use hiroute_domain::delegation::NativeDependencyFailureReasonV1 as Reason;
+
pub struct NativeProbeProcess {
child: Child,
#[cfg(unix)]
@@ -127,6 +129,69 @@ impl Drop for NativeProbeProcess {
}
}
+/// Shared bounded one-shot output capture; the caller selects the command/environment.
+#[cfg(unix)]
+pub(super) fn capture(
+ mut command: std::process::Command,
+ _inherit: bool,
+ timeout: std::time::Duration,
+ output_limit: usize,
+) -> Result<zeroize::Zeroizing<Vec<u8>>, Reason> {
+ use std::os::unix::process::CommandExt;
+ use std::process::Stdio;
+ use std::time::{Duration, Instant};
+ let start = Instant::now();
+ let capture = tempfile::NamedTempFile::new().map_err(|_| Reason::Unavailable)?;
+ let child = command
+ .stdin(Stdio::null())
+ .stdout(capture.reopen().map_err(|_| Reason::Unavailable)?)
+ .stderr(Stdio::null())
+ .process_group(0)
+ .spawn()
+ .map_err(|_| Reason::Unavailable)?;
+ let mut child = super::NativeProbeProcess::new(child);
+ let result = (|| {
+ loop {
+ if start.elapsed() >= timeout {
+ return Err(Reason::Timeout);
+ }
+ match child.observe().map_err(|_| Reason::Unavailable)? {
+ Some(true) => break,
+ Some(false) => return Err(Reason::ProcessFailed),
+ None => {}
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ super::native_probe_process::read_bounded(capture.path(), output_limit)
+ .map_err(|_| Reason::InvalidOutput)
+ })();
+ // A failed check also stops and accounts for its owned scope before returning.
+ child.stop().map_err(|_| Reason::CleanupFailed)?;
+ result
+}
+
+#[cfg(windows)]
+pub(super) fn capture(
+ command: std::process::Command,
+ inherit: bool,
+ timeout: std::time::Duration,
+ output_limit: usize,
+) -> Result<zeroize::Zeroizing<Vec<u8>>, Reason> {
+ super::windows_runtime::bounded(&command, inherit, timeout, output_limit).map_err(|error| {
+ if super::windows_runtime::cleanup_unknown(&error) {
+ Reason::CleanupFailed
+ } else if super::windows_runtime::process_exit_code(&error).is_some() {
+ Reason::ProcessFailed
+ } else {
+ match error.kind() {
+ std::io::ErrorKind::TimedOut => Reason::Timeout,
+ std::io::ErrorKind::InvalidData => Reason::InvalidOutput,
+ _ => Reason::Unavailable,
+ }
+ }
+ })
+}
+
/// Rechecks the limit during the final read, including children that write and exit between polls.
pub(super) fn read_bounded(path: &Path, limit: usize) -> io::Result<zeroize::Zeroizing<Vec<u8>>> {
let mut bytes = zeroize::Zeroizing::new(Vec::new());
diff --git a/crates/integrations/src/agents/native_responses_probe.rs b/crates/integrations/src/agents/native_responses_probe.rs
new file mode 100644
index 00000000..b7146cbc
--- /dev/null
+++ b/crates/integrations/src/agents/native_responses_probe.rs
@@ -0,0 +1,141 @@
+//! Shared bounded Responses peer for explicit native collaboration checks.
+use serde_json::{Value, json};
+use std::io::{Read, Write};
+use std::net::TcpStream;
+use std::time::{Duration, Instant};
+
+pub(super) fn serve(
+ stream: &mut TcpStream,
+ token: &str,
+ model: &str,
+ reply: impl FnOnce(&Value) -> Result<Value, &'static str>,
+) -> Result<(), &'static str> {
+ let body = read_request(stream, token, model)?;
+ let item = reply(&body)?;
+ let response = json!({"id":"resp_hiroute_probe", "object":"response", "created_at":1, "status":"completed", "model":model, "output":[item], "usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}});
+ let mut started = response.clone();
+ started["status"] = "in_progress".into();
+ started["output"] = json!([]);
+ let mut added = item.clone();
+ added["status"] = "in_progress".into();
+ let mut events = vec![("response.created", json!({"response":started}))];
+ if item["type"] == "function_call" {
+ // Qoder validates streaming argument consistency; adding the final arguments and then
+ // appending a delta would duplicate them and fail before any tool executes.
+ added["arguments"] = "".into();
+ events.push((
+ "response.output_item.added",
+ json!({"output_index":0,"item":added}),
+ ));
+ events.push((
+ "response.function_call_arguments.delta",
+ json!({"output_index":0,"item_id":item["id"],"delta":item["arguments"]}),
+ ));
+ events.push((
+ "response.function_call_arguments.done",
+ json!({"output_index":0,"item_id":item["id"],"arguments":item["arguments"]}),
+ ));
+ } else {
+ added["content"] = json!([]);
+ events.push((
+ "response.output_item.added",
+ json!({"output_index":0,"item":added}),
+ ));
+ events.push((
+ "response.output_text.delta",
+ json!({"output_index":0,"content_index":0,"item_id":item["id"],"delta":"OK"}),
+ ));
+ }
+ events.push((
+ "response.output_item.done",
+ json!({"output_index":0,"item":item}),
+ ));
+ events.push(("response.completed", json!({"response":response})));
+ let mut payload = String::new();
+ for (index, (kind, mut event)) in events.into_iter().enumerate() {
+ event["type"] = kind.into();
+ event["sequence_number"] = index.into();
+ payload.push_str(&format!("event: {kind}\ndata: {event}\n\n"));
+ }
+ write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",payload.len()).map_err(|_| "loopback response")
+}
+
+fn read_request(stream: &mut TcpStream, token: &str, model: &str) -> Result<Value, &'static str> {
+ stream.set_nonblocking(false).map_err(|_| "socket mode")?;
+ stream
+ .set_read_timeout(Some(Duration::from_millis(500)))
+ .map_err(|_| "socket timeout")?;
+ stream
+ .set_write_timeout(Some(Duration::from_millis(500)))
+ .map_err(|_| "socket timeout")?;
+ let started = Instant::now();
+ let mut bytes = zeroize::Zeroizing::new(Vec::new());
+ let (header_end, length) = loop {
+ if bytes.len() > 128 * 1024 || started.elapsed() > Duration::from_secs(2) {
+ return Err("request bound");
+ }
+ if let Some(end) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
+ let header = std::str::from_utf8(&bytes[..end]).map_err(|_| "request header")?;
+ if header.lines().next() != Some("POST /v1/responses HTTP/1.1") {
+ return Err("request path");
+ }
+ let mut auth = None;
+ let mut length = None;
+ for line in header.lines().skip(1) {
+ let (name, value) = line.split_once(':').ok_or("request header")?;
+ if name.eq_ignore_ascii_case("authorization")
+ && auth.replace(value.trim()).is_some()
+ {
+ return Err("duplicate auth");
+ }
+ if name.eq_ignore_ascii_case("content-length")
+ && length
+ .replace(
+ value
+ .trim()
+ .parse::<usize>()
+ .map_err(|_| "request length")?,
+ )
+ .is_some()
+ {
+ return Err("duplicate length");
+ }
+ if name.eq_ignore_ascii_case("transfer-encoding") {
+ return Err("request framing");
+ }
+ }
+ if auth.and_then(|value| value.strip_prefix("Bearer ")) != Some(token) {
+ return Err("request credential");
+ }
+ break (
+ end + 4,
+ length
+ .filter(|value| *value <= 128 * 1024)
+ .ok_or("request length")?,
+ );
+ }
+ let mut chunk = [0; 4096];
+ let size = stream.read(&mut chunk).map_err(|_| "request header read")?;
+ if size == 0 {
+ return Err("short request");
+ }
+ bytes.extend_from_slice(&chunk[..size]);
+ };
+ while bytes.len() < header_end + length {
+ if started.elapsed() > Duration::from_secs(2) {
+ return Err("request deadline");
+ }
+ let mut chunk = [0; 4096];
+ let size = stream.read(&mut chunk).map_err(|_| "request body read")?;
+ if size == 0 {
+ return Err("short request");
+ }
+ bytes.extend_from_slice(&chunk[..size]);
+ }
+ let body: Value = serde_json::from_slice(&bytes[header_end..header_end + length])
+ .map_err(|_| "request json")?;
+ if body["model"] != model {
+ return Err("request model");
+ }
+ Ok(body)
+}
diff --git a/crates/integrations/src/agents/observed_capabilities.rs b/crates/integrations/src/agents/observed_capabilities.rs
index fdbd2d34..1c1c4989 100644
--- a/crates/integrations/src/agents/observed_capabilities.rs
+++ b/crates/integrations/src/agents/observed_capabilities.rs
@@ -17,6 +17,19 @@ pub(super) fn attach_file_capabilities(
);
}
+/// Recovery/file editing remains available when a selected native executable disappears.
+pub(super) fn attach_optional_file_capabilities(
+ installation: &mut SupportedAgentInstallationV1,
+ executable: Option<&Path>,
+ target: &Path,
+) {
+ attach_capabilities(
+ installation,
+ dependencies(executable, target),
+ "hiroute.native-files/v1",
+ );
+}
+
/// Settings support is derived from the selected configuration target only. A concrete
/// executable is located separately; its inode, digest, release or version is not a save gate.
pub(super) fn attach_target_file_capabilities(
@@ -117,7 +130,36 @@ fn attach_capabilities(
}
#[cfg(unix)]
-fn dependencies(executable: Option<&Path>, target: &Path) -> Result<(CanonicalDigest, bool), ()> {
+pub(super) fn dependencies(
+ executable: Option<&Path>,
+ target: &Path,
+) -> Result<(CanonicalDigest, bool), ()> {
+ unix_dependencies(executable, target, None)
+}
+
+/// Native Skill checks already confirm these exact bytes and validate the native read receipt.
+/// A ctime-only bookkeeping change is not a new Skill; identity, permissions, links, size and
+/// mtime remain dependencies. Ordinary configuration/Preview keeps its existing version tuple.
+pub(super) fn content_bound_dependencies(
+ executable: Option<&Path>,
+ target: &Path,
+ confirmed_content: &CanonicalDigest,
+) -> Result<(CanonicalDigest, bool), ()> {
+ #[cfg(unix)]
+ return unix_dependencies(executable, target, Some(confirmed_content));
+ #[cfg(not(unix))]
+ {
+ let _ = confirmed_content;
+ dependencies(executable, target)
+ }
+}
+
+#[cfg(unix)]
+fn unix_dependencies(
+ executable: Option<&Path>,
+ target: &Path,
+ confirmed_content: Option<&CanonicalDigest>,
+) -> Result<(CanonicalDigest, bool), ()> {
use std::os::unix::fs::MetadataExt;
let file_identity = |metadata: &std::fs::Metadata| {
(
@@ -182,13 +224,37 @@ fn dependencies(executable: Option<&Path>, target: &Path) -> Result<(CanonicalDi
&& file.as_ref().is_none_or(|metadata| {
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.nlink() == 1
});
- let digest = CanonicalDigest::of(&(
- binary,
- target,
- file.as_ref().map(file_identity),
- parent,
- directory_identity(&parent_metadata),
- ))
+ let digest = if let Some(content) = confirmed_content {
+ let skill_identity = file.as_ref().map(|metadata| {
+ (
+ metadata.dev(),
+ metadata.ino(),
+ metadata.uid(),
+ metadata.gid(),
+ metadata.mode(),
+ metadata.nlink(),
+ metadata.len(),
+ metadata.mtime(),
+ metadata.mtime_nsec(),
+ )
+ });
+ CanonicalDigest::of(&(
+ binary,
+ target,
+ skill_identity,
+ parent,
+ directory_identity(&parent_metadata),
+ content,
+ ))
+ } else {
+ CanonicalDigest::of(&(
+ binary,
+ target,
+ file.as_ref().map(file_identity),
+ parent,
+ directory_identity(&parent_metadata),
+ ))
+ }
.map_err(|_| ())?;
Ok((digest, replace))
}
@@ -197,6 +263,85 @@ fn dependencies(executable: Option<&Path>, target: &Path) -> Result<(CanonicalDi
mod tests {
use super::*;
+ #[test]
+ fn confirmed_skill_content_ignores_ctime_only_churn_and_retains_native_guards() {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ let root = tempfile::tempdir().unwrap();
+ let target = root.path().join("SKILL.md");
+ std::fs::write(&target, b"original Skill body\n").unwrap();
+ std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)).unwrap();
+ let content = CanonicalDigest::of_bytes(b"original Skill body\n");
+ let original = std::fs::metadata(&target).unwrap();
+ let strict = dependencies(None, &target).unwrap();
+ let confirmed = content_bound_dependencies(None, &target, &content).unwrap();
+ // Reproduce the observed native read: ctime changed while bytes, inode,
+ // access policy and mtime remained identical. chmod with the same policy
+ // provides this metadata event without depending on a macOS background service.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
+ let after = loop {
+ std::fs::set_permissions(&target, original.permissions()).unwrap();
+ let after = std::fs::metadata(&target).unwrap();
+ if (original.ctime(), original.ctime_nsec()) != (after.ctime(), after.ctime_nsec()) {
+ break after;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "filesystem ctime did not advance"
+ );
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ };
+ assert_eq!(original.modified().unwrap(), after.modified().unwrap());
+ assert_ne!(strict.0, dependencies(None, &target).unwrap().0);
+ assert_eq!(
+ confirmed,
+ content_bound_dependencies(None, &target, &content).unwrap()
+ );
+
+ std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o640)).unwrap();
+ assert_ne!(
+ confirmed.0,
+ content_bound_dependencies(None, &target, &content)
+ .unwrap()
+ .0
+ );
+ std::fs::set_permissions(&target, original.permissions()).unwrap();
+ let parent_permissions = std::fs::metadata(root.path()).unwrap().permissions();
+ std::fs::set_permissions(root.path(), std::fs::Permissions::from_mode(0o750)).unwrap();
+ assert_ne!(
+ confirmed.0,
+ content_bound_dependencies(None, &target, &content)
+ .unwrap()
+ .0
+ );
+ std::fs::set_permissions(root.path(), parent_permissions).unwrap();
+
+ std::fs::write(&target, b"modified Skill body\n").unwrap();
+ std::fs::File::open(&target)
+ .unwrap()
+ .set_times(std::fs::FileTimes::new().set_modified(original.modified().unwrap()))
+ .unwrap();
+ let changed = CanonicalDigest::of_bytes(b"modified Skill body\n");
+ assert_ne!(
+ confirmed.0,
+ content_bound_dependencies(None, &target, &changed)
+ .unwrap()
+ .0
+ );
+ std::fs::rename(&target, root.path().join("previous.md")).unwrap();
+ std::fs::write(&target, b"original Skill body\n").unwrap();
+ std::fs::set_permissions(&target, original.permissions()).unwrap();
+ std::fs::File::open(&target)
+ .unwrap()
+ .set_times(std::fs::FileTimes::new().set_modified(original.modified().unwrap()))
+ .unwrap();
+ assert_ne!(
+ confirmed.0,
+ content_bound_dependencies(None, &target, &content)
+ .unwrap()
+ .0
+ );
+ }
+
#[test]
fn parent_sibling_churn_does_not_change_native_dependency() {
let root = tempfile::tempdir().unwrap();
@@ -251,7 +396,10 @@ fn dependencies(_executable: Option<&Path>, _target: &Path) -> Result<(Canonical
}
#[cfg(windows)]
-fn dependencies(executable: Option<&Path>, target: &Path) -> Result<(CanonicalDigest, bool), ()> {
+pub(super) fn dependencies(
+ executable: Option<&Path>,
+ target: &Path,
+) -> Result<(CanonicalDigest, bool), ()> {
use hiroute_platform::file_security::capture;
use hiroute_platform::windows::security::{file_identity, file_link_count, open_identity};
use std::os::windows::fs::MetadataExt;
diff --git a/crates/integrations/src/agents/opencode.rs b/crates/integrations/src/agents/opencode.rs
new file mode 100644
index 00000000..f3fff1d8
--- /dev/null
+++ b/crates/integrations/src/agents/opencode.rs
@@ -0,0 +1,750 @@
+//! OpenCode's native path selectors and bounded static configuration, shared by consumers.
+use std::collections::BTreeSet;
+use std::ffi::OsString;
+use std::path::{Component, Path, PathBuf};
+
+use hiroute_domain::CanonicalDigest;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::{AgentFilesystemScanError as Error, QoderNativeError, qoder_error};
+
+#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct OpenCodeNativeContext {
+ pub home: PathBuf,
+ pub config_root: PathBuf,
+ pub data_root: PathBuf,
+ pub cache_root: PathBuf,
+ pub state_root: PathBuf,
+ pub config_file: Option<PathBuf>,
+ pub extra_config_root: Option<PathBuf>,
+ pub database: PathBuf,
+}
+
+impl OpenCodeNativeContext {
+ pub fn from_environment(home: &Path) -> Result<Self, QoderNativeError> {
+ Self::from_lookup(home, |name| std::env::var_os(name))
+ }
+
+ pub fn from_lookup(
+ home: &Path,
+ lookup: impl Fn(&str) -> Option<OsString>,
+ ) -> Result<Self, QoderNativeError> {
+ checked_path(home)?;
+ let root = |key: &str, fallback: &str| -> Result<PathBuf, QoderNativeError> {
+ let path = lookup(key)
+ .filter(|s| !s.is_empty())
+ .map(PathBuf::from)
+ .unwrap_or_else(|| home.join(fallback));
+ checked_path(&path)?;
+ Ok(path.join("opencode"))
+ };
+ let selected = |key: &str| -> Result<Option<PathBuf>, QoderNativeError> {
+ lookup(key)
+ .filter(|s| !s.is_empty())
+ .map(PathBuf::from)
+ .map(|p| checked_path(&p).map(|_| p))
+ .transpose()
+ };
+ let data_root = root("XDG_DATA_HOME", ".local/share")?;
+ let database = match lookup("OPENCODE_DB").filter(|s| !s.is_empty()) {
+ Some(value) => {
+ if value == ":memory:" {
+ return Err(qoder_error("nonresumable OpenCode database"));
+ }
+ let path = PathBuf::from(value);
+ if path.is_absolute() {
+ path
+ } else {
+ data_root.join(path)
+ }
+ }
+ None => data_root.join("opencode.db"),
+ };
+ checked_path(&database)?;
+ Ok(Self {
+ home: home.to_owned(),
+ config_root: root("XDG_CONFIG_HOME", ".config")?,
+ data_root,
+ cache_root: root("XDG_CACHE_HOME", ".cache")?,
+ state_root: root("XDG_STATE_HOME", ".local/state")?,
+ config_file: selected("OPENCODE_CONFIG")?,
+ extra_config_root: selected("OPENCODE_CONFIG_DIR")?,
+ database,
+ })
+ }
+
+ pub fn validate(&self) -> Result<(), QoderNativeError> {
+ for path in [
+ &self.home,
+ &self.config_root,
+ &self.data_root,
+ &self.cache_root,
+ &self.state_root,
+ &self.database,
+ ]
+ .into_iter()
+ .chain(self.config_file.iter())
+ .chain(self.extra_config_root.iter())
+ {
+ checked_path(path)?;
+ }
+ Ok(())
+ }
+
+ pub fn resource_root(&self) -> &Path {
+ self.extra_config_root
+ .as_deref()
+ .unwrap_or(&self.config_root)
+ }
+ pub fn skill_target(&self) -> PathBuf {
+ self.resource_root()
+ .join("skills/hiroute-collaboration/SKILL.md")
+ }
+ pub fn model_target(&self) -> PathBuf {
+ if let Some(path) = &self.config_file {
+ return path.clone();
+ }
+ let root = self.resource_root();
+ let jsonc = root.join("opencode.jsonc");
+ let json = root.join("opencode.json");
+ if !jsonc.exists() && json.exists() {
+ json
+ } else {
+ jsonc
+ }
+ }
+
+ /// Native merge order, restricted to the chosen user and optional project ancestry.
+ /// Project inspection requires the actual filtered Worker PATH, not the host environment.
+ pub fn config_paths(
+ &self,
+ workspace: Option<(&Path, &str)>,
+ ) -> Result<Vec<PathBuf>, QoderNativeError> {
+ let mut paths = vec![
+ self.config_root.join("config.json"),
+ self.config_root.join("opencode.json"),
+ self.config_root.join("opencode.jsonc"),
+ ];
+ paths.extend(self.config_file.iter().cloned());
+ if let Some((workspace, search_path)) = workspace {
+ checked_path(workspace)?;
+ let mut ancestry = project_ancestry(self, workspace, search_path)?;
+ ancestry.reverse();
+ for root in &ancestry {
+ paths.extend([root.join("opencode.json"), root.join("opencode.jsonc")]);
+ }
+ for root in ancestry.iter().rev() {
+ paths.extend([
+ root.join(".opencode/opencode.json"),
+ root.join(".opencode/opencode.jsonc"),
+ ]);
+ }
+ }
+ paths.extend([
+ self.home.join(".opencode/opencode.json"),
+ self.home.join(".opencode/opencode.jsonc"),
+ ]);
+ if let Some(root) = &self.extra_config_root {
+ paths.extend([root.join("opencode.json"), root.join("opencode.jsonc")]);
+ }
+ let mut seen = BTreeSet::new();
+ paths.retain(|p| seen.insert(p.clone()));
+ Ok(paths)
+ }
+
+ pub fn has_remote_configuration(&self) -> Result<bool, Error> {
+ if std::env::var_os("OPENCODE_CONFIG_CONTENT").is_some_and(|v| !v.is_empty())
+ || std::env::var_os("OPENCODE_TEST_MANAGED_CONFIG_DIR").is_some()
+ {
+ return Ok(true);
+ }
+ #[cfg(target_os = "macos")]
+ {
+ let username = nix::unistd::User::from_uid(nix::unistd::getuid())
+ .map_err(|_| Error::SourceUnavailable)?
+ .ok_or(Error::SourceUnavailable)?
+ .name;
+ if [
+ PathBuf::from("/Library/Application Support/opencode"),
+ PathBuf::from("/Library/Managed Preferences/ai.opencode.managed.plist"),
+ PathBuf::from("/Library/Managed Preferences")
+ .join(username)
+ .join("ai.opencode.managed.plist"),
+ ]
+ .iter()
+ .any(|p| p.exists())
+ {
+ return Ok(true);
+ }
+ }
+ #[cfg(target_os = "linux")]
+ if Path::new("/etc/opencode").exists() {
+ return Ok(true);
+ }
+ #[cfg(windows)]
+ if std::env::var_os("ProgramData")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
+ .join("opencode")
+ .exists()
+ {
+ return Ok(true);
+ }
+
+ // Native account configuration is stored in SQLite, not a guessed account file.
+ // Read only the active-organization flag; never credentials or conversation rows.
+ if self
+ .database
+ .try_exists()
+ .map_err(|_| Error::SourceUnavailable)?
+ {
+ let meta =
+ std::fs::symlink_metadata(&self.database).map_err(|_| Error::SourceUnavailable)?;
+ if !meta.is_file() || meta.file_type().is_symlink() {
+ return Err(Error::InvalidConfig);
+ }
+ let db = rusqlite::Connection::open_with_flags(
+ &self.database,
+ rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY
+ | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )
+ .map_err(|_| Error::SourceUnavailable)?;
+ db.busy_timeout(std::time::Duration::from_millis(100))
+ .map_err(|_| Error::SourceUnavailable)?;
+ let remote: bool = db.query_row(
+ "SELECT EXISTS(SELECT 1 FROM account_state WHERE id=1 AND active_account_id IS NOT NULL AND active_org_id IS NOT NULL)",
+ [], |r| r.get(0)).map_err(|_| Error::InvalidConfig)?;
+ if remote {
+ return Ok(true);
+ }
+ }
+ if let Some((bytes, _)) =
+ super::filesystem_config::read_system_config_bytes(&self.data_root.join("auth.json"))?
+ {
+ let mut value: Value =
+ serde_json::from_slice(&bytes).map_err(|_| Error::InvalidConfig)?;
+ let remote = value
+ .as_object()
+ .is_none_or(|o| o.values().any(|v| v["type"] == "wellknown"));
+ super::pi_sources::clear_native_value(&mut value);
+ return Ok(remote);
+ }
+ Ok(false)
+ }
+
+ pub fn read_config(&self, workspace: Option<(&Path, &str)>) -> Result<OpenCodeConfig, Error> {
+ let mut value = serde_json::json!({});
+ let mut documents = Vec::new();
+ let mut schemas_complete = true;
+ let mut executable_plugins = false;
+ for path in self
+ .config_paths(workspace)
+ .map_err(|_| Error::InvalidConfig)?
+ {
+ let raw = super::filesystem_config::read_system_config_bytes(&path)?;
+ let Some((bytes, _)) = raw else {
+ continue;
+ };
+ let parsed = parse_jsonc(&bytes).map_err(|_| Error::InvalidConfig)?;
+ executable_plugins |= parsed
+ .get("plugin")
+ .is_some_and(|v| v.as_array().is_none_or(|v| !v.is_empty()));
+ // The native loader expands substitutions before testing schema truthiness
+ // and writes back to the borrowed file when the result is empty.
+ schemas_complete &= parsed
+ .get("$schema")
+ .and_then(Value::as_str)
+ .is_some_and(|schema| !schema.is_empty() && !substitution(schema));
+ merge(&mut value, parsed);
+ documents.push((path, CanonicalDigest::of_bytes(&bytes)));
+ }
+ for root in [self.config_root.clone(), self.home.join(".opencode")]
+ .into_iter()
+ .chain(self.extra_config_root.iter().cloned())
+ {
+ for name in ["plugin", "plugins"] {
+ match std::fs::read_dir(root.join(name)) {
+ Ok(mut entries) => executable_plugins |= entries.next().is_some(),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(_) => return Err(Error::SourceUnavailable),
+ }
+ }
+ }
+ let digest = CanonicalDigest::of(&documents).map_err(|_| Error::InvalidConfig)?;
+ Ok(OpenCodeConfig {
+ value,
+ documents,
+ digest,
+ schemas_complete,
+ executable_plugins,
+ })
+ }
+
+ pub(super) fn resource_roots(
+ &self,
+ workspace: Option<(&Path, &str)>,
+ ) -> Result<Vec<PathBuf>, QoderNativeError> {
+ let mut roots = vec![self.config_root.clone()];
+ if let Some((workspace, search_path)) = workspace {
+ roots.extend(
+ project_ancestry(self, workspace, search_path)?
+ .iter()
+ .map(|p| p.join(".opencode")),
+ );
+ }
+ roots.push(self.home.join(".opencode"));
+ roots.extend(self.extra_config_root.iter().cloned());
+ let mut seen = BTreeSet::new();
+ roots.retain(|p| seen.insert(p.clone()));
+ Ok(roots)
+ }
+}
+
+pub struct OpenCodeConfig {
+ pub value: Value,
+ pub documents: Vec<(PathBuf, CanonicalDigest)>,
+ pub digest: CanonicalDigest,
+ pub schemas_complete: bool,
+ pub executable_plugins: bool,
+}
+impl Drop for OpenCodeConfig {
+ fn drop(&mut self) {
+ super::pi_sources::clear_native_value(&mut self.value);
+ }
+}
+
+pub(super) fn parse_jsonc(bytes: &[u8]) -> Result<Value, QoderNativeError> {
+ super::additional_native::parse_opencode_jsonc(bytes)
+}
+
+fn merge(target: &mut Value, source: Value) {
+ match (target, source) {
+ (Value::Object(left), Value::Object(right)) => {
+ for (key, value) in right {
+ if key == "instructions"
+ && let (Some(old), Some(new)) = (
+ left.get_mut(&key).and_then(Value::as_array_mut),
+ value.as_array(),
+ )
+ {
+ for item in new {
+ if !old.contains(item) {
+ old.push(item.clone());
+ }
+ }
+ } else {
+ merge(left.entry(key).or_insert(Value::Null), value);
+ }
+ }
+ }
+ (target, source) => *target = source,
+ }
+}
+
+fn checked_path(path: &Path) -> Result<(), QoderNativeError> {
+ if !path.is_absolute()
+ || path.components().any(|p| matches!(p, Component::ParentDir))
+ || path.to_str().is_none_or(|s| s.contains(['\0', '\r', '\n']))
+ {
+ return Err(qoder_error("OpenCode context path"));
+ }
+ Ok(())
+}
+
+/// A bounded inspection is complete only at the same worktree/root stop as native.
+fn project_ancestry(
+ native: &OpenCodeNativeContext,
+ workspace: &Path,
+ search_path: &str,
+) -> Result<Vec<PathBuf>, QoderNativeError> {
+ checked_path(workspace)?;
+ let mut roots = Vec::new();
+ for root in workspace.ancestors().take(64) {
+ roots.push(root.to_owned());
+ if root
+ .join(".git")
+ .try_exists()
+ .map_err(|_| qoder_error("OpenCode project ancestry"))?
+ {
+ super::opencode_project::confirm_root(native, root, search_path)?;
+ return Ok(roots);
+ }
+ if root.parent().is_none() {
+ return Ok(roots);
+ }
+ }
+ Err(qoder_error("OpenCode project ancestry bound"))
+}
+
+/// Shared native SDK declaration. Ordinary grants use their independent fixed header.
+pub fn opencode_provider(
+ endpoint: &str,
+ model: &hiroute_domain::AdditionalAgentModelV1,
+ api_key: &str,
+ local_grant: Option<&str>,
+) -> Result<Value, QoderNativeError> {
+ model
+ .validate_pi()
+ .map_err(|_| qoder_error("OpenCode budget"))?;
+ let sdk = match model.protocol {
+ hiroute_domain::AgentIngressProtocolV1::Responses => "@ai-sdk/openai",
+ hiroute_domain::AgentIngressProtocolV1::Messages => "@ai-sdk/anthropic",
+ hiroute_domain::AgentIngressProtocolV1::ChatCompletions => {
+ return Err(qoder_error("OpenCode routing protocol"));
+ }
+ };
+ let mut options = serde_json::json!({"baseURL":endpoint,"apiKey":api_key});
+ if let Some(grant) = local_grant {
+ options["headers"] = serde_json::json!({"X-HiRoute-Token":grant});
+ }
+ Ok(
+ serde_json::json!({"npm":sdk,"name":"HiRoute","options":options,"models":{(model.alias.clone()):{
+ "id":model.alias,"name":model.alias,"tool_call":true,"modalities":{"input":["text"],"output":["text"]},
+ "limit":{"context":model.context_window_tokens,"output":model.max_output_tokens},"options":{"store":false}
+ }}}),
+ )
+}
+
+fn substitution(value: &str) -> bool {
+ value.contains("{env:") || value.contains("{file:")
+}
+
+/// Native substitutions run before JSON parsing, including inside object keys.
+/// Keep ambiguous structure outside the bounded reader rather than guessing its expansion.
+pub(super) fn dynamic_keys(value: &Value) -> bool {
+ match value {
+ Value::Object(entries) => entries
+ .iter()
+ .any(|(key, value)| substitution(key) || dynamic_keys(value)),
+ Value::Array(values) => values.iter().any(dynamic_keys),
+ _ => false,
+ }
+}
+
+pub(super) fn validate_references(
+ value: &Value,
+ provider: &str,
+ provider_value: &Value,
+ retain: &BTreeSet<String>,
+ resource_models: Option<&[String]>,
+) -> Result<(), QoderNativeError> {
+ if dynamic_keys(value) {
+ return Err(qoder_error("OpenCode dynamic configuration keys"));
+ }
+ let removes_model = provider_value["models"].as_object().is_none_or(|models| {
+ models
+ .keys()
+ .any(|model| !retain.contains(&format!("{provider}/{model}")))
+ });
+ let mut refs = Vec::new();
+ for key in ["model", "small_model"] {
+ if let Some(v) = value.get(key) {
+ refs.push(v);
+ }
+ }
+ for key in ["agent", "mode"] {
+ if let Some(entries) = value.get(key) {
+ for entry in entries
+ .as_object()
+ .ok_or_else(|| qoder_error("OpenCode agents"))?
+ .values()
+ {
+ if let Some(v) = entry.get("model") {
+ refs.push(v);
+ }
+ }
+ }
+ }
+ if removes_model && resource_models.is_none() {
+ // Unknown native frontmatter cannot authorize deleting a model selector.
+ return Err(qoder_error("default in use"));
+ }
+ let check = |selector: &str| {
+ if removes_model && substitution(selector) {
+ return Err(qoder_error("OpenCode dynamic model selector"));
+ }
+ if selector.starts_with(&format!("{provider}/")) && !retain.contains(selector) {
+ return Err(qoder_error("default in use"));
+ }
+ Ok(())
+ };
+ for value in refs {
+ check(
+ value
+ .as_str()
+ .ok_or_else(|| qoder_error("OpenCode model selector"))?,
+ )?;
+ }
+ for selector in resource_models.unwrap_or_default() {
+ check(selector)?;
+ }
+ Ok(())
+}
+
+pub fn validate_opencode_composition(
+ native: &OpenCodeNativeContext,
+ config: &OpenCodeConfig,
+ workspace: &Path,
+ search_path: &str,
+) -> Result<(), QoderNativeError> {
+ let unavailable = || qoder_error("unsupported OpenCode native composition");
+ if dynamic_keys(&config.value)
+ || std::env::var_os("OPENCODE_TEST_MANAGED_CONFIG_DIR").is_some()
+ || std::env::var_os("OPENCODE_CONFIG_CONTENT").is_some_and(|v| !v.is_empty())
+ || config
+ .value
+ .get("mode")
+ .is_some_and(|v| v.as_object().is_none_or(|o| !o.is_empty()))
+ || config.value["skills"]
+ .get("urls")
+ .is_some_and(|v| v.as_array().is_none_or(|v| !v.is_empty()))
+ {
+ return Err(unavailable());
+ }
+ if config.value.get("enabled_providers").is_some() || config.value.get("server").is_some() {
+ return Err(unavailable());
+ }
+ if !config.schemas_complete
+ || native
+ .has_remote_configuration()
+ .map_err(|_| unavailable())?
+ {
+ return Err(unavailable());
+ }
+ if config.value["agent"].as_object().is_some_and(|agents| {
+ agents.values().any(|agent| {
+ ["options", "permission", "tools", "mode"]
+ .iter()
+ .any(|key| agent.get(key).is_some())
+ })
+ }) {
+ return Err(unavailable());
+ }
+ if native.config_root.join("config").exists() {
+ return Err(unavailable());
+ }
+ for root in native.resource_roots(Some((workspace, search_path)))? {
+ for dir in ["tool", "tools", "agent", "agents", "mode", "modes"] {
+ match std::fs::read_dir(root.join(dir)) {
+ Ok(entries) => {
+ if entries.take(1).next().is_some() {
+ return Err(unavailable());
+ }
+ }
+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(unavailable()),
+ _ => {}
+ }
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn project_ancestry_requires_a_proven_native_stop_within_the_bound() {
+ let root = tempfile::tempdir().unwrap();
+ let base = root.path().canonicalize().unwrap();
+ let native = OpenCodeNativeContext::from_lookup(&base, |_| None).unwrap();
+ let search_path = super::super::native_ingress_probe::native_probe_path()
+ .into_string()
+ .unwrap();
+ git(&native, &base, &["init", "-q"], &search_path);
+ let at_limit = (0..63).fold(base.clone(), |path, _| path.join("d"));
+ std::fs::create_dir_all(&at_limit).unwrap();
+ assert_eq!(
+ project_ancestry(&native, &at_limit, &search_path)
+ .unwrap()
+ .len(),
+ 64
+ );
+ assert!(project_ancestry(&native, &at_limit.join("d"), &search_path).is_err());
+ std::fs::remove_dir_all(base.join(".git")).unwrap();
+ assert!(project_ancestry(&native, &at_limit, &search_path).is_err());
+ }
+
+ fn git(native: &OpenCodeNativeContext, cwd: &Path, args: &[&str], path: &str) {
+ let candidate = std::env::split_paths(std::ffi::OsStr::new(path))
+ .map(|dir| dir.join(if cfg!(windows) { "git.exe" } else { "git" }))
+ .find(|path| path.is_file())
+ .unwrap();
+ let binary = super::super::executable::resolve(&candidate)
+ .unwrap()
+ .unwrap();
+ let mut command = std::process::Command::new(binary);
+ command
+ .args(args)
+ .current_dir(cwd)
+ .env_clear()
+ .env("HOME", &native.home)
+ .env("PATH", path);
+ super::super::native_probe_process::capture(
+ command,
+ false,
+ std::time::Duration::from_secs(5),
+ 4096,
+ )
+ .unwrap();
+ }
+
+ #[test]
+ fn opencode_real_git_and_linked_worktree_stop_before_foreign_ancestor_config_and_tools() {
+ let root = tempfile::tempdir().unwrap();
+ let base = root.path().canonicalize().unwrap();
+ let home = base.join("home");
+ #[cfg(not(windows))]
+ let repository = base.join("repository space'Ω ");
+ #[cfg(windows)]
+ let repository = base.join("repository space'Ω");
+ std::fs::create_dir(&home).unwrap();
+ std::fs::create_dir(&repository).unwrap();
+ let native = OpenCodeNativeContext::from_lookup(&home, |_| None).unwrap();
+ let search_path = super::super::native_ingress_probe::native_probe_path()
+ .into_string()
+ .unwrap();
+ git(&native, &repository, &["init", "-q"], &search_path);
+ git(
+ &native,
+ &repository,
+ &[
+ "-c",
+ "user.name=Fixture",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ "commit",
+ "--allow-empty",
+ "-qm",
+ "fixture",
+ ],
+ &search_path,
+ );
+ let linked = base.join("linked");
+ git(
+ &native,
+ &repository,
+ &[
+ "worktree",
+ "add",
+ "--detach",
+ linked.to_str().unwrap(),
+ "HEAD",
+ ],
+ &search_path,
+ );
+ let foreign_config = base.join("opencode.json");
+ let foreign_bytes = br#"{"$schema":"","server":{"port":9}}"#;
+ std::fs::write(&foreign_config, foreign_bytes).unwrap();
+ std::fs::create_dir_all(base.join(".opencode/tools")).unwrap();
+ let tool = base.join(".opencode/tools/custom.ts");
+ std::fs::write(&tool, b"throw new Error('outside confirmed native root')").unwrap();
+ for project in [&repository, &linked] {
+ let workspace = project.join("nested");
+ std::fs::create_dir(&workspace).unwrap();
+ let config = native
+ .read_config(Some((&workspace, &search_path)))
+ .unwrap();
+ assert!(
+ validate_opencode_composition(&native, &config, &workspace, &search_path).is_ok()
+ );
+ assert!(
+ !config
+ .documents
+ .iter()
+ .any(|(path, _)| path == &foreign_config)
+ );
+ assert_eq!(
+ project_ancestry(&native, &workspace, &search_path).unwrap(),
+ [workspace.clone(), project.to_owned()]
+ );
+ #[cfg(windows)]
+ {
+ // The production workspace owner uses ordinary Win32 spelling;
+ // Rust canonicalize returns a verbatim spelling of the same root.
+ let text = workspace.to_str().unwrap();
+ let ordinary = Path::new(text.strip_prefix(r"\\?\").unwrap_or(text));
+ assert!(project_ancestry(&native, ordinary, &search_path).is_ok());
+ }
+ assert_eq!(std::fs::read(&foreign_config).unwrap(), foreign_bytes);
+ assert!(!native.database.exists());
+ }
+ // Git can report a different worktree through local configuration. On
+ // Unix its trailing space must not be trimmed into the marker's root.
+ #[cfg(not(windows))]
+ let redirected = PathBuf::from(format!("{} ", repository.display()));
+ #[cfg(windows)]
+ let redirected = base.join("redirected-worktree");
+ std::fs::create_dir(&redirected).unwrap();
+ git(
+ &native,
+ &repository,
+ &["config", "core.worktree", redirected.to_str().unwrap()],
+ &search_path,
+ );
+ assert!(
+ native
+ .read_config(Some((&repository, &search_path)))
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn context_selectors_are_additive_and_database_is_data_relative() {
+ let home = super::super::test_absolute_path("/native");
+ let extra = home.join("extra");
+ let context = OpenCodeNativeContext::from_lookup(&home, |key| match key {
+ "OPENCODE_CONFIG_DIR" => Some(extra.clone().into_os_string()),
+ "OPENCODE_DB" => Some("worker.db".into()),
+ _ => None,
+ })
+ .unwrap();
+ assert_eq!(context.config_root, home.join(".config/opencode"));
+ assert_eq!(
+ context.database,
+ home.join(".local/share/opencode/worker.db")
+ );
+ assert_eq!(
+ context.skill_target(),
+ extra.join("skills/hiroute-collaboration/SKILL.md")
+ );
+ assert!(
+ context
+ .config_paths(None)
+ .unwrap()
+ .contains(&home.join(".config/opencode/config.json"))
+ );
+ assert!(OpenCodeNativeContext::from_lookup(&home, |_| Some("relative".into())).is_err());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn opencode_git_fixtures_filter_relative_host_paths_in_an_isolated_child() {
+ let inherited = std::env::var_os("PATH").unwrap();
+ let path = std::env::join_paths(
+ [PathBuf::from("."), PathBuf::from("relative/bin")]
+ .into_iter()
+ .chain(std::env::split_paths(&inherited)),
+ )
+ .unwrap();
+ let mut command = std::process::Command::new(std::env::current_exe().unwrap());
+ command
+ .args(["--exact", "agents::opencode::tests::opencode_real_git_and_linked_worktree_stop_before_foreign_ancestor_config_and_tools"])
+ .env("PATH", path);
+ let output = super::super::native_probe_process::capture(
+ command,
+ true,
+ std::time::Duration::from_secs(15),
+ 16 * 1024,
+ )
+ .unwrap();
+ assert!(
+ std::str::from_utf8(&output)
+ .unwrap()
+ .contains("1 passed; 0 failed")
+ );
+ }
+}
diff --git a/crates/integrations/src/agents/opencode_installation.rs b/crates/integrations/src/agents/opencode_installation.rs
new file mode 100644
index 00000000..2cb4f7a5
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_installation.rs
@@ -0,0 +1,203 @@
+//! Metadata-only OpenCode native installation selection, never wrapper execution or hashing.
+use super::{QoderNativeError, qoder_error};
+use serde_json::Value;
+use std::path::{Path, PathBuf};
+
+fn package(root: &Path) -> Result<Option<Value>, QoderNativeError> {
+ let Some((bytes, _)) =
+ super::filesystem_config::read_system_config_bytes(&root.join("package.json"))
+ .map_err(|_| qoder_error("OpenCode package metadata"))?
+ else {
+ return Ok(None);
+ };
+ if bytes.len() > 64 * 1024 {
+ return Err(qoder_error("OpenCode package metadata bound"));
+ }
+ serde_json::from_slice(&bytes)
+ .map(Some)
+ .map_err(|_| qoder_error("OpenCode package metadata"))
+}
+
+/// Resolves the explicitly located official npm wrapper to a single declared native package.
+/// A directly selected standalone binary remains selectable without format capability.
+pub fn opencode_native_executable(selected: &Path) -> Result<Option<PathBuf>, QoderNativeError> {
+ let Some(path) =
+ super::executable::resolve(selected).map_err(|_| qoder_error("OpenCode executable"))?
+ else {
+ return Ok(None);
+ };
+ #[cfg(windows)]
+ let path = if path
+ .extension()
+ .is_some_and(|e| e.as_encoded_bytes().eq_ignore_ascii_case(b"cmd"))
+ {
+ let mut identities = Vec::new();
+ let entry = super::windows_runtime::windows_npm_entry_with_inspection(&path, |path| {
+ identities.push(hiroute_platform::windows::security::open_identity(
+ path, false,
+ )?);
+ Ok(())
+ })
+ .map_err(|_| qoder_error("OpenCode npm entry"))?;
+ super::executable::resolve(&entry)
+ .map_err(|_| qoder_error("OpenCode npm entry"))?
+ .ok_or_else(|| qoder_error("OpenCode npm entry"))?
+ } else {
+ path
+ };
+ let root = path
+ .parent()
+ .and_then(Path::parent)
+ .ok_or_else(|| qoder_error("OpenCode installation"))?;
+ let metadata = package(root)?;
+ if metadata.as_ref().and_then(|m| m["name"].as_str()) != Some("opencode-ai") {
+ if path
+ .extension()
+ .is_some_and(|x| x == "cmd" || x == "js" || x == "mjs")
+ {
+ return Err(qoder_error("OpenCode native executable required"));
+ }
+ return Ok(Some(path));
+ }
+ let version = metadata
+ .as_ref()
+ .and_then(|m| m["version"].as_str())
+ .ok_or_else(|| qoder_error("OpenCode package version"))?;
+ let modules = [
+ root.join("node_modules"),
+ root.parent()
+ .ok_or_else(|| qoder_error("OpenCode package root"))?
+ .to_owned(),
+ ];
+ let mut candidates = Vec::new();
+ for modules in modules.iter().filter(|p| p.is_dir()) {
+ for entry in std::fs::read_dir(modules)
+ .map_err(|_| qoder_error("OpenCode platform packages"))?
+ .take(256)
+ {
+ let entry = entry.map_err(|_| qoder_error("OpenCode platform packages"))?;
+ if !entry.file_name().to_string_lossy().starts_with("opencode-") {
+ continue;
+ }
+ let Some(meta) = package(&entry.path())? else {
+ continue;
+ };
+ if meta["version"].as_str() != Some(version)
+ || !platform_matches(&meta)
+ || !official_package(&meta)
+ || metadata
+ .as_ref()
+ .and_then(|m| m["optionalDependencies"].get(meta["name"].as_str()?))
+ .and_then(Value::as_str)
+ != Some(version)
+ {
+ continue;
+ }
+ let binary = entry.path().join("bin").join(if cfg!(windows) {
+ "opencode.exe"
+ } else {
+ "opencode"
+ });
+ if let Some(executable) = super::executable::resolve(&binary)
+ .map_err(|_| qoder_error("OpenCode platform binary"))?
+ {
+ candidates.push(executable);
+ }
+ }
+ }
+ candidates.sort();
+ candidates.dedup();
+ if candidates.len() != 1 {
+ return Err(qoder_error("ambiguous OpenCode platform package"));
+ }
+ Ok(candidates.pop())
+}
+
+fn platform_matches(meta: &Value) -> bool {
+ let os = if cfg!(target_os = "macos") {
+ "darwin"
+ } else if cfg!(windows) {
+ "win32"
+ } else {
+ "linux"
+ };
+ let cpu = if cfg!(target_arch = "aarch64") {
+ "arm64"
+ } else if cfg!(target_arch = "x86_64") {
+ "x64"
+ } else {
+ "unsupported"
+ };
+ let exact = |key: &str, expected: &str| {
+ meta[key]
+ .as_array()
+ .is_some_and(|values| values.len() == 1 && values[0].as_str() == Some(expected))
+ };
+ exact("os", os)
+ && exact("cpu", cpu)
+ && match meta.get("libc") {
+ None => !cfg!(target_env = "musl"),
+ Some(_) => exact(
+ "libc",
+ if cfg!(target_env = "musl") {
+ "musl"
+ } else {
+ "glibc"
+ },
+ ),
+ }
+}
+
+/// Bounded audited format evidence, independent of general discovery/selection availability.
+pub fn opencode_native_format(
+ selected: &Path,
+) -> Result<&'static [&'static str], QoderNativeError> {
+ let path = opencode_native_executable(selected)?
+ .ok_or_else(|| qoder_error("OpenCode executable missing"))?;
+ let root = path
+ .parent()
+ .and_then(Path::parent)
+ .ok_or_else(|| qoder_error("OpenCode package root"))?;
+ let meta = package(root)?.ok_or_else(|| qoder_error("OpenCode format metadata unavailable"))?;
+ let name = meta["name"]
+ .as_str()
+ .ok_or_else(|| qoder_error("OpenCode package name"))?;
+ if !official_package(&meta)
+ || root.file_name().and_then(|s| s.to_str()) != Some(name)
+ || path.file_name().and_then(|s| s.to_str())
+ != Some(if cfg!(windows) {
+ "opencode.exe"
+ } else {
+ "opencode"
+ })
+ || meta["version"] != "1.19.3"
+ || !platform_matches(&meta)
+ {
+ return Err(qoder_error("OpenCode format metadata unsupported"));
+ }
+ Ok(super::opencode_migrations::IDS)
+}
+
+fn official_package(meta: &Value) -> bool {
+ matches!(
+ meta["name"].as_str(),
+ Some(
+ "opencode-darwin-arm64"
+ | "opencode-darwin-x64"
+ | "opencode-darwin-x64-baseline"
+ | "opencode-linux-x64"
+ | "opencode-linux-x64-baseline"
+ | "opencode-linux-x64-musl"
+ | "opencode-linux-x64-baseline-musl"
+ | "opencode-linux-arm64"
+ | "opencode-linux-arm64-musl"
+ | "opencode-windows-x64"
+ | "opencode-windows-x64-baseline"
+ | "opencode-windows-arm64"
+ )
+ )
+}
+
+#[cfg(all(test, windows))]
+#[path = "opencode_installation_windows_tests.rs"]
+mod windows_tests;
diff --git a/crates/integrations/src/agents/opencode_installation_windows_tests.rs b/crates/integrations/src/agents/opencode_installation_windows_tests.rs
new file mode 100644
index 00000000..f5cb5922
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_installation_windows_tests.rs
@@ -0,0 +1,148 @@
+use super::*;
+use hiroute_platform::windows::security;
+use hiroute_platform_test_support::junction::create as junction;
+
+struct NpmFixture {
+ _root: tempfile::TempDir,
+ bin: PathBuf,
+ wrapper: PathBuf,
+ native: PathBuf,
+ marker: PathBuf,
+}
+impl NpmFixture {
+ fn new(local: bool) -> Self {
+ let root = crate::agents::probe_files::temporary("hiroute-opencode-npm-").unwrap();
+ let prefix = root.path().join("npm prefix 中文 ' & literal");
+ let modules = prefix.join("node_modules");
+ let wrapper = modules.join("opencode-ai");
+ let bin = if local { modules.join(".bin") } else { prefix };
+ std::fs::create_dir_all(&bin).unwrap();
+ std::fs::create_dir_all(wrapper.join("bin")).unwrap();
+ let marker = root.path().join("shim-must-not-run");
+ std::fs::write(
+ bin.join("opencode.cmd"),
+ format!("@echo forbidden > \"{}\"\r\n", marker.display()),
+ )
+ .unwrap();
+ std::fs::write(
+ wrapper.join("bin/opencode"),
+ b"throw new Error('must not run')",
+ )
+ .unwrap();
+ let cpu = if cfg!(target_arch = "aarch64") {
+ "arm64"
+ } else {
+ "x64"
+ };
+ let name = format!("opencode-windows-{cpu}");
+ let platform = modules.join(&name);
+ std::fs::create_dir_all(platform.join("bin")).unwrap();
+ let native = platform.join("bin/opencode.exe");
+ std::fs::write(&native, b"unexecuted native fixture").unwrap();
+ std::fs::write(
+ platform.join("package.json"),
+ serde_json::json!({"name":name,"version":"1.19.3","os":["win32"],"cpu":[cpu]})
+ .to_string(),
+ )
+ .unwrap();
+ std::fs::write(wrapper.join("package.json"), serde_json::json!({"name":"opencode-ai","version":"1.19.3","bin":{"opencode":"bin/opencode"},"optionalDependencies":{(name):"1.19.3"}}).to_string()).unwrap();
+ Self {
+ _root: root,
+ bin,
+ wrapper,
+ native,
+ marker,
+ }
+ }
+
+ fn assert_same_native(selected: &Path, expected: &Path) {
+ let resolved = opencode_native_executable(selected).unwrap().unwrap();
+ assert_eq!(
+ security::file_identity(&security::open_identity(&resolved, false).unwrap()).unwrap(),
+ security::file_identity(&security::open_identity(expected, false).unwrap()).unwrap()
+ );
+ }
+}
+
+#[test]
+fn windows_opencode_npm_shim_path_and_native_share_one_identity_without_execution() {
+ const CHILD: &str = "HIROUTE_TEST_OPENCODE_NPM_BIN";
+ if let Some(bin) = std::env::var_os(CHILD) {
+ let bin = PathBuf::from(bin);
+ let expected = std::env::var_os("HIROUTE_TEST_OPENCODE_NATIVE").unwrap();
+ NpmFixture::assert_same_native(Path::new("opencode"), Path::new(&expected));
+ assert!(bin.join("opencode.cmd").is_file());
+ return;
+ }
+ for local in [false, true] {
+ let fixture = NpmFixture::new(local);
+ for selected in [
+ fixture.bin.join("opencode.cmd"),
+ fixture.bin.join("opencode"),
+ fixture.native.clone(),
+ ] {
+ NpmFixture::assert_same_native(&selected, &fixture.native);
+ }
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap());
+ child.args(["--exact", "agents::opencode_installation::windows_tests::windows_opencode_npm_shim_path_and_native_share_one_identity_without_execution", "--nocapture"])
+ .env(CHILD, &fixture.bin).env("HIROUTE_TEST_OPENCODE_NATIVE", &fixture.native)
+ .env("PATH", &fixture.bin);
+ super::super::windows_runtime::bounded(
+ &child,
+ true,
+ std::time::Duration::from_secs(15),
+ 64 * 1024,
+ )
+ .unwrap();
+ assert!(!fixture.marker.exists());
+ }
+}
+
+#[test]
+fn windows_opencode_npm_rejects_foreign_producer_and_original_reparse_paths() {
+ let fixture = NpmFixture::new(false);
+ let manifest = fixture.wrapper.join("package.json");
+ let original = std::fs::read(&manifest).unwrap();
+ std::fs::write(
+ &manifest,
+ br#"{"name":"foreign-producer","bin":{"opencode":"bin/opencode"}}"#,
+ )
+ .unwrap();
+ assert!(opencode_native_executable(&fixture.bin.join("opencode.cmd")).is_err());
+ std::fs::write(&manifest, original).unwrap();
+ let moved = fixture.wrapper.with_file_name("wrapper-original");
+ std::fs::rename(&fixture.wrapper, &moved).unwrap();
+ junction(&fixture.wrapper, &moved).unwrap();
+ assert!(opencode_native_executable(&fixture.bin.join("opencode.cmd")).is_err());
+ std::fs::remove_dir(&fixture.wrapper).unwrap();
+ std::fs::rename(moved, &fixture.wrapper).unwrap();
+ NpmFixture::assert_same_native(&fixture.bin.join("opencode.cmd"), &fixture.native);
+ let bin = fixture.wrapper.join("bin");
+ let original_bin = fixture.wrapper.join("original-bin");
+ std::fs::rename(&bin, &original_bin).unwrap();
+ junction(&bin, &original_bin).unwrap();
+ assert!(opencode_native_executable(&fixture.bin.join("opencode.cmd")).is_err());
+ std::fs::remove_dir(bin).unwrap();
+ std::fs::rename(original_bin, fixture.wrapper.join("bin")).unwrap();
+}
+
+#[cfg(target_arch = "x86_64")]
+#[test]
+fn windows_opencode_npm_ambiguous_platform_packages_require_native_selection() {
+ let fixture = NpmFixture::new(false);
+ let original = fixture.native.parent().unwrap().parent().unwrap();
+ let name = original.file_name().unwrap().to_str().unwrap().to_owned();
+ let duplicate = original.parent().unwrap().join(format!("{name}-baseline"));
+ std::fs::create_dir_all(duplicate.join("bin")).unwrap();
+ std::fs::copy(&fixture.native, duplicate.join("bin/opencode.exe")).unwrap();
+ let mut metadata: Value =
+ serde_json::from_slice(&std::fs::read(original.join("package.json")).unwrap()).unwrap();
+ metadata["name"] = format!("{name}-baseline").into();
+ std::fs::write(duplicate.join("package.json"), metadata.to_string()).unwrap();
+ let manifest = fixture.wrapper.join("package.json");
+ let mut metadata: Value = serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();
+ metadata["optionalDependencies"][format!("{name}-baseline")] = "1.19.3".into();
+ std::fs::write(manifest, metadata.to_string()).unwrap();
+ assert!(opencode_native_executable(&fixture.bin.join("opencode.cmd")).is_err());
+ NpmFixture::assert_same_native(&fixture.native, &fixture.native);
+}
diff --git a/crates/integrations/src/agents/opencode_migrations.rs b/crates/integrations/src/agents/opencode_migrations.rs
new file mode 100644
index 00000000..f823e1c1
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_migrations.rs
@@ -0,0 +1,43 @@
+// OpenCode v1.19.3 packages/core/src/database/migration.gen.ts and imported migration IDs.
+// Source: https://github.com/anomalyco/opencode/tree/v1.19.3/packages/core/src/database/migration
+// Admission only; never a migration implementation or executable fingerprint.
+pub(super) const IDS: &[&str] = &[
+ "20260127222353_familiar_lady_ursula",
+ "20260211171708_add_project_commands",
+ "20260213144116_wakeful_the_professor",
+ "20260225215848_workspace",
+ "20260227213759_add_session_workspace_id",
+ "20260228203230_blue_harpoon",
+ "20260303231226_add_workspace_fields",
+ "20260309230000_move_org_to_state",
+ "20260312043431_session_message_cursor",
+ "20260323234822_events",
+ "20260410174513_workspace-name",
+ "20260413175956_chief_energizer",
+ "20260423070820_add_icon_url_override",
+ "20260427172553_slow_nightmare",
+ "20260428004200_add_session_path",
+ "20260501142318_next_venus",
+ "20260504145000_add_sync_owner",
+ "20260507164347_add_workspace_time",
+ "20260510033149_session_usage",
+ "20260511000411_data_migration_state",
+ "20260511173437_session-metadata",
+ "20260601010001_normalize_storage_paths",
+ "20260601202201_amazing_prowler",
+ "20260602002951_lowly_union_jack",
+ "20260602182828_add_project_directories",
+ "20260603001617_session_message_projection_indexes",
+ "20260603040000_session_message_projection_order",
+ "20260603141458_session_input_inbox",
+ "20260603160727_jittery_ezekiel_stane",
+ "20260604172448_event_sourced_session_input",
+ "20260605003541_add_session_context_snapshot",
+ "20260605042240_add_context_epoch_agent",
+ "20260611035744_credential",
+ "20260611192811_lush_chimera",
+ "20260612174303_project_dir_strategy",
+ "20260622142730_simplify_session_context_epoch",
+ "20260622170816_reset_v2_session_state",
+ "20260622202450_simplify_session_input",
+];
diff --git a/crates/integrations/src/agents/opencode_probe.rs b/crates/integrations/src/agents/opencode_probe.rs
new file mode 100644
index 00000000..a46d2593
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_probe.rs
@@ -0,0 +1,538 @@
+//! Explicit native Skill/CLI check. Reuses the shared Responses peer and owned process scope.
+use super::qoder_probe::{
+ QoderCollaborationProbeTarget as Target, cli_baseline, confirmed_skill, skill_body,
+};
+use super::{OpenCodeNativeContext, QoderNativeError, qoder_error};
+use hiroute_domain::{
+ AgentCapability, CanonicalDigest, CapabilityState, SupportedAgentInstallationV1,
+};
+use serde_json::{Value, json};
+use std::io::Write;
+#[cfg(unix)]
+use std::os::unix::process::CommandExt;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+const MODEL: &str = "hiroute-collaboration-probe";
+const CONTRACT: &str = "hiroute.opencode-collaboration/v1";
+
+#[derive(Default)]
+pub(super) struct ProofCache {
+ generation: u64,
+ pub evidence: Option<Evidence>,
+}
+impl ProofCache {
+ pub fn begin(&mut self) -> Result<u64, QoderNativeError> {
+ self.evidence = None;
+ self.generation = self
+ .generation
+ .checked_add(1)
+ .ok_or_else(|| qoder_error("check generation"))?;
+ Ok(self.generation)
+ }
+ pub fn finish(&mut self, generation: u64, evidence: Evidence) -> Result<(), QoderNativeError> {
+ if self.generation != generation {
+ return Err(qoder_error("native check superseded"));
+ }
+ self.evidence = Some(evidence);
+ Ok(())
+ }
+}
+pub struct Evidence {
+ cli: PathBuf,
+ target: Target,
+ dependencies: CanonicalDigest,
+ observed: Instant,
+ observed_at: u64,
+}
+impl Evidence {
+ pub fn attach(
+ &self,
+ executable: &Path,
+ native: &OpenCodeNativeContext,
+ installation: &mut SupportedAgentInstallationV1,
+ ) {
+ if self.observed.elapsed() > Duration::from_secs(300)
+ || dependencies(executable, native, &self.cli, &self.target)
+ .ok()
+ .as_ref()
+ != Some(&self.dependencies)
+ {
+ return;
+ }
+ installation.observation_digest = CanonicalDigest::of(&(
+ CONTRACT,
+ &installation.observation_digest,
+ &self.dependencies,
+ ))
+ .expect("bounded proof");
+ for proof in &mut installation.capability_evidence {
+ proof.dependency_digest = installation.observation_digest.clone();
+ if matches!(
+ proof.capability,
+ AgentCapability::SkillLoading | AgentCapability::TrustedCliExecution
+ ) {
+ proof.state = CapabilityState::Proven;
+ proof.reason = None;
+ proof.adapter_contract = CONTRACT.into();
+ proof.observed_at_unix_ms = self.observed_at;
+ }
+ }
+ }
+}
+
+pub struct OpenCodeCollaborationProbe;
+impl OpenCodeCollaborationProbe {
+ pub fn run(
+ executable: &Path,
+ native: &OpenCodeNativeContext,
+ cli: &Path,
+ target: Target,
+ ) -> Result<Evidence, QoderNativeError> {
+ let fail = || qoder_error("OpenCode collaboration check");
+ let executable = super::opencode_native_executable(executable)?.ok_or_else(fail)?;
+ let cli = super::executable::resolve(cli)
+ .map_err(|_| fail())?
+ .ok_or_else(fail)?;
+ let (before, before_parts) = dependency_parts(&executable, native, &cli, &target)?;
+ let root = super::probe_files::temporary("hiroute-opencode-check-").map_err(|_| fail())?;
+ let root_path = std::fs::canonicalize(root.path()).map_err(|_| fail())?;
+ let workspace = root_path.join("workspace");
+ let temporary = root_path.join("tmp");
+ super::probe_files::directory(&temporary).map_err(|_| fail())?;
+ super::probe_files::directory(&workspace).map_err(|_| fail())?;
+ // Installation is independent of daily model configuration. The private native
+ // runtime loads the actual installed file through its supported resource path;
+ // path/body receipts below distinguish it from any substitute or shadow Skill.
+ let probe_home = root_path.join("home");
+ super::probe_files::directory(&probe_home).map_err(|_| fail())?;
+ let runtime = OpenCodeNativeContext::from_lookup(&probe_home, |_| None)?;
+ let (skill_path, content) = match &target {
+ Target::InstalledUserSkill { expected_content } => {
+ let path = native.skill_target();
+ let content = confirmed_skill(&path, expected_content)?;
+ (path, content)
+ }
+ Target::PreinstallCapability => {
+ let mut nonce = [0u8; 16];
+ getrandom::fill(&mut nonce).map_err(|_| fail())?;
+ let nonce = nonce.iter().map(|b| format!("{b:02x}")).collect::<String>();
+ let name = format!("hiroute-check-{nonce}");
+ let path = workspace
+ .join(".opencode/skills")
+ .join(&name)
+ .join("SKILL.md");
+ for directory in [
+ workspace.join(".opencode"),
+ workspace.join(".opencode/skills"),
+ path.parent().ok_or_else(fail)?.to_owned(),
+ ] {
+ super::probe_files::directory(&directory).map_err(|_| fail())?;
+ }
+ let content = format!(
+ "---\nname: {name}\ndescription: HiRoute local capability check\n---\n\nLocal receipt: {nonce}\n"
+ );
+ super::probe_files::file(&path)
+ .and_then(|mut f| f.write_all(content.as_bytes()))
+ .map_err(|_| fail())?;
+ (path, content)
+ }
+ };
+ let directory =
+ std::fs::canonicalize(skill_path.parent().ok_or_else(fail)?).map_err(|_| fail())?;
+ let name = directory
+ .file_name()
+ .and_then(|s| s.to_str())
+ .ok_or_else(fail)?
+ .to_owned();
+ let mut nonce = [0u8; 16];
+ getrandom::fill(&mut nonce).map_err(|_| fail())?;
+ let token = nonce.iter().map(|b| format!("{b:02x}")).collect::<String>();
+ let (shell, cli_command) = probe_shell_command(&cli, &token)?;
+ let mut challenge = Challenge {
+ name,
+ directory: directory.to_str().ok_or_else(fail)?.into(),
+ body: skill_body(&content)?,
+ command: cli_command,
+ expected_cli: cli_baseline(&cli, &root_path)?,
+ nonce: token.clone(),
+ step: 0,
+ };
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(|_| fail())?;
+ listener.set_nonblocking(true).map_err(|_| fail())?;
+ let provider = super::opencode_provider(
+ &format!("http://{}/v1", listener.local_addr().map_err(|_| fail())?),
+ &hiroute_domain::AdditionalAgentModelV1 {
+ alias: MODEL.into(),
+ protocol: hiroute_domain::AgentIngressProtocolV1::Responses,
+ context_window_tokens: 65536,
+ max_output_tokens: 2048,
+ },
+ "{env:HIROUTE_OPENCODE_PROBE_TOKEN}",
+ None,
+ )?;
+ let selector = format!("hiroute-native-probe/{MODEL}");
+ let permission = json!({"*":"deny","skill":"allow","bash":"allow","external_directory":"allow","doom_loop":"allow"});
+
+ let mut overlay = json!({"$schema":"https://opencode.ai/config.json","provider":{"hiroute-native-probe":provider},"model":selector,"small_model":selector,"default_agent":"hiroute-check","enabled_providers":["hiroute-native-probe"],"agent":{"hiroute-check":{"mode":"primary","model":selector,"permission":permission},"title":{"model":selector,"disable":true},"summary":{"model":selector,"disable":true},"compaction":{"model":selector,"disable":true}},"permission":permission,"skills":{"paths":[directory]},"share":"disabled","autoupdate":false,"lsp":false,"formatter":false});
+ if let Some(shell) = shell {
+ overlay["shell"] = json!(shell);
+ }
+ let output =
+ super::probe_files::file(&root_path.join("output.private")).map_err(|_| fail())?;
+ let observer = output.try_clone().map_err(|_| fail())?;
+ let mut command = Command::new(&executable);
+ command
+ .args([
+ "run",
+ "--format",
+ "json",
+ "--model",
+ &selector,
+ "--agent",
+ "hiroute-check",
+ "Complete the local compatibility check.",
+ ])
+ .current_dir(&workspace)
+ .env_clear()
+ .env("HOME", &runtime.home)
+ .env("USERPROFILE", &runtime.home)
+ .env("TMPDIR", &temporary)
+ .env("TMP", &temporary)
+ .env("TEMP", &temporary)
+ .env("PATH", super::native_ingress_probe::native_probe_path())
+ .env("OPENCODE_CONFIG_CONTENT", overlay.to_string())
+ .env("HIROUTE_OPENCODE_PROBE_TOKEN", &token)
+ .env("OPENCODE_DB", root_path.join("probe.db"))
+ .env("OPENCODE_PURE", "true")
+ // Global .agents/.claude discovery can ignore the private HOME and
+ // race the explicitly selected installed file with a same-name Skill.
+ .env("OPENCODE_DISABLE_EXTERNAL_SKILLS", "true")
+ .env("OPENCODE_DISABLE_DEFAULT_PLUGINS", "true")
+ .env("OPENCODE_DISABLE_AUTOUPDATE", "true")
+ .env("OPENCODE_DISABLE_MODELS_FETCH", "true")
+ .env("OPENCODE_DISABLE_LSP_DOWNLOAD", "true")
+ .env("OPENCODE_DISABLE_FFF", "true")
+ .env("OPENCODE_PERMISSION", permission.to_string());
+ for (key, path) in [
+ ("XDG_CONFIG_HOME", &runtime.config_root),
+ ("XDG_DATA_HOME", &runtime.data_root),
+ ("XDG_CACHE_HOME", &runtime.cache_root),
+ ("XDG_STATE_HOME", &runtime.state_root),
+ ] {
+ command.env(key, path.parent().ok_or_else(fail)?);
+ }
+ #[cfg(windows)]
+ for (key, value) in
+ super::windows_runtime::windows_native_system_environment().map_err(|_| fail())?
+ {
+ command.env(key, value);
+ }
+ #[cfg(unix)]
+ let child = command
+ .stdin(Stdio::null())
+ .stdout(output)
+ .stderr(Stdio::null())
+ .process_group(0)
+ .spawn();
+ #[cfg(windows)]
+ let child = super::windows_runtime::spawn(
+ &command,
+ false,
+ hiroute_platform::windows::job::Stream::Null,
+ hiroute_platform::windows::job::Stream::File(&output),
+ hiroute_platform::windows::job::Stream::Null,
+ );
+ let mut child =
+ super::native_probe_process::NativeProbeProcess::new(child.map_err(|_| fail())?);
+ let started = Instant::now();
+ let result = (|| {
+ loop {
+ if started.elapsed() > Duration::from_secs(45) {
+ return Err(qoder_error("native check deadline"));
+ }
+ if observer.metadata().map_err(|_| fail())?.len() > 512 * 1024 {
+ return Err(qoder_error("native output bound"));
+ }
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ super::native_responses_probe::serve(&mut stream, &token, MODEL, |body| {
+ challenge.reply(body)
+ })
+ .map_err(qoder_error)?
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
+ Err(_) => return Err(fail()),
+ }
+ if let Some(status) = child.observe().map_err(|_| fail())? {
+ return Ok(status);
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ })();
+ if child.stop().is_err() {
+ let _ = root.keep();
+ return Err(qoder_error("OpenCode process scope"));
+ }
+ if !result? {
+ return Err(qoder_error("native collaboration execution"));
+ }
+ if challenge.step != 3 {
+ return Err(qoder_error("native collaboration incomplete"));
+ }
+ let (after, after_parts) = dependency_parts(&executable, native, &cli, &target)?;
+ if before != after {
+ for (index, name) in [
+ "native-resource",
+ "native-executable",
+ "trusted-cli",
+ "installed-skill",
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ if before_parts[index] != after_parts[index] {
+ eprintln!("native OpenCode collaboration dependency changed: {name}");
+ }
+ }
+ return Err(qoder_error("native context changed"));
+ }
+ Ok(Evidence {
+ cli,
+ target,
+ dependencies: before,
+ observed: Instant::now(),
+ observed_at: super::native_ingress_probe::now(),
+ })
+ }
+}
+
+fn probe_shell_command(
+ cli: &Path,
+ nonce: &str,
+) -> Result<(Option<PathBuf>, String), QoderNativeError> {
+ #[cfg(windows)]
+ {
+ // OpenCode's tool ID is `bash` even when it executes PowerShell/cmd.
+ // Pin the system shell for this private probe, independently of PATH.
+ let shell = hiroute_platform::windows::launcher::system_executable(Path::new(
+ "WindowsPowerShell/v1.0/powershell.exe",
+ ))
+ .map_err(|_| qoder_error("OpenCode probe shell"))?;
+ let cli = super::managed_launch::windows_executable_path(cli)
+ .map_err(|_| qoder_error("trusted CLI path"))?;
+ let path = cli
+ .to_str()
+ .ok_or_else(|| qoder_error("trusted CLI path"))?;
+ let path = path.replace('\'', "''");
+ Ok((
+ Some(shell),
+ format!(
+ "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[Text.Encoding]::UTF8; & '{path}' schema list --output json; if ($LASTEXITCODE -ne 0) {{ exit $LASTEXITCODE }}; Write-Output '{nonce}'"
+ ),
+ ))
+ }
+ #[cfg(not(windows))]
+ Ok((
+ None,
+ format!(
+ "{} && printf '%s' '{nonce}'",
+ super::qoder_probe::cli_command(cli)?
+ ),
+ ))
+}
+fn dependencies(
+ executable: &Path,
+ native: &OpenCodeNativeContext,
+ cli: &Path,
+ target: &Target,
+) -> Result<CanonicalDigest, QoderNativeError> {
+ dependency_parts(executable, native, cli, target).map(|(digest, _)| digest)
+}
+fn dependency_parts(
+ executable: &Path,
+ native: &OpenCodeNativeContext,
+ cli: &Path,
+ target: &Target,
+) -> Result<(CanonicalDigest, [CanonicalDigest; 4]), QoderNativeError> {
+ let skill = match target {
+ Target::PreinstallCapability => None,
+ Target::InstalledUserSkill { expected_content } => Some(CanonicalDigest::of_bytes(
+ confirmed_skill(&native.skill_target(), expected_content)?.as_bytes(),
+ )),
+ };
+ let resource = match &skill {
+ Some(content) => super::observed_capabilities::content_bound_dependencies(
+ Some(executable),
+ &native.skill_target(),
+ content,
+ ),
+ None => {
+ super::observed_capabilities::dependencies(Some(executable), &native.skill_target())
+ }
+ }
+ .map_err(|_| qoder_error("native resource identity"))?
+ .0;
+ let executable = super::native_ingress_probe::binary_identity(executable)
+ .map_err(|_| qoder_error("native binary identity"))?;
+ let cli = super::native_ingress_probe::binary_identity(cli)
+ .map_err(|_| qoder_error("CLI identity"))?;
+ let skill_digest =
+ CanonicalDigest::of(&skill).map_err(|_| qoder_error("check dependencies"))?;
+ let digest = CanonicalDigest::of(&(CONTRACT, native, &resource, &executable, &cli, skill))
+ .map_err(|_| qoder_error("check dependencies"))?;
+ Ok((digest, [resource, executable, cli, skill_digest]))
+}
+struct Challenge {
+ name: String,
+ directory: String,
+ body: String,
+ command: String,
+ expected_cli: String,
+ nonce: String,
+ step: usize,
+}
+impl Challenge {
+ fn reply(&mut self, body: &Value) -> Result<Value, &'static str> {
+ let input = body["input"].as_array().ok_or("native input")?;
+ let result = |id: &str| {
+ input
+ .iter()
+ .find(|i| i["type"] == "function_call_output" && i["call_id"] == id)
+ .and_then(|i| i["output"].as_str())
+ };
+ let item = match self.step {
+ 0 => {
+ let tools = body["tools"].as_array().ok_or("native tools")?;
+ if !body.to_string().contains(&self.name)
+ || !["skill", "bash"]
+ .iter()
+ .all(|name| tools.iter().any(|t| t["name"] == *name))
+ {
+ return Err("native Skill discovery");
+ }
+ function("skill", "skill", json!({"name":self.name}))
+ }
+ 1 => {
+ let loaded = result("call_hiroute_skill").ok_or("native Skill receipt")?;
+ if !loaded.starts_with(&format!("<skill_content name=\"{}\">", self.name))
+ || !loaded.contains(&format!("\n{}\n", self.body.trim()))
+ || !loaded.contains(&format!(
+ "\nBase directory for this skill: {}\n",
+ self.directory
+ ))
+ {
+ return Err("actual native Skill source");
+ }
+ function(
+ "cli",
+ "bash",
+ json!({"command":self.command,"description":"Read HiRoute public command schema","timeout":10000}),
+ )
+ }
+ 2 => {
+ let output = result("call_hiroute_cli").ok_or("native CLI receipt")?;
+ if !output.contains(&self.expected_cli) || !output.trim_end().ends_with(&self.nonce)
+ {
+ return Err("nonce-correlated CLI receipt");
+ }
+ json!({"id":"msg_probe","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"OK","annotations":[]}]})
+ }
+ _ => return Err("native request bound"),
+ };
+ self.step += 1;
+ Ok(item)
+ }
+}
+fn function(suffix: &str, name: &str, args: Value) -> Value {
+ json!({"id":format!("fc_hiroute_{suffix}"),"type":"function_call","status":"completed","call_id":format!("call_hiroute_{suffix}"),"name":name,"arguments":args.to_string()})
+}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+
+ #[test]
+ fn opencode_probe_cli_shell_preserves_literal_paths_and_requires_success_for_nonce() {
+ let root = tempfile::tempdir().unwrap();
+ let cli = root.path().join("CLI ' space $(literal); & hiroute");
+ let nonce = "0123456789abcdef";
+ for exit in [0, 7] {
+ std::fs::write(
+ &cli,
+ format!("#!/bin/sh\nprintf '%s' 'actual-cli-receipt'\nexit {exit}\n"),
+ )
+ .unwrap();
+ std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let (shell, command) = probe_shell_command(&cli, nonce).unwrap();
+ assert!(shell.is_none());
+ let output = Command::new("/bin/sh")
+ .args(["-c", &command])
+ .output()
+ .unwrap();
+ assert_eq!(output.status.success(), exit == 0);
+ let output = String::from_utf8(output.stdout).unwrap();
+ assert!(output.starts_with("actual-cli-receipt"));
+ assert_eq!(output.ends_with(nonce), exit == 0);
+ }
+ }
+}
+
+#[cfg(all(test, windows))]
+mod windows_tests {
+ use super::*;
+ use base64::Engine;
+
+ #[test]
+ fn windows_opencode_probe_pins_system_powershell_and_parses_cli_as_literal_argv() {
+ let root = super::super::probe_files::temporary("hiroute-opencode-shell-").unwrap();
+ let cli = root.path().join("CLI 中文 ' $() & percent% literal.exe");
+ std::fs::write(&cli, b"parser-only fixture").unwrap();
+ let (shell, script) = probe_shell_command(&cli, "0123456789abcdef").unwrap();
+ let shell = shell.unwrap();
+ assert_eq!(
+ shell,
+ hiroute_platform::windows::launcher::system_executable(Path::new(
+ "WindowsPowerShell/v1.0/powershell.exe"
+ ))
+ .unwrap()
+ );
+ let parser = r#"[Console]::OutputEncoding=[Text.Encoding]::UTF8; $tokens=$null; $errors=$null; $ast=[System.Management.Automation.Language.Parser]::ParseInput($env:HIROUTE_TEST_COMMAND,[ref]$tokens,[ref]$errors); if($errors.Count -ne 0){exit 1}; $calls=@($ast.FindAll({param($node) $node -is [System.Management.Automation.Language.CommandAst] -and $node.InvocationOperator -eq 'Ampersand'},$true)); if($calls.Count -ne 1){exit 2}; @($calls[0].CommandElements | ForEach-Object {if($_ -is [System.Management.Automation.Language.StringConstantExpressionAst]){$_.Value}else{$_.Extent.Text}}) | ConvertTo-Json -Compress"#;
+ let payload = base64::engine::general_purpose::STANDARD.encode(
+ parser
+ .encode_utf16()
+ .flat_map(u16::to_le_bytes)
+ .collect::<Vec<_>>(),
+ );
+ let mut command = Command::new(shell);
+ command
+ .args([
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-EncodedCommand",
+ &payload,
+ ])
+ .env("HIROUTE_TEST_COMMAND", script);
+ let output =
+ super::super::windows_runtime::bounded(&command, true, Duration::from_secs(10), 8192)
+ .unwrap();
+ let text = std::str::from_utf8(&output)
+ .unwrap()
+ .trim_start_matches('\u{feff}');
+ let args: Vec<String> = serde_json::from_str(text).unwrap();
+ let expected = super::super::managed_launch::windows_executable_path(&cli).unwrap();
+ assert_eq!(
+ args,
+ [
+ expected.to_str().unwrap(),
+ "schema",
+ "list",
+ "--output",
+ "json"
+ ]
+ );
+ }
+}
diff --git a/crates/integrations/src/agents/opencode_project.rs b/crates/integrations/src/agents/opencode_project.rs
new file mode 100644
index 00000000..d6e710fc
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_project.rs
@@ -0,0 +1,94 @@
+//! Prove the pinned native Git stop using the Worker's filtered HOME/XDG/PATH.
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::time::Duration;
+
+use super::{OpenCodeNativeContext, QoderNativeError, qoder_error};
+
+pub(super) fn confirm_root(
+ native: &OpenCodeNativeContext,
+ root: &Path,
+ search_path: &str,
+) -> Result<(), QoderNativeError> {
+ let unavailable = || qoder_error("OpenCode project boundary unavailable");
+ // Resolve only the actual child search path. Discovery's ambient fallbacks
+ // cannot prove which Git the native process will execute.
+ let mut selected = None;
+ for directory in std::env::split_paths(search_path) {
+ if !directory.is_absolute() {
+ #[cfg(test)]
+ eprintln!("OpenCode Git boundary stage=search-path reason=relative-component");
+ return Err(unavailable());
+ }
+ #[cfg(windows)]
+ let names = ["git", "git.com", "git.exe", "git.bat", "git.cmd"];
+ #[cfg(not(windows))]
+ let names = ["git"];
+ for name in names {
+ let candidate = directory.join(name);
+ if !candidate.try_exists().map_err(|_| unavailable())? {
+ continue;
+ }
+ #[cfg(windows)]
+ if name != "git.exe" {
+ return Err(unavailable());
+ }
+ selected = super::executable::resolve(&candidate).map_err(|_| unavailable())?;
+ break;
+ }
+ if selected.is_some() {
+ break;
+ }
+ }
+ let git = selected.ok_or_else(|| {
+ #[cfg(test)]
+ eprintln!("OpenCode Git boundary stage=search-path reason=missing-executable");
+ unavailable()
+ })?;
+ // Match Git.repo.discover at OpenCode 1.19.3. Any failure is a scoped
+ // capability refusal; it never licenses stopping at an unverified .git.
+ for option in ["--show-toplevel", "--git-dir", "--git-common-dir"] {
+ let mut command = Command::new(&git);
+ command
+ .args(["rev-parse", option])
+ .current_dir(root)
+ .env_clear()
+ .env("PATH", search_path)
+ .env("HOME", &native.home)
+ .env(
+ "XDG_CONFIG_HOME",
+ native.config_root.parent().ok_or_else(unavailable)?,
+ );
+ #[cfg(windows)]
+ for (key, value) in super::windows_runtime::windows_native_system_environment()
+ .map_err(|_| unavailable())?
+ {
+ command.env(key, value);
+ }
+ let output =
+ super::native_probe_process::capture(command, false, Duration::from_secs(2), 16 * 1024)
+ .map_err(|_reason| {
+ #[cfg(test)]
+ eprintln!("OpenCode Git boundary stage={option} reason={_reason:?}");
+ unavailable()
+ })?;
+ let value = std::str::from_utf8(&output)
+ .map_err(|_| unavailable())?
+ .trim_end_matches(['\r', '\n']);
+ if value.is_empty() || value.contains(['\0', '\r', '\n']) {
+ return Err(unavailable());
+ }
+ if option == "--show-toplevel" {
+ let top = PathBuf::from(value);
+ if !top.is_absolute()
+ || std::fs::canonicalize(top).map_err(|_| unavailable())?
+ != std::fs::canonicalize(root).map_err(|_| unavailable())?
+ {
+ #[cfg(test)]
+ eprintln!("OpenCode Git boundary stage=root reason=unconfirmed-root");
+ return Err(unavailable());
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/crates/integrations/src/agents/opencode_resources.rs b/crates/integrations/src/agents/opencode_resources.rs
new file mode 100644
index 00000000..1dfea81b
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_resources.rs
@@ -0,0 +1,161 @@
+//! Bounded native Markdown model references for the existing settings dependency check.
+//! These borrowed resources are never rewritten or interpreted as an executable config.
+use super::{AgentFilesystemScanError as Error, OpenCodeNativeContext};
+use hiroute_domain::CanonicalDigest;
+use std::path::PathBuf;
+
+pub(super) struct ModelReferences {
+ pub models: Vec<String>,
+ pub documents: Vec<(PathBuf, CanonicalDigest)>,
+}
+
+pub(super) fn model_references(native: &OpenCodeNativeContext) -> Result<ModelReferences, Error> {
+ let mut result = ModelReferences {
+ models: Vec::new(),
+ documents: Vec::new(),
+ };
+ let mut entries_left = 256usize;
+ let mut bytes_left = 4 * 1024 * 1024usize;
+ for root in native
+ .resource_roots(None)
+ .map_err(|_| Error::InvalidConfig)?
+ {
+ for (name, recursive) in [
+ ("agent", true),
+ ("agents", true),
+ ("mode", false),
+ ("modes", false),
+ ] {
+ let mut pending = vec![(root.join(name), 0)];
+ while let Some((directory, depth)) = pending.pop() {
+ if depth > 16 {
+ return Err(Error::ConfigTooLarge);
+ }
+ let metadata = match std::fs::symlink_metadata(&directory) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(error) => return Err(error.into()),
+ };
+ if metadata.file_type().is_symlink() || !metadata.is_dir() {
+ return Err(Error::InvalidConfig);
+ }
+ #[cfg(windows)]
+ let _directory =
+ hiroute_platform::windows::security::open_identity(&directory, true)?;
+ for entry in std::fs::read_dir(&directory)? {
+ entries_left = entries_left.checked_sub(1).ok_or(Error::ConfigTooLarge)?;
+ let entry = entry?;
+ let path = entry.path();
+ let kind = entry.file_type()?;
+ if kind.is_symlink() {
+ return Err(Error::SymlinkConfig);
+ }
+ if kind.is_dir() {
+ if recursive {
+ pending.push((path, depth + 1));
+ }
+ continue;
+ }
+ if path
+ .extension()
+ .is_none_or(|extension| !extension.eq_ignore_ascii_case("md"))
+ {
+ continue;
+ }
+ let (bytes, _) = super::filesystem_config::read_system_config_bytes(&path)?
+ .ok_or(Error::SourceChanged)?;
+ bytes_left = bytes_left
+ .checked_sub(bytes.len())
+ .ok_or(Error::ConfigTooLarge)?;
+ if let Some(model) = model_reference(&bytes)? {
+ result.models.push(model);
+ }
+ result
+ .documents
+ .push((path, CanonicalDigest::of_bytes(&bytes)));
+ }
+ }
+ }
+ }
+ result.documents.sort_by(|a, b| a.0.cmp(&b.0));
+ Ok(result)
+}
+
+fn model_reference(bytes: &[u8]) -> Result<Option<String>, Error> {
+ let text = std::str::from_utf8(bytes)
+ .map_err(|_| Error::InvalidConfig)?
+ .trim_start_matches('\u{feff}');
+ if !text.starts_with("---") {
+ return Ok(None);
+ }
+ let mut lines = text.split_inclusive('\n');
+ if lines.next().map(str::trim_end) != Some("---") {
+ return Err(Error::InvalidConfig);
+ }
+ let mut header = String::new();
+ let mut closed = false;
+ for line in lines {
+ if line.trim_end_matches(['\r', '\n']) == "---" {
+ closed = true;
+ break;
+ }
+ header.push_str(line);
+ }
+ if !closed {
+ return Err(Error::InvalidConfig);
+ }
+ if header.trim().is_empty() {
+ return Ok(None);
+ }
+ let value: serde_yaml::Value =
+ serde_yaml::from_str(&header).map_err(|_| Error::InvalidConfig)?;
+ if value.is_null() {
+ return Ok(None);
+ }
+ let value = value.as_mapping().ok_or(Error::InvalidConfig)?;
+ // Native gray-matter also accepts YAML merges and a permissive fallback. Keep
+ // ambiguous variants unavailable for removal, without implementing its parser.
+ if value
+ .keys()
+ .any(|key| key.as_str().is_none_or(|key| key == "<<"))
+ {
+ return Err(Error::InvalidConfig);
+ }
+ value
+ .get(serde_yaml::Value::String("model".into()))
+ .map(|value| {
+ value
+ .as_str()
+ .filter(|value| !value.is_empty())
+ .map(str::to_owned)
+ .ok_or(Error::InvalidConfig)
+ })
+ .transpose()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_frontmatter_models_are_static_or_explicitly_unknown() {
+ assert_eq!(model_reference(b"plain prompt").unwrap(), None);
+ for text in [
+ "---\nmodel: owned/route\n---\nprompt",
+ "\u{feff}---\r\nmodel: 'owned/route'\r\n---\r\nprompt",
+ ] {
+ assert_eq!(
+ model_reference(text.as_bytes()).unwrap().as_deref(),
+ Some("owned/route")
+ );
+ }
+ for text in [
+ "---\nmodel: [owned/route]\n---\n",
+ "---\n<<: {model: owned/route}\n---\n",
+ "---\nmodel: owned/route\n",
+ "---yaml\nmodel: owned/route\n---\n",
+ ] {
+ assert!(model_reference(text.as_bytes()).is_err(), "{text}");
+ }
+ }
+}
diff --git a/crates/integrations/src/agents/opencode_scanner.rs b/crates/integrations/src/agents/opencode_scanner.rs
new file mode 100644
index 00000000..bc1da731
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_scanner.rs
@@ -0,0 +1,251 @@
+//! Independent OpenCode metadata and settings/Skill targets; no native process is started.
+use super::super::{QoderNativeError, qoder_error};
+use super::*;
+
+impl FilesystemAgentScannerV1 {
+ pub fn opencode_native_context(
+ &self,
+ ) -> Result<&super::super::OpenCodeNativeContext, AgentFilesystemScanError> {
+ self.layout
+ .opencode_context
+ .as_ref()
+ .ok_or(AgentFilesystemScanError::InvalidConfig)
+ }
+ pub fn opencode_user_models_target(&self) -> PathBuf {
+ self.opencode_model_target.clone()
+ }
+ /// Recovery may retain the registered JSON/JSONC sibling, never another root or explicit file.
+ pub fn opencode_model_target_candidates(&self) -> Vec<PathBuf> {
+ let Ok(native) = self.opencode_native_context() else {
+ return Vec::new();
+ };
+ let selected = self.opencode_user_models_target();
+ let mut candidates = vec![selected.clone()];
+ if native.config_file.is_none() {
+ candidates.push(native.resource_root().join(
+ if selected.extension().is_some_and(|x| x == "json") {
+ "opencode.jsonc"
+ } else {
+ "opencode.json"
+ },
+ ));
+ }
+ candidates
+ }
+ pub fn bind_opencode_model_target(
+ &mut self,
+ path: PathBuf,
+ ) -> Result<(), AgentFilesystemScanError> {
+ if !self.opencode_model_target_candidates().contains(&path) {
+ return Err(AgentFilesystemScanError::InvalidConfig);
+ }
+ self.opencode_model_target = path;
+ Ok(())
+ }
+ pub fn opencode_user_skill_target(&self) -> PathBuf {
+ self.layout
+ .opencode_context
+ .as_ref()
+ .map(|c| c.skill_target())
+ .unwrap_or_default()
+ }
+ pub fn opencode_executable_target(&self) -> Option<PathBuf> {
+ let selected = &self.layout.opencode_executable;
+ match super::super::opencode_native_executable(selected) {
+ Ok(None) if selected == std::path::Path::new("opencode") => {
+ // Finder-launched clients may not inherit the installer's shell PATH.
+ // An explicit saved installation must never fall back to another binary.
+ let home = &self.opencode_native_context().ok()?.home;
+ super::super::opencode_native_executable(&home.join(".opencode/bin/opencode"))
+ .ok()
+ .flatten()
+ }
+ result => result.ok().flatten(),
+ }
+ }
+ pub fn opencode_settings_discovery(&self) -> FilesystemAgentDiscoveryV1 {
+ let executable = self.opencode_executable_target();
+ let Ok(context) = self.opencode_native_context() else {
+ return report_only_agent(
+ "agent_opencode_default",
+ AgentKindV1::OpenCode,
+ "not-probed".into(),
+ AgentReportOnlyReasonV1::ConfigUnavailable,
+ );
+ };
+ if executable.is_none()
+ && !context.resource_root().is_dir()
+ && !context.model_target().is_file()
+ {
+ return probe_report(
+ "agent_opencode_default",
+ AgentKindV1::OpenCode,
+ ExecutableProbe::NotFound,
+ );
+ }
+ let mut outcome = resolve_agent_observation(base_observation(
+ "agent_opencode_default",
+ AgentKindV1::OpenCode,
+ "not-probed".into(),
+ ));
+ if let AgentDiscoveryOutcomeV1::Supported { installation } = &mut outcome {
+ super::super::observed_capabilities::attach_optional_file_capabilities(
+ installation,
+ executable.as_deref(),
+ &context.skill_target(),
+ );
+ #[cfg(any(unix, windows))]
+ if let Some(executable) = &executable
+ && let Ok(cache) = self.opencode_collaboration.lock()
+ && let Some(evidence) = &cache.evidence
+ {
+ evidence.attach(executable, context, installation);
+ }
+ }
+ FilesystemAgentDiscoveryV1 {
+ outcome,
+ configuration_issue: None,
+ claude_configuration: None,
+ discovered_credential: None,
+ permission_hardening: None,
+ managed_launch: None,
+ }
+ }
+}
+
+impl FilesystemAgentScannerV1 {
+ /// Non-target user layers are independent dependencies of the existing owned-file effect.
+ pub fn opencode_model_facts(
+ &self,
+ namespace: &str,
+ models: &[hiroute_domain::AdditionalAgentModelV1],
+ ) -> Result<(CanonicalDigest, bool), AgentFilesystemScanError> {
+ let native = self.opencode_native_context()?;
+ if native.has_remote_configuration()? {
+ return Err(AgentFilesystemScanError::InvalidConfig);
+ }
+ let config = native.read_config(None)?;
+ let resources = super::super::opencode_resources::model_references(native);
+ if super::super::opencode::dynamic_keys(&config.value) {
+ return Err(AgentFilesystemScanError::InvalidConfig);
+ }
+ let target = self.opencode_user_models_target();
+ let owned = |id: &str| {
+ id == namespace
+ || id
+ .strip_prefix(&format!("{namespace}-"))
+ .is_some_and(|s| s.len() == 32 && s.bytes().all(|b| b.is_ascii_hexdigit()))
+ };
+ let retain = models
+ .iter()
+ .map(|m| {
+ format!(
+ "{}/{}",
+ hiroute_domain::additional_model_plan_provider_id(namespace, &m.alias),
+ m.alias
+ )
+ })
+ .collect::<BTreeSet<_>>();
+ for (path, _) in &config.documents {
+ if *path == target {
+ continue;
+ }
+ if let Some((bytes, _)) =
+ super::super::filesystem_config::read_system_config_bytes(path)?
+ {
+ let document = super::super::pi_sources::Document(
+ super::super::opencode::parse_jsonc(&bytes)
+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?,
+ );
+ if document.0["provider"]
+ .as_object()
+ .is_some_and(|providers| providers.keys().any(|id| owned(id)))
+ {
+ return Err(AgentFilesystemScanError::InvalidConfig);
+ }
+ }
+ }
+ let mut default_in_use = false;
+ if let Some(providers) = config.value["provider"].as_object() {
+ for id in providers.keys().filter(|id| owned(id)) {
+ if let Err(error) = super::super::opencode::validate_references(
+ &config.value,
+ id,
+ &config.value["provider"][id],
+ &retain,
+ resources.as_ref().ok().map(|r| r.models.as_slice()),
+ ) {
+ if error.stage != "default in use" {
+ return Err(AgentFilesystemScanError::InvalidConfig);
+ }
+ default_in_use = true;
+ }
+ }
+ }
+ for model in models {
+ let id = hiroute_domain::additional_model_plan_provider_id(namespace, &model.alias);
+ if config.value["enabled_providers"]
+ .as_array()
+ .is_some_and(|v| !v.iter().any(|x| x.as_str() == Some(&id)))
+ || config.value["disabled_providers"]
+ .as_array()
+ .is_some_and(|v| v.iter().any(|x| x.as_str() == Some(&id)))
+ {
+ return Err(AgentFilesystemScanError::InvalidConfig);
+ }
+ }
+ let mut documents = config
+ .documents
+ .iter()
+ .filter(|(path, _)| *path != target)
+ .collect::<Vec<_>>();
+ let digest = if let Ok(resources) = &resources {
+ documents.extend(resources.documents.iter());
+ CanonicalDigest::of(&documents)
+ } else {
+ CanonicalDigest::of(&(documents, "unavailable native model references"))
+ }
+ .map_err(|_| AgentFilesystemScanError::InvalidConfig)?;
+ Ok((digest, default_in_use))
+ }
+ pub fn opencode_model_dependencies(
+ &self,
+ namespace: &str,
+ models: &[hiroute_domain::AdditionalAgentModelV1],
+ ) -> Result<CanonicalDigest, AgentFilesystemScanError> {
+ let (digest, in_use) = self.opencode_model_facts(namespace, models)?;
+ if in_use {
+ return Err(AgentFilesystemScanError::SourceChanged);
+ }
+ Ok(digest)
+ }
+}
+
+#[cfg(any(unix, windows))]
+impl FilesystemAgentScannerV1 {
+ pub fn check_opencode_collaboration(
+ &self,
+ cli: &Path,
+ target: super::super::QoderCollaborationProbeTarget,
+ ) -> Result<(), QoderNativeError> {
+ let generation = self
+ .opencode_collaboration
+ .lock()
+ .map_err(|_| qoder_error("evidence cache"))?
+ .begin()?;
+ let executable = self
+ .opencode_executable_target()
+ .ok_or_else(|| qoder_error("selected executable"))?;
+ let evidence = super::super::OpenCodeCollaborationProbe::run(
+ &executable,
+ self.opencode_native_context()
+ .map_err(|_| qoder_error("native context"))?,
+ cli,
+ target,
+ )?;
+ self.opencode_collaboration
+ .lock()
+ .map_err(|_| qoder_error("evidence cache"))?
+ .finish(generation, evidence)
+ }
+}
diff --git a/crates/integrations/src/agents/opencode_sources.rs b/crates/integrations/src/agents/opencode_sources.rs
new file mode 100644
index 00000000..66be4d26
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_sources.rs
@@ -0,0 +1,365 @@
+//! Passive OpenCode API-key import; no SDK/plugin/helper execution or native OAuth ownership.
+use super::pi_sources::Document;
+use super::{
+ AgentFilesystemScanError as Error, DiscoveredAuthSource, DiscoveredCredentialRefV1,
+ FILESYSTEM_AGENT_SCANNER_ID_V1, FILESYSTEM_AGENT_SCANNER_VERSION_V1, FilesystemAgentScannerV1,
+ NativeApiSource,
+};
+use hiroute_domain::{CanonicalDigest, ProtectedSecret, UpstreamProtocol};
+use serde_json::Value;
+use std::path::{Path, PathBuf};
+use zeroize::Zeroizing;
+
+type Material = Option<(Zeroizing<String>, ProtectedSecret)>;
+
+impl FilesystemAgentScannerV1 {
+ pub fn opencode_api_sources(&self) -> Result<Vec<NativeApiSource>, Error> {
+ self.opencode_sources_inner(None).map(|(items, _)| items)
+ }
+ pub fn read_opencode_api_source(
+ &self,
+ selected: &NativeApiSource,
+ ) -> Result<(Zeroizing<String>, ProtectedSecret), Error> {
+ let (items, material) = self.opencode_sources_inner(Some(&selected.source_ref))?;
+ if !items.iter().any(|i| i == selected) {
+ return Err(Error::SourceChanged);
+ }
+ let material = material.ok_or(Error::SourceUnavailable)?;
+ if !self.opencode_api_sources()?.iter().any(|i| i == selected) {
+ return Err(Error::SourceChanged);
+ }
+ Ok(material)
+ }
+ pub(super) fn read_opencode_secret(
+ &self,
+ descriptor: &DiscoveredCredentialRefV1,
+ ) -> Result<ProtectedSecret, Error> {
+ let selected = self
+ .opencode_api_sources()?
+ .into_iter()
+ .find(|s| s.credential.as_ref() == Some(descriptor))
+ .ok_or(Error::SourceChanged)?;
+ self.read_opencode_api_source(&selected)
+ .map(|(_, secret)| secret)
+ }
+ fn opencode_sources_inner(
+ &self,
+ selected: Option<&str>,
+ ) -> Result<(Vec<NativeApiSource>, Material), Error> {
+ let native = self.opencode_native_context()?;
+ let config = native.read_config(None)?;
+ let dynamic_keys = super::opencode::dynamic_keys(&config.value);
+ let remote = native.has_remote_configuration()?;
+ let auth = super::filesystem_config::read_validated_config_bytes(
+ &native.data_root.join("auth.json"),
+ )?;
+ let auth_digest =
+ CanonicalDigest::of_bytes(auth.as_ref().map_or(&[][..], |(b, _)| b.as_slice()));
+ let auth = Document(match auth {
+ Some((bytes, _)) => serde_json::from_slice(&bytes).map_err(|_| Error::InvalidConfig)?,
+ None => serde_json::json!({}),
+ });
+ let Some(providers) = config.value.get("provider").and_then(Value::as_object) else {
+ return Ok((Vec::new(), None));
+ };
+ if providers.len() > 256 {
+ return Err(Error::ConfigTooLarge);
+ }
+ let mut items = Vec::new();
+ let mut material = None;
+ for (provider_id, provider) in providers {
+ if provider_id.starts_with("hiroute-") {
+ continue;
+ }
+ if !bounded(provider_id) {
+ continue;
+ }
+ let mut origin = self.opencode_user_models_target();
+ for (path, _) in &config.documents {
+ if let Some((bytes, _)) = super::filesystem_config::read_system_config_bytes(path)?
+ {
+ let doc = Document(
+ super::opencode::parse_jsonc(&bytes).map_err(|_| Error::InvalidConfig)?,
+ );
+ if doc.0["provider"][provider_id]["options"]
+ .get("apiKey")
+ .is_some()
+ {
+ origin = path.clone();
+ }
+ }
+ }
+ let options = &provider["options"];
+ let stored = &auth.0[provider_id];
+ let mut key_evidence = Vec::new();
+ let mut key_available = true;
+ let (authentication, secret) = if let Some(value) = options.get("apiKey") {
+ match resolve_key(value.as_str(), &origin, &native.home, &mut key_evidence) {
+ Ok(key) => key,
+ Err(_) => {
+ // A provider-local credential cannot hide independent candidates.
+ // No descriptor/material is issued; selected reads still compare
+ // the full fresh candidate and reject any changed evidence.
+ key_available = false;
+ (DiscoveredAuthSource::Missing, None)
+ }
+ }
+ } else if stored["type"] == "api" {
+ (
+ DiscoveredAuthSource::InlineToken,
+ stored["key"]
+ .as_str()
+ .filter(|s| valid_key(s))
+ .map(|s| Zeroizing::new(s.into())),
+ )
+ } else if stored["type"] == "oauth" {
+ (DiscoveredAuthSource::NativeSessionNeedsConfirmation, None)
+ } else {
+ let env = provider["env"]
+ .as_array()
+ .filter(|v| v.len() == 1)
+ .and_then(|v| v[0].as_str())
+ .or_else(|| match provider["npm"].as_str() {
+ Some("@ai-sdk/openai") => Some("OPENAI_API_KEY"),
+ Some("@ai-sdk/anthropic") => Some("ANTHROPIC_API_KEY"),
+ _ => None,
+ });
+ match env {
+ Some(name) if env_name(name) => (
+ DiscoveredAuthSource::EnvironmentKey,
+ std::env::var(name)
+ .ok()
+ .filter(|s| valid_key(s))
+ .map(Zeroizing::new),
+ ),
+ _ => (DiscoveredAuthSource::Missing, None),
+ }
+ };
+ let clean = |v: &Value| v.is_null() || v.as_object().is_some_and(|v| v.is_empty());
+ let representable = key_available
+ && !remote
+ && !dynamic_keys
+ && stored["type"] != "oauth"
+ && clean(&options["headers"])
+ && options.as_object().is_none_or(|o| {
+ o.keys()
+ .all(|k| matches!(k.as_str(), "baseURL" | "apiKey" | "headers"))
+ })
+ && !config.executable_plugins;
+ let declarations = provider["models"]
+ .as_object()
+ .map(|m| m.iter().map(|(k, v)| (k.clone(), v)).collect::<Vec<_>>())
+ .unwrap_or_else(|| vec![(String::new(), &Value::Null)]);
+ for (native_id, model) in declarations {
+ if items.len() >= 256 {
+ return Err(Error::ConfigTooLarge);
+ }
+ let id = model["id"].as_str().unwrap_or(&native_id);
+ if !id.is_empty() && !bounded(id) {
+ continue;
+ }
+ let protocol = match model["provider"]["npm"]
+ .as_str()
+ .or_else(|| provider["npm"].as_str())
+ {
+ Some("@ai-sdk/openai") => Some(UpstreamProtocol::Responses),
+ Some("@ai-sdk/anthropic") => Some(UpstreamProtocol::Messages),
+ Some("@ai-sdk/openai-compatible") => Some(UpstreamProtocol::ChatCompletions),
+ _ => None,
+ };
+ let endpoint = options["baseURL"]
+ .as_str()
+ .or_else(|| model["provider"]["api"].as_str())
+ .or_else(|| provider["api"].as_str());
+ let endpoint = endpoint.filter(|s| {
+ s.len() <= 8192
+ && !s.contains(['{', '}', '\r', '\n'])
+ && (s.starts_with("https://") || s.starts_with("http://"))
+ });
+ let supported = representable
+ && !native_id.is_empty()
+ && !id.is_empty()
+ && !id.contains(['{', '}'])
+ && endpoint.is_some()
+ && protocol.is_some()
+ && clean(&model["headers"])
+ && clean(&model["options"]);
+ let source_digest = CanonicalDigest::of(&(native, provider_id, &native_id))
+ .map_err(|_| Error::InvalidConfig)?;
+ let source_ref = format!("opencode-source/{}", &source_digest.as_str()[7..]);
+ let evidence_digest = CanonicalDigest::of(&(
+ "opencode-api-evidence/v1",
+ &source_ref,
+ &config.digest,
+ &auth_digest,
+ &key_evidence,
+ secret
+ .as_ref()
+ .map(|s| CanonicalDigest::of_bytes(s.as_bytes())),
+ remote,
+ ))
+ .map_err(|_| Error::InvalidConfig)?;
+ let revision = u64::from_str_radix(&evidence_digest.as_str()[7..23], 16)
+ .map_err(|_| Error::InvalidConfig)?
+ .max(1);
+ let credential =
+ secret
+ .as_ref()
+ .filter(|_| supported)
+ .map(|_| DiscoveredCredentialRefV1 {
+ source: "discovered_config".into(),
+ scanner_id: FILESYSTEM_AGENT_SCANNER_ID_V1.into(),
+ scanner_version: FILESYSTEM_AGENT_SCANNER_VERSION_V1.into(),
+ discovered_source_ref: source_ref.clone(),
+ field_selector: "opencode.api-key".into(),
+ observed_revision: revision,
+ });
+ if selected == Some(&source_ref)
+ && supported
+ && let (Some(endpoint), Some(secret)) = (endpoint, secret.as_ref())
+ {
+ material = Some((
+ Zeroizing::new(endpoint.into()),
+ ProtectedSecret::new(secret.as_bytes().to_vec())
+ .map_err(|_| Error::InvalidConfig)?,
+ ));
+ }
+ items.push(NativeApiSource {
+ point_binding: endpoint.map(|endpoint| super::NativeApiPointBindingV1 {
+ native_scope: CanonicalDigest::of(&("opencode-native-scope/v1", native))
+ .expect("native scope"),
+ provider_definition: format!("provider/{provider_id}"),
+ endpoint: endpoint.into(),
+ authentication: if protocol == Some(UpstreamProtocol::Messages) {
+ hiroute_domain::GatewayAuthenticationSemanticsV1::ApiKeyHeader {
+ header: "x-api-key".into(),
+ }
+ } else {
+ hiroute_domain::GatewayAuthenticationSemanticsV1::Bearer
+ },
+ endpoint_selector: if options.get("baseURL").is_some() {
+ format!("provider/{provider_id}/options/baseURL")
+ } else if model["provider"].get("api").is_some() {
+ format!("provider/{provider_id}/models/{native_id}/provider/api")
+ } else {
+ format!("provider/{provider_id}/api")
+ },
+ protocol_selector: if model["provider"].get("npm").is_some() {
+ format!("provider/{provider_id}/models/{native_id}/provider/npm")
+ } else {
+ format!("provider/{provider_id}/npm")
+ },
+ model_override_scope: (model["provider"].get("api").is_some()
+ || model["provider"].get("npm").is_some())
+ .then(|| native_id.clone()),
+ credential_binding: format!(
+ "provider/{provider_id}/{}:{}",
+ if options.get("apiKey").is_some() {
+ "configuration-api-key"
+ } else {
+ "auth-json"
+ },
+ CanonicalDigest::of(&origin)
+ .expect("native credential origin")
+ .as_str()
+ ),
+ configured_default_model_id: config.value["model"]
+ .as_str()
+ .and_then(|default| default.strip_prefix(&format!("{provider_id}/")))
+ .and_then(|default| {
+ provider["models"][default]["id"].as_str().or(Some(default))
+ })
+ .map(str::to_owned),
+ }),
+ provider_id: provider_id.clone(),
+ model_id: id.into(),
+ protocol,
+ display_name: model["name"]
+ .as_str()
+ .filter(|s| bounded(s))
+ .unwrap_or(&native_id)
+ .into(),
+ context_tokens: model["limit"]["context"].as_u64(),
+ max_output_tokens: model["limit"]["output"].as_u64(),
+ vision: model["modalities"]["input"]
+ .as_array()
+ .map(|v| v.iter().any(|x| x == "image")),
+ reasoning: model["reasoning"].as_bool(),
+ authentication,
+ source_ref,
+ evidence_digest,
+ revision,
+ credential,
+ supported_auth: supported,
+ });
+ }
+ }
+ Ok((items, material))
+ }
+}
+
+fn bounded(s: &str) -> bool {
+ !s.is_empty() && s.len() <= 256 && !s.chars().any(char::is_control)
+}
+fn valid_key(s: &str) -> bool {
+ !s.is_empty() && s.len() <= 64 * 1024 && !s.contains(['\0', '\r', '\n'])
+}
+fn env_name(s: &str) -> bool {
+ bounded(s) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
+}
+fn resolve_key(
+ value: Option<&str>,
+ origin: &Path,
+ home: &Path,
+ evidence: &mut Vec<(PathBuf, CanonicalDigest)>,
+) -> Result<(DiscoveredAuthSource, Option<Zeroizing<String>>), Error> {
+ let Some(value) = value else {
+ return Ok((DiscoveredAuthSource::Missing, None));
+ };
+ if let Some(name) = value
+ .strip_prefix("{env:")
+ .and_then(|s| s.strip_suffix('}'))
+ .filter(|s| env_name(s))
+ {
+ return Ok((
+ DiscoveredAuthSource::EnvironmentKey,
+ std::env::var(name)
+ .ok()
+ .filter(|s| valid_key(s))
+ .map(Zeroizing::new),
+ ));
+ }
+ if let Some(relative) = value
+ .strip_prefix("{file:")
+ .and_then(|s| s.strip_suffix('}'))
+ {
+ if relative.contains(['{', '}', '\0']) {
+ return Ok((DiscoveredAuthSource::Missing, None));
+ }
+ let raw = if let Some(tail) = relative.strip_prefix("~/") {
+ home.join(tail)
+ } else {
+ PathBuf::from(relative)
+ };
+ let path = if raw.is_absolute() {
+ raw
+ } else {
+ origin.parent().ok_or(Error::InvalidConfig)?.join(raw)
+ };
+ let Some((bytes, _)) = super::filesystem_config::read_validated_config_bytes(&path)? else {
+ return Ok((DiscoveredAuthSource::Missing, None));
+ };
+ evidence.push((path, CanonicalDigest::of_bytes(&bytes)));
+ let value = std::str::from_utf8(&bytes)
+ .map_err(|_| Error::InvalidConfig)?
+ .trim();
+ return Ok((
+ DiscoveredAuthSource::InlineToken,
+ valid_key(value).then(|| Zeroizing::new(value.into())),
+ ));
+ }
+ Ok((
+ DiscoveredAuthSource::InlineToken,
+ (!value.contains(['{', '}']) && valid_key(value)).then(|| Zeroizing::new(value.into())),
+ ))
+}
diff --git a/crates/integrations/src/agents/opencode_tests.rs b/crates/integrations/src/agents/opencode_tests.rs
new file mode 100644
index 00000000..f077eb5d
--- /dev/null
+++ b/crates/integrations/src/agents/opencode_tests.rs
@@ -0,0 +1,272 @@
+//! OpenCode uses the same edit/restore machinery, with its native SDK and JSONC policy.
+use super::additional_native::{Restore, configure};
+use super::opencode::parse_jsonc;
+use hiroute_domain::{
+ AdditionalAgentModelV1, AgentAccessGrantMaterial, AgentIngressProtocolV1, AgentKindV1,
+};
+const OWNER: &str = "hiroute-main-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+fn models() -> Vec<AdditionalAgentModelV1> {
+ [
+ AgentIngressProtocolV1::Responses,
+ AgentIngressProtocolV1::Messages,
+ ]
+ .into_iter()
+ .enumerate()
+ .map(|(i, protocol)| AdditionalAgentModelV1 {
+ alias: format!("hiroute/{i:016x}"),
+ protocol,
+ context_window_tokens: 16384,
+ max_output_tokens: 4096,
+ })
+ .collect()
+}
+#[test]
+fn opencode_routes_preserve_jsonc_defaults_and_restore_after_unowned_edits() {
+ let original = br#"{
+ // Daily default remains native.
+ "model":"daily/first",
+ "small_model":"daily/small",
+ "provider":{"daily":{"npm":"@ai-sdk/openai","models":{"first":{},"small":{},},},},
+ "extension":{"array":[1,2,],},
+ }"#;
+ let models = models();
+ let token = AgentAccessGrantMaterial::from_csprng_entropy([7; 32]);
+ let edit = configure(
+ AgentKindV1::OpenCode,
+ Some(original),
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models,
+ &token,
+ None,
+ )
+ .unwrap();
+ let value = parse_jsonc(&edit.bytes).unwrap();
+ assert_eq!(value["model"], "daily/first");
+ assert_eq!(value["small_model"], "daily/small");
+ assert!(value.get("providers").is_none());
+ for m in &models {
+ let id = hiroute_domain::additional_model_provider_for(OWNER, &models, m);
+ let p = &value["provider"][&id];
+ assert_eq!(
+ p["npm"],
+ if m.protocol == AgentIngressProtocolV1::Responses {
+ "@ai-sdk/openai"
+ } else {
+ "@ai-sdk/anthropic"
+ }
+ );
+ assert_eq!(p["models"].as_object().unwrap().len(), 1);
+ assert_eq!(p["models"][&m.alias]["id"], m.alias);
+ assert_eq!(
+ p["options"]["headers"]["X-HiRoute-Token"],
+ std::str::from_utf8(token.expose()).unwrap()
+ );
+ assert_eq!(p["options"]["baseURL"], "http://127.0.0.1:4321/v1");
+ assert!(p["models"][&m.alias]["limit"].get("input").is_none());
+ }
+ let restore = Restore::decode(&edit.restore.encode().unwrap()).unwrap();
+ assert_eq!(
+ restore
+ .restore(Some(&edit.bytes))
+ .unwrap()
+ .unwrap()
+ .as_slice(),
+ original
+ );
+ let edited = String::from_utf8(edit.bytes.to_vec())
+ .unwrap()
+ .replace("\"array\":[1,2,]", "\"array\":[1,2,3,]");
+ let restored = restore.restore(Some(edited.as_bytes())).unwrap().unwrap();
+ assert!(
+ std::str::from_utf8(&restored)
+ .unwrap()
+ .contains("\"array\":[1,2,3,]")
+ );
+ assert_eq!(
+ parse_jsonc(&restored).unwrap()["provider"]
+ .as_object()
+ .unwrap()
+ .len(),
+ 1
+ );
+}
+#[test]
+fn opencode_referenced_selector_can_rotate_but_cannot_disappear() {
+ let models = models();
+ let token = AgentAccessGrantMaterial::from_csprng_entropy([7; 32]);
+ let edit = configure(
+ AgentKindV1::OpenCode,
+ None,
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models,
+ &token,
+ None,
+ )
+ .unwrap();
+ let mut value = parse_jsonc(&edit.bytes).unwrap();
+ let id = hiroute_domain::additional_model_provider_for(OWNER, &models, &models[0]);
+ value["agent"] = serde_json::json!({"custom":{"model":format!("{id}/{}",models[0].alias)}});
+ let current = serde_json::to_vec(&value).unwrap();
+ assert!(edit.restore.restore(Some(&current)).is_err());
+ let rotated = AgentAccessGrantMaterial::from_csprng_entropy([8; 32]);
+ assert!(
+ configure(
+ AgentKindV1::OpenCode,
+ Some(&current),
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models,
+ &rotated,
+ Some(&edit.restore)
+ )
+ .is_ok()
+ );
+ assert!(
+ configure(
+ AgentKindV1::OpenCode,
+ Some(&current),
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models[1..],
+ &rotated,
+ Some(&edit.restore)
+ )
+ .is_err()
+ );
+}
+
+#[test]
+fn opencode_new_native_file_has_schema_without_adopting_an_existing_user_file() {
+ let models = models();
+ let token = AgentAccessGrantMaterial::from_csprng_entropy([3; 32]);
+ let edit = configure(
+ AgentKindV1::OpenCode,
+ None,
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models,
+ &token,
+ None,
+ )
+ .unwrap();
+ assert_eq!(
+ parse_jsonc(&edit.bytes).unwrap()["$schema"],
+ "https://opencode.ai/config.json"
+ );
+ assert!(edit.restore.restore(Some(&edit.bytes)).unwrap().is_none());
+ let existing = br#"{"extension":true}"#;
+ let edit = configure(
+ AgentKindV1::OpenCode,
+ Some(existing),
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models,
+ &token,
+ None,
+ )
+ .unwrap();
+ assert!(parse_jsonc(&edit.bytes).unwrap().get("$schema").is_none());
+}
+
+#[test]
+fn opencode_format_metadata_is_bounded_and_does_not_execute_the_selected_binary() {
+ let root = tempfile::tempdir().unwrap();
+ let platform = if cfg!(target_os = "macos") {
+ "darwin"
+ } else if cfg!(windows) {
+ "windows"
+ } else {
+ "linux"
+ };
+ let cpu = if cfg!(target_arch = "aarch64") {
+ "arm64"
+ } else {
+ "x64"
+ };
+ let name = format!(
+ "opencode-{platform}-{cpu}{}",
+ if cfg!(target_env = "musl") {
+ "-musl"
+ } else {
+ ""
+ }
+ );
+ let package = root.path().join(&name);
+ let bin = package.join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ let native = bin.join(if cfg!(windows) {
+ "opencode.exe"
+ } else {
+ "opencode"
+ });
+ std::fs::write(&native, b"unexecuted native metadata fixture").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&native, std::fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ let mut metadata = serde_json::json!({"name":name,"version":"1.19.3","os":[if cfg!(windows){"win32"}else{platform}],"cpu":[cpu]});
+ if cfg!(target_env = "musl") {
+ metadata["libc"] = serde_json::json!(["musl"]);
+ }
+ let path = package.join("package.json");
+ std::fs::write(&path, metadata.to_string()).unwrap();
+ assert_eq!(super::opencode_native_format(&native).unwrap().len(), 38);
+ metadata["version"] = "unaudited".into();
+ std::fs::write(&path, metadata.to_string()).unwrap();
+ assert!(
+ super::opencode_native_executable(&native)
+ .unwrap()
+ .is_some()
+ );
+ assert!(super::opencode_native_format(&native).is_err());
+}
+
+#[test]
+fn opencode_symbolic_model_choices_block_removal_but_allow_retained_token_rotation() {
+ let models = models();
+ let token = AgentAccessGrantMaterial::from_csprng_entropy([7; 32]);
+ let edit = configure(
+ AgentKindV1::OpenCode,
+ None,
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models,
+ &token,
+ None,
+ )
+ .unwrap();
+ for choice in [
+ serde_json::json!({"model":"{env:NATIVE_MODEL}"}),
+ serde_json::json!({"small_model":"{file:small-model.txt}"}),
+ serde_json::json!({"agent":{"daily":{"model":"{env:NATIVE_MODEL}"}}}),
+ serde_json::json!({"mode":{"daily":{"model":"{file:agent-model.txt}"}}}),
+ ] {
+ let mut value = parse_jsonc(&edit.bytes).unwrap();
+ value
+ .as_object_mut()
+ .unwrap()
+ .extend(choice.as_object().unwrap().clone());
+ let current = serde_json::to_vec(&value).unwrap();
+ assert!(
+ edit.restore.restore(Some(&current)).is_err(),
+ "an unresolved native selector cannot authorize removal"
+ );
+ let rotated = AgentAccessGrantMaterial::from_csprng_entropy([8; 32]);
+ assert!(
+ configure(
+ AgentKindV1::OpenCode,
+ Some(&current),
+ OWNER,
+ "http://127.0.0.1:4321/v1",
+ &models,
+ &rotated,
+ Some(&edit.restore),
+ )
+ .is_ok(),
+ "retaining every selector can rotate the grant without interpreting native choices"
+ );
+ }
+}
diff --git a/crates/integrations/src/agents/pi_runtime.rs b/crates/integrations/src/agents/pi_runtime.rs
index ff90943c..64b706b8 100644
--- a/crates/integrations/src/agents/pi_runtime.rs
+++ b/crates/integrations/src/agents/pi_runtime.rs
@@ -191,51 +191,7 @@ use hiroute_domain::delegation::{
NativeDependencyCheckV1, NativeDependencyFailureReasonV1, NativeDependencyFailureV1,
};
-#[cfg(unix)]
-fn bounded_check(
- mut command: std::process::Command,
- check: NativeDependencyCheckV1,
- timeout: std::time::Duration,
- output_limit: usize,
-) -> Result<zeroize::Zeroizing<Vec<u8>>, NativeDependencyFailureV1> {
- use NativeDependencyFailureReasonV1 as Reason;
- use std::os::unix::process::CommandExt;
- use std::process::Stdio;
- use std::time::{Duration, Instant};
- let failure = |reason| NativeDependencyFailureV1 { check, reason };
- let start = Instant::now();
- let capture = tempfile::NamedTempFile::new().map_err(|_| failure(Reason::Unavailable))?;
- let child = command
- .env_remove("NODE_OPTIONS")
- .env_remove("HIROUTE_RUN_TOKEN")
- .stdin(Stdio::null())
- .stdout(capture.reopen().map_err(|_| failure(Reason::Unavailable))?)
- .stderr(Stdio::null())
- .process_group(0)
- .spawn()
- .map_err(|_| failure(Reason::Unavailable))?;
- let mut child = super::NativeProbeProcess::new(child);
- let result = (|| {
- loop {
- if start.elapsed() >= timeout {
- return Err(failure(Reason::Timeout));
- }
- match child.observe().map_err(|_| failure(Reason::Unavailable))? {
- Some(true) => break,
- Some(false) => return Err(failure(Reason::ProcessFailed)),
- None => {}
- }
- std::thread::sleep(Duration::from_millis(5));
- }
- super::native_probe_process::read_bounded(capture.path(), output_limit)
- .map_err(|_| failure(Reason::InvalidOutput))
- })();
- // A failed check also stops and accounts for its owned scope before returning.
- child.stop().map_err(|_| failure(Reason::CleanupFailed))?;
- result
-}
-
-#[cfg(windows)]
+#[cfg(any(unix, windows))]
fn bounded_check(
mut command: std::process::Command,
check: NativeDependencyCheckV1,
@@ -245,24 +201,8 @@ fn bounded_check(
command
.env_remove("NODE_OPTIONS")
.env_remove("HIROUTE_RUN_TOKEN");
- super::windows_runtime::bounded(&command, true, timeout, output_limit).map_err(|error| {
- NativeDependencyFailureV1 {
- check,
- reason: if super::windows_runtime::cleanup_unknown(&error) {
- NativeDependencyFailureReasonV1::CleanupFailed
- } else if super::windows_runtime::process_exit_code(&error).is_some() {
- NativeDependencyFailureReasonV1::ProcessFailed
- } else {
- match error.kind() {
- std::io::ErrorKind::TimedOut => NativeDependencyFailureReasonV1::Timeout,
- std::io::ErrorKind::InvalidData => {
- NativeDependencyFailureReasonV1::InvalidOutput
- }
- _ => NativeDependencyFailureReasonV1::Unavailable,
- }
- },
- }
- })
+ super::native_probe_process::capture(command, true, timeout, output_limit)
+ .map_err(|reason| NativeDependencyFailureV1 { check, reason })
}
#[cfg(all(test, unix))]
diff --git a/crates/integrations/src/agents/pi_sources.rs b/crates/integrations/src/agents/pi_sources.rs
index c38b059c..5574a167 100644
--- a/crates/integrations/src/agents/pi_sources.rs
+++ b/crates/integrations/src/agents/pi_sources.rs
@@ -480,3 +480,65 @@ impl FilesystemAgentScannerV1 {
Ok((items, material))
}
}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum NativeApiEcosystem {
+ Pi,
+ Dsh,
+ OpenCode,
+}
+impl NativeApiEcosystem {
+ pub const ALL: [Self; 3] = [Self::Pi, Self::Dsh, Self::OpenCode];
+ pub fn agent_id(self) -> &'static str {
+ match self {
+ Self::Pi => "agent_pi_default",
+ Self::Dsh => "agent_dsh_default",
+ Self::OpenCode => "agent_opencode_default",
+ }
+ }
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Pi => "Pi",
+ Self::Dsh => "DSH",
+ Self::OpenCode => "OpenCode",
+ }
+ }
+ pub fn from_source(source: &NativeApiSource) -> Option<Self> {
+ Self::from_selector(match source.source_ref.split_once('/')?.0 {
+ "pi-source" => "pi.api-key",
+ "dsh-source" => "dsh.api-key",
+ "opencode-source" => "opencode.api-key",
+ _ => return None,
+ })
+ }
+ pub fn from_selector(selector: &str) -> Option<Self> {
+ match selector {
+ "pi.api-key" => Some(Self::Pi),
+ "dsh.api-key" => Some(Self::Dsh),
+ "opencode.api-key" => Some(Self::OpenCode),
+ _ => None,
+ }
+ }
+}
+impl FilesystemAgentScannerV1 {
+ pub fn native_api_sources(
+ &self,
+ ecosystem: NativeApiEcosystem,
+ ) -> Result<Vec<NativeApiSource>, Error> {
+ match ecosystem {
+ NativeApiEcosystem::Pi => self.pi_api_sources(),
+ NativeApiEcosystem::Dsh => self.dsh_api_sources(),
+ NativeApiEcosystem::OpenCode => self.opencode_api_sources(),
+ }
+ }
+ pub fn read_native_api_source(
+ &self,
+ source: &NativeApiSource,
+ ) -> Result<(Zeroizing<String>, ProtectedSecret), Error> {
+ match NativeApiEcosystem::from_source(source).ok_or(Error::InvalidConfig)? {
+ NativeApiEcosystem::Pi => self.read_pi_api_source(source),
+ NativeApiEcosystem::Dsh => self.read_dsh_api_source(source),
+ NativeApiEcosystem::OpenCode => self.read_opencode_api_source(source),
+ }
+ }
+}
diff --git a/crates/integrations/src/agents/qoder_jsonc.rs b/crates/integrations/src/agents/qoder_jsonc.rs
index 361abfc7..ce777c9a 100644
--- a/crates/integrations/src/agents/qoder_jsonc.rs
+++ b/crates/integrations/src/agents/qoder_jsonc.rs
@@ -1,5 +1,5 @@
//! Bounded JSON-with-comments edits preserve every byte outside the selected object member.
-//! Qoder accepts comments. Duplicate keys and trailing commas are rejected, never normalized.
+//! Native syntax policy preserves each consumer's grammar; duplicate keys always fail.
use std::ops::Range;
use serde_json::{Map, Value};
@@ -12,6 +12,7 @@ pub(super) const LIMIT: usize = 1024 * 1024;
pub(super) struct Document<'a> {
bytes: &'a [u8],
pub root: Node,
+ trailing_commas: bool,
}
pub(super) struct Node {
@@ -29,10 +30,21 @@ struct Member {
impl<'a> Document<'a> {
pub fn parse(bytes: &'a [u8]) -> Result<Self, QoderNativeError> {
+ Self::parse_with_trailing_commas(bytes, false)
+ }
+
+ pub fn parse_with_trailing_commas(
+ bytes: &'a [u8],
+ trailing_commas: bool,
+ ) -> Result<Self, QoderNativeError> {
if bytes.len() > LIMIT || std::str::from_utf8(bytes).is_err() {
return Err(invalid());
}
- let mut parser = Parser { bytes, pos: 0 };
+ let mut parser = Parser {
+ bytes,
+ pos: 0,
+ trailing_commas,
+ };
// Match Qoder's BOM handling without changing the original bytes.
if bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
parser.pos = 3;
@@ -42,7 +54,11 @@ impl<'a> Document<'a> {
if parser.pos != bytes.len() || !root.value.is_object() {
return Err(invalid());
}
- Ok(Self { bytes, root })
+ Ok(Self {
+ bytes,
+ root,
+ trailing_commas,
+ })
}
pub fn object(&self, parent: &Node, key: &str) -> Result<Option<Node>, QoderNativeError> {
@@ -52,6 +68,7 @@ impl<'a> Document<'a> {
let mut parser = Parser {
bytes: self.bytes,
pos: member.value.start,
+ trailing_commas: self.trailing_commas,
};
let node = parser.value(0)?;
if !node.value.is_object() {
@@ -88,7 +105,11 @@ impl<'a> Document<'a> {
}
}
} else if let Some(value) = value {
- let mut insert = if object.members.is_empty() {
+ let trailing = object
+ .members
+ .last()
+ .is_some_and(|member| member.comma.is_some());
+ let mut insert = if object.members.is_empty() || trailing {
Vec::new()
} else {
b",".to_vec()
@@ -97,6 +118,9 @@ impl<'a> Document<'a> {
insert.extend(serde_json::to_vec(key).map_err(|_| invalid())?);
insert.push(b':');
insert.extend(serde_json::to_vec(value).map_err(|_| invalid())?);
+ if trailing {
+ insert.push(b',');
+ }
insert.push(b'\n');
edits.push((object.range.end - 1..object.range.end - 1, insert));
}
@@ -105,7 +129,7 @@ impl<'a> Document<'a> {
for (range, replacement) in edits {
result.splice(range, replacement);
}
- Document::parse(&result)?;
+ Document::parse_with_trailing_commas(&result, self.trailing_commas)?;
Ok(result)
}
}
@@ -113,6 +137,7 @@ impl<'a> Document<'a> {
struct Parser<'a> {
bytes: &'a [u8],
pos: usize,
+ trailing_commas: bool,
}
impl Parser<'_> {
@@ -221,6 +246,10 @@ impl Parser<'_> {
break;
}
self.pos += 1;
+ self.skip()?;
+ if self.trailing_commas && self.bytes.get(self.pos) == Some(&b'}') {
+ break;
+ }
}
}
if self.bytes.get(self.pos) != Some(&b'}') {
@@ -241,6 +270,10 @@ impl Parser<'_> {
break;
}
self.pos += 1;
+ self.skip()?;
+ if self.trailing_commas && self.bytes.get(self.pos) == Some(&b']') {
+ break;
+ }
}
}
if self.bytes.get(self.pos) != Some(&b']') {
@@ -277,3 +310,47 @@ impl Parser<'_> {
fn invalid() -> QoderNativeError {
qoder_error("native settings JSON")
}
+
+#[cfg(test)]
+mod syntax_tests {
+ use super::*;
+
+ #[test]
+ fn opencode_trailing_separators_survive_owned_edits() {
+ let input = b"{ // unrelated\n\"list\":[1,2,],\n\"provider\":{\"user\":{\"key\":true,},}, // preserve\n}";
+ assert!(Document::parse(input).is_err());
+ let document = Document::parse_with_trailing_commas(input, true).unwrap();
+ let providers = document
+ .object(&document.root, "provider")
+ .unwrap()
+ .unwrap();
+ let added = document
+ .edit(
+ &providers,
+ "managed",
+ Some(&serde_json::json!({"id":"route"})),
+ )
+ .unwrap();
+ assert!(String::from_utf8_lossy(&added).contains("// preserve"));
+ assert!(String::from_utf8_lossy(&added).contains("\"list\":[1,2,]"));
+ let document = Document::parse_with_trailing_commas(&added, true).unwrap();
+ let providers = document
+ .object(&document.root, "provider")
+ .unwrap()
+ .unwrap();
+ let removed = document.edit(&providers, "managed", None).unwrap();
+ let parsed = Document::parse_with_trailing_commas(&removed, true).unwrap();
+ assert_eq!(
+ parsed.root.value["provider"],
+ serde_json::json!({"user":{"key":true}})
+ );
+ assert!(String::from_utf8_lossy(&removed).contains("\"user\":{\"key\":true,}"));
+ }
+
+ #[test]
+ fn opencode_policy_never_admits_duplicate_or_empty_members() {
+ for input in [b"{\"a\":1,\"a\":2,}".as_slice(), b"{\"a\":[1,,]}", b"{,}"] {
+ assert!(Document::parse_with_trailing_commas(input, true).is_err());
+ }
+ }
+}
diff --git a/crates/integrations/src/agents/qoder_probe.rs b/crates/integrations/src/agents/qoder_probe.rs
index 4941889f..1750738e 100644
--- a/crates/integrations/src/agents/qoder_probe.rs
+++ b/crates/integrations/src/agents/qoder_probe.rs
@@ -456,7 +456,10 @@ impl QoderCollaborationProbe {
}
}
-fn confirmed_skill(path: &Path, expected: &CanonicalDigest) -> Result<String, QoderNativeError> {
+pub(super) fn confirmed_skill(
+ path: &Path,
+ expected: &CanonicalDigest,
+) -> Result<String, QoderNativeError> {
let metadata =
fs::symlink_metadata(path).map_err(|_| qoder_error("installed user Skill missing"))?;
if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 128 * 1024 {
@@ -472,7 +475,7 @@ fn confirmed_skill(path: &Path, expected: &CanonicalDigest) -> Result<String, Qo
.map_err(|_| qoder_error("installed user Skill encoding"))
}
-fn skill_body(content: &str) -> Result<String, QoderNativeError> {
+pub(super) fn skill_body(content: &str) -> Result<String, QoderNativeError> {
content
.strip_prefix("---\n")
.and_then(|text| text.split_once("\n---\n"))
@@ -609,7 +612,7 @@ fn shell_quote(path: &Path) -> Result<String, QoderNativeError> {
))
}
-fn cli_command(cli: &Path) -> Result<String, QoderNativeError> {
+pub(super) fn cli_command(cli: &Path) -> Result<String, QoderNativeError> {
// Qoder 1.1.65's Bash tool uses Git Bash on Windows, independently of its
// separate PowerShell tool. The resolved native image already passed the
// shared ordinary-drive projection; retain that same identity when making
@@ -642,7 +645,7 @@ fn cli_command(cli: &Path) -> Result<String, QoderNativeError> {
}
#[cfg(unix)]
-fn cli_baseline(cli: &Path, root: &Path) -> Result<String, QoderNativeError> {
+pub(super) fn cli_baseline(cli: &Path, root: &Path) -> Result<String, QoderNativeError> {
let output = private_file(&root.join("cli.private"))?;
let observer = output
.try_clone()
@@ -713,7 +716,7 @@ fn cli_baseline(cli: &Path, root: &Path) -> Result<String, QoderNativeError> {
}
#[cfg(windows)]
-fn cli_baseline(cli: &Path, root: &Path) -> Result<String, QoderNativeError> {
+pub(super) fn cli_baseline(cli: &Path, root: &Path) -> Result<String, QoderNativeError> {
let mut command = Command::new(cli);
command
.args(["schema", "list", "--output", "json"])
diff --git a/crates/integrations/src/agents/qoder_probe_http.rs b/crates/integrations/src/agents/qoder_probe_http.rs
index 4f2c067a..feff176e 100644
--- a/crates/integrations/src/agents/qoder_probe_http.rs
+++ b/crates/integrations/src/agents/qoder_probe_http.rs
@@ -4,9 +4,7 @@
mod cli_diagnostic;
use serde_json::{Value, json};
-use std::io::{Read, Write};
use std::net::TcpStream;
-use std::time::{Duration, Instant};
pub(super) struct Challenge {
pub skill_name: String,
@@ -130,134 +128,7 @@ pub(super) fn serve(
model: &str,
challenge: &mut Challenge,
) -> Result<(), &'static str> {
- let body = read_request(stream, token, model)?;
- let item = challenge.reply(&body)?;
- let response = json!({"id":"resp_hiroute_probe", "object":"response", "created_at":1, "status":"completed", "model":model, "output":[item], "usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}});
- let mut started = response.clone();
- started["status"] = "in_progress".into();
- started["output"] = json!([]);
- let mut added = item.clone();
- added["status"] = "in_progress".into();
- let mut events = vec![("response.created", json!({"response":started}))];
- if item["type"] == "function_call" {
- // Qoder validates streaming argument consistency; adding the final arguments and then
- // appending a delta would duplicate them and fail before any tool executes.
- added["arguments"] = "".into();
- events.push((
- "response.output_item.added",
- json!({"output_index":0,"item":added}),
- ));
- events.push((
- "response.function_call_arguments.delta",
- json!({"output_index":0,"item_id":item["id"],"delta":item["arguments"]}),
- ));
- events.push((
- "response.function_call_arguments.done",
- json!({"output_index":0,"item_id":item["id"],"arguments":item["arguments"]}),
- ));
- } else {
- added["content"] = json!([]);
- events.push((
- "response.output_item.added",
- json!({"output_index":0,"item":added}),
- ));
- events.push((
- "response.output_text.delta",
- json!({"output_index":0,"content_index":0,"item_id":item["id"],"delta":"OK"}),
- ));
- }
- events.push((
- "response.output_item.done",
- json!({"output_index":0,"item":item}),
- ));
- events.push(("response.completed", json!({"response":response})));
- let mut payload = String::new();
- for (index, (kind, mut event)) in events.into_iter().enumerate() {
- event["type"] = kind.into();
- event["sequence_number"] = index.into();
- payload.push_str(&format!("event: {kind}\ndata: {event}\n\n"));
- }
- write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",payload.len()).map_err(|_| "loopback response")
-}
-
-fn read_request(stream: &mut TcpStream, token: &str, model: &str) -> Result<Value, &'static str> {
- stream.set_nonblocking(false).map_err(|_| "socket mode")?;
- stream
- .set_read_timeout(Some(Duration::from_millis(500)))
- .map_err(|_| "socket timeout")?;
- stream
- .set_write_timeout(Some(Duration::from_millis(500)))
- .map_err(|_| "socket timeout")?;
- let started = Instant::now();
- let mut bytes = zeroize::Zeroizing::new(Vec::new());
- let (header_end, length) = loop {
- if bytes.len() > 128 * 1024 || started.elapsed() > Duration::from_secs(2) {
- return Err("request bound");
- }
- if let Some(end) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
- let header = std::str::from_utf8(&bytes[..end]).map_err(|_| "request header")?;
- if header.lines().next() != Some("POST /v1/responses HTTP/1.1") {
- return Err("request path");
- }
- let mut auth = None;
- let mut length = None;
- for line in header.lines().skip(1) {
- let (name, value) = line.split_once(':').ok_or("request header")?;
- if name.eq_ignore_ascii_case("authorization")
- && auth.replace(value.trim()).is_some()
- {
- return Err("duplicate auth");
- }
- if name.eq_ignore_ascii_case("content-length")
- && length
- .replace(
- value
- .trim()
- .parse::<usize>()
- .map_err(|_| "request length")?,
- )
- .is_some()
- {
- return Err("duplicate length");
- }
- if name.eq_ignore_ascii_case("transfer-encoding") {
- return Err("request framing");
- }
- }
- if auth.and_then(|value| value.strip_prefix("Bearer ")) != Some(token) {
- return Err("request credential");
- }
- break (
- end + 4,
- length
- .filter(|value| *value <= 128 * 1024)
- .ok_or("request length")?,
- );
- }
- let mut chunk = [0; 4096];
- let size = stream.read(&mut chunk).map_err(|_| "request header read")?;
- if size == 0 {
- return Err("short request");
- }
- bytes.extend_from_slice(&chunk[..size]);
- };
- while bytes.len() < header_end + length {
- if started.elapsed() > Duration::from_secs(2) {
- return Err("request deadline");
- }
- let mut chunk = [0; 4096];
- let size = stream.read(&mut chunk).map_err(|_| "request body read")?;
- if size == 0 {
- return Err("short request");
- }
- bytes.extend_from_slice(&chunk[..size]);
- }
- let body: Value = serde_json::from_slice(&bytes[header_end..header_end + length])
- .map_err(|_| "request json")?;
- if body["model"] != model {
- return Err("request model");
- }
- Ok(body)
+ super::super::native_responses_probe::serve(stream, token, model, |body| challenge.reply(body))
}
#[cfg(test)]
diff --git a/crates/integrations/src/agents/registry.rs b/crates/integrations/src/agents/registry.rs
index 483bf47a..5fcf51b0 100644
--- a/crates/integrations/src/agents/registry.rs
+++ b/crates/integrations/src/agents/registry.rs
@@ -24,6 +24,7 @@ pub fn builtin_agent_profiles() -> Vec<AgentProfileV1> {
qoder_collaboration_profile_v1(),
pi_profile_v1(),
dsh_profile_v1(),
+ opencode_profile_v1(),
hermes_profile_v1(),
]
}
@@ -212,3 +213,24 @@ pub fn hermes_profile_v1() -> AgentProfileV1 {
managed_launch: None,
}
}
+
+pub const OPENCODE_PROFILE_ID_V1: &str = "opencode-responses-v1";
+pub const OPENCODE_INTEGRATION_PROFILE_REF_V1: &str = "builtin/opencode-responses/v1";
+
+pub fn opencode_profile_v1() -> AgentProfileV1 {
+ AgentProfileV1 {
+ schema: AGENT_PROFILE_SCHEMA_V1.into(),
+ profile_id: OPENCODE_PROFILE_ID_V1.into(),
+ integration_profile_ref: OPENCODE_INTEGRATION_PROFILE_REF_V1.into(),
+ kind: AgentKindV1::OpenCode,
+ legacy_exact_versions: BTreeSet::new(),
+ ingress_protocol: Some(AgentIngressProtocolV1::Responses),
+ config_precedence: AgentKindV1::OpenCode.config_precedence().to_vec(),
+ owned_config_fields: vec![field("additional_provider", "hiroute.additional_provider")],
+ dynamic_catalog: false,
+ static_catalog_fallback: false,
+ native_subagent_routing: false,
+ spawn_guidance: None,
+ managed_launch: None,
+ }
+}
diff --git a/crates/integrations/src/agents/tests.rs b/crates/integrations/src/agents/tests.rs
index e1f51695..ee0069a5 100644
--- a/crates/integrations/src/agents/tests.rs
+++ b/crates/integrations/src/agents/tests.rs
@@ -21,7 +21,7 @@ fn observation(kind: AgentKindV1, version: &str) -> AgentScanObservationV1 {
#[test]
fn agents_registry_binds_codex_to_responses_and_claude_to_messages() {
let profiles = builtin_agent_profiles();
- assert_eq!(profiles.len(), 6);
+ assert_eq!(profiles.len(), 7);
for profile in &profiles {
profile.validate().unwrap();
}
diff --git a/crates/integrations/src/agents/windows_runtime.rs b/crates/integrations/src/agents/windows_runtime.rs
index a37cf66b..7393a951 100644
--- a/crates/integrations/src/agents/windows_runtime.rs
+++ b/crates/integrations/src/agents/windows_runtime.rs
@@ -96,6 +96,7 @@ pub fn windows_npm_entry_with_inspection(
"pi" => "@earendil-works/pi-coding-agent",
"dsh" => "@deepseek-ai/dsh",
"qoder" | "qodercli" => "@qoder-ai/qodercli",
+ "opencode" => "opencode-ai",
_ => return Err(io::Error::other("unknown npm producer")),
};
let bin_directory = shim.parent().ok_or_else(|| io::Error::other("npm root"))?;
diff --git a/crates/local-storage/src/control/worker_dependencies.rs b/crates/local-storage/src/control/worker_dependencies.rs
index 4ae8a13e..0dc92f28 100644
--- a/crates/local-storage/src/control/worker_dependencies.rs
+++ b/crates/local-storage/src/control/worker_dependencies.rs
@@ -629,6 +629,7 @@ pub(super) const fn harness_key(harness: WorkerHarnessV1) -> &'static str {
WorkerHarnessV1::ClaudeCode => "claude_code",
WorkerHarnessV1::QoderCli => "qoder_cli",
WorkerHarnessV1::Pi => "pi",
+ WorkerHarnessV1::OpenCode => "opencode",
WorkerHarnessV1::DeepseekHarness => "deepseek_harness",
}
}
@@ -639,6 +640,7 @@ fn parse_harness(value: &str) -> PortResult<WorkerHarnessV1> {
"claude_code" => Ok(WorkerHarnessV1::ClaudeCode),
"qoder_cli" => Ok(WorkerHarnessV1::QoderCli),
"pi" => Ok(WorkerHarnessV1::Pi),
+ "opencode" => Ok(WorkerHarnessV1::OpenCode),
"deepseek_harness" => Ok(WorkerHarnessV1::DeepseekHarness),
_ => Err(port(
PortErrorCode::Corrupt,
diff --git a/crates/local-storage/src/control/worker_dependencies_tests.rs b/crates/local-storage/src/control/worker_dependencies_tests.rs
index b5c4fde7..73ff4e46 100644
--- a/crates/local-storage/src/control/worker_dependencies_tests.rs
+++ b/crates/local-storage/src/control/worker_dependencies_tests.rs
@@ -36,6 +36,7 @@ fn selection_operation(
WorkerHarnessV1::QoderCli => "qoder_cli",
WorkerHarnessV1::Pi => "pi",
WorkerHarnessV1::DeepseekHarness => "deepseek_harness",
+ WorkerHarnessV1::OpenCode => "opencode",
};
let expected_revisions = RevisionSetV1 {
target: change.before_revision,
diff --git a/crates/local-storage/src/migrations/mod.rs b/crates/local-storage/src/migrations/mod.rs
index 21133a62..2c828fbd 100644
--- a/crates/local-storage/src/migrations/mod.rs
+++ b/crates/local-storage/src/migrations/mod.rs
@@ -46,6 +46,7 @@ mod worker_dependencies_v24;
mod worker_dependencies_v24_tests;
mod worker_dependencies_v26;
mod worker_dependencies_v27;
+mod worker_dependencies_v30;
mod worker_instance_v19;
#[cfg(test)]
@@ -54,7 +55,7 @@ mod convergence_tests;
/// Current stable storage format, including native ACP Worker dependency selections.
/// Production source admission is defined in `startup_format`; supported upgrades retain the
/// existing durable three-store backup and recovery coordinator.
-pub const LATEST_SCHEMA_VERSION: u32 = 29;
+pub const LATEST_SCHEMA_VERSION: u32 = 30;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DatabaseKind {
@@ -471,7 +472,7 @@ impl MigrationSetCoordinator {
};
if !matches!(
set.target_schema_version(),
- 24 | 25 | 26 | LATEST_SCHEMA_VERSION
+ 24 | 25 | 26 | 29 | LATEST_SCHEMA_VERSION
) || (set.target_schema_version() == 24
&& [
set.control.manifest(),
@@ -867,6 +868,8 @@ fn migration_sql(kind: DatabaseKind, version: u32) -> Result<&'static str, Local
CREATE UNIQUE INDEX secret_owner_fingerprint_idx
ON secret_entries(owner_scope, fingerprint) WHERE purpose != 'http-header';"),
(DatabaseKind::Control | DatabaseKind::Runtime, 29) => Ok(NOOP_V9),
+ (DatabaseKind::Control, 30) => Ok(worker_dependencies_v30::CONTROL),
+ (DatabaseKind::Runtime | DatabaseKind::Secrets, 30) => Ok(NOOP_V9),
_ => Err(LocalStorageError::InvalidData),
}
}
diff --git a/crates/local-storage/src/migrations/startup_format.rs b/crates/local-storage/src/migrations/startup_format.rs
index 3af5a2b3..be7c3d5b 100644
--- a/crates/local-storage/src/migrations/startup_format.rs
+++ b/crates/local-storage/src/migrations/startup_format.rs
@@ -36,7 +36,7 @@ pub(crate) fn validate_startup_format(root: &Path) -> Result<(), LocalStorageErr
// Schema 23 is the first stable format; 24 preserves that same marker.
// A mixed supported live set is only a candidate for the existing coordinator:
// it must still prove its complete source backup, store identities, key and phase.
- if !matches!(version, 23 | 24 | 25 | 26 | 27 | 28 | LATEST_SCHEMA_VERSION) {
+ if !matches!(version, 23..=LATEST_SCHEMA_VERSION) {
return Err(LocalStorageError::UpgradeSourceUnsupported);
}
let marker = connection.query_row(
diff --git a/crates/local-storage/src/migrations/worker_dependencies_v30.rs b/crates/local-storage/src/migrations/worker_dependencies_v30.rs
new file mode 100644
index 00000000..1b05ec81
--- /dev/null
+++ b/crates/local-storage/src/migrations/worker_dependencies_v30.rs
@@ -0,0 +1,81 @@
+//! Admit OpenCode native selections, preserving all existing row and journal bytes.
+
+pub(super) const CONTROL: &str = r#"
+CREATE TABLE worker_dependency_selections_v30 (
+ workspace_id TEXT NOT NULL,
+ harness TEXT NOT NULL CHECK(harness IN ('codex_cli','claude_code','qoder_cli','pi','deepseek_harness','opencode')),
+ revision INTEGER NOT NULL
+ CHECK(typeof(revision) = 'integer' AND revision > 0),
+ selection_json TEXT NOT NULL,
+ owner_operation_id TEXT NOT NULL REFERENCES operations(operation_id),
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY(workspace_id, harness)
+);
+
+CREATE TABLE worker_dependency_selection_effects_v30 (
+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id) ON DELETE CASCADE,
+ workspace_id TEXT NOT NULL,
+ harness TEXT NOT NULL CHECK(harness IN ('codex_cli','claude_code','qoder_cli','pi','deepseek_harness','opencode')),
+ before_revision INTEGER NOT NULL
+ CHECK(typeof(before_revision) = 'integer' AND before_revision >= 0),
+ before_json TEXT,
+ before_owner_operation_id TEXT,
+ after_revision INTEGER NOT NULL
+ CHECK(typeof(after_revision) = 'integer' AND after_revision > 0),
+ after_json TEXT NOT NULL,
+ activated INTEGER NOT NULL DEFAULT 0 CHECK(activated IN (0,1)),
+ compensated INTEGER NOT NULL DEFAULT 0 CHECK(compensated IN (0,1)),
+ UNIQUE(workspace_id, harness, after_revision)
+);
+
+INSERT INTO worker_dependency_selections_v30
+ SELECT workspace_id, harness, revision, selection_json, owner_operation_id, updated_at
+ FROM worker_dependency_selections;
+INSERT INTO worker_dependency_selection_effects_v30
+ SELECT operation_id, workspace_id, harness, before_revision, before_json,
+ before_owner_operation_id, after_revision, after_json, activated, compensated
+ FROM worker_dependency_selection_effects;
+
+DROP TABLE worker_dependency_selection_effects;
+DROP TABLE worker_dependency_selections;
+ALTER TABLE worker_dependency_selections_v30 RENAME TO worker_dependency_selections;
+ALTER TABLE worker_dependency_selection_effects_v30 RENAME TO worker_dependency_selection_effects;
+CREATE INDEX worker_dependency_selection_effects_state
+ ON worker_dependency_selection_effects(activated, compensated, operation_id);
+"#;
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn opencode_selection_constraint_extends_existing_tables_without_changing_raw_rows() {
+ let db = rusqlite::Connection::open_in_memory().unwrap();
+ db.execute_batch("CREATE TABLE operations(operation_id TEXT PRIMARY KEY); INSERT INTO operations VALUES('accepted');
+ CREATE TABLE worker_dependency_selections(workspace_id TEXT,harness TEXT,revision INTEGER,selection_json TEXT,owner_operation_id TEXT,updated_at INTEGER);
+ CREATE TABLE worker_dependency_selection_effects(operation_id TEXT,workspace_id TEXT,harness TEXT,before_revision INTEGER,before_json TEXT,before_owner_operation_id TEXT,after_revision INTEGER,after_json TEXT,activated INTEGER,compensated INTEGER);
+ CREATE INDEX worker_dependency_selection_effects_state ON worker_dependency_selection_effects(activated,compensated,operation_id);").unwrap();
+ let raw = "{ \"harness\": \"pi\", \"cli_path\": \"/selected/pi\", \"node_path\":\"/selected/node\" }";
+ db.execute(
+ "INSERT INTO worker_dependency_selections VALUES('w','pi',7,?1,'accepted',99)",
+ [raw],
+ )
+ .unwrap();
+ db.execute("INSERT INTO worker_dependency_selection_effects VALUES('accepted','w','pi',6,?1,'previous',7,?1,1,0)",[raw]).unwrap();
+ db.execute_batch(super::CONTROL).unwrap();
+ assert_eq!(
+ db.query_row(
+ "SELECT selection_json FROM worker_dependency_selections WHERE harness='pi'",
+ [],
+ |r| r.get::<_, String>(0)
+ )
+ .unwrap(),
+ raw
+ );
+ assert_eq!(db.query_row("SELECT before_json,after_json,activated,compensated FROM worker_dependency_selection_effects",[],|r|Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,i64>(2)?,r.get::<_,i64>(3)?))).unwrap(),(raw.into(),raw.into(),1,0));
+ db.execute(
+ "INSERT INTO worker_dependency_selections VALUES('w','opencode',1,'{}','accepted',100)",
+ [],
+ )
+ .unwrap();
+ assert!(db.execute("INSERT INTO worker_dependency_selections VALUES('w','unregistered',1,'{}','accepted',100)",[]).is_err());
+ }
+}
diff --git a/crates/product-session/src/agent_check_session.rs b/crates/product-session/src/agent_check_session.rs
index df370ebb..72335e73 100644
--- a/crates/product-session/src/agent_check_session.rs
+++ b/crates/product-session/src/agent_check_session.rs
@@ -125,6 +125,7 @@ impl AgentCheckConfirmation {
"agent_qoder_default" => "Qoder",
"agent_pi_default" => "Pi",
"agent_dsh_default" => "DeepSeek Harness",
+ "agent_opencode_default" => "OpenCode",
_ => "Codex",
};
if self.request.scope == AgentCheckScopeV1::Live {
@@ -140,6 +141,7 @@ impl AgentCheckConfirmation {
AgentModelSurfaceV2::QoderCli => "Qoder CLI",
AgentModelSurfaceV2::PiCli => "Pi CLI",
AgentModelSurfaceV2::DshCli => "DeepSeek Harness",
+ AgentModelSurfaceV2::OpenCodeCli => "OpenCode",
AgentModelSurfaceV2::HermesCli => "Hermes",
};
let models = target.client_model_ids.join(", ");
@@ -279,7 +281,9 @@ impl AgentCheckInput {
};
let supported = match self.agent_id.as_str() {
"agent_codex_default" | "agent_claude_default" => true,
- "agent_pi_default" | "agent_dsh_default" => scope == AgentCheckScopeV1::Collaboration,
+ "agent_pi_default" | "agent_dsh_default" | "agent_opencode_default" => {
+ scope == AgentCheckScopeV1::Collaboration
+ }
"agent_qoder_default" => matches!(
scope,
AgentCheckScopeV1::Collaboration | AgentCheckScopeV1::Live
@@ -391,7 +395,12 @@ mod tests {
#[test]
fn additional_agents_keep_collaboration_independent_and_require_explicit_live_targets() {
- for agent in ["agent_qoder_default", "agent_pi_default"] {
+ for agent in [
+ "agent_qoder_default",
+ "agent_pi_default",
+ "agent_dsh_default",
+ "agent_opencode_default",
+ ] {
let mut input = AgentCheckInput {
agent_id: agent.into(),
language: "en".into(),
@@ -463,6 +472,8 @@ mod tests {
("agent_claude_default", vec![AgentModelSurfaceV2::ClaudeCli]),
("agent_qoder_default", vec![AgentModelSurfaceV2::QoderCli]),
("agent_pi_default", vec![]),
+ ("agent_dsh_default", vec![]),
+ ("agent_opencode_default", vec![]),
] {
for surface in [
AgentModelSurfaceV2::CodexCli,
@@ -470,6 +481,8 @@ mod tests {
AgentModelSurfaceV2::ClaudeCli,
AgentModelSurfaceV2::QoderCli,
AgentModelSurfaceV2::PiCli,
+ AgentModelSurfaceV2::DshCli,
+ AgentModelSurfaceV2::OpenCodeCli,
] {
let mut target = live_target();
target.surface = surface;
diff --git a/docs/code-map/README.md b/docs/code-map/README.md
index 63c14c4a..8db045d3 100644
--- a/docs/code-map/README.md
+++ b/docs/code-map/README.md
@@ -44,7 +44,7 @@ results in the relevant run record.
| Map | Scope |
| --- | --- |
| [Architecture and ownership](architecture.md) | Shared layers, source admission, durable state, observation and change boundaries |
-| [Agent integrations and Workers](worker-context.md) | Shared configuration/lifecycle owners, with Codex, Claude, Qoder, Pi and DSH differences together |
+| [Agent integrations and Workers](worker-context.md) | Shared configuration/lifecycle owners, with Codex, Claude, Qoder, Pi, DSH and OpenCode differences together |
| [Decision models and routing](decision-foundation.md) | Saved connections, provider adapters, per-turn policy and competence attribution |
| [Tests as product documentation](testing.md) | Proof levels, reusable fixtures, representative fault cases and validation selection |
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index 5ab899aa..4e7e4b7a 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -112,7 +112,7 @@ The name must fit any runtime root that supports `hiroute/control.sock`, includi
| User step | Owners to follow | Representative guard |
| --- | --- | --- |
| Add an API connection and choose its models | [Connection directory](../../apps/desktop/src/features/model-connections/ConnectionDirectory.tsx), [form and draft ownership](../../apps/desktop/src/features/model-connections/README.md), [registered check](../../crates/daemon/src/control/runtime/model_connections/registered.rs) | The executable catalog supplies the complete directory. A source name survives check/save; per-product credentials stay in the dialog and protected input. Released public registered probes may omit the name and use the authenticated option label; the current Desktop check requires an explicit label. |
-| Discover a native source without executing it | [Native model connections](../../crates/integrations/src/model_connections), [Pi reader](../../crates/integrations/src/agents/pi_sources.rs), [DSH reader](../../crates/integrations/src/agents/dsh_sources.rs), [Hermes reader](../../crates/integrations/src/agents/hermes_sources.rs) | Shared [point grouping](../../crates/integrations/src/agents/native_points.rs) keeps scope/provider/address/protocol/authentication distinct; static scan never executes helpers |
+| Discover a native source without executing it | [Native model connections](../../crates/integrations/src/model_connections), [Pi reader](../../crates/integrations/src/agents/pi_sources.rs), [DSH reader](../../crates/integrations/src/agents/dsh_sources.rs), [OpenCode reader](../../crates/integrations/src/agents/opencode_sources.rs), [Hermes reader](../../crates/integrations/src/agents/hermes_sources.rs) | Shared [point grouping](../../crates/integrations/src/agents/native_points.rs) keeps scope/provider/address/protocol/authentication distinct; static scan never executes helpers |
| Display, prepare and save the selected source | [Safe shared product projection](../../crates/product-session/src/commands/model_connection_web.rs), [V2 points/catalog qualification](../../crates/daemon/src/control/runtime/model_connections/points.rs), [daemon preparation](../../crates/daemon/src/control/runtime/model_connections/pi_discovered.rs) | Exact native/catalog provenance and explicit model selection remain visible; privileged locators stay private; stale facts cannot expand an accepted selection; legacy one-model handles retain their meaning |
| Rename a connection, append models or remove saved configuration | [Shared lifecycle planner](../../crates/application/src/compute_management/mutations/lifecycle.rs), [transactional reference guards](../../crates/local-storage/src/control/compute/management/references.rs), [Desktop lifecycle dialog](../../apps/desktop/src/features/models/ConnectionLifecycleDialog.tsx) | Templates do not own credentials. Explicit append preserves saved members; enabled/disabled routes and retained recovery versions block removal. Removing the last model requires explicit connection deletion; owned secrets follow the same recoverable operation. |
| Save Key order or use current Keys with an older plan | [Single-save edits](../../apps/desktop/src/features/models/model-draft.ts), [request admission](../../crates/gateway/src/core_runtime/credentials.rs), [current pool authority](../../crates/local-storage/src/control/compute/management/runtime_pool.rs), [safe Key masks](../../crates/daemon/src/control/runtime/model_connections/key_masks.rs) | A request owns its admitted Key IDs and order; later exact leases enforce current source/Key eligibility and generation. Admission retains closed permission denials in the existing request summary. Shared Plan content stays frozen. Masks are a separate authenticated query; saved plaintext never reaches Desktop. |
@@ -146,8 +146,9 @@ does not establish Agent convergence. Port selection belongs to the shared
[listener store](../../crates/host-runtime/src/gateway_listener.rs), including Desktop.
Follow discovery through an ordinary request using the saved source. The
-[Pi](../../tools/product-e2e/tests/PI_INTEGRATION.md) and
-[DSH](../../tools/product-e2e/tests/DSH_INTEGRATION.md) acceptance entries cover
+[Pi](../../tools/product-e2e/tests/PI_INTEGRATION.md),
+[DSH](../../tools/product-e2e/tests/DSH_INTEGRATION.md) and
+[OpenCode](../../tools/product-e2e/tests/OPENCODE_INTEGRATION.md) acceptance entries cover
Scan → Prepare → Save → restart → native use, including stale-source rejection.
The shared product-session layer in `crates/product-session` owns Preview composition, confirmation permits, retry identity and protected-input lifetime. Desktop supplies its inherited-channel `HostAuthority` adapter in `apps/desktop/src-tauri/src/bootstrap/authority.rs`; native startup, updater and window authority stay with the Desktop host.
diff --git a/docs/code-map/testing.md b/docs/code-map/testing.md
index 7a3412bb..55d563f7 100644
--- a/docs/code-map/testing.md
+++ b/docs/code-map/testing.md
@@ -10,6 +10,8 @@ Windows development execution is owned by [windows-dev.py](../../scripts/windows
and its [native executor](../../scripts/windows-dev-host.py), reached through
`validation.py windows`. HOME configuration owns machine/session/client locations;
the project owns artifact admission, exact-case execution and revision-bound evidence.
+Its four temporary-directory native artifact ACL/recovery cases can execute without
+replacing an existing installation; installed-product cases still require a fresh profile.
[Orphaned data preparation](../../scripts/windows-dev-profile.py) preserves complete
backups after explicit user authorization; it does not establish a product scenario.
[Native Desktop session actions](../../scripts/windows-desktop-session.py) admit
@@ -332,6 +334,9 @@ they retain neither arbitrary result text nor a guessed per-run failure cause.
The [cancel publication fixture](../../crates/daemon/tests/support/windows_worker_cancel.rs)
waits for the complete nonce receipt within the original deadline; file existence
alone does not prove that the native writer has published its contents.
+The shared model oracle follows the declared shell timeout units. OpenCode's
+Windows shell receipt uses the runner's pinned Node with encoded paths, so the
+same cancellation check works with PowerShell, cmd and Git Bash.
Its residual binding reader distinguishes incomplete publication from fatal native
identity errors. The [residual oracle](../../crates/daemon/tests/support/windows_worker_residual_oracle.rs)
keeps correlated tool errors observable, with fixed stage/error facts and no native
diff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.md
index 7c4984e1..8b13f923 100644
--- a/docs/code-map/worker-context.md
+++ b/docs/code-map/worker-context.md
@@ -15,7 +15,7 @@ a prerequisite, not a model call, installed Skill invocation or resumable task.
| Configure, edit and restore models | [Settings transaction](../../crates/application/src/agent_connection/settings), [typed facts](../../crates/daemon/src/control/runtime/settings_facts), [Desktop Agent feature](../../apps/desktop/src/features/agents/README.md) | [Additional native provider guide](../../crates/integrations/src/agents/additional_native/README.md), [saved-model journey](../../crates/daemon/tests/support/additional_model_product.py), [Windows ordinary Pi/DSH clients](../../crates/daemon/tests/support/windows_user_models.rs), [Windows Qoder official-account journey](../../crates/daemon/tests/support/windows_qoder_user_models.rs) |
| Enable, edit or disable task collaboration independently | [CLI intent workflow](../../crates/cli/src/collaboration.rs), [Skill effects](../../crates/application/src/agent_connection), [shared session checks](../../crates/product-session/src/agent_check_session.rs) | [CLI workflow regressions](../../crates/cli/src/collaboration/tests.rs), [real main-Agent → public CLI → Worker journey](../../crates/daemon/tests/support/collaboration_product.py) |
-Qoder/Pi/DSH saved models use one owned provider per Plan with an explicit
+Qoder/Pi/DSH/OpenCode saved models use one owned provider per Plan with an explicit
Responses/Messages choice. [Route grants](../../crates/domain/src/agents/model_grant.rs)
and [Gateway trust](../../crates/gateway/src/publication/trust.rs) preserve alias,
protocol and receipt authority across publication/restart. `work.protocol` is the
@@ -24,6 +24,17 @@ report the actual installed consumers; [safe conflict facts](../../crates/domain
retain rejection identity through compensation and client observation.
Native defaults and collaboration stay independent;
restoration must verify ownership rather than infer it from a provider name.
+OpenCode's [startup target binding](../../crates/daemon/src/control/runtime.rs) keeps
+the physical JSON/JSONC file verified by existing recovery markers;
+[effective model facts](../../crates/integrations/src/agents/opencode_scanner.rs)
+also feed the shared configured/drift status.
+Its [bounded Markdown reference reader](../../crates/integrations/src/agents/opencode_resources.rs)
+adds native user Agent/Mode selectors to the same settings dependency checks;
+removal requires complete references, while retaining selectors permits grant rotation.
+Worker project ancestry uses the [native Git boundary check](../../crates/integrations/src/agents/opencode_project.rs)
+with the filtered child HOME/XDG/PATH and shared bounded probe process. Both configuration
+and resource inspection require a confirmed Git stop or the filesystem root within the
+existing bound; an invalid marker or unavailable Git cannot truncate admission.
Hermes uses an [explicit effective profile](../../crates/integrations/src/agents/hermes/README.md)
and one default main-model Plan. Desktop keeps Hermes in the common Agent list;
@@ -51,7 +62,7 @@ the existing local Worker CLI and does not become a Worker executor.
| Resolve resources and construct a run | [Installation](../../crates/daemon/src/delegation/installation.rs), [native context](../../crates/daemon/src/delegation/profile/native_context.rs), [profile guide](../../crates/daemon/src/delegation/profile/README.md) | Effective instance HOME/config root supplies resources; per-run overrides supply route, credential and permission policy |
| Project native context/output budgets | [Shared budget policy](../../crates/domain/src/agents/additional_model.rs), [native projection](../../crates/integrations/src/agents/qoder_budget.rs) | Preserve the frozen Plan's active-candidate/protocol bounds; Gateway output capping alone cannot prove native compaction limits |
| Admit and attribute model requests | [Run authority](../../crates/daemon/src/delegation/run_authority.rs), [Gateway dispatch](../../crates/gateway/src/dispatch/run.rs) | Sealed Plan, live run, harness, protocol and observation identity must agree |
-| Confirm the native session/model | [ACP model confirmation](../../crates/daemon/src/delegation/acp/model.rs), [ACP driver](../../crates/daemon/src/delegation/acp/mod.rs) | Confirm the exact native model before prompt; missing capability cannot silently change the route |
+| Confirm the native session/model | [ACP model confirmation](../../crates/daemon/src/delegation/acp/model.rs), [ACP driver](../../crates/daemon/src/delegation/acp/mod.rs) | Confirm typed mode before the final typed model for OpenCode; confirm the exact native model before prompt; missing capability cannot silently change the route |
| Continue the same task | [History binding](../../crates/daemon/src/delegation/profile/native_history.rs), [resume](../../crates/daemon/src/delegation/executor/resume.rs) | Restore the exact frozen context/session with a fresh credential; never select the newest history or start a replacement conversation |
| Start, cancel and finalize processes | [Executor](../../crates/daemon/src/delegation/executor.rs), [OS launcher](../../crates/daemon/src/delegation/local_worker/README.md), [finalization](../../crates/daemon/src/delegation/finalization.rs) | Explicit argv/environment/materials and owned process identity; stopping and successful task completion are separate facts |
| Read, hide, expire or clean up content | [Reads](../../crates/daemon/src/control/runtime/delegation_reads.rs), [Continue admission](../../crates/daemon/src/control/runtime/delegation_continue.rs), [maintenance](../../crates/daemon/src/control/runtime/delegation_maintenance.rs), [native cleanup](../../crates/daemon/src/delegation/native_cleanup.rs) | Saved progress is independent of execution/cleanup state; current content permission and exact cleanup ownership still apply; borrowed history is not a deletion target |
@@ -65,6 +76,12 @@ the existing local Worker CLI and does not become a Worker executor.
| Qoder | HOME/QODER_CONFIG_DIR and project Skills | Selected native ACP CLI; [profile](../../crates/daemon/src/delegation/profile/qoder.rs) | Borrowed opaque history, exact ACP load; [Qoder guide](../../tools/product-e2e/tests/QODER_DELEGATION.md) |
| Pi | HOME/PI_CODING_AGENT_DIR, project and installed package Skills | Selected npm CLI + Node, bundled SDK→ACP bridge; [profile](../../crates/daemon/src/delegation/profile/pi.rs) | Task-owned v3 transcript, validated before open; [Pi guide](../../tools/product-e2e/tests/PI_INTEGRATION.md) |
| DeepSeek Harness (DSH) | HOME/DSH_HOME, project and custom Skill roots | Selected native ACP CLI and public run patch; [profile](../../crates/daemon/src/delegation/profile/dsh.rs) | Task-owned opaque history, exact ACP resume; [DSH guide](../../tools/product-e2e/tests/DSH_INTEGRATION.md) |
+| OpenCode | HOME/XDG, explicit config and additive resource roots, project Skills | Selected native ACP binary; [profile](../../crates/daemon/src/delegation/profile/opencode.rs) | Borrowed opaque SQLite history, bounded format admission and exact ACP load; [OpenCode guide](../../tools/product-e2e/tests/OPENCODE_INTEGRATION.md) |
+
+OpenCode's passive Agent and Worker discovery also inspect the official installer's
+`~/.opencode/bin` directory when a GUI launch lacks its shell PATH. Agent discovery
+keeps the PATH entry first; a saved explicit installation never falls back to a
+different binary. This does not grant a Worker selection or native-format capability.
The [profile guide](../../crates/daemon/src/delegation/profile/README.md) owns startup
flags, credential delivery, native tool permissions and resource restrictions.
@@ -84,6 +101,10 @@ image and trusted helper handles. UNC and device aliases remain outside this con
capture output in private files and retain the process Job until all owned tools
stop. Follow those owners for shell, environment, timeout or background-session
differences rather than duplicating ecosystem lifecycle code.
+OpenCode's isolated collaboration probe pins the system Windows PowerShell and
+quotes the public CLI for that shell. The native tool ID `bash` does not imply
+Git Bash. Its npm locator uses the shared declared-producer reader after PATH
+resolution, then selects the unique native platform package without running a shim.
The Windows [Qoder collaboration probe](../../crates/integrations/src/agents/qoder_probe.rs)
retains the actual Skill directory and file before launching the client. Its
@@ -211,9 +232,12 @@ has started, cancellation still needs owned-process stop evidence. Startup may
settle the old revision-2 `Cancelling` record only when the exact record proves
that preparation, process binding and prompt intent never occurred.
-Codex [startup coordination](../../crates/daemon/src/delegation/lifecycle/startup.rs)
-serializes only same-daemon, same borrowed-root spawn/initialize, releasing before
-session creation or prompt. An unconfirmed initializer retains occupancy until
+The shared [startup coordinator](../../crates/daemon/src/delegation/lifecycle/startup.rs)
+protects same-daemon Codex borrowed-root initialization and OpenCode database
+initialization. OpenCode rechecks the captured configuration and read-only database
+admission after waiting on its frozen database path. Coordination ends at successful
+ACP initialize, before session creation/load or prompt; tasks remain concurrent.
+An unconfirmed initializer retains occupancy until
[owned stop](../../crates/daemon/src/delegation/lifecycle.rs) verifies its exact process.
Retry Cancel through the existing task action; residual acknowledgement or daemon
restart is not proof that the original processes stopped. Other roots and clients
@@ -237,3 +261,10 @@ Mac `desktop-pilot --all-targets` compile gate; ignored native targets need expl
execution. Shared Product Session filters are `commands::worker_tasks::tests`,
`session::checks::tests` and `commands::model_connection_web::tests`; zero selected
tests prove nothing about those consumers.
+
+The OpenCode native Windows leaf is
+[`windows_opencode_business.rs`](../../crates/daemon/tests/support/windows_opencode_business.rs),
+selected by `actual_windows_opencode_worker_native_history_and_cancellation` in
+[`windows_headless.rs`](../../crates/daemon/tests/windows_headless.rs). It shares the
+public routing/Worker receipt oracle and Job cancellation assertions with existing
+Windows acceptance; it adds no alternative production lifecycle.
diff --git a/docs/local-user-configuration.md b/docs/local-user-configuration.md
index 67a8f82e..e41bf686 100644
--- a/docs/local-user-configuration.md
+++ b/docs/local-user-configuration.md
@@ -81,3 +81,48 @@ Local CLI callers can resume that same operation through `agents connect apply`
This retry accepts no new settings or grants. The daemon checks the stored operation and its
context before continuing. First-time creation and edits still require normal Preview/Apply.
+
+## OpenCode
+
+In Agents, enable OpenCode model routing and select the published routes and each
+route's Responses or Messages protocol. Save, restart ordinary OpenCode in the
+selected native context, and choose an added route in its model picker. Native
+default/small-model choices and other providers remain independent. A model or
+agent setting that still references an owned route must be changed before that
+route can be removed; rotating its token can retain the same selector.
+
+Once configured, model edits and recovery retain the original native file. Adding
+an `opencode.jsonc` beside a managed `opencode.json` does not move that binding.
+An effective user layer that overrides or disables an owned provider is reported
+as configuration drift; unrelated settings can change independently.
+
+Dynamic configuration keys are unavailable for managed model settings, static API
+import and Workers. A model choice expressed through an environment/file
+substitution must become an explicit native selector before removing a route it
+could reference. Keeping all current selectors can still rotate their token.
+These limits do not prevent independent Skill installation.
+Static import also leaves unresolved model-ID substitutions unavailable rather
+than importing the substitution text as an upstream model name.
+
+Task collaboration installs the shared `hiroute-collaboration` Skill independently
+of model routing. It can be enabled with no published route or model connection.
+Model restore and Skill restore are separate actions. The prerequisite check proves
+native Skill/CLI capability; completed delegated work has its own task result.
+
+Worker installation is selected in the route editor using one native OpenCode CLI.
+The initial supported history format is the official npm platform package for
+OpenCode 1.19.3. Detection can resolve a unique official npm launcher to that native
+executable without running the launcher. Other installation forms can retain
+independent model configuration and Skill capabilities.
+
+The daemon uses the selected native HOME/XDG context, optional absolute
+`OPENCODE_CONFIG`, additive `OPENCODE_CONFIG_DIR`, and native database location.
+Set context selectors on the process that starts HiRoute. Continue retains the
+original workspace, context, native session and route with fresh run credentials;
+changing today's environment does not select another conversation.
+Worker XDG roots must still map to the native `opencode` directory after canonical
+resolution. A directory link to a differently named leaf is unavailable for
+Worker launch and Continue; it does not disable ordinary settings or Skill installation.
+
+OpenCode Go uses ordinary API-source setup or a supported static import. Its API
+key does not create a HiRoute subscription/CPA login or quota-management entry.
diff --git a/docs/test-selection.md b/docs/test-selection.md
index 1949c883..5d6abd68 100644
--- a/docs/test-selection.md
+++ b/docs/test-selection.md
@@ -122,7 +122,17 @@ provider or credential override can substitute for this fifth journey.
Record all five journey outcomes and their revision, not only the
Cargo exit code. Python fixture tests check the oracle, not the installed Agent journey.
-Shared `native_context_*` fixtures select `worker_native_context` and `qoder_delegation`;
+The OpenCode entry selects all seven tests in `opencode_delegation`: saved ordinary
+Responses/Messages routes and independent restore, the installed user Skill calling
+the public HiRoute CLI, native Worker tools with exact Continue for both protocols,
+concurrent routing/cancellation and missing-history refusal, stale-safe static API
+import, and automatic native compaction plus auxiliary calls on the frozen route.
+The [OpenCode journey guide](../tools/product-e2e/tests/OPENCODE_INTEGRATION.md)
+defines the selected official installation, isolated context and per-case evidence.
+Run every required case; a successful build or an ignored test does not replace it.
+
+Shared `native_context_*` fixtures retain their registered Codex/Claude, Qoder,
+Pi, DeepSeek Harness and OpenCode native consumers;
`worker_product_support` and shared delegation/runtime setup retain all known Worker
consumers. Qoder-only fixtures and collaboration settings select the Qoder gate without
adding the old Codex/Claude lifecycle/read journeys. Registered journey guides and files
diff --git a/docs/validation-routing.md b/docs/validation-routing.md
index 37a2b25f..8fe11965 100644
--- a/docs/validation-routing.md
+++ b/docs/validation-routing.md
@@ -275,6 +275,13 @@ without the selected passing case is failure. Archive entries must be flat,
manifested x64 executables with matching size/hash; partial stages cannot be reused.
Cross-built artifacts never become native CI producers.
+The four `hiroute_local_storage.exe` cases in
+`control::windows_artifacts_tests` use only unique temporary directories. The runner
+admits these exact non-ignored cases alongside an existing installation and records
+`temporary_artifact_component`; it does not collect that installation's diagnostics.
+Other test cases retain the fresh-profile requirement. Temporary ACL/recovery checks
+prove native file behavior, not installed-product acceptance.
+
`inspect-installation` runs a read-only inventory in the configured account. Collect
and finish it normally; its success is inspection evidence, not a product scenario.
When the user explicitly authorizes clearing old validation data, use
diff --git a/e2e/product/schema/contract-set.v1.json b/e2e/product/schema/contract-set.v1.json
index e5a8e17a..2409f3ab 100644
--- a/e2e/product/schema/contract-set.v1.json
+++ b/e2e/product/schema/contract-set.v1.json
@@ -1,10 +1,10 @@
{
- "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c",
+ "descriptor_digest": "sha256:599207be26345edcb2ca69333ea50fb0580337aeff58ed0afe8f1fe5e0eca30e",
"files": {
"dependency-gate.v1.json": "sha256:b8ac81155266dca921f159d1cfabec6605f2e4bab0320ad6b23a3dbee51e6fa1",
"product-action.v1.schema.json": "sha256:faf815b27fd292e564a7d51de20c5a2825abbe710315a2364a9932ae3b5e4b7e",
"product-oracle-evidence.v1.schema.json": "sha256:faab6582bf3fba307b0f9f2949c51726409a209b0fa62e847114e0c6301038c6",
- "product-oracle-manifest.v1.json": "sha256:6d7ff50ffdc3d7b8e6c32654a364f6a271e0a56768e6ed63111c326117f72f0b",
+ "product-oracle-manifest.v1.json": "sha256:03478cafcbb2634d89dd044b2beea0f095e0d52e0672a586c08ee99d72a0826e",
"product-result.v1.schema.json": "sha256:72fc76be77572e40eed7516754911b45fdc9d55a8c089ba74c21427a33809def"
},
"schema_version": {
diff --git a/e2e/product/schema/product-oracle-manifest.v1.json b/e2e/product/schema/product-oracle-manifest.v1.json
index 92b3019c..1dafaf5a 100644
--- a/e2e/product/schema/product-oracle-manifest.v1.json
+++ b/e2e/product/schema/product-oracle-manifest.v1.json
@@ -1,5 +1,5 @@
{
- "descriptor_digest": "sha256:6442c5e2453d65985ee602d119f10db1467c7671cd770be616ebb2b9b284c39c",
+ "descriptor_digest": "sha256:599207be26345edcb2ca69333ea50fb0580337aeff58ed0afe8f1fe5e0eca30e",
"expected_red_reasons": [],
"planned_commands": [
"console.open",
diff --git a/issue-spec/specs/agent-connections/spec.md b/issue-spec/specs/agent-connections/spec.md
index 4b69038f..0082477f 100644
--- a/issue-spec/specs/agent-connections/spec.md
+++ b/issue-spec/specs/agent-connections/spec.md
@@ -15,7 +15,7 @@ Model settings own default/Fixed/allowed Plan routes; collaboration owns the sha
Skill and explicit (default) or delegate_by_default trigger mode, never a caller
Worker allowlist. Keeping another facet cannot read/validate its unused native files.
Collaboration configuration needs neither active publication nor a plan; an empty
-runtime directory is a legitimate outcome. A collaboration-only Qoder context
+runtime directory is a legitimate outcome. A collaboration-only Qoder or OpenCode context
cannot acquire a fake model grant/token/file effect or ingress capability merely
because its model settings are absent/malformed.
@@ -28,6 +28,7 @@ The current native model surfaces are:
| Qoder | Explicit supplementary Plan providers; native default remains independent | Selected normally logged-in native context |
| Pi | Per-Plan owned members in user models.json | Selected native Skills/resources |
| DSH | Public standard Web/home composition and per-Plan provider rows | Public native Skills/CLI capabilities |
+| OpenCode | Supplementary per-Plan native providers; defaults remain independent | Selected native user Skill/resource context |
| Hermes | One selected effective profile default main model using a published Plan alias | Profile-local collaboration and independent management Skills |
A Fixed route always retains exact source/account/physical model. Selecting a plan
@@ -37,6 +38,8 @@ HiRoute SHALL manage management and collaboration Skills as distinct resources a
Management preparation is available for all listed Agent families and requires neither a Plan nor a model grant. Hermes collaboration follows the same independent intent and trigger policy as other supported initiators, without adding a Hermes Worker executor. Neither Skill preparation nor model routing creates a new CLI authority.
+Prior contract source: https://github.com/higress-group/HiRoute/issues/125#issuecomment-6186244519
+
#### Scenario: Prepare Hermes management without model connection
- **WHEN** a Hermes profile requests management-Skill preparation with its model facet kept
@@ -62,8 +65,13 @@ Management preparation is available for all listed Agent families and requires n
- **WHEN** a resource changes after Preview or a multi-resource operation is interrupted
- **THEN** the existing stale/ownership and recovery rules apply to exact targets; no successful state hides unfinished effects or removes unrelated content.
+#### Scenario: Collaboration without model routing
+
+- **WHEN** a user enables collaboration while OpenCode continues to use its own model provider and no HiRoute Plan exists
+- **THEN** the owned Skill can be installed independently, no model grant/file effect is created, and the runtime directory truthfully contains no delegate target.
+
Source SPEC comments:
-- https://github.com/higress-group/HiRoute/issues/125#issuecomment-6186244519
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258607139
### Requirement: Settings bind current facts once through one transaction
@@ -303,7 +311,7 @@ plan catalog cannot imply one client effort changes all candidates.
### Requirement: Supplementary providers retain native defaults and exact protocols
-Qoder/Pi/DSH model configuration contains explicitly selected published Plan routes,
+Qoder/Pi/DSH/OpenCode model configuration MUST contain explicitly selected published Plan routes,
one stable owned provider per plan and user-chosen Responses/Messages protocol.
Recommendation considers all active/fallback candidates' native protocols and
explains conversion, never overrides selection or starts paid calls. Protocol change
@@ -332,10 +340,18 @@ offline without native auth store/helpers/extensions/downloads/model calls. Chan
selected CLI invalidates process-local proof, not a generic version-label whitelist.
Every supplementary provider obeys [installed-budget protection](../routing-plans/spec.md)
-for surviving current grants, including Pi/DSH; completed service with pending file
+for surviving current grants, including Pi/DSH/OpenCode; completed service with pending file
tail remains recoverable before conflicting publication. Scope/rotation/restoration
never chooses a native default or takes over an unowned equal-name provider.
+#### Scenario: Referenced managed route retains its identity
+
+- **WHEN** a native model reference still selects an owned supplementary provider/model while its token is rotated
+- **THEN** rotation MUST retain that selector; removing it MUST report an actionable reference conflict before the file switch.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258609244
+
### Requirement: DSH configuration uses public static composition
DSH uses public CLI/ACP/config, no internal SDK/plugin/session decoder. Static scan
@@ -359,7 +375,7 @@ native evidence. Model and collaboration restore remain independent.
### Requirement: Collaboration proofs distinguish preinstall from installed Skill
-Codex/Claude initial collaboration install uses user-triggered private-context proof
+Codex/Claude/OpenCode initial collaboration install MUST use user-triggered private-context proof
of Skill loading and controlled read-only trusted HiRoute CLI, without daily config,
upstream calls, or borrowing another client's proof. Current-client/installation/
short-lived evidence binds Preview/Apply; missing/expired proof retains edits and
@@ -384,6 +400,32 @@ drift/invalidity, context/dependency/check failure without raw output/paths/cred
An auth challenge followed by collaboration proof cannot erase still-valid auth
capability, nor grant unrequested Skill access to model settings.
+OpenCode checks use private native configuration/history and controlled upstream
+replies. The installed-Skill check loads the actual owned user resource path through
+the native resource loader and binds its exact path/body and generation to the
+nonce-correlated trusted public CLI result. It does not parse daily model settings,
+require a published Plan/model grant, or inject a copied substitute installed Skill.
+The real main-Agent journey separately proves native context use and delegated
+completion; prerequisite evidence alone cannot make that claim.
+
+#### Scenario: Collaboration without model routing
+
+- **WHEN** a user enables collaboration while OpenCode continues to use its own model provider and no HiRoute Plan exists
+- **THEN** the owned Skill can be installed independently, no model grant/file effect is created, and the runtime directory truthfully contains no delegate target.
+
+#### Scenario: Real delegated journey
+
+- **WHEN** OpenCode loads the actual installed user collaboration Skill and the user requests work through an available HiRoute Plan
+- **THEN** OpenCode invokes the trusted public CLI, retains the returned task identity, and obtains the actual Worker outcome rather than treating Skill installation as task completion.
+
+#### Scenario: Shadowed or edited resource
+
+- **WHEN** a same-named project Skill shadows the installed user Skill or the managed user Skill is edited
+- **THEN** verification cannot accept the substitute as the owned installed resource and restoration cannot overwrite user edits without resolving the ownership conflict.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258610209
+
### Requirement: Skill and reference maintenance never becomes Worker authority
The shared Skill queries published purposes and public task CLI, explains local trust,
@@ -593,6 +635,55 @@ to native remains a separate labelled action with its existing ownership rules.
Source SPEC comments:
- https://github.com/higress-group/HiRoute/issues/140#issuecomment-6235502571
+### Requirement: OpenCode discovery preserves exact native context and scoped capabilities
+
+HiRoute MUST recognize OpenCode as an explicit Agent identity and selectable native ACP Harness through existing Desktop and public CLI surfaces on macOS, Linux and native Windows. Passive discovery MUST use bounded installation/configuration metadata without launching OpenCode, executing shims, authenticating, downloading, changing native files or making model requests. It MUST distinguish executable discovery, model-configuration capability, collaboration capability and Worker execution/Continue capability. It MUST resolve the selected context using native HOME/XDG and explicit OpenCode configuration-root semantics without guessing another account from executable location. An explicit selected installation remains selected when missing or unusable; no automatic candidate substitution is permitted. Worker selection uses the native OpenCode CLI, not a fictitious separate ACP adapter. Platform-specific launch dependencies MUST be explicit where the actual installation form requires them. Normal configuration actions MUST reuse the shared enable/edit/restore and Operation flow rather than introduce a separate OpenCode setup or verification workflow.
+
+#### Scenario: Partial discovery
+
+- **WHEN** one OpenCode configuration or installation candidate is unreadable while other candidates remain valid
+- **THEN** HiRoute reports the affected item as unavailable or unknown and preserves the other findings without running the client.
+
+#### Scenario: Missing selected installation
+
+- **WHEN** the explicitly selected OpenCode installation disappears or becomes unusable
+- **THEN** subsequent affected actions report the selected dependency failure and retain its identity instead of launching another PATH candidate.
+
+#### Scenario: Separate capabilities
+
+- **WHEN** OpenCode model configuration is supported but native ACP or Continue capability is unavailable
+- **THEN** model configuration remains usable and Worker/Continue availability is reported independently, without claiming model success from discovery.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258607139
+
+### Requirement: OpenCode supplementary model routes are native and reversibly owned
+
+HiRoute MUST configure explicitly selected published Plan aliases as supplementary OpenCode providers, one owned provider per Plan, with a selected Responses or Messages protocol. The ordinary OpenCode client MUST be able to select and use these aliases from saved native settings without transient route or credential injection. HiRoute MUST preserve native defaults, other providers, unrelated fields, comments and native extensions. Native provider-prefixed selectors MUST map to the original Plan alias without changing routing authority. Ordinary model grants MUST use the existing protected connection-grant channel, separate from upstream keys and Worker credentials. Configure, adjustment, token rotation and restore MUST use the shared ownership/dependency/recovery transaction, preserving original protected recovery material and rejecting unowned collisions or ambiguous JSON/JSONC composition. Effective configuration precedence and relevant native model/default references MUST be checked for the requested operation; conflicting higher-priority settings cannot produce a false connected/active claim. Restore MUST remove only owned effects and retain unrelated user edits; references to a removed managed model require actionable conflict handling. Context/output declarations MUST follow the selected Plan and OpenCode native compaction policy and participate in existing installed-budget protection. Saving configuration MUST NOT change the native default or perform paid inference.
+
+#### Scenario: Ordinary saved model use
+
+- **WHEN** the user saves selected Plan routes and then starts ordinary OpenCode and selects one of their native model entries
+- **THEN** requests use that exact Plan alias and selected protocol through the saved local grant, with native defaults and unrelated settings preserved.
+
+#### Scenario: Rotation and independent restore
+
+- **WHEN** the user rotates the model grant or restores OpenCode model settings while collaboration remains enabled
+- **THEN** rotation revokes the old grant for new requests and updates native consumption consistently; model restore preserves the collaboration Skill and unrelated native configuration.
+
+#### Scenario: Late configuration conflict
+
+- **WHEN** a relevant effective override, owned member or native default dependency changes after Preview
+- **THEN** Apply or the affected recovery path rejects stale authority without overwriting user changes, falsely claiming activation or bypassing the original pending Operation.
+
+#### Scenario: Budget change
+
+- **WHEN** publication would invalidate the native context/output declaration of a surviving installed OpenCode Plan route
+- **THEN** the shared publication guard reports the affected installed consumer rather than leaving a silently invalid native declaration.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258609244
+
## Implementation references
- [Shared settings transaction](../../../crates/application/src/agent_connection/settings/transaction.rs)
diff --git a/issue-spec/specs/agent-delegation/spec.md b/issue-spec/specs/agent-delegation/spec.md
index e28ab8e0..92f2d86e 100644
--- a/issue-spec/specs/agent-delegation/spec.md
+++ b/issue-spec/specs/agent-delegation/spec.md
@@ -10,9 +10,8 @@ and exact native-session continuation.
### Requirement: Supported Harnesses share one lifecycle
-The current supported list, used by plan editing and executor availability in the
-same stable order, is Codex CLI, Claude Code, Qoder CLI, Pi, and DeepSeek Harness
-(DSH). Native differences do not duplicate admission, run authority, result, or
+HiRoute MUST use the same stable supported Harness order in plan editing and executor
+availability: Codex CLI, Claude Code, Qoder CLI, Pi, DeepSeek Harness (DSH), and OpenCode. Native differences do not duplicate admission, run authority, result, or
retention workflows. Installation, protocol, policy, and Continue capabilities are
separate; being listed cannot promise every action is available.
@@ -22,6 +21,14 @@ collaboration. A fixed single-model plan is sufficient, and ordinary model calls
never start an Agent process. Goals, needed context/files, constraints, and acceptance
criteria are explicit; a Worker cannot assume the complete main conversation.
+#### Scenario: Native-only OpenCode installation
+
+- **WHEN** OpenCode is selected as the execution Harness
+- **THEN** installation selection MUST require its native CLI only and retain independent saved choices for other Harnesses; no fictitious ACP adapter or Node field is required.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258607139
+
### Requirement: Local submissions require product intent, not caller credentials
A local caller able to use trusted CLI/Local Control may submit stable Plan, cwd,
@@ -79,8 +86,9 @@ Lowering capacity preserves existing work and limits only later admission.
### Requirement: Native resource context is borrowed, routing is per run
-Workers use the product instance's effective HOME and explicit native roots
-(CODEX_HOME, CLAUDE_CONFIG_DIR, QODER_CONFIG_DIR, PI_CODING_AGENT_DIR, DSH_HOME), including
+Workers MUST use the product instance's effective HOME and explicit native roots
+(CODEX_HOME, CLAUDE_CONFIG_DIR, QODER_CONFIG_DIR, PI_CODING_AGENT_DIR, DSH_HOME,
+and the selected OpenCode HOME/XDG/config/data selectors), including
isolated Pilot contexts. Installation paths cannot choose a different user's root
or recover a hidden daily HOME. Existing user/project Skills are discovered by the
native client; directory existence or prompt echo is not invocation evidence.
@@ -93,6 +101,14 @@ environment, upstream tokens, or shell startup scripts. Private launch materials
same-UID execution are not a sandbox. Concurrent routes keep credentials/settings/
process cleanup isolated.
+#### Scenario: Borrowed resources and real tools
+
+- **WHEN** a supported OpenCode Worker executes a coding task requiring an existing user/project Skill, read, edit and shell tools
+- **THEN** the native resources are actually invoked, expected file/shell effects occur, and every admitted model request remains bound to the run and its frozen route without changing shared settings.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258611907
+
### Requirement: Codex startup overrides precede its native auth/catalog checks
Codex MUST select a task-specific provider and private single-alias catalog before
@@ -220,6 +236,38 @@ materials were retained. Every Continue receives a new run/admission time/creden
not today's replacement plan. Failed admission preserves the previous successful
task and recovery qualification.
+OpenCode binds one exact native/ACP session ID and the original canonical workspace,
+resource/config/data/database locations and frozen route. Continue uses native
+load with fresh credentials and mode/model confirmation, including after daemon
+restart. It MUST NOT replay, fork, choose newest history, migrate/repair opaque
+history or create a replacement session on failure. Borrowed history remains outside
+HiRoute recursive cleanup. Root exit, ACP cancel acknowledgement or closed stdio
+alone cannot prove the owned tool chain and loopback listener stopped; existing
+process-group/Windows Job finalization and uncertain-cleanup rules apply.
+
+#### Scenario: Exact Continue after restart
+
+- **WHEN** a completed OpenCode task is continued after the HiRoute daemon restarts and current defaults or Plan publication have changed
+- **THEN** the original workspace/resource context/session and frozen route are used with a new credential; newly published defaults do not create a replacement conversation.
+
+#### Scenario: Missing or unusable history
+
+- **WHEN** the bound OpenCode history is absent, inaccessible, incompatible or cannot be loaded by the selected native client
+- **THEN** Continue fails explicitly without session/new, newest-session selection, history mutation or replay of previous work.
+
+#### Scenario: Concurrent cancellation
+
+- **WHEN** one of two independent OpenCode Worker runs is cancelled while a native shell tool is active
+- **THEN** the cancelled run stops its owned execution and listener with actual cleanup evidence, while the neighboring task retains its session, credentials and progress.
+
+#### Scenario: Content retention
+
+- **WHEN** HiRoute hides or expires an OpenCode task body while native user history remains present
+- **THEN** existing visibility/Continue policy remains authoritative and cleanup does not delete or reimport the borrowed native history.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258613091
+
### Requirement: Task projections are durable and consistent across clients
Instance task list is newest-latest-admission first with exclusive cursor, bounded
@@ -271,7 +319,7 @@ terminal state. Idle save checks do not write until progress exists.
### Requirement: Executor availability is a prerequisite, not a behavior probe
-Availability is independent of plans/main-Agent configuration and returns all five
+Availability MUST be independent of plans/main-Agent configuration and return all six
Harnesses with ready/unavailable/unknown plus closed reasons. Basic paths/executability
and Pi's explicitly bounded offline SDK checks establish only start-approve-all
prerequisites. Cancel-ready indicates an entry, not confirmed stop. Without a real
@@ -294,6 +342,56 @@ task rather than blocking startup, and may conservatively retain durable occupan
Real Exec/Continue reports actual spawn/handshake/model/mode/load/timeout stages.
Environment variables or a successful installation query are not execution evidence.
+OpenCode Worker/Continue format admission is a separate bounded capability. Its
+initial supported producer is the official npm platform package for 1.19.3, identified
+through adjacent package/layout/platform metadata without launching a shim or
+fingerprinting a binary. Standalone, unknown or ambiguous installations remain
+unavailable for this action without disabling independent model/Skill configuration.
+
+#### Scenario: Separate capabilities
+
+- **WHEN** OpenCode model configuration is supported but native ACP or Continue capability is unavailable
+- **THEN** model configuration remains usable and Worker/Continue availability is reported independently, without claiming model success from discovery.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258607139
+
+### Requirement: OpenCode Worker execution binds native ACP to one frozen route
+
+HiRoute MUST execute an explicitly selected OpenCode native ACP installation through its existing Worker admission, run-authority and execution lifecycle. A run MUST use the frozen Plan alias, selected Responses/Messages protocol, exact native model selector and fresh run credential. Both new and restored sessions MUST confirm the exact model through typed ACP config options before prompt intent; missing or contradictory model capability fails explicitly without native-provider fallback. Native resource roots, project rules and user/project Skills are borrowed; per-run settings MUST NOT rewrite daily configuration or copy ambient upstream credentials. All admitted main, small/title and compaction model calls MUST stay on the frozen route and use the Plan-derived native context/output budget. Effective project/managed settings and native extensions MUST NOT override routing, authentication, budget or permissions; an unenforceable composition fails before model work. The initial Worker surface supports native Skill/read/search/edit/shell under approve-all; native nested delegation, external MCP and executable plugins/custom tools are excluded, and unsupported restricted policies MUST NOT be upgraded silently. Native terminal errors and cancellations MUST NOT become successful assistant results. The ACP-internal HTTP listener MUST stay local, protected as necessary for per-run ownership, and within the same owned lifecycle; no separately managed persistent server is introduced.
+
+The selected native context freezes HOME, XDG roots, optional absolute OPENCODE_CONFIG, additive OPENCODE_CONFIG_DIR and the exact database selector. Supported existing history is admitted by a bounded read-only native migration-ID set check before startup, without decoding or migrating conversations. Missing history may be initialized for new work only. Typed primary mode selection MUST complete before final model confirmation from the latest config options. Unknown late configuration, native schema/conversion writes, organization/managed sources or executable custom composition fail before launch.
+
+Concurrent OpenCode starts sharing one native database MUST coordinate only native initialization and final read-only history/composition admission. Release that coordination after successful ACP initialize, before New/Load or prompt, and preserve the existing deadline, cancellation, live-authority and uncertain-cleanup boundaries. Do not prewarm, repair or migrate history or serialize whole task execution.
+
+#### Scenario: Exact model before work
+
+- **WHEN** a new OpenCode ACP session reports a different current model than the task-selected provider/alias
+- **THEN** HiRoute selects and confirms the exact expected model before prompting, or fails the run without model work if that cannot be established.
+
+#### Scenario: Borrowed resources and real tools
+
+- **WHEN** a supported OpenCode Worker executes a coding task requiring an existing user/project Skill, read, edit and shell tools
+- **THEN** the native resources are actually invoked, expected file/shell effects occur, and every admitted model request remains bound to the run and its frozen route without changing shared settings.
+
+#### Scenario: Auxiliary routing and compaction
+
+- **WHEN** native title/small-model work or context compaction occurs during an OpenCode Worker task
+- **THEN** those model requests use the frozen authorized route and native budget rather than ambient provider defaults or another model account.
+
+#### Scenario: Unenforceable overrides
+
+- **WHEN** project or managed configuration or an enabled executable extension conflicts with the required route, credential, tool or budget boundary
+- **THEN** the affected Worker action reports a scoped capability/configuration failure before model work, without disabling unrelated Agent configuration capabilities.
+
+#### Scenario: Native provider failure
+
+- **WHEN** OpenCode reports a model authentication or inference failure through its ACP response
+- **THEN** the run records failure with bounded safe diagnostics instead of accepting error-shaped assistant prose or an ordinary success result.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258611907
+
## Implementation references
- [Admission](../../../crates/daemon/src/control/runtime/delegation_tasks.rs),
diff --git a/issue-spec/specs/model-discovery/spec.md b/issue-spec/specs/model-discovery/spec.md
index 16bd3747..f0a51132 100644
--- a/issue-spec/specs/model-discovery/spec.md
+++ b/issue-spec/specs/model-discovery/spec.md
@@ -86,6 +86,17 @@ remain non-importable. Provider and model identities remain visible separately.
DSH's static composition uses its own native reader through the same prepare/save
workflow; it must not be guessed from Pi rules.
+OpenCode uses its bounded native static reader through that same workflow. Require
+explicit nonempty model declarations, a known supported SDK/protocol/endpoint and
+representable options. Resolve literal or unambiguous environment/file API keys
+using native precedence: supported stored API keys follow environment-derived keys,
+while explicit provider options win at SDK construction. Ignore HiRoute-owned
+providers. OAuth, executable helpers/SDKs, plugin-dependent auth, unresolved remote
+configuration and ambiguous substitution remain non-importable without execution.
+Configuration and selected credential/reference facts bind preparation and save.
+Missing catalog/capability evidence stays unknown. OpenCode Go remains an ordinary
+API-key source, with no new subscription, CPA, login, refresh or quota authority.
+
The frontend submits opaque discovery/preparation identities. Daemon preparation
re-reads the native source and binds endpoint, raw model ID, credential, and native
source/catalog snapshot. Save rechecks those facts and rejects a stale source or
@@ -99,6 +110,29 @@ tool, streaming, or reasoning constants cannot be promoted to verified capabilit
- **THEN** save MUST reject the stale candidate without modifying the source,
and the user can rescan/prepare through the same protected path.
+#### Scenario: Static source import
+
+- **WHEN** the user selects an explicitly configured OpenCode API provider with a known endpoint/protocol, explicit models and a safely resolvable API key
+- **THEN** the shared prepare/save workflow creates the selected ordinary API source without model inference, native configuration edits or credential exposure.
+
+#### Scenario: Unsupported dynamic source
+
+- **WHEN** a provider requires executing code, a plugin/authentication helper, OAuth-only credentials or unresolved configuration composition
+- **THEN** the candidate explains its unsupported import capability while independent installations/providers remain discoverable; no helper, login or refresh is executed.
+
+#### Scenario: Stale source
+
+- **WHEN** the selected effective endpoint, model declaration or credential changes between protected preparation and Save
+- **THEN** Save rejects the stale candidate and preserves the native source and any existing saved connection.
+
+#### Scenario: Go source boundary
+
+- **WHEN** an OpenCode Go API-key source is added manually or imported through a supported static declaration
+- **THEN** it follows ordinary API-source ownership and routing rather than introducing subscription/CPA lifecycle or claiming unverified account/model availability.
+
+Source SPEC comments:
+- https://github.com/higress-group/HiRoute/issues/159#issuecomment-6258614406
+
### Requirement: Discover configured Hermes model sources through existing scan flows
HiRoute SHALL add the selected effective Hermes profile as a native producer in the shared connection-point discovery and model-selection workflow. Its configured default main model and statically declared provider/model sources SHALL retain profile/native provenance, with exact resolvable product, endpoint, protocol and authentication-reference semantics. A user-named Coding Plan provider SHALL be recognized by the supported endpoint/product facts rather than requiring a built-in provider name. Configured native models, catalog candidates and unobserved live selections SHALL remain distinct. Supported Hermes findings SHALL use the same connection-level preparation and explicit model save as other supported scanners; unresolved/helper-dependent findings retain precise reasons and cannot silently become importable or recursive HiRoute upstream sources. The shared model-discovery passive/protected contracts and connection-point selection requirement remain authoritative.
diff --git a/scripts/check-contract-convergence.py b/scripts/check-contract-convergence.py
index 6fdf73f6..25befd2a 100755
--- a/scripts/check-contract-convergence.py
+++ b/scripts/check-contract-convergence.py
@@ -14,7 +14,7 @@ REGISTRY_PATH = Path("contracts/compatibility-support.v1.json")
# must deliberately update this gate after reviewing migrations/startup_format.rs and
# docs/upgrade-storage-design.md; fixtures cannot satisfy it. This is not a migration test.
DATABASE_SCHEMA_SOURCE = "crates/local-storage/src/migrations/mod.rs"
-EXPECTED_DATABASE_SCHEMA_VERSION = 29
+EXPECTED_DATABASE_SCHEMA_VERSION = 30
VERSION_SUFFIX = re.compile(r"/v[0-9]+")
INTERNAL_CONTRACT = re.compile(r"hiroute(?:\.[a-z0-9][a-z0-9-]*)+/v[0-9]+")
VALID_MODES = {
diff --git a/scripts/ci-shards.py b/scripts/ci-shards.py
index dd38bcb6..f5c97055 100755
--- a/scripts/ci-shards.py
+++ b/scripts/ci-shards.py
@@ -101,6 +101,7 @@ INTEGRATION_SHARDS = {
("hiroute-product-e2e", "dsh_delegation"),
("hiroute-product-e2e", "gateway_adapter_contract"),
("hiroute-product-e2e", "local_observation"),
+ ("hiroute-product-e2e", "opencode_delegation"),
("hiroute-product-e2e", "pi_delegation"),
("hiroute-product-e2e", "product_oracle"),
("hiroute-product-e2e", "qoder_delegation"),
diff --git a/scripts/test-agent-product-support.py b/scripts/test-agent-product-support.py
index 5856b17c..7490da62 100644
--- a/scripts/test-agent-product-support.py
+++ b/scripts/test-agent-product-support.py
@@ -128,6 +128,17 @@ class ObservationReadRetryTests(unittest.TestCase):
class NativeInstallationTests(unittest.TestCase):
+ def test_opencode_gets_only_the_native_ripgrep_dependency_in_its_private_path(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ (root / 'bin').mkdir()
+ cli = root / 'selected-cli'; cli.write_text('fixture'); cli.chmod(0o700)
+ rg = root / 'selected-rg'; rg.write_text('fixture'); rg.chmod(0o700)
+ with patch('shutil.which', return_value=str(rg)):
+ expose_native_installation(SimpleNamespace(root=root), 'opencode', cli)
+ self.assertEqual((root / 'bin/rg').resolve(), rg)
+ self.assertEqual({p.name for p in (root / 'bin').iterdir()}, {'rg', 'opencode'})
+
def test_selected_cli_and_required_runtime_share_the_private_fixture_path(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory).resolve()
diff --git a/scripts/test-contract-convergence.py b/scripts/test-contract-convergence.py
index 222b705b..cfc7e207 100755
--- a/scripts/test-contract-convergence.py
+++ b/scripts/test-contract-convergence.py
@@ -47,7 +47,7 @@ class ContractConvergenceTests(unittest.TestCase):
'"hiroute.sample/v2"'
),
"crates/local-storage/src/migrations/mod.rs": (
- "pub const LATEST_SCHEMA_VERSION: u32 = 29;\n"
+ "pub const LATEST_SCHEMA_VERSION: u32 = 30;\n"
),
# Historical/test text must never stand in for the production declaration.
"tests/old_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 17;",
@@ -70,34 +70,34 @@ class ContractConvergenceTests(unittest.TestCase):
self.assertTrue(any("lacks owner" in error for error in self.run_audit({"legacy.rs": '"hiroute.sample/v1"'}, value)))
def test_database_schema_change_is_not_hidden_by_a_fixture(self):
- for version in (17, 22, 23, 24, 25, 26, 27, 28, 30):
+ for version in (17, 22, 23, 24, 25, 26, 27, 28, 29, 31):
with self.subTest(version=version):
errors = self.run_audit({
"legacy.rs": '"hiroute.sample/v1"',
"crates/local-storage/src/migrations/mod.rs": (
f"pub const LATEST_SCHEMA_VERSION: u32 = {version};\n"
),
- "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 29;",
+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 30;",
})
self.assertTrue(any("database schema" in error for error in errors), errors)
def test_database_schema_requires_the_authoritative_production_declaration(self):
for source in (
"// declaration removed\n",
- "#[cfg(test)]\nmod fixture {\n pub const LATEST_SCHEMA_VERSION: u32 = 29;\n}\n",
- "/*\npub const LATEST_SCHEMA_VERSION: u32 = 29;\n*/\n",
- "pub const LATEST_SCHEMA_VERSION: u32 = 29;\npub const LATEST_SCHEMA_VERSION: u32 = 30;\n",
+ "#[cfg(test)]\nmod fixture {\n pub const LATEST_SCHEMA_VERSION: u32 = 30;\n}\n",
+ "/*\npub const LATEST_SCHEMA_VERSION: u32 = 30;\n*/\n",
+ "pub const LATEST_SCHEMA_VERSION: u32 = 30;\npub const LATEST_SCHEMA_VERSION: u32 = 31;\n",
):
with self.subTest(source=source):
errors = self.run_audit({
"legacy.rs": '"hiroute.sample/v1"',
"crates/local-storage/src/migrations/mod.rs": source,
- "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 29;",
+ "tests/current_schema_fixture.rs": "pub const LATEST_SCHEMA_VERSION: u32 = 30;",
})
self.assertTrue(any("database schema" in error for error in errors), errors)
def test_database_schema_requires_an_unconditional_top_level_constant(self):
- declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 29;\n"
+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 30;\n"
for source in (
"#[cfg(all(unix, test))]\n" + declaration,
"#[cfg(any(unix, test))]\n" + declaration,
@@ -118,7 +118,7 @@ class ContractConvergenceTests(unittest.TestCase):
self.assertTrue(any("database schema" in error for error in errors), errors)
def test_database_schema_fails_closed_on_unterminated_lexical_input(self):
- declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 29;\n"
+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 30;\n"
for suffix in ('/* unclosed', 'const TEXT: &str = r#"unclosed',
'const TEXT: &str = "unclosed', 'mod fixture {', ']'):
with self.subTest(suffix=suffix):
@@ -129,7 +129,7 @@ class ContractConvergenceTests(unittest.TestCase):
self.assertTrue(any("database schema" in error for error in errors), errors)
def test_database_schema_ignores_literal_and_comment_declarations(self):
- declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 29;\n"
+ declaration = "pub const LATEST_SCHEMA_VERSION: u32 = 30;\n"
for source in (
'const FIXTURE: &str = "\n' + declaration + '";\n',
'const FIXTURE: &str = r"\n' + declaration + '";\n',
@@ -157,7 +157,7 @@ const BRACE: char = '}';
mod fixture {
pub const LATEST_SCHEMA_VERSION: u32 = 17;
}
-pub const LATEST_SCHEMA_VERSION: u32 = 29;
+pub const LATEST_SCHEMA_VERSION: u32 = 30;
'''
self.assertEqual(self.run_audit({
"legacy.rs": '"hiroute.sample/v1"',
diff --git a/scripts/test-native-context-product.py b/scripts/test-native-context-product.py
index d2ac191a..552fb90e 100644
--- a/scripts/test-native-context-product.py
+++ b/scripts/test-native-context-product.py
@@ -26,6 +26,22 @@ class NativeContextOracleTests(unittest.TestCase):
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
+ def test_product_does_not_inherit_native_context_overrides(self):
+ keys = ('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',
+ 'OPENCODE_CONFIG', 'OPENCODE_CONFIG_DIR', 'OPENCODE_CONFIG_CONTENT',
+ 'OPENCODE_DB')
+ with patch.dict(os.environ, {key: 'host-context-override' for key in keys}):
+ product = Product(REPO, root=self.root / 'isolated-context-product')
+ try:
+ self.assertTrue(all(key not in product.env for key in keys))
+ self.assertEqual(Path(product.env['CLAUDE_CONFIG_DIR']),
+ product.root / 'home/.claude')
+ finally:
+ product.close()
+
def test_product_listener_is_outside_the_hosts_outbound_ephemeral_range(self):
product = Product(REPO, root=self.root / 'listener-product')
try:
diff --git a/scripts/test-plan.py b/scripts/test-plan.py
index b3cb7937..dc314ae8 100644
--- a/scripts/test-plan.py
+++ b/scripts/test-plan.py
@@ -217,6 +217,20 @@ WORKER_PRODUCT_CHECKS = {
"missing_environment": "fail",
},
}
+WORKER_PRODUCT_CHECKS["opencode_delegation"] = {
+ "id":"opencode.delegation","harnesses":["opencode"],
+ "guide":"tools/product-e2e/tests/OPENCODE_INTEGRATION.md",
+ "required_tests":["opencode_worker_uses_native_skills_and_continues_the_frozen_task",
+ "opencode_agent_saved_model_routes_preserve_defaults_and_restore_independently",
+ "opencode_agent_uses_installed_user_skill_to_delegate_through_public_cli",
+ "opencode_workers_route_independently_cancel_and_refuse_missing_history",
+ "opencode_static_api_import_rechecks_source_and_preserves_native_files",
+ "opencode_messages_worker_preserves_tools_and_exact_continue",
+ "opencode_native_compaction_and_auxiliary_requests_keep_the_frozen_route"],
+ "required_environment":["HIROUTE_PRODUCT_CANDIDATE_SHA","HIROUTE_WORKER_OPENCODE_BINARY"],
+ "missing_environment":"fail",
+}
+
OPT_IN_WORKER_TARGETS = set(WORKER_PRODUCT_CHECKS)
PRODUCT_GUIDES = {entry["guide"] for entry in WORKER_PRODUCT_CHECKS.values()} | {
"crates/daemon/tests/support/NATIVE_CONTEXT_BOUNDARIES.md"}
@@ -286,16 +300,18 @@ def e2e_consumers(path):
return [("hiroute-product-e2e", name) for name in WORKER_PRODUCT_CHECKS]
if path.startswith("tools/product-e2e/tests/") and Path(path).stem in OPT_IN_WORKER_TARGETS:
return [("hiroute-product-e2e", Path(path).stem)]
+ if path.startswith("crates/daemon/tests/support/opencode_"):
+ return [("hiroute-product-e2e","opencode_delegation")]
if path.startswith("crates/daemon/tests/support/native_context_"):
- return [("hiroute-product-e2e", name) for name in ("worker_native_context", "qoder_delegation", "pi_delegation", "dsh_delegation")]
+ return [("hiroute-product-e2e", name) for name in ("worker_native_context", "qoder_delegation", "pi_delegation", "dsh_delegation", "opencode_delegation")]
if path == "crates/daemon/tests/support/native_task_witness.py":
return [("hiroute-product-e2e", name) for name in ("qoder_delegation", "dsh_delegation")]
if path == "crates/daemon/tests/support/agent_product_support.py" or path.startswith(ADDITIONAL_NATIVE_FIXTURE_PREFIXES):
- return [("hiroute-product-e2e", name) for name in ("qoder_delegation", "pi_delegation", "dsh_delegation")]
+ return [("hiroute-product-e2e", name) for name in ("qoder_delegation", "pi_delegation", "dsh_delegation", "opencode_delegation")]
if path.startswith("crates/daemon/tests/support/dsh_") or path == "crates/daemon/tests/support/native_acp_client.py":
return [("hiroute-product-e2e", "dsh_delegation")]
if path == "crates/daemon/tests/support/pi_discovery_product.py":
- return [("hiroute-product-e2e", "pi_delegation"),("hiroute-product-e2e", "dsh_delegation")]
+ return [("hiroute-product-e2e", name) for name in ("pi_delegation","dsh_delegation","opencode_delegation")]
if path.startswith("crates/daemon/tests/support/pi_"):
return [("hiroute-product-e2e", "pi_delegation")]
if path.startswith("crates/daemon/tests/support/qoder_"):
@@ -333,16 +349,18 @@ def worker_product_checks(paths):
continue
selected.update(target for package, target in e2e_consumers(path)
if package == "hiroute-product-e2e" and target in OPT_IN_WORKER_TARGETS)
- if path.startswith(DSH_PRODUCT_PREFIXES):
+ if path.startswith(("crates/integrations/src/agents/opencode", "crates/daemon/src/delegation/profile/opencode", "crates/integrations/src/agents/filesystem_tests/opencode")):
+ selected.add("opencode_delegation")
+ elif path.startswith(DSH_PRODUCT_PREFIXES):
selected.add("dsh_delegation")
elif path.startswith(PI_PRODUCT_PREFIXES):
selected.add("pi_delegation")
elif path.startswith(ADDITIONAL_MODEL_PREFIXES):
- selected.update(("qoder_delegation", "pi_delegation", "dsh_delegation"))
+ selected.update(("qoder_delegation", "pi_delegation", "dsh_delegation", "opencode_delegation"))
elif path in QODER_PRODUCT_PATHS or path.startswith(QODER_PRODUCT_PREFIXES):
selected.add("qoder_delegation")
if path in QODER_PRODUCT_PATHS or path.startswith(("crates/application/src/agent_connection/settings/", "crates/application/src/agent_connection/skill")):
- selected.update(("pi_delegation", "dsh_delegation"))
+ selected.update(("pi_delegation", "dsh_delegation", "opencode_delegation"))
elif path.startswith(("crates/daemon/src/delegation/", "crates/application/src/delegation/",
"crates/domain/src/delegation/")) or path in SHARED_WORKER_FIXTURES:
selected.update(OPT_IN_WORKER_TARGETS)
diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.py
index 4af533f5..2a558989 100644
--- a/scripts/test-test-plan.py
+++ b/scripts/test-test-plan.py
@@ -167,7 +167,7 @@ class SelectionTests(unittest.TestCase):
):
with self.subTest(path=path):
result = plan.select([path])
- expected = ['qoder_delegation', 'pi_delegation', 'dsh_delegation'] if (path in plan.QODER_PRODUCT_PATHS or path.startswith(('crates/application/src/agent_connection/skill', 'crates/application/src/agent_connection/settings/'))) else ['qoder_delegation']
+ expected = ['qoder_delegation', 'pi_delegation', 'dsh_delegation', 'opencode_delegation'] if (path in plan.QODER_PRODUCT_PATHS or path.startswith(('crates/application/src/agent_connection/skill', 'crates/application/src/agent_connection/settings/'))) else ['qoder_delegation']
self.assertEqual([check['command'][6] for check in result['product_checks']], expected)
self.assertIn(['python3', 'scripts/test-qoder-product.py'], result['commands'])
# Model-specific settings are not consumers of the independent Qoder Skill path.
@@ -179,7 +179,7 @@ class SelectionTests(unittest.TestCase):
def test_shared_agent_journey_helper_selects_current_consumers_and_its_ownership_checks(self):
result = plan.select(['crates/daemon/tests/support/agent_product_support.py'])
self.assertEqual(result['mode'], 'affected')
- self.assertEqual([check['command'][6] for check in result['product_checks']], ['qoder_delegation', 'pi_delegation', 'dsh_delegation'])
+ self.assertEqual([check['command'][6] for check in result['product_checks']], ['qoder_delegation', 'pi_delegation', 'dsh_delegation', 'opencode_delegation'])
self.assertIn(['python3', 'scripts/test-agent-product-support.py'], result['commands'])
tooling = plan.select(['scripts/test-agent-product-support.py'])
self.assertEqual(tooling['product_checks'], [])
@@ -193,7 +193,7 @@ class SelectionTests(unittest.TestCase):
result = plan.select([path])
self.assertEqual(result['mode'], 'affected')
self.assertEqual({check['command'][6] for check in result['product_checks']},
- {'worker_native_context', 'qoder_delegation', 'pi_delegation', 'dsh_delegation'})
+ {'worker_native_context', 'qoder_delegation', 'pi_delegation', 'dsh_delegation', 'opencode_delegation'})
def test_qoder_production_gates_preserve_ordinary_owner_checks_and_deduplicate(self):
result = plan.select(['crates/integrations/src/agents/qoder.rs',
@@ -216,12 +216,21 @@ class SelectionTests(unittest.TestCase):
'crates/daemon/src/control/runtime/native_additional_model.rs'):
with self.subTest(path=path):
checks = plan.select([path])['product_checks']
- self.assertEqual({check['command'][6] for check in checks}, {'qoder_delegation', 'pi_delegation', 'dsh_delegation'})
+ self.assertEqual({check['command'][6] for check in checks}, {'qoder_delegation', 'pi_delegation', 'dsh_delegation', 'opencode_delegation'})
checks = plan.select(['crates/integrations/src/agents/pi_sources.rs'])['product_checks']
self.assertEqual([check['command'][6] for check in checks], ['pi_delegation'])
self.assertIn('pi_worker_recovers_length_overflow_and_continues_edited_history', checks[0]['required_tests'])
self.assertEqual(checks[0]['missing_environment'], 'fail')
+ def test_opencode_native_leaf_selects_its_actual_product_journey(self):
+ for path in ('crates/integrations/src/agents/opencode.rs',
+ 'crates/daemon/src/delegation/profile/opencode.rs',
+ 'crates/daemon/tests/support/opencode_native_context.py'):
+ checks=plan.worker_product_checks([path])
+ self.assertEqual([check['id'] for check in checks],['opencode.delegation'])
+ self.assertEqual(checks[0]['missing_environment'],'fail')
+ self.assertIn('HIROUTE_WORKER_OPENCODE_BINARY',checks[0]['required_environment'])
+
def test_qoder_guide_and_settings_docs_do_not_expand_product_scope(self):
result = plan.select(['tools/product-e2e/tests/QODER_DELEGATION.md',
'docs/test-selection.md'])
@@ -237,7 +246,7 @@ class SelectionTests(unittest.TestCase):
self.assertEqual([row['id'] for row in checks],['dsh.delegation'])
self.assertEqual(checks[0]['missing_environment'],'fail')
shared = plan.worker_product_checks(['crates/daemon/tests/support/pi_discovery_product.py'])
- self.assertEqual({row['id'] for row in shared},{'pi.delegation','dsh.delegation'})
+ self.assertEqual({row['id'] for row in shared},{'pi.delegation','dsh.delegation','opencode.delegation'})
witness = plan.worker_product_checks(['crates/daemon/tests/support/native_task_witness.py'])
self.assertEqual({row['id'] for row in witness},{'qoder.delegation','dsh.delegation'})
diff --git a/scripts/test-windows-dev.py b/scripts/test-windows-dev.py
index ba32e3e2..2a50638a 100644
--- a/scripts/test-windows-dev.py
+++ b/scripts/test-windows-dev.py
@@ -835,6 +835,32 @@ class Runner(unittest.TestCase):
with self.subTest(value=value), self.assertRaises(ValueError):
controller.windows_path(value)
+ def test_temporary_acl_cases_preserve_an_existing_product_profile(self):
+ home, local = self.root / 'home', self.root / 'local'
+ marker = home / '.local/share/hiroute/standalone.json'
+ marker.parent.mkdir(parents=True)
+ marker.write_bytes(b'preserve installed product')
+ cases = (
+ 'windows_artifact_restart_restores_original_content_and_native_acl',
+ 'windows_acl_change_loses_compensation_ownership_even_with_equal_content',
+ 'windows_backup_authentication_binds_native_permission_facts',
+ 'windows_owned_directory_cleanup_preserves_user_additions_and_replacements',
+ )
+ for case in cases:
+ request = dict(binary='hiroute_local_storage.exe', ignored=False,
+ case='control::windows_artifacts_tests::' + case)
+ with self.subTest(case=case):
+ self.assertEqual(host.admit_test_profile(request, home, local), 'temporary_artifact_component')
+ for changed in ({'binary': 'windows_headless.exe'}, {'ignored': True},
+ {'case': request['case'] + '_unknown'}):
+ with self.assertRaisesRegex(ValueError, 'existing installation'):
+ host.admit_test_profile({**request, **changed}, home, local)
+ self.assertEqual(marker.read_bytes(), b'preserve installed product')
+ marker.unlink()
+ self.assertEqual(host.admit_test_profile(dict(binary='windows_headless.exe',
+ ignored=True, case='actual_windows_complete_public_headless_business'), home, local),
+ 'disposable_installation_profile')
+
def test_shell_payload_preserves_quotes_without_interpolation(self):
value = "C:/space ' $env:PATH ; directory/file.py"
script = '& ' + controller.ps_literal(value)
diff --git a/scripts/windows-dev-host.py b/scripts/windows-dev-host.py
index ea75e642..fabe353c 100644
--- a/scripts/windows-dev-host.py
+++ b/scripts/windows-dev-host.py
@@ -291,6 +291,27 @@ $tasks=@(Get-ScheduledTask | Where-Object {
return json.loads(ps(script))
+def admit_test_profile(request, home, localappdata):
+ # These native ACL cases create only tempfile-owned artifacts. They can share
+ # a logged-on account with an installed product without touching its profile.
+ artifact_cases = {
+ 'windows_artifact_restart_restores_original_content_and_native_acl',
+ 'windows_acl_change_loses_compensation_ownership_even_with_equal_content',
+ 'windows_backup_authentication_binds_native_permission_facts',
+ 'windows_owned_directory_cleanup_preserves_user_additions_and_replacements',
+ }
+ prefix = 'control::windows_artifacts_tests::'
+ if (request['binary'] == 'hiroute_local_storage.exe' and not request['ignored']
+ and request['case'] in {prefix + name for name in artifact_cases}):
+ return 'temporary_artifact_component'
+ # Never manufacture HOME or remove an existing installation to make a gate pass.
+ for path in (localappdata / 'HiRoute/cli', home / '.local/share/hiroute/standalone.json',
+ home / '.local/bin/hiroute.exe'):
+ if path.exists():
+ raise ValueError('Disposable installed-product gate found an existing installation')
+ return 'disposable_installation_profile'
+
+
def worker(request):
config = request['config']
root = plain(config['root'])
@@ -403,12 +424,8 @@ def worker(request):
result.update(passed=True, assessment='preparation_only', archival=archived,
inspection_sha256=digest(parent / 'result.json'))
return 0
- # Never manufacture HOME or remove an existing installation to make a gate pass.
home = Path.home()
- for path in (Path(os.environ['LOCALAPPDATA']) / 'HiRoute/cli',
- home / '.local/share/hiroute/standalone.json', home / '.local/bin/hiroute.exe'):
- if path.exists():
- raise ValueError('Disposable installed-product gate found an existing installation')
+ result['execution_scope'] = admit_test_profile(request, home, Path(os.environ['LOCALAPPDATA']))
if (request['binary'] == 'windows_desktop.exe' and
request['case'] == 'actual_nsis_silent_install_repeat_console_and_uninstall_preserve_data'):
profile_helper(request).require_fresh_nsis_packages(home)
@@ -448,7 +465,8 @@ def worker(request):
child.wait(timeout=30)
raise TimeoutError('Whole test process exceeded its watchdog')
diagnostics = Path(os.environ['LOCALAPPDATA']) / 'HiRoute/cli/diagnostics'
- for path in diagnostics.rglob('*.jsonl'):
+ for path in (diagnostics.rglob('*.jsonl') if
+ result['execution_scope'] == 'disposable_installation_profile' else ()):
try:
if path.stat().st_size <= 8 * 1024 * 1024:
name = hashlib.sha256(str(path.relative_to(diagnostics)).encode()).hexdigest()[:16]
diff --git a/scripts/windows-dev.py b/scripts/windows-dev.py
index bfab9049..13ef57db 100644
--- a/scripts/windows-dev.py
+++ b/scripts/windows-dev.py
@@ -21,7 +21,7 @@ ENVIRONMENT = {
'HIROUTE_WORKER_CODEX_BINARY', 'HIROUTE_WORKER_CLAUDE_BINARY',
'HIROUTE_WORKER_QODER_BINARY', 'HIROUTE_WORKER_CODEX_ACP_ADAPTER',
'HIROUTE_WORKER_CLAUDE_ACP_ADAPTER', 'HIROUTE_WORKER_PI_BINARY',
- 'HIROUTE_WORKER_DSH_BINARY',
+ 'HIROUTE_WORKER_DSH_BINARY', 'HIROUTE_WORKER_OPENCODE_BINARY',
}
diff --git a/tools/product-e2e/tests/OPENCODE_INTEGRATION.md b/tools/product-e2e/tests/OPENCODE_INTEGRATION.md
new file mode 100644
index 00000000..760b7a2e
--- /dev/null
+++ b/tools/product-e2e/tests/OPENCODE_INTEGRATION.md
@@ -0,0 +1,68 @@
+# OpenCode native integration acceptance
+
+OpenCode uses the shared Agent settings transaction, static API import and native ACP Worker lifecycle. This guide owns the native acceptance inputs; the [Worker map](../../../docs/code-map/worker-context.md) locates production code.
+
+## Installation and context
+
+Select the actual native executable explicitly. The official `opencode-ai` npm launcher can locate a platform package without being executed. An ambiguous platform/CPU variant requires choosing its native binary. Initial Worker format admission supports the official v1.19.3 platform package with adjacent name/version/os/cpu/libc metadata; a standalone copied binary or an unaudited format remains unavailable for Worker/Continue. Discovery, ordinary model settings and Skill ownership do not depend on this database-format capability.
+
+Use a dedicated synthetic HOME and workspace for acceptance. OpenCode uses native HOME/XDG config/data/cache/state semantics, absolute `OPENCODE_CONFIG`, additive `OPENCODE_CONFIG_DIR` and an absolute frozen database selector. Do not use daily credentials or move a real user's history. The production Worker borrows these roots; its owned task directory contains only descriptors and run material. Existing database migration IDs must match the audited native format before launch. Unknown/pending/legacy formats are preserved and refused.
+
+Windows npm discovery accepts the official declared `opencode.cmd` entry, including
+an extensionless PATH lookup, through the shared protected producer reader. It never
+executes the shim or adds a Node dependency to native launch. Wrong producers,
+reparse paths and ambiguous platform packages remain unavailable.
+
+Saved-model reference checks include bounded Markdown frontmatter from the selected
+user `agent(s)/**/*.md` and `mode(s)/*.md` resource directories. The existing
+Preview/staging/activation/retry dependency digest binds these files as well as
+JSON/JSONC. Referenced selectors cannot be removed or restored away; keeping them
+permits token rotation. Unreadable or ambiguous resources cannot authorize removal,
+and their original bytes remain untouched. Worker admission independently refuses
+empty/substituted `$schema` values and incomplete project ancestry before native
+startup, so it cannot trigger native schema repair or omit ancestor custom tools.
+The stop must be confirmed by bounded Git checks using the Worker's filtered
+HOME/XDG/PATH; `.git` existence alone is insufficient. Invalid markers, broken
+worktree pointers and missing/rejecting Git fail before launch. The core Worker
+journeys use real Git repositories/linked worktrees, place foreign configuration
+and an import sentinel beyond the confirmed stop, and exercise false stops through
+the public CLI before native database creation, tool import or model work.
+
+## Real product entry
+
+Set `HIROUTE_PRODUCT_CANDIDATE_SHA` to the exact candidate and `HIROUTE_WORKER_OPENCODE_BINARY` to the selected official native binary. Unix acceptance also requires installed `rg` on the runner PATH: the fixture exposes that exact native tool in its private PATH so Skill loading does not depend on an upstream tool download. Run through the [configured validation runner](../../../docs/validation-routing.md):
+
+```text
+cargo test --locked -p hiroute-product-e2e --test opencode_delegation -- --ignored --nocapture --test-threads=1
+```
+
+Missing inputs fail. The tests build the production CLI and daemon and use their public Local Control/Worker commands. Only upstream model replies and fixture-owned user files are synthetic. A normal Cargo run that leaves these tests ignored does not establish acceptance.
+
+The shared journeys cover saved Responses/Messages routes, daemon restart, grant rotation, default-reference refusal, independent model/Skill restore, passive source prepare/save with stale-credential refusal, actual installed Skill → public CLI → Worker, native Skill/read/edit/shell effects, concurrent routing/cancellation, missing-history refusal and exact Continue. OpenCode also exercises automatic native compaction and auxiliary requests on the frozen model route, including summary consumption after restart. A changed current Plan or current environment cannot select a new session on Continue.
+
+The explicit collaboration prerequisite check uses private configuration and history while loading the actual installed user Skill directory through OpenCode's resource loader. It disables native external `.agents`/`.claude` Skill discovery only for that isolated check, so an unrelated same-name global Skill cannot race the explicit resource. It validates exact path/body and a nonce-correlated trusted CLI result. It does not parse daily model configuration to authorize installation, inject a substitute installed Skill, or establish real delegated completion. Ordinary Agent and Worker Skill discovery remains native; a successful isolated check does not prove that an existing daily session loaded this file.
+
+On Windows this private check explicitly selects system Windows PowerShell and
+uses its literal native-command syntax; Qoder's Git Bash command contract is
+unchanged. The nonce is emitted only after a successful CLI exit. Static-source
+acceptance also includes independent provider credential failures (symbolic/hard
+links or oversized files): these stay non-importable while the valid source completes
+public Scan/Prepare/Save and still rejects stale credentials.
+
+## Evidence and platform limits
+
+Require every selected business case to be green in its scenario report. A successful build, fixture response or process exit alone is insufficient. Retain the exact source SHA, native package identity, selected protocol, task/native-session identities, source request kinds, owned-child cancellation and preserved native files. The product tests must not promote SDK metadata or mock IPC to native success.
+
+macOS/Linux/native Windows each need their real filesystem, installation and process boundary evidence. The Unix product entry above does not establish Windows acceptance. Windows compilation and native execution follow the existing [Windows validation workflow](../../../docs/validation-routing.md#windows-iteration-and-release-validation); neither another OS nor a cross-compile replaces execution. Browser component checks cover OpenCode forms separately and do not prove native Desktop authorization or persistence.
+
+For the native Windows boundary, configure the pinned `HIROUTE_WORKER_OPENCODE_BINARY`
+path in the existing HOME Windows validation configuration and include its native
+package metadata. Compile the `windows_headless` target through the managed MSVC
+workbench, export/stage its verified bundle, and select
+`actual_windows_opencode_worker_native_history_and_cancellation` with the existing
+`validation.py windows run` entry. It reuses the public source/Plan/Worker fixture,
+real Skill and file-tool receipts, Job cancellation checks and daemon restart with
+exact Continue. Native roots are created before daemon startup and borrowed
+configuration must remain byte-identical. This case establishes those Windows
+boundaries; saved ordinary model routes, static import and native Main delegation
+retain their separate journeys above.
diff --git a/tools/product-e2e/tests/opencode_delegation.rs b/tools/product-e2e/tests/opencode_delegation.rs
new file mode 100644
index 00000000..064377fb
--- /dev/null
+++ b/tools/product-e2e/tests/opencode_delegation.rs
@@ -0,0 +1,61 @@
+#![cfg(unix)]
+mod worker_product_support;
+#[test]
+#[ignore = "requires selected official OpenCode and production binaries"]
+fn opencode_worker_uses_native_skills_and_continues_the_frozen_task() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_OPENCODE_CORE",
+ "worker-native-context-core",
+ );
+}
+#[test]
+#[ignore = "requires selected official OpenCode and production binaries"]
+fn opencode_agent_saved_model_routes_preserve_defaults_and_restore_independently() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_OPENCODE_MODELS",
+ "opencode-persisted-model-routes",
+ );
+}
+#[test]
+#[ignore = "requires selected official OpenCode and production binaries"]
+fn opencode_agent_uses_installed_user_skill_to_delegate_through_public_cli() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_OPENCODE_MAIN",
+ "opencode-main-agent-delegation",
+ );
+}
+
+#[test]
+#[ignore = "requires selected official OpenCode and production binaries"]
+fn opencode_workers_route_independently_cancel_and_refuse_missing_history() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_OPENCODE_BOUNDARIES",
+ "worker-native-context-boundaries",
+ );
+}
+#[test]
+#[ignore = "requires selected official OpenCode and production binaries"]
+fn opencode_static_api_import_rechecks_source_and_preserves_native_files() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_OPENCODE_DISCOVERY",
+ "opencode-static-source-import",
+ );
+}
+
+#[test]
+#[ignore = "requires selected official OpenCode and production binaries"]
+fn opencode_messages_worker_preserves_tools_and_exact_continue() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_OPENCODE_MESSAGES",
+ "worker-native-context-core",
+ );
+}
+
+#[test]
+#[ignore = "requires selected official OpenCode and production binaries"]
+fn opencode_native_compaction_and_auxiliary_requests_keep_the_frozen_route() {
+ worker_product_support::run_real_worker_scenario(
+ "HIROUTE_PRODUCT_OPENCODE_COMPACTION",
+ "opencode-worker-compaction-route",
+ );
+}
diff --git a/tools/product-e2e/tests/worker_product_support/mod.rs b/tools/product-e2e/tests/worker_product_support/mod.rs
index 6f7a1eee..20f1291c 100644
--- a/tools/product-e2e/tests/worker_product_support/mod.rs
+++ b/tools/product-e2e/tests/worker_product_support/mod.rs
@@ -15,6 +15,27 @@ const REQUIRED_INSTALLATIONS: [&str; 5] = [
];
pub fn run_real_worker_scenario(mode: &str, expected_scenario: &str) {
+ let opencode_script = match mode {
+ "HIROUTE_PRODUCT_OPENCODE_CORE" | "HIROUTE_PRODUCT_OPENCODE_MESSAGES" => {
+ Some("native_context_product.py")
+ }
+ "HIROUTE_PRODUCT_OPENCODE_MODELS" => Some("additional_model_product.py"),
+ "HIROUTE_PRODUCT_OPENCODE_MAIN" => Some("collaboration_product.py"),
+ "HIROUTE_PRODUCT_OPENCODE_BOUNDARIES" => Some("native_context_boundaries.py"),
+ "HIROUTE_PRODUCT_OPENCODE_DISCOVERY" => Some("pi_discovery_product.py"),
+ "HIROUTE_PRODUCT_OPENCODE_COMPACTION" => Some("native_compaction_product.py"),
+ _ => None,
+ };
+ if let Some(script) = opencode_script {
+ run_scenario(
+ script,
+ mode,
+ expected_scenario,
+ &["opencode"],
+ &["HIROUTE_WORKER_OPENCODE_BINARY"],
+ );
+ return;
+ }
let dsh_script = match mode {
"HIROUTE_PRODUCT_DSH_CORE" => Some("native_context_product.py"),
"HIROUTE_PRODUCT_DSH_BOUNDARIES" => Some("native_context_boundaries.py"),
@@ -145,6 +166,9 @@ fn run_scenario(
command.args(["--harness", harness]);
}
command.env(mode, "1");
+ if mode == "HIROUTE_PRODUCT_OPENCODE_MESSAGES" {
+ command.env("HIROUTE_PRODUCT_AGENT_PROTOCOL", "messages");
+ }
let output = command
.output()
.expect("run the real Worker product scenario");
@@ -201,22 +225,28 @@ fn assert_scenario(output: Output, scenario: &str, harness: &str, candidate: &st
"worker.context.tool-summary-route",
"worker.context.compaction-route",
],
- "pi-worker-compaction-route" => &["worker.context.compaction-route"],
- "pi-static-source-import" | "dsh-static-source-import" => &[
+ "pi-worker-compaction-route" | "opencode-worker-compaction-route" => {
+ &["worker.context.compaction-route"]
+ }
+ "pi-static-source-import"
+ | "dsh-static-source-import"
+ | "opencode-static-source-import" => &[
"agent.sources.effective-static-import",
"agent.sources.changed-source-rejected",
"agent.sources.imported-route-usable",
],
"qoder-main-agent-delegation"
| "pi-main-agent-delegation"
- | "dsh-main-agent-delegation" => &[
+ | "dsh-main-agent-delegation"
+ | "opencode-main-agent-delegation" => &[
"agent.collaboration.user-skill",
"agent.collaboration.public-worker-delegation",
"agent.collaboration.disable-owned-skill",
],
"qoder-persisted-model-routes"
| "pi-persisted-model-routes"
- | "dsh-persisted-model-routes" => &[
+ | "dsh-persisted-model-routes"
+ | "opencode-persisted-model-routes" => &[
"agent.models.persisted-routes",
"agent.models.credential-rotation",
"agent.models.independent-restore",