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: preserve automatic Gateway ports and detect stale Agent endpoints (#108)

澄潭4bcc234a1c97
diff --git a/crates/cli/src/host_commands.rs b/crates/cli/src/host_commands.rs
index 940ba3c8..dd3e9787 100644
--- a/crates/cli/src/host_commands.rs
+++ b/crates/cli/src/host_commands.rs
@@ -1,9 +1,11 @@
use std::time::Duration;
use hiroute_application_api::{
- ErrorCode, LOCAL_CONTROL_SCHEMA_V2, LocalControlWireRequestV2, MachineStatus,
- STANDALONE_PROTECTED_INPUT_RESPONSE_SCHEMA_V1, StandaloneProtectedInputRequestV1,
- release_manifest,
+ AGENT_CONNECTION_STATUS_SCHEMA_V1, AGENT_SETTINGS_SCHEMA_V2, AgentConnectionStateV1,
+ AgentConnectionStatusRequestV1, AgentConnectionStatusV1, AgentModelSettingsStateV2,
+ AgentSettingsStatusRequestV2, AgentSettingsStatusV2, ErrorCode, LOCAL_CONTROL_SCHEMA_V2,
+ LocalControlWireRequestV2, MachineStatus, STANDALONE_PROTECTED_INPUT_RESPONSE_SCHEMA_V1,
+ StandaloneProtectedInputRequestV1, release_manifest,
};
use hiroute_host_runtime::{
GatewayListenerDesiredV1, GatewayListenerStore, StandaloneLayout, connect_address,
@@ -101,14 +103,14 @@ fn gateway_command(
.map_err(|_| ErrorCode::GatewayUnavailable)?;
let store = GatewayListenerStore::new(layout.gateway_config_root());
match arguments {
- [verb] if verb == "show" => gateway_status(&store),
+ [verb] if verb == "show" => gateway_status(&store, globals),
[verb] if verb == "recover" => {
store.recover().map_err(|_| ErrorCode::GatewayUnavailable)?;
if service::restart(globals.timeout.unwrap_or(Duration::from_secs(30))).is_err() {
let _ = store.mark_failed("SERVICE_RESTART_FAILED");
return Err(ErrorCode::DaemonUnavailable);
}
- gateway_status(&store)
+ gateway_status(&store, globals)
}
[verb, options @ ..] if verb == "set" => {
let desired = parse_gateway_settings(options)?;
@@ -119,7 +121,7 @@ fn gateway_command(
let _ = store.mark_failed("SERVICE_RESTART_FAILED");
return Err(ErrorCode::DaemonUnavailable);
}
- gateway_status(&store)
+ gateway_status(&store, globals)
}
_ => Err(ErrorCode::InvalidArguments),
}
@@ -170,7 +172,10 @@ fn parse_gateway_settings(options: &[String]) -> Result<GatewayListenerDesiredV1
Ok(desired)
}
-fn gateway_status(store: &GatewayListenerStore) -> Result<serde_json::Value, ErrorCode> {
+fn gateway_status(
+ store: &GatewayListenerStore,
+ globals: &Globals,
+) -> Result<serde_json::Value, ErrorCode> {
let config = store
.load_or_default()
.map_err(|_| ErrorCode::GatewayUnavailable)?;
@@ -182,11 +187,30 @@ fn gateway_status(store: &GatewayListenerStore) -> Result<serde_json::Value, Err
std::net::TcpStream::connect_timeout(&address, Duration::from_millis(750)).is_ok()
});
let suggested_agent_base_url = connect.map(|value| format!("http://{value}/v1"));
- let existing_agent_count = discovered_agent_count();
- let update_required = existing_agent_count.is_some_and(|count| count > 0)
- && config.operation.as_ref().is_some_and(|operation| {
- operation.state == hiroute_host_runtime::GatewayListenerOperationStateV1::Succeeded
- });
+ let client = LocalControlClient::cli_from_environment()
+ .ok()
+ // Native discovery can run executable probes; use the normal control-call deadline.
+ .map(|client| client.with_timeout(globals.timeout.unwrap_or(Duration::from_secs(30))));
+ let (update_required, existing_agent_count) = agent_update_status(|operation_id, payload| {
+ let response = client
+ .as_ref()
+ .ok_or(ErrorCode::DaemonUnavailable)?
+ .call(LocalControlWireRequestV2 {
+ schema_version: LOCAL_CONTROL_SCHEMA_V2,
+ request_id: format!("gateway-agents-{}", std::process::id()),
+ operation_id: operation_id.into(),
+ payload,
+ protected_grant: None,
+ })
+ .map_err(|_| ErrorCode::DaemonUnavailable)?;
+ if response.status == MachineStatus::Succeeded {
+ response.data.ok_or(ErrorCode::Internal)
+ } else {
+ Err(response
+ .error
+ .map_or(ErrorCode::Internal, |error| error.code))
+ }
+ });
let (preview_command_id, apply_command_id) = public_agent_update_commands();
Ok(json!({
"schema": "hiroute.gateway-listener-status/v1",
@@ -219,32 +243,115 @@ fn public_agent_update_commands() -> (Option<&'static str>, Option<&'static str>
}
}
-fn discovered_agent_count() -> Option<usize> {
- let request = LocalControlWireRequestV2 {
- schema_version: LOCAL_CONTROL_SCHEMA_V2,
- request_id: format!("gateway-agents-{}", std::process::id()),
- operation_id: "ListAgents".into(),
- payload: json!({}),
- protected_grant: None,
+fn agent_update_status(
+ mut query: impl FnMut(&str, serde_json::Value) -> Result<serde_json::Value, ErrorCode>,
+) -> (bool, Option<usize>) {
+ let Ok(list) = query("ListAgents", json!({})) else {
+ return (true, None);
};
- let response = LocalControlClient::cli_from_environment()
- .ok()?
- .with_timeout(Duration::from_millis(750))
- .call(request)
- .ok()?;
- if response.status != MachineStatus::Succeeded {
- return None;
+ let Some(agents) = list.get("agents").and_then(serde_json::Value::as_array) else {
+ return (true, None);
+ };
+ let mut contexts = std::collections::BTreeSet::new();
+ let mut legacy_connections = std::collections::BTreeSet::new();
+ for agent in agents {
+ match agent.get("context_id") {
+ None | Some(serde_json::Value::Null) => {}
+ Some(serde_json::Value::String(context)) if !context.is_empty() => {
+ contexts.insert(context.clone());
+ let Some(agent_id) = agent
+ .get("agent_id")
+ .and_then(serde_json::Value::as_str)
+ .filter(|id| !id.is_empty())
+ else {
+ return (true, None);
+ };
+ let Some(profile_id) = agent
+ .get("profile_id")
+ .and_then(serde_json::Value::as_str)
+ .filter(|id| !id.is_empty())
+ else {
+ return (true, None);
+ };
+ legacy_connections.insert((
+ context,
+ format!("agent-connection/{agent_id}/{profile_id}"),
+ agent_id,
+ profile_id,
+ ));
+ }
+ _ => return (true, None),
+ }
}
- response.data?.get("agents")?.as_array().map(|agents| {
- agents
- .iter()
- .filter(|agent| {
- agent
- .get("context_id")
- .is_some_and(|value| !value.is_null())
+ let mut required = false;
+ let mut legacy_contexts = std::collections::BTreeSet::new();
+ for context in &contexts {
+ let status = query(
+ "GetAgentConnectionStatus",
+ json!(AgentSettingsStatusRequestV2 {
+ schema_version: AGENT_SETTINGS_SCHEMA_V2,
+ context_id: context.clone(),
+ }),
+ )
+ .ok()
+ .and_then(|value| serde_json::from_value::<AgentSettingsStatusV2>(value).ok())
+ .filter(|status| status.valid() && status.context_id() == context);
+ // Unavailable inspection is not evidence that installed endpoints are current.
+ if status
+ .as_ref()
+ .and_then(AgentSettingsStatusV2::model)
+ .is_some_and(|model| {
+ matches!(
+ model.state,
+ AgentModelSettingsStateV2::NotConfigured | AgentModelSettingsStateV2::Restored
+ )
})
- .count()
- })
+ {
+ legacy_contexts.insert(context.clone());
+ }
+ required |= status.is_none_or(|status| {
+ status.model().is_some_and(|model| {
+ matches!(
+ model.state,
+ AgentModelSettingsStateV2::Drift
+ | AgentModelSettingsStateV2::Pending
+ | AgentModelSettingsStateV2::NeedsAttention
+ )
+ })
+ });
+ }
+ // Released V1 connections use installation/profile IDs, not V2 context IDs. An absent
+ // journal is normal for a fresh installation; an unreadable journal is not a clean result.
+ // A current configured V2 target has already proved convergence. Its superseded V1
+ // grant can remain in history, so only unconfigured/restored targets need this fallback.
+ for (context, connection_id, agent_id, profile_id) in legacy_connections {
+ if !legacy_contexts.contains(context) {
+ continue;
+ }
+ let status = query(
+ "GetAgentConnectionStatus",
+ json!(AgentConnectionStatusRequestV1 {
+ connection_id: connection_id.clone(),
+ }),
+ );
+ if matches!(status, Err(ErrorCode::ResourceNotFound)) {
+ continue;
+ }
+ let status = status
+ .ok()
+ .and_then(|value| serde_json::from_value::<AgentConnectionStatusV1>(value).ok())
+ .filter(|status| {
+ status.schema == AGENT_CONNECTION_STATUS_SCHEMA_V1
+ && status.connection_id == connection_id
+ && status.agent_id == agent_id
+ && status.profile_id == profile_id
+ });
+ required |= status.is_none_or(|status| {
+ status.state == AgentConnectionStateV1::Disconnected
+ || (status.state == AgentConnectionStateV1::Active && !status.launch_ready)
+ });
+ }
+ (required, Some(contexts.len()))
}
fn protected_input_command(
@@ -416,4 +523,158 @@ mod tests {
(Some("agents.connect.preview"), Some("agents.connect.apply"))
);
}
+
+ #[test]
+ fn agent_update_hint_tracks_current_model_state_and_unknown_reads() {
+ let context = "agent-context/pi";
+ for (state, required) in [
+ ("not_configured", false),
+ ("restored", false),
+ ("configured", false),
+ ("drift", true),
+ ("pending", true),
+ ("needs_attention", true),
+ ] {
+ let status = json!({
+ "schema":"hiroute.agent-model-settings-status/v2", "context_id":context,
+ "state":state, "operation_id":null, "operation_state":null,
+ "restore_point_ref":null, "applied_revision":null,
+ "surface_results":[], "model_verified":false,
+ });
+ assert_eq!(
+ agent_update_status(|operation, payload| {
+ if operation == "ListAgents" {
+ Ok(discovered_agent(context))
+ } else if payload.get("connection_id").is_some() {
+ Err(ErrorCode::ResourceNotFound)
+ } else {
+ assert_eq!(operation, "GetAgentConnectionStatus");
+ assert_eq!(payload["context_id"], context);
+ Ok(status.clone())
+ }
+ }),
+ (required, Some(1)),
+ "{state}"
+ );
+ }
+ assert_eq!(
+ agent_update_status(|_, _| Err(ErrorCode::DaemonUnavailable)),
+ (true, None)
+ );
+ assert_eq!(
+ agent_update_status(|operation, _| {
+ if operation == "ListAgents" {
+ Ok(discovered_agent(context))
+ } else {
+ Err(ErrorCode::DaemonUnavailable)
+ }
+ }),
+ (true, Some(1))
+ );
+ assert_eq!(
+ agent_update_status(|_, _| Ok(json!({"agents":[{}, {"context_id":null}]}))),
+ (false, Some(0))
+ );
+ }
+
+ #[test]
+ fn collaboration_only_and_duplicate_targets_do_not_require_model_updates() {
+ let context = "agent-context/qoder";
+ let (required, count) = agent_update_status(|operation, payload| {
+ assert!(
+ payload.get("connection_id").is_none(),
+ "collaboration-only has no model fallback"
+ );
+ Ok(if operation == "ListAgents" {
+ let mut list = discovered_agent(context);
+ let agent = list["agents"][0].clone();
+ list["agents"].as_array_mut().unwrap().push(agent);
+ list
+ } else {
+ json!({"schema":"hiroute.agent-collaboration-only-settings-status/v2",
+ "context_id":context, "collaboration":{
+ "schema":"hiroute.agent-collaboration-settings-status/v2",
+ "state":"configured", "operation_id":null,"operation_state":null,
+ "restore_point_ref":null,
+ }})
+ })
+ });
+ assert!(!required);
+ assert_eq!(count, Some(1));
+ assert_eq!(
+ agent_update_status(|operation, _| Ok(if operation == "ListAgents" {
+ discovered_agent(context)
+ } else {
+ json!({"schema":"unknown","context_id":context})
+ })),
+ (true, Some(1))
+ );
+ }
+
+ fn discovered_agent(context: &str) -> serde_json::Value {
+ json!({"agents":[{"context_id":context,"agent_id":"agent_claude_default","profile_id":"claude-messages-v1"}, {"context_id":null}]})
+ }
+
+ #[test]
+ fn legacy_connections_are_checked_after_unconfigured_or_restored_settings() {
+ let context = "agent-context/claude";
+ let connection = "agent-connection/agent_claude_default/claude-messages-v1";
+ for current in ["not_configured", "restored", "configured"] {
+ for (legacy, ready, expected) in [
+ ("active", true, false),
+ ("active", false, true),
+ ("disconnected", false, true),
+ ("revoked", false, false),
+ ] {
+ let mut legacy_reads = 0;
+ let result = agent_update_status(|operation, payload| {
+ if operation == "ListAgents" {
+ Ok(discovered_agent(context))
+ } else if payload.get("context_id").is_some() {
+ Ok(
+ json!({"schema":"hiroute.agent-model-settings-status/v2","context_id":context,"state":current,
+ "operation_id":null,"operation_state":null,"restore_point_ref":null,"applied_revision":null,
+ "surface_results":[],"model_verified":false}),
+ )
+ } else {
+ legacy_reads += 1;
+ assert_eq!(payload, json!({"connection_id":connection}));
+ Ok(
+ json!({"schema":AGENT_CONNECTION_STATUS_SCHEMA_V1,"connection_id":connection,
+ "agent_id":"agent_claude_default","profile_id":"claude-messages-v1","installed_version":"fixture",
+ "state":legacy,"activation_mode":"managed_configuration","revision":1,"launch_ready":ready}),
+ )
+ }
+ });
+ assert_eq!(
+ result,
+ (current != "configured" && expected, Some(1)),
+ "{current}/{legacy}/{ready}"
+ );
+ assert_eq!(legacy_reads, usize::from(current != "configured"));
+ }
+ }
+ for (legacy, expected) in [
+ (Err(ErrorCode::ResourceNotFound), false),
+ (Err(ErrorCode::DaemonUnavailable), true),
+ (Ok(json!({"schema":"unknown"})), true),
+ ] {
+ assert_eq!(
+ agent_update_status(|operation, payload| {
+ if operation == "ListAgents" {
+ Ok(discovered_agent(context))
+ } else if payload.get("context_id").is_some() {
+ Ok(
+ json!({"schema":"hiroute.agent-model-settings-status/v2","context_id":context,"state":"not_configured",
+ "operation_id":null,"operation_state":null,"restore_point_ref":null,"applied_revision":null,
+ "surface_results":[],"model_verified":false}),
+ )
+ } else {
+ legacy.clone()
+ }
+ }),
+ (expected, Some(1))
+ );
+ }
+ }
}
diff --git a/crates/cli/tests/contracts.rs b/crates/cli/tests/contracts.rs
index 3f730942..a4cdfa3e 100644
--- a/crates/cli/tests/contracts.rs
+++ b/crates/cli/tests/contracts.rs
@@ -287,6 +287,136 @@ fn real_hiroute_launch_rejects_override_before_transport_and_is_stably_unavailab
}
}
+#[cfg(unix)]
+#[test]
+fn gateway_show_waits_for_native_discovery_and_honors_control_timeout() {
+ use std::io::{BufRead, BufReader, Write};
+ use std::os::unix::net::UnixListener;
+ use std::time::{Duration, Instant};
+
+ use hiroute_application_api::{
+ ClientHelloV1, LocalControlWireRequestV2, MachineEnvelopeV2, negotiate_hello,
+ };
+ use serde_json::json;
+
+ for explicit_timeout in [false, true] {
+ let directory = tempfile::tempdir_in("/tmp").unwrap();
+ let home = directory.path().canonicalize().unwrap();
+ let marker = home.join(".local/share/hiroute/standalone.json");
+ std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
+ std::fs::write(
+ marker,
+ serde_json::to_vec(&json!({
+ "schema_version": "hiroute.standalone-install/v1", "version": "0.3.1",
+ "target": "fixture", "install_root": home.join("install"),
+ "service_definition": home.join("service"),
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ let runtime = home.join("run");
+ std::fs::create_dir_all(runtime.join("hiroute")).unwrap();
+ let listener = UnixListener::bind(runtime.join("hiroute/control.sock")).unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let (finished, completion) = std::sync::mpsc::channel();
+ let server = std::thread::spawn(move || {
+ for operation in ["ListAgents", "GetAgentConnectionStatus"] {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ let stream = loop {
+ match listener.accept() {
+ Ok((stream, _)) => break stream,
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ if completion.try_recv().is_ok() {
+ return;
+ }
+ assert!(Instant::now() < deadline, "CLI never requested {operation}");
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ Err(error) => panic!("{error}"),
+ }
+ };
+ stream
+ .set_read_timeout(Some(Duration::from_secs(5)))
+ .unwrap();
+ let mut stream = BufReader::new(stream);
+ let mut line = String::new();
+ if !stream.read_line(&mut line).is_ok_and(|count| count > 0) {
+ return;
+ }
+ let hello: ClientHelloV1 = serde_json::from_str(&line).unwrap();
+ let hello = negotiate_hello(&hello).unwrap();
+ if writeln!(
+ stream.get_mut(),
+ "{}",
+ serde_json::to_string(&hello).unwrap()
+ )
+ .is_err()
+ {
+ return;
+ }
+ line.clear();
+ if !stream.read_line(&mut line).is_ok_and(|count| count > 0) {
+ return;
+ }
+ let request: LocalControlWireRequestV2 = serde_json::from_str(&line).unwrap();
+ assert_eq!(request.operation_id, operation);
+ // Native executable probes legitimately exceed the TCP readiness probe's 750ms.
+ std::thread::sleep(Duration::from_secs(1));
+ let data = if operation == "ListAgents" {
+ json!({"agents":[{"context_id":"agent-context/pi",
+ "agent_id":"agent_pi_default", "profile_id":"pi-default"}]})
+ } else {
+ assert_eq!(request.payload["context_id"], "agent-context/pi");
+ json!({"schema":"hiroute.agent-model-settings-status/v2",
+ "context_id":"agent-context/pi", "state":"configured",
+ "operation_id":null, "operation_state":null, "restore_point_ref":null,
+ "applied_revision":null, "surface_results":[], "model_verified":false})
+ };
+ let response = MachineEnvelopeV2::succeeded(data, Some(request.request_id));
+ if writeln!(
+ stream.get_mut(),
+ "{}",
+ serde_json::to_string(&response).unwrap()
+ )
+ .is_err()
+ {
+ return;
+ }
+ }
+ });
+ let mut command = Command::new(env!("CARGO_BIN_EXE_hiroute"));
+ command
+ .env("HOME", home)
+ .env("HIROUTE_RUNTIME_DIR", &runtime)
+ .env_remove("XDG_STATE_HOME")
+ .env_remove("XDG_DATA_HOME")
+ .env_remove("XDG_RUNTIME_DIR")
+ .args(["gateway", "show", "--output", "json"]);
+ if explicit_timeout {
+ command.args(["--timeout", "50ms"]);
+ }
+ let output = command.output().unwrap();
+ let _ = finished.send(());
+ server.join().unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let update = &response["data"]["agent_update"];
+ assert_eq!(update["required"], explicit_timeout);
+ assert_eq!(
+ update["existing_agent_count"],
+ if explicit_timeout {
+ json!(null)
+ } else {
+ json!(1)
+ }
+ );
+ }
+}
+
#[cfg(unix)]
#[test]
fn real_hidden_helper_uses_only_the_owner_raw_endpoint_and_stdout_token_boundary() {
diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rs
index 56b76256..9158421d 100644
--- a/crates/daemon/src/control/runtime/agent_connection.rs
+++ b/crates/daemon/src/control/runtime/agent_connection.rs
@@ -89,6 +89,7 @@ impl LocalControlAdapter {
}
}
}
+ self.verify_connection_endpoint(&connection, &operation, installation)?;
let stores = self
.stores
@@ -142,14 +143,6 @@ impl LocalControlAdapter {
{
return Err(ControlReadError::Denied);
}
- if self
- .managed_agent_runtime
- .lock()
- .map_err(|_| ControlReadError::Unavailable)?
- .is_none()
- {
- return Err(ControlReadError::Unavailable);
- }
Ok(ActiveJoinV1 {
connection,
grant,
@@ -653,9 +646,7 @@ mod tests {
);
let storage = directory.path().join("storage");
let stores = LocalStorageSet::open_for_daemon_startup(&storage).unwrap();
- let artifacts = stores
- .open_managed_artifacts(storage.join("artifacts"), storage.join("restores"))
- .unwrap();
+ let artifacts = discovery::open_endpoint_test_artifacts(&stores, &scanner, &storage);
let mut publication =
serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
"../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
@@ -1090,5 +1081,7 @@ mod tests {
// Replacing the executable invalidates its identity proof, independently of the
// diagnostic version printed by that executable.
assert!(adapter.resolve_active_agent_grant(&connection_id).is_err());
+ write_claude(&claude, "2.1.231");
+ discovery::assert_persisted_endpoint_convergence(&adapter, &spec);
}
}
diff --git a/crates/daemon/src/control/runtime/agent_connection_discovery.rs b/crates/daemon/src/control/runtime/agent_connection_discovery.rs
index 2ac0a8e2..02b64cfd 100644
--- a/crates/daemon/src/control/runtime/agent_connection_discovery.rs
+++ b/crates/daemon/src/control/runtime/agent_connection_discovery.rs
@@ -1,10 +1,69 @@
use hiroute_application::control::ControlReadError;
-use hiroute_domain::{ActiveAgentConnectionV1, WorkspaceId};
+use hiroute_domain::{
+ ActiveAgentConnectionV1, AgentActivationModeV1, AgentIngressProtocolV1,
+ SupportedAgentInstallationV1, WorkspaceId,
+};
use hiroute_integrations::{AgentDiscoveryOutcomeV1, FilesystemAgentDiscoveryV1};
use super::{APPLY_OPERATION, LocalControlAdapter};
impl LocalControlAdapter {
+ pub(super) fn verify_connection_endpoint(
+ &self,
+ connection: &ActiveAgentConnectionV1,
+ operation: &hiroute_local_storage::SucceededAgentOperationV1,
+ installation: &SupportedAgentInstallationV1,
+ ) -> Result<(), ControlReadError> {
+ let runtime = self
+ .managed_agent_runtime
+ .lock()
+ .map_err(|_| ControlReadError::Unavailable)?;
+ let runtime = runtime.as_ref().ok_or(ControlReadError::Unavailable)?;
+ if connection.connection.activation_mode != AgentActivationModeV1::ManagedConfiguration {
+ return Ok(());
+ }
+ let path = &installation
+ .profile
+ .field("base_endpoint")
+ .ok_or(ControlReadError::Corrupt)?
+ .path;
+ let intent = operation
+ .plan
+ .external()
+ .iter()
+ .find(|intent| intent.effect_id() == "agent-connection-managed-configuration")
+ .ok_or(ControlReadError::Corrupt)?;
+ let change = self
+ .native_claude_change(intent)
+ .map_err(super::super::map_port)?
+ .ok_or(ControlReadError::Corrupt)?;
+ // A V1 change is a delta: an already matching endpoint may have no changed field.
+ let endpoint = change
+ .fields
+ .iter()
+ .find(|field| &field.path == path)
+ .and_then(|field| field.after.as_ref())
+ .or_else(|| {
+ installation
+ .effective_config
+ .get(path)
+ .map(|field| &field.value)
+ })
+ .and_then(serde_json::Value::as_str)
+ .ok_or(ControlReadError::Denied)?;
+ let expected = match connection.connection.protocol {
+ AgentIngressProtocolV1::Responses => runtime.gateway_base_url.as_str(),
+ AgentIngressProtocolV1::Messages => runtime
+ .gateway_base_url
+ .strip_suffix("/v1")
+ .ok_or(ControlReadError::Corrupt)?,
+ };
+ if endpoint != expected {
+ return Err(ControlReadError::Denied);
+ }
+ Ok(())
+ }
+
pub(super) fn latest_connection_operation(
&self,
connection_id: &str,
@@ -69,3 +128,11 @@ impl LocalControlAdapter {
.map(|(connection, _)| connection)
}
}
+
+#[cfg(test)]
+#[path = "agent_connection_endpoint_tests.rs"]
+mod endpoint_tests;
+#[cfg(test)]
+pub(super) use endpoint_tests::{
+ assert_persisted_endpoint_convergence, open_endpoint_test_artifacts,
+};
diff --git a/crates/daemon/src/control/runtime/agent_connection_endpoint_tests.rs b/crates/daemon/src/control/runtime/agent_connection_endpoint_tests.rs
new file mode 100644
index 00000000..dde0079b
--- /dev/null
+++ b/crates/daemon/src/control/runtime/agent_connection_endpoint_tests.rs
@@ -0,0 +1,228 @@
+use hiroute_application::TransactionCoordinator;
+use hiroute_application::agent_connection::AgentConnectionPlanner;
+use hiroute_application::control::{AgentConnectionControlPort, ControlReadError};
+use hiroute_application_api::{
+ AgentConnectSpecV1, AgentConnectionStateV1, AgentConnectionStatusRequestV1,
+};
+use hiroute_domain::{
+ AgentActivationModeV1, AgentConnectionEffectRoleV1, AgentConnectionTransactionSubjectV1,
+ BeginOperationOutcome, CanonicalDigest, ControlRepositoryPort, IdempotencyScopeV1, OperationId,
+ OperationState, OperationV1, ProtectedApplyCapability, PublicationRepositoryPort,
+ SecretStorePort, WorkspaceId,
+};
+use hiroute_local_storage::{ApplyCapabilityRegistrationV1, LocalStorageSet, ManagedArtifactStore};
+
+use super::LocalControlAdapter;
+
+pub(in super::super) fn open_endpoint_test_artifacts(
+ stores: &LocalStorageSet,
+ scanner: &hiroute_integrations::FilesystemAgentScannerV1,
+ storage: &std::path::Path,
+) -> ManagedArtifactStore {
+ use std::os::unix::fs::PermissionsExt;
+ let native = scanner.claude_user_settings_target();
+ std::fs::write(&native, b"{}\n").unwrap();
+ std::fs::set_permissions(&native, std::fs::Permissions::from_mode(0o600)).unwrap();
+ let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(
+ "agent_claude_default",
+ "claude-messages-v1",
+ "builtin/claude-messages/v1",
+ )
+ .unwrap();
+ stores
+ .open_managed_artifacts_with_external_targets(
+ storage.join("artifacts"),
+ storage.join("restores"),
+ [(
+ AgentConnectionEffectRoleV1::ManagedConfiguration
+ .target_for(&subject)
+ .unwrap(),
+ native,
+ )],
+ )
+ .unwrap()
+}
+
+// Reuse the isolated durable-store fixture and the current V1 planner. This proves the legacy
+// endpoint boundary, not native authentication or end-to-end readiness. Ordinary V1 discovery
+// still treats the local Gateway as an unregistered upstream; do not broaden raw-grant admission.
+pub(in super::super) fn assert_persisted_endpoint_convergence(
+ adapter: &LocalControlAdapter,
+ spec: &AgentConnectSpecV1,
+) {
+ let mut facts = adapter.planning_facts(spec).unwrap().facts;
+ for iteration in 0..2 {
+ facts.activation_mode = AgentActivationModeV1::ManagedConfiguration;
+ for proof in &mut facts.installation.capability_evidence {
+ if hiroute_domain::AgentAction::ConfigureModel
+ .requires()
+ .contains(&proof.capability)
+ {
+ proof.state = hiroute_domain::CapabilityState::Proven;
+ proof.reason = None;
+ }
+ }
+ let preview = AgentConnectionPlanner::preview_connect(spec.clone(), facts.clone()).unwrap();
+ assert_eq!(
+ preview
+ .config_change
+ .fields
+ .iter()
+ .any(|field| field.path == "env.ANTHROPIC_BASE_URL"),
+ iteration == 0,
+ "the second apply must exercise an endpoint omitted from the sealed delta"
+ );
+ let plan = AgentConnectionPlanner::seal_apply(
+ &preview,
+ &preview.change_digest,
+ &preview.expected_revisions,
+ &preview.expected_revisions,
+ )
+ .unwrap();
+ let workspace = WorkspaceId::default();
+ let scope = IdempotencyScopeV1::new(
+ "interactive-user",
+ "ApplyAgentConnectionChange",
+ format!("persisted-endpoint-{iteration}"),
+ )
+ .unwrap();
+ let request_digest = CanonicalDigest::of_bytes(scope.key.as_bytes());
+ let operation = OperationV1::new(
+ OperationId::derive(&workspace, &scope, &request_digest),
+ workspace.clone(),
+ scope,
+ request_digest,
+ preview.change_digest.clone(),
+ preview.expected_revisions.clone(),
+ plan,
+ )
+ .unwrap();
+ let capability = format!("persisted-endpoint-capability-0123456789abcdef-{iteration}");
+ let expires = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs() as i64
+ + 60;
+ {
+ let stores = adapter.stores.lock().unwrap();
+ stores
+ .apply_capability_registrar()
+ .register(
+ ApplyCapabilityRegistrationV1::from_protected_launcher(
+ capability.clone(),
+ operation.idempotency.principal.clone(),
+ workspace.clone(),
+ operation.idempotency.operation_kind.clone(),
+ operation.accepted_digest.clone(),
+ operation.expected_revisions.clone(),
+ expires,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let authorization = stores
+ .control()
+ .verify_apply_authorization(
+ &ProtectedApplyCapability::new(capability).unwrap(),
+ &workspace,
+ &operation.idempotency.principal,
+ &operation.idempotency.operation_kind,
+ &operation.accepted_digest,
+ &operation.expected_revisions,
+ )
+ .unwrap();
+ assert_eq!(
+ stores
+ .control()
+ .begin_operation(&operation, &authorization)
+ .unwrap(),
+ BeginOperationOutcome::Created
+ );
+ }
+ let completed = TransactionCoordinator::new(
+ adapter,
+ adapter,
+ adapter,
+ adapter,
+ adapter,
+ &adapter.admission,
+ )
+ .run(&operation.operation_id)
+ .unwrap();
+ assert_eq!(completed.state, OperationState::Succeeded, "{completed:#?}");
+ let request = AgentConnectionStatusRequestV1 {
+ connection_id: preview.change_spec.resource_id.clone().unwrap(),
+ };
+ let (connection, succeeded) = adapter
+ .latest_connection_operation(&request.connection_id)
+ .unwrap();
+ let (mut installation, _) = adapter
+ .scanner
+ .claude_installation_for_applied_user_change(&preview.config_change)
+ .unwrap();
+ assert!(
+ adapter
+ .verify_connection_endpoint(&connection, &succeeded, &installation)
+ .is_ok()
+ );
+ // The existing public V1 status remains conservative for an unregistered local upstream.
+ assert_eq!(
+ adapter.connection_status(&request).unwrap().state,
+ AgentConnectionStateV1::Disconnected
+ );
+ adapter
+ .managed_agent_runtime
+ .lock()
+ .unwrap()
+ .as_mut()
+ .unwrap()
+ .gateway_base_url = "http://127.0.0.1:5838/v1".to_owned();
+ let stale = adapter.connection_status(&request).unwrap();
+ assert_eq!(stale.state, AgentConnectionStateV1::Disconnected);
+ assert!(!stale.launch_ready);
+ assert!(matches!(
+ adapter.verify_connection_endpoint(&connection, &succeeded, &installation),
+ Err(ControlReadError::Denied)
+ ));
+ adapter
+ .managed_agent_runtime
+ .lock()
+ .unwrap()
+ .as_mut()
+ .unwrap()
+ .gateway_base_url = "http://127.0.0.1:5837/v1".to_owned();
+ assert!(
+ adapter
+ .verify_connection_endpoint(&connection, &succeeded, &installation)
+ .is_ok()
+ );
+ // Refresh component facts from the real applied file and durable publication. Public
+ // V1 re-planning is outside this fixture because it requires ordinary upstream discovery.
+ installation.version = spec.installed_version.clone();
+ facts.installation = installation;
+ facts.current_config = adapter.scanner.claude_user_config_document().unwrap();
+ let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(
+ &spec.agent_id,
+ &spec.profile_id,
+ "builtin/claude-messages/v1",
+ )
+ .unwrap();
+ let stores = adapter.stores.lock().unwrap();
+ facts.expected_revisions = stores.control().current_revisions(&workspace).unwrap();
+ facts.publication_digest = stores
+ .control()
+ .active_publication(&workspace)
+ .unwrap()
+ .unwrap()
+ .digest;
+ facts.expected_grant_generation = stores
+ .secrets()
+ .inspect_agent_access_grant(WorkspaceId::DEFAULT, &request.connection_id)
+ .unwrap()
+ .unwrap()
+ .generation();
+ facts.before_fingerprints = adapter
+ .before_fingerprints(&subject, facts.publication_digest.clone())
+ .unwrap();
+ }
+}
diff --git a/crates/daemon/src/control/runtime/native_model_tests.rs b/crates/daemon/src/control/runtime/native_model_tests.rs
index e96ffa6f..8f49af62 100644
--- a/crates/daemon/src/control/runtime/native_model_tests.rs
+++ b/crates/daemon/src/control/runtime/native_model_tests.rs
@@ -130,6 +130,30 @@ fn settings_status_joins_surface_checks_with_the_active_publication_revision() {
);
assert!(!first.model_verified);
+ // An untouched native file is historical evidence, not proof that its endpoint
+ // still reaches the current Gateway after a listener change.
+ adapter
+ .managed_agent_runtime
+ .lock()
+ .unwrap()
+ .as_mut()
+ .unwrap()
+ .gateway_base_url = "http://127.0.0.1:5838/v1".into();
+ let moved = status();
+ assert_eq!(moved.state, AgentModelSettingsStateV2::Drift);
+ assert!(moved.current_selection.is_none());
+ assert!(moved.live_check_targets.is_empty());
+ assert!(!moved.model_verified);
+ assert_eq!(fs::read_to_string(&path).unwrap(), configured);
+ adapter
+ .managed_agent_runtime
+ .lock()
+ .unwrap()
+ .as_mut()
+ .unwrap()
+ .gateway_base_url = "http://127.0.0.1:5837/v1".into();
+ assert_eq!(status().state, AgentModelSettingsStateV2::Configured);
+
// Native clients may update unrelated settings after HiRoute configures the route.
// A collaboration skill restore likewise must not turn this model selection off.
let unrelated = configured.replace("user_setting = true", "user_setting = false");
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 d550019e..1b1106e2 100644
--- a/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_qoder_model_tests.rs
@@ -39,6 +39,78 @@ fn restore_spec(fixture: &QoderFixture, status: &serde_json::Value) -> serde_jso
json!({"schema_version":{"major":2,"minor":0},"context_id":fixture.context,"model":{"intent":"restore","restore_point_ref":status["restore_point_ref"]}})
}
+#[test]
+fn saved_pi_and_qoder_endpoints_drift_until_public_reconfiguration() {
+ let tools = crate::test_support::private_tempdir();
+ let node = tools.path().join("node");
+ private_file(&node, b"#!/bin/sh\nif [ \"$1\" = --version ]; then echo v22.19.0; elif [ \"$2\" = --check ] && [ \"$4\" = models ]; then echo hiroute.pi-sdk-capability/v1:ok; else exit 97; fi\n");
+ fs::set_permissions(&node, fs::Permissions::from_mode(0o700)).unwrap();
+ let path =
+ std::env::join_paths([tools.path(), Path::new("/usr/bin"), Path::new("/bin")]).unwrap();
+ if crate::test_support::isolated_agent_home_with_path(
+ "control::runtime::native_model::tests::settings_entry_tests::qoder::models::saved_pi_and_qoder_endpoints_drift_until_public_reconfiguration",
+ &path,
+ ) {
+ return;
+ }
+ for kind in [AgentKindV1::Pi, AgentKindV1::Qoder] {
+ let fixture = QoderFixture::with_kind(true, kind);
+ let mut spec = model_spec(&fixture);
+ if kind == AgentKindV1::Pi {
+ spec["model"]["settings"]["mode"] = json!("pi_additional");
+ }
+ apply(
+ &fixture.service,
+ &fixture.runtime,
+ spec.clone(),
+ "endpoint-original",
+ );
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ let before = fs::read(&fixture.native_config).unwrap();
+ fixture
+ .runtime
+ .adapter
+ .managed_agent_runtime
+ .lock()
+ .unwrap()
+ .as_mut()
+ .unwrap()
+ .gateway_base_url = "http://127.0.0.1:5838/v1".into();
+ let stale = model_status(&fixture);
+ assert_eq!(stale["state"], "drift");
+ assert!(stale.get("current_selection").is_none());
+ assert_eq!(fs::read(&fixture.native_config).unwrap(), before);
+
+ let refreshed = apply(&fixture.service, &fixture.runtime, spec, "endpoint-refresh");
+ assert_eq!(refreshed["state"], "succeeded");
+ assert_eq!(model_status(&fixture)["state"], "configured");
+ let after: serde_json::Value =
+ serde_json::from_slice(&fs::read(&fixture.native_config).unwrap()).unwrap();
+ let before: serde_json::Value = serde_json::from_slice(&before).unwrap();
+ assert_eq!(after["providers"]["native"], before["providers"]["native"]);
+ assert_eq!(after["unknown"], before["unknown"]);
+ assert_eq!(after["model"], before["model"]);
+ let providers = after["providers"].as_object().unwrap();
+ let (_, provider) = providers
+ .iter()
+ .find(|(name, _)| name.starts_with("hiroute-main-"))
+ .unwrap();
+ assert!(
+ provider["baseUrl"]
+ .as_str()
+ .unwrap()
+ .contains("127.0.0.1:5838/")
+ );
+ let (_, old_provider) = before["providers"]
+ .as_object()
+ .unwrap()
+ .iter()
+ .find(|(name, _)| name.starts_with("hiroute-main-"))
+ .unwrap();
+ assert_eq!(provider["models"], old_provider["models"]);
+ }
+}
+
#[test]
fn pi_default_selected_after_prepare_blocks_final_removal_without_losing_models() {
// Supply only the model-capability receipt, without a machine-wide Node dependency.
diff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rs
index 9086e4ab..4913c889 100644
--- a/crates/daemon/src/control/runtime/settings_status.rs
+++ b/crates/daemon/src/control/runtime/settings_status.rs
@@ -286,7 +286,24 @@ impl LocalControlAdapter {
}
None => false,
};
- let configured = file_applied && current.as_ref() == Some(&expected) && published;
+ let endpoint_current = {
+ let runtime = self
+ .managed_agent_runtime
+ .lock()
+ .map_err(|_| ControlReadError::Unavailable)?;
+ let runtime = runtime.as_ref().ok_or(ControlReadError::Unavailable)?;
+ model_endpoint_matches_runtime(
+ class,
+ &operation,
+ intent,
+ &runtime.gateway_base_url,
+ )
+ .map_err(super::map_port)?
+ };
+ let configured = file_applied
+ && endpoint_current
+ && current.as_ref() == Some(&expected)
+ && published;
status.state = if configured {
State::Configured
} else {
@@ -506,3 +523,39 @@ fn model_action(
}
}
}
+
+// The native adapter proves the owned file still matches the sealed configuration.
+// That historical endpoint must also match today's running Gateway.
+fn model_endpoint_matches_runtime(
+ class: SettingsAgentClass,
+ operation: &(impl hiroute_domain::AgentOperationRead + ?Sized),
+ intent: &hiroute_domain::ExternalEffectIntentV1,
+ gateway_base_url: &str,
+) -> hiroute_domain::PortResult<bool> {
+ use hiroute_application::agent_connection::{
+ AdditionalModelFileAction, additional_model_kind,
+ settings_additional_model_file_for_operation,
+ };
+ match class {
+ SettingsAgentClass::Codex | SettingsAgentClass::CodexProfile => Ok(matches!(
+ settings_codex_model_file_for_operation(operation, intent)?.change,
+ CodexModelFileAction::Configure { endpoint, .. } if endpoint == gateway_base_url
+ )),
+ SettingsAgentClass::Claude => Ok(matches!(
+ settings_claude_model_file_for_operation(operation, intent)?.change,
+ ClaudeModelFileAction::Configure { gateway_base_url: endpoint, .. }
+ if endpoint == gateway_base_url
+ )),
+ SettingsAgentClass::Qoder | SettingsAgentClass::Pi | SettingsAgentClass::Dsh => {
+ let endpoint = super::native_additional_model::additional_model_endpoint(
+ additional_model_kind(intent)?,
+ gateway_base_url,
+ )?;
+ Ok(matches!(
+ settings_additional_model_file_for_operation(operation, intent)?.change,
+ AdditionalModelFileAction::Configure { endpoint: configured, .. }
+ if configured == endpoint
+ ))
+ }
+ }
+}
diff --git a/crates/host-runtime/src/gateway_listener.rs b/crates/host-runtime/src/gateway_listener.rs
index ce77ff1b..231c2da3 100644
--- a/crates/host-runtime/src/gateway_listener.rs
+++ b/crates/host-runtime/src/gateway_listener.rs
@@ -298,10 +298,18 @@ impl GatewayListenerStore {
pub fn configure(
&self,
- desired: GatewayListenerDesiredV1,
+ mut desired: GatewayListenerDesiredV1,
) -> Result<GatewayListenerConfigV1, GatewayListenerError> {
desired.validate()?;
let mut config = self.load_or_default()?;
+ // Automatic selects only when no durable choice exists. Changing the mode or
+ // address must not invalidate endpoints already installed in native clients.
+ if desired.port_mode == GatewayPortModeV1::Automatic && desired.port.is_none() {
+ desired.port = config
+ .desired
+ .port
+ .or_else(|| config.applied.as_ref().map(|applied| applied.port));
+ }
config.desired = desired.clone();
config.operation = Some(GatewayListenerOperationV1 {
operation_id: random_hex().map_err(|_| GatewayListenerError::Unavailable)?,
@@ -550,6 +558,92 @@ mod tests {
);
}
+ #[test]
+ fn repeated_auto_and_scope_changes_preserve_the_durable_port() {
+ let root = tempfile::tempdir().unwrap();
+ let store = GatewayListenerStore::new(root.path());
+ let listen = store.reserve().unwrap().release();
+ store.mark_applied(listen).unwrap();
+ for address in ["127.0.0.1", "0.0.0.0"] {
+ let configured = store
+ .configure(GatewayListenerDesiredV1::automatic(address))
+ .unwrap();
+ assert_eq!(configured.desired.port, Some(listen.port()));
+ assert_eq!(configured.operation.unwrap().desired, configured.desired);
+ let selected = store.reserve().unwrap().release();
+ assert_eq!(selected.port(), listen.port());
+ store.mark_applied(selected).unwrap();
+ }
+ let reopened = GatewayListenerStore::new(root.path());
+ assert_eq!(reopened.reserve().unwrap().listen.port(), listen.port());
+ }
+
+ #[test]
+ fn auto_prefers_desired_then_applied_and_respects_explicit_fixed_ports() {
+ let root = tempfile::tempdir().unwrap();
+ let store = GatewayListenerStore::new(root.path());
+ let first = store.reserve().unwrap().release();
+ store.mark_applied(first).unwrap();
+ let requested = if first.port() == 45837 { 45838 } else { 45837 };
+ store
+ .configure(GatewayListenerDesiredV1::fixed("127.0.0.1", requested))
+ .unwrap();
+ store.mark_failed("SERVICE_RESTART_FAILED").unwrap();
+ assert_eq!(
+ store
+ .configure(GatewayListenerDesiredV1::automatic("127.0.0.1"))
+ .unwrap()
+ .desired
+ .port,
+ Some(requested)
+ );
+ // An old persisted request may have cleared desired while retaining applied.
+ let mut old = store.load().unwrap().unwrap();
+ old.desired.port = None;
+ old.operation.as_mut().unwrap().desired.port = None;
+ store.save(&old).unwrap();
+ assert_eq!(
+ store
+ .configure(GatewayListenerDesiredV1::automatic("127.0.0.1"))
+ .unwrap()
+ .desired
+ .port,
+ Some(first.port())
+ );
+ let mut explicit = GatewayListenerDesiredV1::automatic("127.0.0.1");
+ explicit.port = Some(requested);
+ assert_eq!(
+ store.configure(explicit).unwrap().desired.port,
+ Some(requested)
+ );
+ }
+
+ #[test]
+ fn failed_restart_then_foreground_activation_preserves_operation_history() {
+ let root = tempfile::tempdir().unwrap();
+ let store = GatewayListenerStore::new(root.path());
+ let listen = store.reserve().unwrap().release();
+ store.mark_applied(listen).unwrap();
+ store
+ .configure(GatewayListenerDesiredV1::automatic("127.0.0.1"))
+ .unwrap();
+ let failed = store
+ .mark_failed("SERVICE_RESTART_FAILED")
+ .unwrap()
+ .operation;
+ let selected = store.reserve().unwrap().release();
+ assert_eq!(selected, listen);
+ let activated = store.mark_applied(selected).unwrap();
+ assert_eq!(activated.applied_address().unwrap(), Some(listen));
+ assert_eq!(activated.operation, failed);
+ let occupied = store.reserve().unwrap();
+ assert!(matches!(
+ store.reserve(),
+ Err(GatewayListenerError::AddressUnavailable)
+ ));
+ assert_eq!(store.load().unwrap().unwrap(), occupied.config);
+ }
+
#[test]
fn desired_applied_and_failure_states_do_not_overstate_activation() {
let root = tempfile::tempdir().unwrap();
diff --git a/docs/code-map/architecture.md b/docs/code-map/architecture.md
index 30140a97..598511d1 100644
--- a/docs/code-map/architecture.md
+++ b/docs/code-map/architecture.md
@@ -55,6 +55,15 @@ cover that distinction. DSH module replacement and credential-store precedence
are located in the [native composition guide](../../crates/integrations/src/agents/additional_native/README.md#dsh-static-composition).
Do not move either rule into a generic provider merge.
+[Model settings status](../../crates/daemon/src/control/runtime/settings_status.rs)
+joins owned native configuration with the current Gateway endpoint as well as
+grant/publication evidence. [CLI listener status](../../crates/cli/src/host_commands.rs)
+uses that read and, for unconfigured/restored targets, the
+[released V1 connection join](../../crates/daemon/src/control/runtime/agent_connection_discovery.rs)
+to request explicit reconfiguration; listener operation history alone
+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
diff --git a/docs/standalone-cli.md b/docs/standalone-cli.md
index 3033b1c3..dbd89a4c 100644
--- a/docs/standalone-cli.md
+++ b/docs/standalone-cli.md
@@ -669,7 +669,27 @@ hiroute gateway recover --output json
```
`set` saves desired state, restarts, and advances applied state only after real readiness.
-The first automatically chosen port is persisted. Local management clients see a
+The first automatically chosen port is persisted. Repeating `--port auto`, switching
+from fixed to automatic, or changing the address retains the saved desired port
+(or the last applied port if no desired port has been selected). A port is selected
+only when neither exists; a binding collision fails without choosing a replacement.
+If the service-manager restart fails, desired state remains saved and the operation
+remains failed. A later `hiroute service run` applies that desired state after readiness.
+`recover` selects the current applied listener, not an earlier historical address.
+
+`gateway show` checks public Agent settings status against the current runtime endpoint.
+Its `agent_update.required` hint requests a check/reconfiguration for drift, pending
+changes or unavailable inspection; it does not depend on the last listener operation's
+success. A null `existing_agent_count` means discovery was unavailable. Configured
+targets that agree and collaboration-only targets do not require model updates.
+Unconfigured/restored model targets also check any saved V1 connection; a missing
+old record needs no update, while a disconnected configuration requires a check.
+Current configured settings take precedence over superseded connection history.
+After a real endpoint change, use fresh
+`agents connect preview` / `agents connect apply` with the intended model selection;
+HiRoute does not rewrite native Agent configuration during a listener restart.
+
+Local management clients see a
`0.0.0.0` listener as `127.0.0.1:<port>`. A non-loopback address requires explicit risk
acceptance. HiRoute never changes a firewall, configures TLS, or manages a remote Agent.
IPv6, multiple listeners, and firewall management are not supported.
diff --git a/docs/standalone-cli.zh-CN.md b/docs/standalone-cli.zh-CN.md
index 006bcbd6..6dd86907 100644
--- a/docs/standalone-cli.zh-CN.md
+++ b/docs/standalone-cli.zh-CN.md
@@ -572,7 +572,21 @@ hiroute gateway set --address 192.0.2.10 --port 8317 \
hiroute gateway recover --output json
```
-`set` 保存 desired 后重启,并只在真实 ready 后推进 applied。自动端口首次选定后持久化;
+`set` 保存 desired 后重启,并只在真实 ready 后推进 applied。自动端口首次选定后持久化。
+重复 `--port auto`、固定转自动或只修改地址时,优先保留已保存的 desired 端口;
+desired 尚未选定端口时复用最近 applied 的端口,两者都没有才首次选择。
+端口冲突会明确失败,不另选端口。服务管理器重启失败后 desired 仍保留,操作仍为 failed;
+随后通过 `hiroute service run` 启动时,真实 ready 后记录该 desired 为 applied。
+`recover` 使用当前 applied 地址,不会恢复任意历史端口。
+
+`gateway show` 通过公开 Agent settings status 核对配置与当前运行地址。
+`agent_update.required` 在配置偏移、变更待完成或无法完成检查时提示核查/重新配置,
+不依赖最近监听器操作是否成功;`existing_agent_count` 为 null 表示发现不可用。
+配置已一致和仅启用协作的目标无需更新模型。未配置/已恢复模型还会检查已保存的 V1 接入:
+没有旧记录时无需更新;旧配置已断开时提示核查。当前已配置状态优先于已被取代的历史接入。
+地址实际变化后,保留所需模型选择,重新执行 `agents connect preview` / `agents connect apply`;
+监听器重启不会自动改写原生 Agent 配置。
+
`0.0.0.0` 对本机管理客户端显示为 `127.0.0.1:<port>`。非 loopback 配置要求显式风险确认。
HiRoute 不自动修改防火墙、TLS 或远端 Agent。暂不支持 IPv6、多监听器和防火墙管理。