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.

fix(cli): configure collaboration using the Agent root context (#105)

澄潭5232db559bb8
diff --git a/assets/skills/hiroute-management/SKILL.md b/assets/skills/hiroute-management/SKILL.md
index 3f95ceab..b56798c9 100644
--- a/assets/skills/hiroute-management/SKILL.md
+++ b/assets/skills/hiroute-management/SKILL.md
@@ -108,6 +108,15 @@ invent capability, reasoning, price, timeout, or delegation choices.
`agents connect preview` and `agents connect apply`. Standalone already supplies its resident
service, so do not add Desktop login-item steps. After status is configured, the user continues
through the original `codex` entry.
+- For collaboration, read `hiroute agents collaboration --help`, then use `configure` with the
+ exact discovered Agent ID and `--trigger explicit` or `--trigger delegate-by-default`.
+ `--preview` is read-only; save performs only missing bounded local checks before Preview/Apply.
+ Use a stable `--idempotency-key` and retry that same intent/key after uncertain delivery.
+ `status` observes collaboration, and `disable --preview` followed by user-authorized
+ `disable --yes` restores only the collaboration facet. Accepted is pending, not completion.
+ The workflow selects Codex's original root context while keeping its model profile unchanged.
+ Advanced JSON collaboration requests must use `codex_access.root_context_id`, never the
+ top-level model profile context. A root-context diagnostic is not a request for another token.
- Use only profile-compatible plan protocols. Do not attach a Responses-only plan to a
Messages-only surface.
- Save the returned restore point. Restore only through `agents restore preview` and
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index de6f590b..807294ad 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -6,6 +6,7 @@
"hiroute.agent-check-request/v1",
"hiroute.agent-check/v1",
"hiroute.agent-collaboration-check-failure/v1",
+ "hiroute.agent-collaboration-cli-receipt/v1",
"hiroute.agent-collaboration-credential/v1",
"hiroute.agent-collaboration-grant/v1",
"hiroute.agent-collaboration-only-settings-status/v2",
diff --git a/crates/application/src/control/mod.rs b/crates/application/src/control/mod.rs
index 5419ef29..f991435e 100644
--- a/crates/application/src/control/mod.rs
+++ b/crates/application/src/control/mod.rs
@@ -45,6 +45,8 @@ pub enum ControlReadError {
Unavailable,
Corrupt,
Denied,
+ /// A model-only Codex profile cannot own the collaboration Skill in the original HOME.
+ CollaborationRootRequired,
}
pub trait ClassifierDiagnosticPort: Send + Sync {
diff --git a/crates/application/src/control_plane/agent_settings.rs b/crates/application/src/control_plane/agent_settings.rs
index 75fc664c..81b5c704 100644
--- a/crates/application/src/control_plane/agent_settings.rs
+++ b/crates/application/src/control_plane/agent_settings.rs
@@ -36,7 +36,7 @@ pub(crate) fn preview(
};
let input = match port.settings_facts(&payload.spec) {
Ok(input) => input,
- Err(error) => return failed(map_control_error(error), request.request_id),
+ Err(error) => return settings_read_failure(error, request.request_id),
};
let preview = match preview_agent_settings(payload.spec, &input.facts) {
Ok(preview) => preview,
@@ -173,7 +173,7 @@ pub(crate) fn apply(
};
let input = match port.settings_facts(&payload.spec) {
Ok(input) => input,
- Err(error) => return failed(map_control_error(error), request.request_id),
+ Err(error) => return settings_read_failure(error, request.request_id),
};
if !input
.facts
@@ -261,6 +261,28 @@ fn confirmation_error(error: SettingsConfirmationError) -> ErrorCode {
}
}
+fn settings_read_failure(
+ error: crate::control::ControlReadError,
+ request_id: String,
+) -> MachineEnvelopeV2<Value> {
+ let mut response = failed(map_control_error(error), request_id);
+ if error == crate::control::ControlReadError::CollaborationRootRequired {
+ response
+ .error
+ .as_mut()
+ .expect("failed envelope has an error")
+ .message_key = "error.agent_collaboration_root_context_required".into();
+ response
+ .next_actions
+ .push(hiroute_application_api::NextActionV1 {
+ command_id: "agents.scan".into(),
+ input: json!({}),
+ reason_code: "COLLABORATION_ROOT_CONTEXT_REQUIRED".into(),
+ });
+ }
+ response
+}
+
pub(crate) fn status(
service: &ApplicationService,
request: LocalControlRequestV2,
diff --git a/crates/application/src/lib.rs b/crates/application/src/lib.rs
index cca1ce19..e82d1941 100644
--- a/crates/application/src/lib.rs
+++ b/crates/application/src/lib.rs
@@ -740,7 +740,8 @@ fn map_control_error(error: control::ControlReadError) -> ErrorCode {
control::ControlReadError::Unavailable | control::ControlReadError::Corrupt => {
ErrorCode::DaemonUnavailable
}
- control::ControlReadError::Denied => ErrorCode::CapabilityDenied,
+ control::ControlReadError::Denied
+ | control::ControlReadError::CollaborationRootRequired => ErrorCode::CapabilityDenied,
}
}
diff --git a/crates/application/src/observation_query/control.rs b/crates/application/src/observation_query/control.rs
index e107e290..6b24d8f6 100644
--- a/crates/application/src/observation_query/control.rs
+++ b/crates/application/src/observation_query/control.rs
@@ -360,7 +360,9 @@ fn decode_cursor(cursor: &str) -> Result<SessionCursor<'_>, ObservationQueryErro
fn map_control(error: ControlReadError) -> ObservationQueryError {
match error {
- ControlReadError::Denied => ObservationQueryError::Unauthorized,
+ ControlReadError::Denied | ControlReadError::CollaborationRootRequired => {
+ ObservationQueryError::Unauthorized
+ }
ControlReadError::NotFound => ObservationQueryError::NotFound,
ControlReadError::Corrupt => ObservationQueryError::Corrupt,
ControlReadError::Unavailable | ControlReadError::SnapshotChanged => {
diff --git a/crates/cli/src/args.rs b/crates/cli/src/args.rs
index c8aeee25..18e1659d 100644
--- a/crates/cli/src/args.rs
+++ b/crates/cli/src/args.rs
@@ -32,10 +32,22 @@ pub(crate) fn split_globals(
arguments: Vec<String>,
) -> Result<(Vec<String>, Globals), GlobalSplitError> {
let worker = is_worker_invocation(&arguments);
+ let collaboration = arguments
+ .windows(2)
+ .any(|pair| pair == ["agents", "collaboration"]);
let mut remaining = Vec::new();
let mut globals = Globals::default();
let mut index = 0;
while index < arguments.len() {
+ if collaboration && matches!(arguments[index].as_str(), "--trigger" | "--idempotency-key") {
+ remaining.push(arguments[index].clone());
+ let Some(value) = arguments.get(index + 1) else {
+ return Err(split_error(globals, worker));
+ };
+ remaining.push(value.clone());
+ index += 2;
+ continue;
+ }
if worker {
if arguments[index] == "--" {
remaining.extend(arguments[index..].iter().cloned());
diff --git a/crates/cli/src/client.rs b/crates/cli/src/client.rs
index bacfc4aa..b531ef00 100644
--- a/crates/cli/src/client.rs
+++ b/crates/cli/src/client.rs
@@ -133,29 +133,43 @@ impl LocalControlClient {
&self,
request: LocalControlWireRequestV2,
) -> Result<MachineEnvelopeV2<serde_json::Value>, LocalControlClientError> {
+ self.call_detailed(request)
+ .map_err(|error| match error.code {
+ hiroute_client_core::FailureCode::LocatorUnavailable => {
+ LocalControlClientError::LocatorUnavailable
+ }
+ hiroute_client_core::FailureCode::TransportUnavailable
+ | hiroute_client_core::FailureCode::Deadline
+ | hiroute_client_core::FailureCode::UnsupportedPlatform => {
+ LocalControlClientError::Transport
+ }
+ _ => LocalControlClientError::Protocol,
+ })
+ }
+
+ pub(crate) fn call_detailed(
+ &self,
+ request: LocalControlWireRequestV2,
+ ) -> Result<MachineEnvelopeV2<serde_json::Value>, hiroute_client_core::ClientFailure> {
let client = self.shared_client();
let execute = move || {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
- .map_err(|_| LocalControlClientError::Transport)?
+ .map_err(|_| {
+ hiroute_client_core::ClientFailure::before_send(
+ hiroute_client_core::FailureCode::TransportUnavailable,
+ )
+ })?
.block_on(client.call_wire(request))
- .map_err(|error| match error.code {
- hiroute_client_core::FailureCode::LocatorUnavailable => {
- LocalControlClientError::LocatorUnavailable
- }
- hiroute_client_core::FailureCode::TransportUnavailable
- | hiroute_client_core::FailureCode::Deadline
- | hiroute_client_core::FailureCode::UnsupportedPlatform => {
- LocalControlClientError::Transport
- }
- _ => LocalControlClientError::Protocol,
- })
};
if tokio::runtime::Handle::try_current().is_ok() {
std::thread::spawn(execute)
.join()
- .map_err(|_| LocalControlClientError::Transport)?
+ .map_err(|_| hiroute_client_core::ClientFailure {
+ code: hiroute_client_core::FailureCode::TransportUnavailable,
+ submission: hiroute_client_core::SubmissionState::MayHaveReachedServer,
+ })?
} else {
execute()
}
diff --git a/crates/cli/src/collaboration.rs b/crates/cli/src/collaboration.rs
new file mode 100644
index 00000000..2f7f5da1
--- /dev/null
+++ b/crates/cli/src/collaboration.rs
@@ -0,0 +1,175 @@
+//! Presentation workflow for the independent collaboration facet. Application still owns
+//! capability checks, preview digests, admission and field-owned restore.
+mod flow;
+mod receipt;
+#[cfg(test)]
+mod tests;
+
+use hiroute_application_api::{AgentCollaborationTriggerModeV2, ErrorCode};
+use serde::{Deserialize, Serialize};
+
+use crate::args::{Globals, OutputMode};
+use crate::{CliExecution, LocalControlClient, failure, render};
+
+const HELP: &str = "Configure task collaboration independently of model settings.\n\nUsage\n hiroute agents collaboration configure <AGENT_ID> --trigger explicit|delegate-by-default [--preview] [--idempotency-key KEY] --output json\n hiroute agents collaboration disable <AGENT_ID> [--preview | --yes] [--idempotency-key KEY] --output json\n hiroute agents collaboration status <AGENT_ID> --output json\n\nUse the exact Agent ID from 'hiroute agents scan'. Codex collaboration uses its original HOME/root context, including when the model profile is occupied.\nConfigure enables or edits the Skill trigger. Save may run missing bounded local checks and then the existing Preview/Apply transaction; it never calls a provider model. --preview has no side effects and never runs a check or writes a submission receipt. Disable requires --yes unless previewing.\nSave freezes its request before submission. Use the same --idempotency-key to retry the same intent; a changed intent needs a new key. The response includes cli_submission.idempotency_key. An accepted Operation is pending: use 'hiroute operations get <OPERATION_ID>' or collaboration status to observe completion.\nThe advanced 'agents connect/restore preview/apply --request-stdin' commands retain their exact context semantics.\n";
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
+pub(super) enum Intent {
+ Configure {
+ trigger_mode: AgentCollaborationTriggerModeV2,
+ },
+ Disable,
+ Status,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub(super) struct Selection {
+ agent_id: String,
+ intent: Intent,
+}
+
+#[derive(Debug)]
+pub(super) struct Invocation {
+ selection: Selection,
+ preview: bool,
+ key: Option<String>,
+}
+
+pub(crate) fn execute(arguments: &[String], globals: &Globals) -> Option<CliExecution> {
+ if arguments.get(..2)? != ["agents", "collaboration"] {
+ return None;
+ }
+ if globals.help {
+ return Some(CliExecution {
+ exit_code: 0,
+ stdout: HELP.into(),
+ stderr: String::new(),
+ });
+ }
+ let request_id = globals
+ .request_id
+ .clone()
+ .unwrap_or_else(crate::next_request_id);
+ if globals.agent.is_some()
+ || globals.capability_fd.is_some()
+ || globals.output != OutputMode::Json
+ {
+ return Some(failure(ErrorCode::InvalidArguments, Some(request_id)));
+ }
+ let invocation = match parse(&arguments[2..]) {
+ Ok(invocation) => invocation,
+ Err(code) => return Some(failure(code, Some(request_id))),
+ };
+ let client = match LocalControlClient::cli_from_environment() {
+ Ok(client) => client.with_timeout(
+ globals
+ .timeout
+ .unwrap_or(std::time::Duration::from_secs(30)),
+ ),
+ Err(_) => return Some(failure(ErrorCode::DaemonUnavailable, Some(request_id))),
+ };
+ // Read-only commands do not require writable state or even a state layout. Submission
+ // records outlive a login/runtime directory and remain scoped to the selected endpoint.
+ let receipts = if invocation.preview || invocation.selection.intent == Intent::Status {
+ std::path::PathBuf::new()
+ } else {
+ match hiroute_host_runtime::StandaloneLayout::from_environment()
+ .map_err(|_| ErrorCode::DaemonUnavailable)
+ .and_then(|layout| receipt::root(&layout.state_root, &client.endpoint()))
+ {
+ Ok(root) => root,
+ Err(code) => return Some(failure(code, Some(request_id))),
+ }
+ };
+ Some(render(flow::run(
+ &client, &receipts, invocation, request_id,
+ )))
+}
+
+fn parse(options: &[String]) -> Result<Invocation, ErrorCode> {
+ let invalid = ErrorCode::InvalidArguments;
+ let [verb, agent_id, options @ ..] = options else {
+ return Err(invalid);
+ };
+ if !bounded(agent_id, 256) || agent_id.starts_with('-') {
+ return Err(invalid);
+ }
+ let mut trigger = None;
+ let mut preview = false;
+ let mut yes = false;
+ let mut key = None;
+ let mut index = 0;
+ while index < options.len() {
+ match options[index].as_str() {
+ "--preview" if !preview => preview = true,
+ "--yes" if !yes => yes = true,
+ "--trigger" if trigger.is_none() => {
+ index += 1;
+ trigger = Some(match options.get(index).map(String::as_str) {
+ Some("explicit") => AgentCollaborationTriggerModeV2::Explicit,
+ Some("delegate-by-default") => {
+ AgentCollaborationTriggerModeV2::DelegateByDefault
+ }
+ _ => return Err(invalid),
+ });
+ }
+ "--idempotency-key" if key.is_none() => {
+ index += 1;
+ key = Some(
+ options
+ .get(index)
+ .filter(|value| {
+ !value.is_empty()
+ && value.len() <= 200
+ && !value.starts_with('-')
+ && value.bytes().all(|byte| {
+ byte.is_ascii_alphanumeric()
+ || matches!(byte, b'.' | b'_' | b':' | b'-')
+ })
+ })
+ .ok_or(invalid)?
+ .clone(),
+ );
+ }
+ _ => return Err(invalid),
+ }
+ index += 1;
+ }
+ if preview && (yes || key.is_some()) {
+ return Err(invalid);
+ }
+ let intent = match verb.as_str() {
+ "configure" if !yes => Intent::Configure {
+ trigger_mode: trigger.ok_or(invalid)?,
+ },
+ "disable" if trigger.is_none() && (preview || yes) => Intent::Disable,
+ "status" if trigger.is_none() && !preview && !yes && key.is_none() => Intent::Status,
+ _ => return Err(invalid),
+ };
+ Ok(Invocation {
+ selection: Selection {
+ agent_id: agent_id.clone(),
+ intent,
+ },
+ preview,
+ key,
+ })
+}
+
+fn bounded(value: &str, max: usize) -> bool {
+ !value.is_empty() && value.len() <= max && !value.contains(char::is_control)
+}
+
+pub(super) fn random_key() -> Result<String, ErrorCode> {
+ let mut entropy = [0_u8; 16];
+ getrandom::fill(&mut entropy).map_err(|_| ErrorCode::DaemonUnavailable)?;
+ Ok(format!(
+ "collaboration-{}",
+ entropy
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect::<String>()
+ ))
+}
diff --git a/crates/cli/src/collaboration/flow.rs b/crates/cli/src/collaboration/flow.rs
new file mode 100644
index 00000000..9ab50fa3
--- /dev/null
+++ b/crates/cli/src/collaboration/flow.rs
@@ -0,0 +1,364 @@
+use std::path::Path;
+
+use hiroute_application_api::{
+ AGENT_SETTINGS_SCHEMA_V2, AgentAccessTokenIntentV1, AgentCheckRequestV1, AgentCheckScopeV1,
+ AgentCheckSuiteV1, AgentCollaborationSelectionV2, AgentFacetIntent, AgentSettingsApplyV2,
+ AgentSettingsPreviewRequestV2, AgentSettingsSpecV2, AgentSettingsStatusRequestV2,
+ AgentSettingsStatusV2, CanonicalDigest, ErrorCode, ErrorV1, LOCAL_CONTROL_SCHEMA_V2,
+ LocalControlWireRequestV2, MachineEnvelopeV2, MachineStatus, NextActionV1, RevisionSetV1,
+};
+use hiroute_client_core::{ClientFailure, SubmissionState};
+use serde::Deserialize;
+use serde_json::{Value, json};
+
+use super::{Intent, Invocation, Selection, random_key, receipt};
+
+pub(super) trait Control {
+ fn call(
+ &self,
+ request: LocalControlWireRequestV2,
+ ) -> Result<MachineEnvelopeV2<Value>, ClientFailure>;
+}
+impl Control for crate::LocalControlClient {
+ fn call(
+ &self,
+ request: LocalControlWireRequestV2,
+ ) -> Result<MachineEnvelopeV2<Value>, ClientFailure> {
+ self.call_detailed(request)
+ }
+}
+
+// Deliberately decode only the safe scan projection this presentation workflow consumes.
+// The daemon's discovered credential and model catalog projections are not needed here.
+#[derive(Deserialize)]
+struct Scan {
+ agents: Vec<Agent>,
+}
+#[derive(Deserialize)]
+struct Agent {
+ agent_id: String,
+ supported: bool,
+ context_id: Option<String>,
+ codex_access: Option<CodexAccess>,
+}
+#[derive(Deserialize)]
+struct CodexAccess {
+ root_context_id: String,
+}
+#[derive(Deserialize)]
+struct Preview {
+ schema: String,
+ spec: AgentSettingsSpecV2,
+ applicable: bool,
+ accept_digest: CanonicalDigest,
+ dependency_digest: CanonicalDigest,
+ expected_revisions: RevisionSetV1,
+ blockers: Vec<Block>,
+}
+#[derive(Deserialize)]
+struct Block {
+ #[serde(default)]
+ capabilities: Vec<Capability>,
+}
+#[derive(Deserialize)]
+struct Capability {
+ capability: String,
+}
+
+pub(super) fn run(
+ client: &impl Control,
+ receipts: &Path,
+ invocation: Invocation,
+ request_id: String,
+) -> MachineEnvelopeV2<Value> {
+ match workflow(client, receipts, &invocation, &request_id) {
+ Ok(response) => response,
+ Err(response) => *response,
+ }
+}
+type FlowResult<T> = Result<T, Box<MachineEnvelopeV2<Value>>>;
+
+fn workflow(
+ client: &impl Control,
+ receipts: &Path,
+ invocation: &Invocation,
+ request_id: &str,
+) -> FlowResult<MachineEnvelopeV2<Value>> {
+ let selection = &invocation.selection;
+ let key = if invocation.preview || selection.intent == Intent::Status {
+ None
+ } else {
+ Some(
+ invocation
+ .key
+ .clone()
+ .map(Ok)
+ .unwrap_or_else(random_key)
+ .map_err(|code| fail(code, request_id))?,
+ )
+ };
+ if let Some(key) = key.as_deref() {
+ // Replay the immutable original request before discovery/check/preview can change its
+ // accepted digest. A key reused for a different intent fails before any native check.
+ if let Some(saved) =
+ receipt::load(receipts, key, selection).map_err(|code| fail(code, request_id))?
+ {
+ return Ok(submit(client, saved, selection, request_id));
+ }
+ }
+ let scan: Scan = query(client, "ScanAgents", json!({}), request_id)?;
+ let mut agents = scan
+ .agents
+ .into_iter()
+ .filter(|agent| agent.agent_id == selection.agent_id);
+ let agent = agents
+ .next()
+ .ok_or_else(|| fail(ErrorCode::ResourceNotFound, request_id))?;
+ if agents.next().is_some() {
+ return Err(fail(ErrorCode::InvalidArguments, request_id));
+ }
+ if !agent.supported {
+ return Err(fail(ErrorCode::NoSupportedAgent, request_id));
+ }
+ let context_id = if let Some(access) = agent.codex_access {
+ access.root_context_id
+ } else {
+ agent
+ .context_id
+ .ok_or_else(|| fail(ErrorCode::ResourceNotFound, request_id))?
+ };
+ if !super::bounded(&context_id, 256) {
+ return Err(fail(ErrorCode::DaemonUnavailable, request_id));
+ }
+ if selection.intent == Intent::Status {
+ return call(
+ client,
+ "GetAgentConnectionStatus",
+ json!(AgentSettingsStatusRequestV2 {
+ schema_version: AGENT_SETTINGS_SCHEMA_V2,
+ context_id
+ }),
+ request_id,
+ );
+ }
+ let collaboration = match selection.intent {
+ Intent::Configure { trigger_mode } => AgentFacetIntent::Configure {
+ settings: AgentCollaborationSelectionV2 { trigger_mode },
+ },
+ Intent::Disable => {
+ let status: AgentSettingsStatusV2 = query(
+ client,
+ "GetAgentConnectionStatus",
+ json!(AgentSettingsStatusRequestV2 {
+ schema_version: AGENT_SETTINGS_SCHEMA_V2,
+ context_id: context_id.clone()
+ }),
+ request_id,
+ )?;
+ if !status.valid() || status.context_id() != context_id {
+ return Err(fail(ErrorCode::DaemonUnavailable, request_id));
+ }
+ let restore_point_ref = status
+ .collaboration()
+ .and_then(|facet| facet.restore_point_ref.clone())
+ .ok_or_else(|| fail(ErrorCode::ResourceNotFound, request_id))?;
+ AgentFacetIntent::Restore { restore_point_ref }
+ }
+ Intent::Status => unreachable!(),
+ };
+ let spec = AgentSettingsSpecV2 {
+ schema_version: AGENT_SETTINGS_SCHEMA_V2,
+ context_id,
+ model: AgentFacetIntent::Keep,
+ collaboration,
+ restore_native_model: None,
+ protected_native_model_ids: Vec::new(),
+ access_token: AgentAccessTokenIntentV1::Keep,
+ };
+ let restore = spec.is_restore_only();
+ let preview_operation = if restore {
+ "PreviewAgentConnectionRestore"
+ } else {
+ "PreviewAgentConnectionChange"
+ };
+ let mut response = call(
+ client,
+ preview_operation,
+ json!(AgentSettingsPreviewRequestV2 { spec: spec.clone() }),
+ request_id,
+ )?;
+ let mut preview = decode_preview(&response, &spec, request_id)?;
+ if invocation.preview {
+ return Ok(response);
+ }
+ // Match Desktop's prerequisite selection, but re-evaluate after each check. A successful
+ // local check is not proof that the fresh preview is applicable or that Skill installation
+ // has occurred. Each scope is attempted at most once; Live is never part of this workflow.
+ let mut checked = Vec::new();
+ while !preview.applicable {
+ let scope = prerequisite(&preview);
+ let Some(scope) = scope.filter(|scope| !checked.contains(scope)) else {
+ response.status = MachineStatus::Conflict;
+ response.error = Some(ErrorV1::new(ErrorCode::FeatureNotEnabled));
+ return Err(Box::new(response));
+ };
+ call(
+ client,
+ "CheckAgentConnection",
+ json!(AgentCheckRequestV1 {
+ agent_id: selection.agent_id.clone(),
+ scope,
+ suite: AgentCheckSuiteV1::Quick,
+ allow_model_call: false,
+ target: None
+ }),
+ request_id,
+ )?;
+ checked.push(scope);
+ response = call(
+ client,
+ preview_operation,
+ json!(AgentSettingsPreviewRequestV2 { spec: spec.clone() }),
+ request_id,
+ )?;
+ preview = decode_preview(&response, &spec, request_id)?;
+ }
+ let apply = AgentSettingsApplyV2 {
+ spec: preview.spec,
+ accept_digest: preview.accept_digest,
+ dependency_digest: preview.dependency_digest,
+ expected_revisions: preview.expected_revisions,
+ idempotency_key: key.expect("a save has a submission key"),
+ login_item: None,
+ };
+ let saved =
+ receipt::freeze(receipts, selection, apply).map_err(|code| fail(code, request_id))?;
+ Ok(submit(client, saved, selection, request_id))
+}
+
+fn decode_preview(
+ response: &MachineEnvelopeV2<Value>,
+ spec: &AgentSettingsSpecV2,
+ request_id: &str,
+) -> FlowResult<Preview> {
+ let preview: Preview = serde_json::from_value(
+ response
+ .data
+ .clone()
+ .ok_or_else(|| fail(ErrorCode::DaemonUnavailable, request_id))?,
+ )
+ .map_err(|_| fail(ErrorCode::DaemonUnavailable, request_id))?;
+ // Preview may seal protected native model names even for model.keep. Preserve those names
+ // in Apply, while rejecting any change to the user's context, facets or token intent.
+ let mut intent = preview.spec.clone();
+ intent.protected_native_model_ids.clear();
+ if preview.schema != "hiroute.agent-settings-preview/v2"
+ || &intent != spec
+ || preview.applicable != preview.blockers.is_empty()
+ {
+ return Err(fail(ErrorCode::DaemonUnavailable, request_id));
+ }
+ Ok(preview)
+}
+
+fn prerequisite(preview: &Preview) -> Option<AgentCheckScopeV1> {
+ let missing = |name| {
+ preview
+ .blockers
+ .iter()
+ .flat_map(|block| &block.capabilities)
+ .any(|capability| capability.capability == name)
+ };
+ if missing("ingress_authentication") {
+ Some(AgentCheckScopeV1::NativeAuthentication)
+ } else if missing("skill_loading") || missing("trusted_cli_execution") {
+ Some(AgentCheckScopeV1::Collaboration)
+ } else {
+ None
+ }
+}
+
+fn submit(
+ client: &impl Control,
+ apply: AgentSettingsApplyV2,
+ selection: &Selection,
+ request_id: &str,
+) -> MachineEnvelopeV2<Value> {
+ let operation = if apply.spec.is_restore_only() {
+ "ApplyAgentConnectionRestore"
+ } else {
+ "ApplyAgentConnectionChange"
+ };
+ let mut response = match client.call(wire(operation, json!(apply), request_id)) {
+ Ok(response) => response,
+ Err(error) => {
+ let mut response = *fail(ErrorCode::DaemonUnavailable, request_id);
+ response.next_actions.push(NextActionV1 {
+ command_id: if apply.spec.is_restore_only() {
+ "agents.restore.apply"
+ } else {
+ "agents.connect.apply"
+ }
+ .into(),
+ input: json!(apply),
+ reason_code: match error.submission {
+ SubmissionState::NotSent => "SUBMISSION_NOT_SENT",
+ SubmissionState::MayHaveReachedServer => "SUBMISSION_UNKNOWN",
+ }
+ .into(),
+ });
+ response
+ }
+ };
+ let submission = json!({"agent_id":selection.agent_id, "context_id":apply.spec.context_id, "idempotency_key":apply.idempotency_key});
+ let data = response.data.get_or_insert_with(|| json!({}));
+ if let Some(data) = data.as_object_mut() {
+ data.insert("cli_submission".into(), submission);
+ }
+ response
+}
+
+fn wire(operation: &str, payload: Value, request_id: &str) -> LocalControlWireRequestV2 {
+ LocalControlWireRequestV2 {
+ schema_version: LOCAL_CONTROL_SCHEMA_V2,
+ request_id: request_id.into(),
+ operation_id: operation.into(),
+ payload,
+ protected_grant: None,
+ }
+}
+fn call(
+ client: &impl Control,
+ operation: &str,
+ payload: Value,
+ request_id: &str,
+) -> FlowResult<MachineEnvelopeV2<Value>> {
+ let response = client
+ .call(wire(operation, payload, request_id))
+ .map_err(|_| fail(ErrorCode::DaemonUnavailable, request_id))?;
+ if response.status == MachineStatus::Succeeded {
+ Ok(response)
+ } else {
+ Err(Box::new(response))
+ }
+}
+fn query<T: serde::de::DeserializeOwned>(
+ client: &impl Control,
+ operation: &str,
+ payload: Value,
+ request_id: &str,
+) -> FlowResult<T> {
+ let response = call(client, operation, payload, request_id)?;
+ serde_json::from_value(
+ response
+ .data
+ .ok_or_else(|| fail(ErrorCode::DaemonUnavailable, request_id))?,
+ )
+ .map_err(|_| fail(ErrorCode::DaemonUnavailable, request_id))
+}
+fn fail(code: ErrorCode, request_id: &str) -> Box<MachineEnvelopeV2<Value>> {
+ Box::new(MachineEnvelopeV2::failed(
+ ErrorV1::new(code),
+ Some(request_id.into()),
+ ))
+}
diff --git a/crates/cli/src/collaboration/receipt.rs b/crates/cli/src/collaboration/receipt.rs
new file mode 100644
index 00000000..2ee59ed3
--- /dev/null
+++ b/crates/cli/src/collaboration/receipt.rs
@@ -0,0 +1,223 @@
+//! Immutable, credential-free submission binding. User retries reuse the exact Preview/Apply
+//! bytes; a crash or corrupt record never authorizes reconstructing a different request.
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+
+use hiroute_application_api::{
+ AgentAccessTokenIntentV1, AgentFacetIntent, AgentSettingsApplyV2, CanonicalDigest, ErrorCode,
+};
+use serde::{Deserialize, Serialize};
+
+use super::{Intent, Selection};
+
+const SCHEMA: &str = "hiroute.agent-collaboration-cli-receipt/v1";
+
+pub(super) fn root(state: &Path, endpoint: &Path) -> Result<PathBuf, ErrorCode> {
+ let digest =
+ CanonicalDigest::of(&(SCHEMA, endpoint)).map_err(|_| ErrorCode::DaemonUnavailable)?;
+ Ok(state
+ .join("cli-collaboration")
+ .join(digest.as_str().trim_start_matches("sha256:")))
+}
+
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+struct Record {
+ schema: String,
+ instance: CanonicalDigest,
+ selection: Selection,
+ apply: AgentSettingsApplyV2,
+}
+
+fn instance(root: &Path) -> Result<CanonicalDigest, ErrorCode> {
+ CanonicalDigest::of(&(SCHEMA, root)).map_err(|_| ErrorCode::DaemonUnavailable)
+}
+fn path(root: &Path, key: &str) -> Result<PathBuf, ErrorCode> {
+ let digest = CanonicalDigest::of(&(SCHEMA, key)).map_err(|_| ErrorCode::DaemonUnavailable)?;
+ Ok(root.join(format!(
+ "{}.json",
+ digest.as_str().trim_start_matches("sha256:")
+ )))
+}
+
+pub(super) fn load(
+ root: &Path,
+ key: &str,
+ selection: &Selection,
+) -> Result<Option<AgentSettingsApplyV2>, ErrorCode> {
+ let path = path(root, key)?;
+ match std::fs::symlink_metadata(&path) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(_) => return Err(ErrorCode::DaemonUnavailable),
+ Ok(_) => {}
+ }
+ private(root.parent().ok_or(ErrorCode::DaemonUnavailable)?, true)?;
+ private(root, true)?;
+ private(&path, false)?;
+ let mut bytes = Vec::new();
+ std::fs::File::open(&path)
+ .and_then(|file| file.take(65_537).read_to_end(&mut bytes))
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ if bytes.len() > 65_536 {
+ return Err(ErrorCode::DaemonUnavailable);
+ }
+ let record: Record =
+ serde_json::from_slice(&bytes).map_err(|_| ErrorCode::DaemonUnavailable)?;
+ if record.schema != SCHEMA
+ || record.instance != instance(root)?
+ || record.apply.idempotency_key != key
+ {
+ return Err(ErrorCode::DaemonUnavailable);
+ }
+ if &record.selection != selection {
+ return Err(ErrorCode::IdempotencyKeyReused);
+ }
+ let spec = &record.apply.spec;
+ let valid_intent = match (&selection.intent, &spec.collaboration) {
+ (Intent::Configure { trigger_mode }, AgentFacetIntent::Configure { settings }) => {
+ trigger_mode == &settings.trigger_mode
+ }
+ (Intent::Disable, AgentFacetIntent::Restore { restore_point_ref }) => {
+ !restore_point_ref.is_empty()
+ }
+ _ => false,
+ };
+ if !valid_intent
+ || spec.schema_version != hiroute_application_api::AGENT_SETTINGS_SCHEMA_V2
+ || !super::bounded(&spec.context_id, 256)
+ || !matches!(spec.model, AgentFacetIntent::Keep)
+ || !matches!(spec.access_token, AgentAccessTokenIntentV1::Keep)
+ || spec.restore_native_model.is_some()
+ || record.apply.login_item.is_some()
+ {
+ return Err(ErrorCode::DaemonUnavailable);
+ }
+ Ok(Some(record.apply))
+}
+
+pub(super) fn freeze(
+ root: &Path,
+ selection: &Selection,
+ apply: AgentSettingsApplyV2,
+) -> Result<AgentSettingsApplyV2, ErrorCode> {
+ let namespace = root.parent().ok_or(ErrorCode::DaemonUnavailable)?;
+ create_private_directory(namespace)?;
+ create_private_directory(root)?;
+ let destination = path(root, &apply.idempotency_key)?;
+ let temporary = root.join(format!(".{}", super::random_key()?));
+ let record = Record {
+ schema: SCHEMA.into(),
+ instance: instance(root)?,
+ selection: selection.clone(),
+ apply,
+ };
+ let result = (|| {
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options
+ .open(&temporary)
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ serde_json::to_writer(&mut file, &record).map_err(|_| ErrorCode::DaemonUnavailable)?;
+ file.write_all(b"\n")
+ .and_then(|_| file.sync_all())
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ // The first writer wins. A simultaneous same-intent retry must load that writer's
+ // frozen request instead of submitting its own newer Preview digest.
+ std::fs::hard_link(&temporary, &destination)
+ .or_else(|error| {
+ if error.kind() == std::io::ErrorKind::AlreadyExists {
+ Ok(())
+ } else {
+ Err(error)
+ }
+ })
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ #[cfg(unix)]
+ std::fs::File::open(root)
+ .and_then(|directory| directory.sync_all())
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ load(root, &record.apply.idempotency_key, selection)?.ok_or(ErrorCode::DaemonUnavailable)
+ })();
+ let _ = std::fs::remove_file(temporary);
+ result
+}
+
+fn create_private_directory(path: &Path) -> Result<(), ErrorCode> {
+ create_directory_tree(path)?;
+ private(path, true)
+}
+
+fn create_directory_tree(path: &Path) -> Result<(), ErrorCode> {
+ match std::fs::symlink_metadata(path) {
+ Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {
+ // Another first writer may have just created it but not synced its parent yet.
+ return sync_directory_entry(path);
+ }
+ Ok(_) => return Err(ErrorCode::DaemonUnavailable),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(_) => return Err(ErrorCode::DaemonUnavailable),
+ }
+ let parent = path.parent().ok_or(ErrorCode::DaemonUnavailable)?;
+ create_directory_tree(parent)?;
+ let mut builder = std::fs::DirBuilder::new();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ builder.mode(0o700);
+ }
+ builder
+ .create(path)
+ .or_else(|error| {
+ if error.kind() == std::io::ErrorKind::AlreadyExists {
+ Ok(())
+ } else {
+ Err(error)
+ }
+ })
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ private(path, true)?;
+ // A new namespace must itself survive interruption, not only its eventual receipt file.
+ // Persist every newly created directory entry before allowing a network submission.
+ sync_directory_entry(path)
+}
+
+fn sync_directory_entry(path: &Path) -> Result<(), ErrorCode> {
+ #[cfg(unix)]
+ {
+ std::fs::File::open(path)
+ .and_then(|directory| directory.sync_all())
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ if let Some(parent) = path.parent() {
+ std::fs::File::open(parent)
+ .and_then(|directory| directory.sync_all())
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ }
+ }
+ #[cfg(not(unix))]
+ let _ = path;
+ Ok(())
+}
+
+fn private(path: &Path, directory: bool) -> Result<(), ErrorCode> {
+ let metadata = std::fs::symlink_metadata(path).map_err(|_| ErrorCode::DaemonUnavailable)?;
+ if metadata.file_type().is_symlink()
+ || (directory && !metadata.is_dir())
+ || (!directory && !metadata.is_file())
+ {
+ return Err(ErrorCode::DaemonUnavailable);
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ if metadata.uid() != nix::unistd::Uid::effective().as_raw() || metadata.mode() & 0o077 != 0
+ {
+ return Err(ErrorCode::DaemonUnavailable);
+ }
+ }
+ Ok(())
+}
diff --git a/crates/cli/src/collaboration/tests.rs b/crates/cli/src/collaboration/tests.rs
new file mode 100644
index 00000000..546ec556
--- /dev/null
+++ b/crates/cli/src/collaboration/tests.rs
@@ -0,0 +1,610 @@
+use std::cell::RefCell;
+use std::collections::VecDeque;
+
+use hiroute_application_api::{
+ AgentSettingsApplyV2, ErrorV1, LocalControlWireRequestV2, MachineEnvelopeV2, MachineStatus,
+};
+use hiroute_client_core::{ClientFailure, FailureCode, SubmissionState};
+use serde_json::{Value, json};
+
+use super::*;
+
+type Reply = Result<MachineEnvelopeV2<Value>, ClientFailure>;
+struct Script {
+ replies: RefCell<VecDeque<(&'static str, Reply)>>,
+ calls: RefCell<Vec<LocalControlWireRequestV2>>,
+}
+impl Script {
+ fn new(replies: Vec<(&'static str, Reply)>) -> Self {
+ Self {
+ replies: RefCell::new(replies.into()),
+ calls: RefCell::new(Vec::new()),
+ }
+ }
+ fn done(&self) {
+ assert!(self.replies.borrow().is_empty());
+ }
+}
+impl flow::Control for Script {
+ fn call(&self, request: LocalControlWireRequestV2) -> Reply {
+ let (operation, reply) = self
+ .replies
+ .borrow_mut()
+ .pop_front()
+ .expect("unexpected extra call");
+ assert_eq!(request.operation_id, operation);
+ assert!(request.protected_grant.is_none());
+ self.calls.borrow_mut().push(request);
+ reply
+ }
+}
+fn succeeded(data: Value) -> Reply {
+ Ok(MachineEnvelopeV2::succeeded(data, Some("request".into())))
+}
+fn scan(agent_id: &str, codex: bool) -> Reply {
+ succeeded(
+ json!({"agents":[{"agent_id":agent_id,"supported":true,"context_id":"agent-context/profile", "codex_access": if codex { json!({"root_context_id":"agent-context/root", "profile_context_id":"agent-context/profile", "selected_mode":"profile", "slot_occupied":true}) } else { Value::Null }}]}),
+ )
+}
+fn spec(context: &str, mode: &str) -> Value {
+ json!({"schema_version":{"major":2,"minor":0},"context_id":context,"model":{"intent":"keep"},"access_token":{"intent":"keep"},"collaboration":{"intent":"configure","settings":{"trigger_mode":mode}}})
+}
+fn preview(spec: Value, capabilities: &[&str], extra_block: bool) -> Reply {
+ let digest = hiroute_application_api::CanonicalDigest::of_bytes(b"preview");
+ let blockers = if capabilities.is_empty() && !extra_block {
+ json!([])
+ } else {
+ json!([{"facet":"collaboration", "reason":if extra_block { "skill_file_conflict" } else { "capability_unavailable" },"capabilities":capabilities.iter().map(|capability| json!({"capability":capability})).collect::<Vec<_>>()}])
+ };
+ succeeded(
+ json!({"schema":"hiroute.agent-settings-preview/v2","spec":spec,"applicable":blockers.as_array().unwrap().is_empty(),"blockers":blockers,"accept_digest":digest,"dependency_digest":digest,"expected_revisions":{"target":0,"dependencies":{}}}),
+ )
+}
+fn accepted() -> Reply {
+ let mut response = MachineEnvelopeV2::succeeded(
+ json!({"operation_id":"operation/1"}),
+ Some("request".into()),
+ );
+ response.status = MachineStatus::Accepted;
+ Ok(response)
+}
+fn invocation(arguments: &[&str]) -> Invocation {
+ parse(
+ &arguments
+ .iter()
+ .map(|item| item.to_string())
+ .collect::<Vec<_>>(),
+ )
+ .unwrap()
+}
+fn test_directory() -> tempfile::TempDir {
+ let directory = tempfile::tempdir().unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ // A shared state ancestor is legal. Do not let the runner's private umask
+ // hide an incorrectly selected receipt namespace in this fixture.
+ std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ directory
+}
+fn receipt_root(directory: &tempfile::TempDir) -> std::path::PathBuf {
+ receipt::root(
+ &directory.path().join("state"),
+ &directory.path().join("run/control.sock"),
+ )
+ .unwrap()
+}
+fn run(script: &Script, arguments: &[&str]) -> MachineEnvelopeV2<Value> {
+ let directory = test_directory();
+ let response = flow::run(
+ script,
+ &receipt_root(&directory),
+ invocation(arguments),
+ "request".into(),
+ );
+ script.done();
+ response
+}
+
+#[test]
+fn configure_occupied_codex_profile_checks_then_saves_root_with_model_keep() {
+ let original = spec("agent-context/root", "explicit");
+ let mut sealed = original.clone();
+ sealed["protected_native_model_ids"] = json!(["native-model"]);
+ let script = Script::new(vec![
+ ("ScanAgents", scan("agent_codex_default", true)),
+ (
+ "PreviewAgentConnectionChange",
+ preview(original, &["skill_loading", "trusted_cli_execution"], false),
+ ),
+ (
+ "CheckAgentConnection",
+ succeeded(json!({"scope":"collaboration","model_call":false})),
+ ),
+ ("PreviewAgentConnectionChange", preview(sealed, &[], false)),
+ ("ApplyAgentConnectionChange", accepted()),
+ ]);
+ let response = run(
+ &script,
+ &[
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--idempotency-key",
+ "save1",
+ ],
+ );
+ assert_eq!(response.status, MachineStatus::Accepted);
+ let calls = script.calls.borrow();
+ assert_eq!(calls[2].payload["scope"], "collaboration");
+ assert_eq!(calls[2].payload["allow_model_call"], false);
+ assert!(calls[2].payload.get("target").is_none());
+ let apply: AgentSettingsApplyV2 = serde_json::from_value(calls[4].payload.clone()).unwrap();
+ assert_eq!(apply.spec.context_id, "agent-context/root");
+ assert!(matches!(
+ apply.spec.model,
+ hiroute_application_api::AgentFacetIntent::Keep
+ ));
+ assert_eq!(apply.spec.protected_native_model_ids, ["native-model"]);
+ assert_eq!(
+ response.data.unwrap()["cli_submission"]["idempotency_key"],
+ "save1"
+ );
+}
+
+#[test]
+fn preview_is_read_only_and_other_agents_use_their_own_context() {
+ for (agent_id, codex) in [
+ ("agent_codex_default", true),
+ ("agent_claude_default", false),
+ ("agent_qoder_default", false),
+ ("agent_pi_default", false),
+ ("agent_dsh_default", false),
+ ] {
+ let script = Script::new(vec![
+ ("ScanAgents", scan(agent_id, codex)),
+ (
+ "PreviewAgentConnectionChange",
+ preview(
+ spec(
+ if codex {
+ "agent-context/root"
+ } else {
+ "agent-context/profile"
+ },
+ "explicit",
+ ),
+ &["skill_loading"],
+ false,
+ ),
+ ),
+ ]);
+ let directory = test_directory();
+ let receipts = receipt_root(&directory);
+ let response = flow::run(
+ &script,
+ &receipts,
+ invocation(&["configure", agent_id, "--trigger", "explicit", "--preview"]),
+ "request".into(),
+ );
+ assert_eq!(response.status, MachineStatus::Succeeded);
+ assert_eq!(response.data.unwrap()["applicable"], false);
+ assert!(!receipts.exists());
+ script.done();
+ }
+}
+
+#[test]
+fn a_successful_check_cannot_override_a_blocker_or_an_unexpected_preview_intent() {
+ for changed_context in [false, true] {
+ let initial = spec("agent-context/root", "explicit");
+ let mut next = initial.clone();
+ if changed_context {
+ next["context_id"] = json!("agent-context/profile");
+ }
+ let script = Script::new(vec![
+ ("ScanAgents", scan("agent_codex_default", true)),
+ (
+ "PreviewAgentConnectionChange",
+ preview(initial, &["skill_loading"], false),
+ ),
+ ("CheckAgentConnection", succeeded(json!({}))),
+ (
+ "PreviewAgentConnectionChange",
+ preview(next, &[], !changed_context),
+ ),
+ ]);
+ let response = run(
+ &script,
+ &["configure", "agent_codex_default", "--trigger", "explicit"],
+ );
+ assert_eq!(
+ response.status,
+ if changed_context {
+ MachineStatus::Unavailable
+ } else {
+ MachineStatus::Conflict
+ }
+ );
+ }
+}
+
+#[test]
+fn ingress_and_collaboration_checks_are_bounded_and_a_failed_check_stops_save() {
+ let initial = spec("agent-context/root", "explicit");
+ let script = Script::new(vec![
+ ("ScanAgents", scan("agent_codex_default", true)),
+ (
+ "PreviewAgentConnectionChange",
+ preview(
+ initial.clone(),
+ &["ingress_authentication", "skill_loading"],
+ false,
+ ),
+ ),
+ ("CheckAgentConnection", succeeded(json!({}))),
+ (
+ "PreviewAgentConnectionChange",
+ preview(initial.clone(), &["skill_loading"], false),
+ ),
+ ("CheckAgentConnection", succeeded(json!({}))),
+ (
+ "PreviewAgentConnectionChange",
+ preview(initial, &["ingress_authentication"], false),
+ ),
+ ]);
+ let response = run(
+ &script,
+ &["configure", "agent_codex_default", "--trigger", "explicit"],
+ );
+ assert_eq!(response.status, MachineStatus::Conflict);
+ let calls = script.calls.borrow();
+ assert_eq!(calls[2].payload["scope"], "native_authentication");
+ assert_eq!(calls[4].payload["scope"], "collaboration");
+ drop(calls);
+ let script = Script::new(vec![
+ ("ScanAgents", scan("agent_codex_default", true)),
+ (
+ "PreviewAgentConnectionChange",
+ preview(
+ spec("agent-context/root", "explicit"),
+ &["skill_loading"],
+ false,
+ ),
+ ),
+ (
+ "CheckAgentConnection",
+ Ok(MachineEnvelopeV2::failed(
+ ErrorV1::new(ErrorCode::CapabilityDenied),
+ Some("request".into()),
+ )),
+ ),
+ ]);
+ assert_eq!(
+ run(
+ &script,
+ &["configure", "agent_codex_default", "--trigger", "explicit"]
+ )
+ .status,
+ MachineStatus::Denied
+ );
+}
+
+#[test]
+fn uncertain_delivery_replays_the_frozen_request_and_changed_intent_conflicts_before_checks() {
+ for submission in [
+ SubmissionState::NotSent,
+ SubmissionState::MayHaveReachedServer,
+ ] {
+ let directory = test_directory();
+ let runtime = directory.path().join("run");
+ std::fs::create_dir(&runtime).unwrap();
+ let state = directory.path().join("state");
+ let endpoint = runtime.join("hiroute/control.sock");
+ let receipts = receipt::root(&state, &endpoint).unwrap();
+ assert_ne!(
+ receipts,
+ receipt::root(&state, &directory.path().join("other/control.sock")).unwrap()
+ );
+ let script = Script::new(vec![
+ ("ScanAgents", scan("agent_codex_default", true)),
+ (
+ "PreviewAgentConnectionChange",
+ preview(spec("agent-context/root", "explicit"), &[], false),
+ ),
+ (
+ "ApplyAgentConnectionChange",
+ Err(ClientFailure {
+ code: FailureCode::Deadline,
+ submission,
+ }),
+ ),
+ ("ApplyAgentConnectionChange", accepted()),
+ ]);
+ let args = [
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--idempotency-key",
+ "retry1",
+ ];
+ let first = flow::run(&script, &receipts, invocation(&args), "request".into());
+ assert_eq!(first.status, MachineStatus::Unavailable);
+ assert_eq!(
+ first.next_actions[0].reason_code,
+ if submission == SubmissionState::NotSent {
+ "SUBMISSION_NOT_SENT"
+ } else {
+ "SUBMISSION_UNKNOWN"
+ }
+ );
+ let conflicting = flow::run(
+ &script,
+ &receipts,
+ invocation(&[
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "delegate-by-default",
+ "--idempotency-key",
+ "retry1",
+ ]),
+ "request".into(),
+ );
+ assert_eq!(
+ conflicting.error.unwrap().code,
+ ErrorCode::IdempotencyKeyReused
+ );
+ // A logout/reboot clears sockets, not the immutable submission. Reopening the same
+ // endpoint must return the original operation without rescanning or new digests.
+ std::fs::remove_dir_all(&runtime).unwrap();
+ std::fs::create_dir(&runtime).unwrap();
+ let reopened = receipt::root(&state, &endpoint).unwrap();
+ assert_eq!(receipts, reopened);
+ let retry = flow::run(&script, &reopened, invocation(&args), "request".into());
+ assert_eq!(retry.status, MachineStatus::Accepted);
+ let calls = script.calls.borrow();
+ assert_eq!(calls[2].payload, calls[3].payload);
+ script.done();
+ }
+}
+
+#[test]
+fn disable_reads_the_root_collaboration_restore_point_and_keeps_the_model() {
+ let status = json!({"schema":"hiroute.agent-collaboration-only-settings-status/v2", "context_id":"agent-context/root", "collaboration":{"schema":"hiroute.agent-collaboration-settings-status/v2", "state":"configured", "operation_id":null,"operation_state":null,"restore_point_ref":"restore/skill"}});
+ let restore = json!({"schema_version":{"major":2,"minor":0},"context_id":"agent-context/root","model":{"intent":"keep"},"access_token":{"intent":"keep"},"collaboration":{"intent":"restore","restore_point_ref":"restore/skill"}});
+ let script = Script::new(vec![
+ ("ScanAgents", scan("agent_codex_default", true)),
+ ("GetAgentConnectionStatus", succeeded(status)),
+ (
+ "PreviewAgentConnectionRestore",
+ preview(restore, &[], false),
+ ),
+ ("ApplyAgentConnectionRestore", accepted()),
+ ]);
+ assert_eq!(
+ run(&script, &["disable", "agent_codex_default", "--yes"]).status,
+ MachineStatus::Accepted
+ );
+ assert_eq!(
+ script.calls.borrow()[3].payload["spec"]["model"]["intent"],
+ "keep"
+ );
+ assert_eq!(
+ script.calls.borrow()[3].payload["spec"]["collaboration"]["restore_point_ref"],
+ "restore/skill"
+ );
+}
+
+#[test]
+fn invalid_or_unconfirmed_arguments_are_rejected_without_transport() {
+ for arguments in [
+ vec!["disable", "agent_codex_default"],
+ vec!["configure", "agent_codex_default"],
+ vec!["configure", "agent_codex_default", "--trigger", "live"],
+ vec![
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--preview",
+ "--idempotency-key",
+ "k",
+ ],
+ vec!["status", "agent_codex_default", "--yes"],
+ vec![
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--trigger",
+ "explicit",
+ ],
+ ] {
+ assert!(
+ parse(
+ &arguments
+ .iter()
+ .map(|value| value.to_string())
+ .collect::<Vec<_>>()
+ )
+ .is_err(),
+ "{arguments:?}"
+ );
+ }
+ let (arguments, globals) = crate::args::split_globals(
+ [
+ "agents",
+ "collaboration",
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--idempotency-key",
+ "--help",
+ ]
+ .map(str::to_owned)
+ .to_vec(),
+ )
+ .unwrap();
+ assert!(!globals.help);
+ assert!(parse(&arguments[2..]).is_err());
+ for key in ["retry/1", "retry 1", "重试", "", "--help"] {
+ // Exercise the real argv entry, so invalid keys cannot reach environment/transport,
+ // native prerequisites or receipt creation (even when no daemon is available).
+ let execution = crate::execute([
+ "agents",
+ "collaboration",
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--idempotency-key",
+ key,
+ ]);
+ let envelope: MachineEnvelopeV2<Value> = serde_json::from_str(&execution.stdout).unwrap();
+ assert_eq!(envelope.error.unwrap().code, ErrorCode::InvalidArguments);
+ }
+ for (length, valid) in [(200, true), (201, false)] {
+ let key = "a".repeat(length);
+ let arguments = [
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--idempotency-key",
+ &key,
+ ];
+ assert_eq!(parse(&arguments.map(str::to_owned)).is_ok(), valid);
+ }
+}
+
+#[test]
+fn concurrent_submissions_preserve_the_first_frozen_request_and_isolate_endpoints() {
+ let directory = test_directory();
+ let state = directory.path().join("state");
+ let receipts = receipt::root(&state, &directory.path().join("one/control.sock")).unwrap();
+ let selection =
+ invocation(&["configure", "agent_codex_default", "--trigger", "explicit"]).selection;
+ let make_apply = |digest: &[u8]| AgentSettingsApplyV2 {
+ spec: serde_json::from_value(spec("agent-context/root", "explicit")).unwrap(),
+ accept_digest: hiroute_application_api::CanonicalDigest::of_bytes(digest),
+ dependency_digest: hiroute_application_api::CanonicalDigest::of_bytes(digest),
+ expected_revisions: hiroute_application_api::RevisionSetV1 {
+ target: 0,
+ dependencies: Default::default(),
+ },
+ idempotency_key: "concurrent".into(),
+ login_item: None,
+ };
+ let barrier = std::sync::Barrier::new(2);
+ let winners = std::thread::scope(|scope| {
+ let first = scope.spawn(|| {
+ barrier.wait();
+ receipt::freeze(&receipts, &selection, make_apply(b"first")).unwrap()
+ });
+ let second = scope.spawn(|| {
+ barrier.wait();
+ receipt::freeze(&receipts, &selection, make_apply(b"second")).unwrap()
+ });
+ [first.join().unwrap(), second.join().unwrap()]
+ });
+ assert_eq!(winners[0], winners[1]);
+ assert_eq!(
+ receipt::load(&receipts, "concurrent", &selection).unwrap(),
+ Some(winners[0].clone())
+ );
+ let other = receipt::root(&state, &directory.path().join("two/control.sock")).unwrap();
+ assert!(
+ receipt::load(&other, "concurrent", &selection)
+ .unwrap()
+ .is_none()
+ );
+ // Moving a record across endpoint namespaces does not grant replay authority.
+ std::fs::create_dir_all(&other).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&other, std::fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ let record = std::fs::read_dir(&receipts)
+ .unwrap()
+ .next()
+ .unwrap()
+ .unwrap()
+ .path();
+ std::fs::copy(&record, other.join(record.file_name().unwrap())).unwrap();
+ assert_eq!(
+ receipt::load(&other, "concurrent", &selection).unwrap_err(),
+ ErrorCode::DaemonUnavailable
+ );
+}
+
+#[test]
+fn corrupted_or_nonprivate_receipts_never_reconstruct_an_apply() {
+ let directory = test_directory();
+ let receipts = receipt_root(&directory);
+ let script = Script::new(vec![
+ ("ScanAgents", scan("agent_codex_default", true)),
+ (
+ "PreviewAgentConnectionChange",
+ preview(spec("agent-context/root", "explicit"), &[], false),
+ ),
+ ("ApplyAgentConnectionChange", accepted()),
+ ]);
+ let args = [
+ "configure",
+ "agent_codex_default",
+ "--trigger",
+ "explicit",
+ "--idempotency-key",
+ "corrupt",
+ ];
+ let initial = flow::run(&script, &receipts, invocation(&args), "request".into());
+ assert_eq!(initial.status, MachineStatus::Accepted);
+ let path = std::fs::read_dir(&receipts)
+ .unwrap()
+ .next()
+ .unwrap()
+ .unwrap()
+ .path();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode =
+ |path: &std::path::Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode(directory.path()), 0o755);
+ for private_directory in [receipts.parent().unwrap(), receipts.as_path()] {
+ assert_eq!(mode(private_directory), 0o700);
+ std::fs::set_permissions(private_directory, std::fs::Permissions::from_mode(0o755))
+ .unwrap();
+ // A nonprivate namespace or endpoint must reject replay before any Control
+ // call and preserve the existing permissions instead of repairing them.
+ let replay = flow::run(&script, &receipts, invocation(&args), "request".into());
+ assert_eq!(replay.status, MachineStatus::Unavailable);
+ assert_eq!(replay.error.unwrap().code, ErrorCode::DaemonUnavailable);
+ assert_eq!(mode(private_directory), 0o755);
+ std::fs::set_permissions(private_directory, std::fs::Permissions::from_mode(0o700))
+ .unwrap();
+ }
+ assert_eq!(
+ std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
+ assert_eq!(
+ flow::run(&script, &receipts, invocation(&args), "request".into()).status,
+ MachineStatus::Unavailable
+ );
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
+ }
+ std::fs::write(&path, b"incomplete").unwrap();
+ assert_eq!(
+ flow::run(&script, &receipts, invocation(&args), "request".into()).status,
+ MachineStatus::Unavailable
+ );
+ script.done();
+}
diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs
index 77f2d94d..a647fe30 100644
--- a/crates/cli/src/lib.rs
+++ b/crates/cli/src/lib.rs
@@ -7,6 +7,7 @@
mod args;
mod client;
+mod collaboration;
mod control_plane;
mod host_commands;
mod managed_launch;
@@ -104,6 +105,9 @@ where
if let Some(execution) = host_commands::execute(&path_and_options, &globals) {
return execution;
}
+ if let Some(execution) = collaboration::execute(&path_and_options, &globals) {
+ return execution;
+ }
let Some((descriptor, option_start)) = resolve_callable(&path_and_options) else {
return failure(ErrorCode::UnknownCommand, globals.request_id);
};
@@ -614,6 +618,12 @@ const DAEMON_UNAVAILABLE_HINT: &str = "HiRoute 服务不可用。Standalone 请
fn render(envelope: MachineEnvelopeV2<Value>) -> CliExecution {
let stderr = if envelope
+ .error
+ .as_ref()
+ .is_some_and(|error| error.message_key == "error.agent_collaboration_root_context_required")
+ {
+ "Codex 协作配置属于原始 HOME 的 root context;请使用 agents scan 中的 codex_access.root_context_id,或运行 hiroute agents collaboration configure <AGENT_ID> --trigger explicit。模型 profile context 不支持协作配置。\n".to_owned()
+ } else if envelope
.error
.as_ref()
.is_some_and(|error| error.code == ErrorCode::DaemonUnavailable)
@@ -658,7 +668,7 @@ pub fn root_help() -> String {
.collect::<Vec<_>>()
.join("\n");
format!(
- "HiRoute headless product CLI\n\nUsage\n hiroute <command> [options]\n\nPublic command families\n{commands}\n\nHost management: run 'hiroute service --help', 'hiroute gateway --help', 'hiroute protected-input --help', or 'hiroute subscription-proxy --help'.\nApplication/Local Control: run 'hiroute schema list --output json' and 'hiroute schema show --command-id <ID> --output json', then append '--help' to a complete command path, for example 'hiroute worker dependencies discover --help'.\n"
+ "HiRoute headless product CLI\n\nUsage\n hiroute <command> [options]\n\nPublic command families\n{commands}\n\nHost management: run 'hiroute service --help', 'hiroute gateway --help', 'hiroute protected-input --help', or 'hiroute subscription-proxy --help'.\nAgent collaboration workflow: run 'hiroute agents collaboration --help' to enable, edit, disable or inspect collaboration independently of model settings.\nApplication/Local Control: run 'hiroute schema list --output json' and 'hiroute schema show --command-id <ID> --output json', then append '--help' to a complete command path, for example 'hiroute worker dependencies discover --help'.\n"
)
}
diff --git a/crates/cpa-bridge/src/runtime/tests.rs b/crates/cpa-bridge/src/runtime/tests.rs
index b379bdd9..c495a143 100644
--- a/crates/cpa-bridge/src/runtime/tests.rs
+++ b/crates/cpa-bridge/src/runtime/tests.rs
@@ -781,7 +781,10 @@ fn crash_restart_is_bounded_and_reports_child_exit_separately() {
let backend = Arc::new(FakeBackend::default());
let control = Arc::new(FakeControl::default());
control.set_accounts(vec![snapshot(CpaAccountKind::Codex, 'a', "gpt-5.5")]);
- let runtime = fixture_runtime(&root, Arc::clone(&backend), control, 1);
+ let mut runtime = fixture_runtime(&root, Arc::clone(&backend), control, 1);
+ // Count these crashes within the production window, independently of how long
+ // the real account/file checks between them take on a busy test host.
+ runtime.spec.restart_policy.window = RestartPolicy::default().window;
runtime.start().unwrap();
let materialized = runtime
.materialize_account("connector.cpa.codex", "endpoint.cpa.codex")
@@ -842,11 +845,23 @@ fn crash_restart_is_bounded_and_reports_child_exit_separately() {
assert_eq!(restarted.address(), target.address());
assert_eq!(restarted.runtime_epoch(), target.runtime_epoch());
assert_eq!(restarted.target_epoch(), target.target_epoch());
+ {
+ let mut inner = runtime.inner.lock();
+ assert_eq!(inner.crashes.len(), 1);
+ // Model slow account/file validation between crashes without sleeping or
+ // depending on the host finishing that work within the old one-second window.
+ *inner.crashes.front_mut().unwrap() = std::time::Instant::now() - Duration::from_secs(2);
+ }
backend.crash_latest(31);
- assert!(matches!(
- runtime.discover_registered_sources(),
- Err(CpaLifecycleError::CrashLoop(CpaExit { code: Some(31) }))
- ));
+ let outcome = runtime.discover_registered_sources();
+ assert!(
+ matches!(
+ &outcome,
+ Err(CpaLifecycleError::CrashLoop(CpaExit { code: Some(31) }))
+ ),
+ "second crash must exhaust the restart budget: {outcome:?}"
+ );
+ assert_eq!(backend.spawn_count(), 2);
assert_eq!(runtime.last_exit(), Some(CpaExit { code: Some(31) }));
}
diff --git a/crates/daemon/src/control/runtime/settings_codex_profile.rs b/crates/daemon/src/control/runtime/settings_codex_profile.rs
index 883a186f..e57125fc 100644
--- a/crates/daemon/src/control/runtime/settings_codex_profile.rs
+++ b/crates/daemon/src/control/runtime/settings_codex_profile.rs
@@ -109,9 +109,11 @@ impl LocalControlAdapter {
return Ok(());
}
if class == SettingsAgentClass::CodexProfile
- && (!matches!(spec.collaboration, AgentFacetIntent::Keep)
- || spec.restore_native_model.is_some())
+ && !matches!(spec.collaboration, AgentFacetIntent::Keep)
{
+ return Err(ControlReadError::CollaborationRootRequired);
+ }
+ if class == SettingsAgentClass::CodexProfile && spec.restore_native_model.is_some() {
return Err(ControlReadError::Denied);
}
if matches!(spec.model, AgentFacetIntent::Keep) {
diff --git a/crates/daemon/src/control/runtime/settings_profile_tests.rs b/crates/daemon/src/control/runtime/settings_profile_tests.rs
index e28bd594..fdb52e36 100644
--- a/crates/daemon/src/control/runtime/settings_profile_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_profile_tests.rs
@@ -91,6 +91,34 @@ fn profile_lifecycle_inheritance_slot_and_safe_restore() {
fs::write(&root, original).unwrap();
apply(&service, &runtime, spec.clone(), "create-profile");
assert_eq!(fs::read_to_string(&root).unwrap(), original);
+ // Scan selects the occupied model profile. Collaboration must stay in the original HOME.
+ let preserved_profile = fs::read(&profile).unwrap();
+ let misplaced_skill = json!({"schema_version":{"major":2,"minor":0},"context_id":context,
+ "model":{"intent":"keep"},"collaboration":{"intent":"configure","settings":{"trigger_mode":"explicit"}}});
+ for operation in ["PreviewAgentConnectionChange", "ApplyAgentConnectionChange"] {
+ let payload = if operation.starts_with("Preview") {
+ json!({"spec":misplaced_skill})
+ } else {
+ let digest = CanonicalDigest::of_bytes(b"misplaced-skill");
+ json!({"spec":misplaced_skill,"accept_digest":digest,"dependency_digest":digest,
+ "expected_revisions":{"target":0,"dependencies":{}},"idempotency_key":"misplaced-skill"})
+ };
+ let rejected = service.dispatch_wire(request(operation, payload, None));
+ let error = rejected.error.unwrap();
+ assert_eq!(error.code, api::ErrorCode::CapabilityDenied);
+ assert_eq!(
+ error.message_key,
+ "error.agent_collaboration_root_context_required"
+ );
+ assert_eq!(rejected.next_actions[0].command_id, "agents.scan");
+ assert_eq!(
+ rejected.next_actions[0].reason_code,
+ "COLLABORATION_ROOT_CONTEXT_REQUIRED"
+ );
+ assert!(rejected.data.is_none());
+ assert_eq!(fs::read(&profile).unwrap(), preserved_profile);
+ assert_eq!(fs::read_to_string(&root).unwrap(), original);
+ }
let configured = fs::read_to_string(&profile).unwrap();
assert!(configured.contains("requires_openai_auth = false"));
// Root and profile have distinct context ids but share the same home slot.
diff --git a/crates/daemon/src/control/runtime/source_authorization.rs b/crates/daemon/src/control/runtime/source_authorization.rs
index e93f927d..804d45b2 100644
--- a/crates/daemon/src/control/runtime/source_authorization.rs
+++ b/crates/daemon/src/control/runtime/source_authorization.rs
@@ -232,7 +232,10 @@ fn map_control_read(error: hiroute_application::control::ControlReadError) -> Po
hiroute_application::control::ControlReadError::SnapshotChanged => PortErrorCode::Conflict,
hiroute_application::control::ControlReadError::Unavailable => PortErrorCode::Unavailable,
hiroute_application::control::ControlReadError::NotFound => PortErrorCode::NotFound,
- hiroute_application::control::ControlReadError::Denied => PortErrorCode::PermissionDenied,
+ hiroute_application::control::ControlReadError::Denied
+ | hiroute_application::control::ControlReadError::CollaborationRootRequired => {
+ PortErrorCode::PermissionDenied
+ }
hiroute_application::control::ControlReadError::Corrupt => PortErrorCode::Corrupt,
};
PortError::new(code, "release.compute.discovery")
diff --git a/docs/code-map/worker-context.md b/docs/code-map/worker-context.md
index b5e1cc60..6d3b3071 100644
--- a/docs/code-map/worker-context.md
+++ b/docs/code-map/worker-context.md
@@ -13,7 +13,7 @@ a prerequisite, not a model call, installed Skill invocation or resumable task.
| --- | --- | --- |
| Scan, prepare and import model sources | [Source admission map](architecture.md#model-sources-and-native-configuration), [model connection assembly](../../crates/daemon/src/control/runtime/model_connections.rs) | [Pi acceptance](../../tools/product-e2e/tests/PI_INTEGRATION.md), [DSH acceptance](../../tools/product-e2e/tests/DSH_INTEGRATION.md) |
| 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) |
-| Enable task collaboration independently | [Skill effects](../../crates/application/src/agent_connection), [local checks](../../apps/desktop/src-tauri/src/agent_check_session.rs) | [Real main-Agent → public CLI → Worker journey](../../crates/daemon/tests/support/collaboration_product.py) |
+| Enable, edit or disable task collaboration independently | [CLI intent workflow](../../crates/cli/src/collaboration.rs), [Skill effects](../../crates/application/src/agent_connection), [local checks](../../apps/desktop/src-tauri/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
Responses/Messages choice. [Route grants](../../crates/domain/src/agents/model_grant.rs)
diff --git a/docs/standalone-cli.md b/docs/standalone-cli.md
index 0e182ca6..3033b1c3 100644
--- a/docs/standalone-cli.md
+++ b/docs/standalone-cli.md
@@ -459,6 +459,45 @@ submit the complete editor. A stale revision/digest returns conflict while the o
continues serving. Read again, edit, Preview, and Apply. A normal model request performs only
routing and never starts a Worker implicitly because the plan enables delegation.
+## Configure Agent collaboration
+
+Enable, edit or disable collaboration independently of model settings. Copy the exact Agent ID
+from `hiroute agents scan`, then use:
+
+```sh
+hiroute agents collaboration configure agent_codex_default --trigger explicit --preview --output json
+hiroute agents collaboration configure agent_codex_default --trigger explicit --idempotency-key codex-collab-1 --output json
+hiroute agents collaboration configure agent_codex_default --trigger delegate-by-default --idempotency-key codex-collab-2 --output json
+hiroute agents collaboration status agent_codex_default --output json
+hiroute agents collaboration disable agent_codex_default --preview --output json
+hiroute agents collaboration disable agent_codex_default --yes --idempotency-key codex-collab-off-1 --output json
+```
+
+`explicit` delegates only when requested; `delegate-by-default` lets the Agent decide.
+The workflow also accepts other supported Agent IDs returned by scan. Like Desktop, it selects
+the collaboration context: Codex uses `codex_access.root_context_id` even with an occupied
+model profile, and other Agents use their own context. Model and access-token settings remain.
+
+`--preview` runs no local check, writes no submission record and saves no configuration.
+A save runs an existing bounded local check only for missing capabilities reported by Preview,
+then previews again. It makes no provider model call. Failed checks, file conflicts or remaining
+blockers stop the save. Disable uses collaboration's own restore point and requires `--yes`.
+
+Before submission, the CLI freezes the credential-free request in a private file under
+`cli-collaboration/` in the persistent CLI state directory listed above, isolated by control
+endpoint digest. Runtime cleanup or reboot does not discard it. Keys contain 1–200 ASCII
+letters/digits or `. _ : -` and cannot start with `-`. Omit the key to generate one, returned as
+`data.cli_submission.idempotency_key`; automation should supply `--idempotency-key` explicitly.
+A retry with the same intent and key reuses the exact frozen request. A different intent needs
+a new key. After uncertain delivery, follow the returned recovery action or retry with that
+same key. `accepted` means the Operation was admitted: use
+`hiroute operations get OPERATION_ID --output json` and collaboration status to confirm completion.
+A corrupt or incompatible record stops replay; deleting it must not hide uncertain admission.
+
+The advanced JSON interfaces below retain exact context semantics. A collaboration request
+using Codex's model profile still returns `CAPABILITY_DENIED`, with
+`COLLABORATION_ROOT_CONTEXT_REQUIRED` guidance, instead of silently redirecting the request.
+
## Connect, check, and restore Codex
```sh
diff --git a/docs/standalone-cli.zh-CN.md b/docs/standalone-cli.zh-CN.md
index 817df74e..006bcbd6 100644
--- a/docs/standalone-cli.zh-CN.md
+++ b/docs/standalone-cli.zh-CN.md
@@ -388,6 +388,41 @@ hiroute routing show PLAN_ID --output json
editor。过期 revision/digest 会返回 conflict,旧发布继续服务;重新读取、编辑、preview 后再 apply。
普通模型请求只执行路由,不会因为计划启用了 Worker 而隐式启动任务。
+## 配置 Agent 协作
+
+协作可独立启用、修改触发方式和关闭,不需要手工选择 context。从 `hiroute agents scan`
+取得精确 Agent ID,然后运行:
+
+```sh
+hiroute agents collaboration configure agent_codex_default --trigger explicit --preview --output json
+hiroute agents collaboration configure agent_codex_default --trigger explicit --idempotency-key codex-collab-1 --output json
+hiroute agents collaboration configure agent_codex_default --trigger delegate-by-default --idempotency-key codex-collab-2 --output json
+hiroute agents collaboration status agent_codex_default --output json
+hiroute agents collaboration disable agent_codex_default --preview --output json
+hiroute agents collaboration disable agent_codex_default --yes --idempotency-key codex-collab-off-1 --output json
+```
+
+`explicit` 只在明确要求时委派;`delegate-by-default` 由 Agent 判断是否委派。入口也接受扫描
+得到的其他受支持 Agent ID。它与 Desktop 一样按协作意图选择位置:Codex 使用
+`codex_access.root_context_id`,模型 profile 已配置时也使用原始 HOME 的 root context;
+其他 Agent 使用自己的 context。模型和访问 token 保持原设置。
+
+`--preview` 不执行本地检查、写入提交记录或保存配置。实际保存仅在预览报告能力证明缺失时
+执行既有的本地有界检查,然后重新预览,不产生上游模型调用。检查失败、文件冲突或仍有
+blocker 时停止保存。关闭使用协作自己的 restore point,并要求 `--yes` 确认。
+
+保存前会在上文 CLI 持久状态目录的 `cli-collaboration/` 写入私有、不含凭据的原始提交记录,
+按 control endpoint 摘要隔离实例;清空运行目录或重启不会丢失记录。提交标识为 1–200 个
+ASCII 字母、数字或 `. _ : -`,不能以 `-` 开头。
+可省略提交标识,由 CLI 生成并在 `data.cli_submission.idempotency_key` 返回;自动化应明确
+传入 `--idempotency-key`。相同意图用同一标识重试时沿用已冻结请求;不同意图需要新标识。
+响应丢失时,读取返回的恢复 action 或用相同标识重试。`accepted` 表示 Operation 已接收,
+须用 `hiroute operations get OPERATION_ID --output json` 和协作 status 确认完成。
+记录损坏或版本不符会停止重试;不要通过删除记录掩盖未确定的提交状态。
+
+下方原始 JSON 接口仍采用显式传入的 context。协作请求误用 Codex model profile 时,保留
+`CAPABILITY_DENIED` 并返回 `COLLABORATION_ROOT_CONTEXT_REQUIRED` 提示,不会自动重定向。
+
## 接入、检查和恢复 Codex
```sh