Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

feat: establish the 0.2 upgrade and stable storage foundation (#37)

澄潭c3f5309a9f96
diff --git a/.github/scripts/release-contract-pr.sh b/.github/scripts/release-contract-pr.sh
new file mode 100644
index 00000000..b074a2e0
--- /dev/null
+++ b/.github/scripts/release-contract-pr.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+: "${RELEASE_TAG:?published release tag required}"
+: "${RELEASE_REVISION:?verified source revision required}"
+: "${WEBSITE_REVISION:?verified release-manifest revision required}"
+: "${GH_REPO:?repository required}"
+
+root=$(git rev-parse --show-toplevel)
+scratch=$(mktemp -d)
+worktree="$scratch/pr"
+cleanup() {
+ git -C "$root" worktree remove --force "$worktree" >/dev/null 2>&1 || true
+ rm -rf "$scratch"
+}
+trap cleanup EXIT
+
+# Resolve and validate the published source before any branch/PR write.
+git show "${WEBSITE_REVISION}:apps/website/data/releases.json" > "$scratch/releases.json"
+gh release view "$RELEASE_TAG" --repo "$GH_REPO" \
+ --json tagName,isDraft,isPrerelease,publishedAt,assets > "$scratch/release.json"
+python3 -c 'import json,sys; assert json.load(open(sys.argv[1]))["tagName"] == sys.argv[2], "release tag mismatch"' \
+ "$scratch/release.json" "$RELEASE_TAG"
+python3 "$root/scripts/release-contracts.py" record --repo "$root" \
+ --directory "$scratch/verified" --manifest "$scratch/releases.json" \
+ --release-json "$scratch/release.json" --revision "$RELEASE_REVISION" \
+ --repository "$GH_REPO" > /dev/null
+
+branch="chore/release-contracts-${RELEASE_TAG}"
+git fetch origin main --tags
+# Fast path after the generated PR has already merged.
+git worktree add --detach "$worktree" origin/main
+python3 "$root/scripts/release-contracts.py" record --repo "$root" \
+ --directory "$worktree/contracts/releases" --manifest "$scratch/releases.json" \
+ --release-json "$scratch/release.json" --revision "$RELEASE_REVISION" \
+ --repository "$GH_REPO" > /dev/null
+if [[ -z $(git -C "$worktree" status --porcelain -- contracts/releases) ]]; then
+ echo 'Published contract snapshot is already recorded on main.'
+ exit 0
+fi
+git worktree remove --force "$worktree"
+
+existing=$(gh pr list --repo "$GH_REPO" --head "$branch" --base main \
+ --state all --json state,url --jq '.[0] // {}')
+state=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("state", ""))' <<< "$existing")
+if [[ "$state" == CLOSED || "$state" == MERGED ]]; then
+ echo 'A prior snapshot PR is closed but main lacks this exact record; resolve that discrepancy before retrying.' >&2
+ exit 1
+fi
+
+git config user.name 'github-actions[bot]'
+git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
+if git ls-remote --exit-code --heads origin "$branch" > "$scratch/remote-ref"; then
+ git fetch origin "$branch:refs/remotes/origin/$branch"
+ changed=$(git diff --name-only "origin/main...origin/$branch")
+ if [[ -n "$changed" ]] && ! python3 -c \
+ 'import sys; raise SystemExit(any(not p.startswith("contracts/releases/") for p in sys.stdin.read().splitlines()))' <<< "$changed"; then
+ echo 'Existing automation branch contains unrelated changes.' >&2
+ exit 1
+ fi
+ git worktree add --detach "$worktree" "origin/$branch"
+ git -C "$worktree" merge --no-edit --signoff origin/main
+else
+ status=$?
+ [[ "$status" == 2 ]] || exit "$status"
+ git worktree add --detach "$worktree" origin/main
+fi
+
+python3 "$root/scripts/release-contracts.py" record --repo "$root" \
+ --directory "$worktree/contracts/releases" --manifest "$scratch/releases.json" \
+ --release-json "$scratch/release.json" --revision "$RELEASE_REVISION" \
+ --repository "$GH_REPO" > /dev/null
+python3 "$root/scripts/release-contracts.py" check --repo "$root" \
+ --directory "$worktree/contracts/releases" --base origin/main > /dev/null
+git -C "$worktree" add -- contracts/releases
+if ! git -C "$worktree" diff --cached --quiet; then
+ git -C "$worktree" commit -s -m "chore(release): record contracts for $RELEASE_TAG"
+fi
+gh auth setup-git
+git -C "$worktree" push origin "HEAD:refs/heads/$branch"
+
+if [[ "$state" == OPEN ]]; then
+ python3 -c 'import json,sys; print(json.load(sys.stdin)["url"])' <<< "$existing"
+else
+ cat > "$scratch/body.md" <<EOF
+Record the published $RELEASE_TAG contract inventory from source $RELEASE_REVISION,
+including storage schema, frozen contract descriptors and installer identities.
+
+The release publication and package-verification jobs succeeded before this update.
+Merging this PR advances the recorded stable baseline when this is a newer stable release;
+previous snapshots remain immutable. This inventory does not claim migration acceptance.
+
+Validation: deterministic snapshot generation and frozen-source/index verification.
+EOF
+ gh pr create --repo "$GH_REPO" --base main --head "$branch" \
+ --title "chore(release): record contracts for $RELEASE_TAG" --body-file "$scratch/body.md"
+fi
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index cfefeaeb..8b53b1a1 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -113,3 +113,24 @@ jobs:
export PATH="$RUNNER_TEMP/bin:$PATH"
.github/scripts/publish-release-oss.sh "$RUNNER_TEMP/release-assets" apps/website/data/releases.json "$RELEASE_TAG"
.github/scripts/deploy-website-oss.sh apps/website/dist apps/website/data/releases.json
+
+ record-contracts:
+ needs: [verify-release, publish]
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ permissions:
+ contents: write
+ pull-requests: write
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ needs.verify-release.outputs.website_revision }}
+ fetch-depth: 0
+ persist-credentials: false
+ - name: Propose the published contract snapshot
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ RELEASE_REVISION: ${{ needs.verify-release.outputs.revision }}
+ WEBSITE_REVISION: ${{ needs.verify-release.outputs.website_revision }}
+ run: bash .github/scripts/release-contract-pr.sh
diff --git a/Cargo.lock b/Cargo.lock
index 5f3d6e90..772b2b36 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2133,7 +2133,7 @@ dependencies = [
[[package]]
name = "hiroute-application-api"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"hiroute-domain",
"serde",
@@ -2144,7 +2144,7 @@ dependencies = [
[[package]]
name = "hiroute-cli"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"getrandom 0.3.4",
"hiroute-application",
@@ -2204,7 +2204,7 @@ dependencies = [
[[package]]
name = "hiroute-daemon"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"agent-client-protocol",
"arc-swap",
@@ -2240,7 +2240,7 @@ dependencies = [
[[package]]
name = "hiroute-desktop"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"command-fds",
"fs2",
@@ -2252,8 +2252,10 @@ dependencies = [
"hiroute-domain",
"hiroute-host-runtime",
"nix",
+ "reqwest",
"serde",
"serde_json",
+ "sha2",
"tauri",
"tauri-build",
"tauri-plugin-dialog",
@@ -2387,8 +2389,10 @@ version = "0.1.0"
dependencies = [
"getrandom 0.3.4",
"nix",
+ "semver",
"serde",
"serde_json",
+ "sha2",
"tempfile",
"thiserror 2.0.20",
]
@@ -2418,11 +2422,14 @@ name = "hiroute-local-storage"
version = "0.1.0"
dependencies = [
"aes-gcm",
+ "base64 0.22.1",
+ "fs2",
"getrandom 0.3.4",
"hiroute-application",
"hiroute-application-api",
"hiroute-diagnostics",
"hiroute-domain",
+ "hiroute-host-runtime",
"hiroute-integrations",
"hmac",
"rusqlite",
diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.json
index 6169f7ea..4222d3a2 100644
--- a/apps/desktop/package-lock.json
+++ b/apps/desktop/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "hiroute-desktop-ui",
- "version": "0.1.0",
+ "version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "hiroute-desktop-ui",
- "version": "0.1.0",
+ "version": "0.2.0",
"dependencies": {
"@tauri-apps/api": "2.11.1",
"react": "19.2.8",
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index c72571dd..36675dc6 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -1,6 +1,6 @@
{
"name": "hiroute-desktop-ui",
- "version": "0.1.0",
+ "version": "0.2.0",
"private": true,
"type": "module",
"scripts": {
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 27fb134c..4dd9db5b 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "hiroute-desktop"
-version = "0.1.0"
+version = "0.2.0"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
@@ -22,6 +22,8 @@ tokio.workspace = true
zeroize.workspace = true
getrandom.workspace = true
fs2.workspace = true
+reqwest = { version = "=0.13.4" }
+sha2.workspace = true
tauri = { version = "2.11.1", optional = true }
tauri-plugin-dialog = { version = "2.7.3", default-features = false, features = ["xdg-portal"], optional = true }
tauri-plugin-pilot = { git = "https://github.com/mpiton/tauri-pilot", rev = "ed31926726b4cd7b3ffbc11f188e046f2b5e0faa", default-features = false, optional = true }
diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs
index 59e0c5c4..bc498b90 100644
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@ -72,6 +72,11 @@ fn main() {
"diagnostic_status",
"startup_status",
"open_startup_recovery_directory",
+ "update_status",
+ "update_check",
+ "update_download",
+ "update_install",
+ "update_cancel",
"set_diagnostic_level",
"open_diagnostic_directory",
"open_external_url",
diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json
index 293918bd..3a56e168 100644
--- a/apps/desktop/src-tauri/capabilities/main.json
+++ b/apps/desktop/src-tauri/capabilities/main.json
@@ -67,6 +67,11 @@
"allow-diagnostic-status",
"allow-startup-status",
"allow-open-startup-recovery-directory",
+ "allow-update-status",
+ "allow-update-check",
+ "allow-update-download",
+ "allow-update-install",
+ "allow-update-cancel",
"allow-set-diagnostic-level",
"allow-open-diagnostic-directory",
"allow-open-external-url",
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/update_cancel.toml b/apps/desktop/src-tauri/permissions/autogenerated/update_cancel.toml
new file mode 100644
index 00000000..853f6b2b
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/update_cancel.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-update-cancel"
+description = "Enables the update_cancel command without any pre-configured scope."
+commands.allow = ["update_cancel"]
+
+[[permission]]
+identifier = "deny-update-cancel"
+description = "Denies the update_cancel command without any pre-configured scope."
+commands.deny = ["update_cancel"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/update_check.toml b/apps/desktop/src-tauri/permissions/autogenerated/update_check.toml
new file mode 100644
index 00000000..8a4fef9a
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/update_check.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-update-check"
+description = "Enables the update_check command without any pre-configured scope."
+commands.allow = ["update_check"]
+
+[[permission]]
+identifier = "deny-update-check"
+description = "Denies the update_check command without any pre-configured scope."
+commands.deny = ["update_check"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/update_download.toml b/apps/desktop/src-tauri/permissions/autogenerated/update_download.toml
new file mode 100644
index 00000000..ae7efb31
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/update_download.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-update-download"
+description = "Enables the update_download command without any pre-configured scope."
+commands.allow = ["update_download"]
+
+[[permission]]
+identifier = "deny-update-download"
+description = "Denies the update_download command without any pre-configured scope."
+commands.deny = ["update_download"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/update_install.toml b/apps/desktop/src-tauri/permissions/autogenerated/update_install.toml
new file mode 100644
index 00000000..eb584ac4
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/update_install.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-update-install"
+description = "Enables the update_install command without any pre-configured scope."
+commands.allow = ["update_install"]
+
+[[permission]]
+identifier = "deny-update-install"
+description = "Denies the update_install command without any pre-configured scope."
+commands.deny = ["update_install"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/update_status.toml b/apps/desktop/src-tauri/permissions/autogenerated/update_status.toml
new file mode 100644
index 00000000..702315bb
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/update_status.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-update-status"
+description = "Enables the update_status command without any pre-configured scope."
+commands.allow = ["update_status"]
+
+[[permission]]
+identifier = "deny-update-status"
+description = "Denies the update_status command without any pre-configured scope."
+commands.deny = ["update_status"]
diff --git a/apps/desktop/src-tauri/src/bootstrap.rs b/apps/desktop/src-tauri/src/bootstrap.rs
index 2f4a724d..1f465616 100644
--- a/apps/desktop/src-tauri/src/bootstrap.rs
+++ b/apps/desktop/src-tauri/src/bootstrap.rs
@@ -24,6 +24,7 @@ use zeroize::Zeroizing;
use crate::native_diagnostics::NativeDiagnostics;
const DAEMON_READY_TIMEOUT: Duration = Duration::from_secs(210);
+mod startup_progress;
pub enum ApplyPurpose {
AgentPlan,
SourcePrice,
@@ -73,6 +74,8 @@ fn decode_startup_failure(value: &serde_json::Value) -> Result<Option<&'static s
}
Ok(Some(match failure.code {
StartupFailureCode::StorageUnavailable => "DAEMON_STORAGE_UNREADABLE",
+ StartupFailureCode::UpgradeSourceUnsupported => "DAEMON_UPGRADE_SOURCE_UNSUPPORTED",
+ StartupFailureCode::UpgradeStorageFailed => "DAEMON_UPGRADE_STORAGE_FAILED",
StartupFailureCode::ReleaseFactsInvalid => "DAEMON_RELEASE_INVALID",
StartupFailureCode::DependencyUnavailable => "DAEMON_DEPENDENCY_UNAVAILABLE",
StartupFailureCode::GatewayUnavailable => "DAEMON_GATEWAY_UNAVAILABLE",
@@ -93,6 +96,84 @@ struct Ack {
}
impl Resident {
+ pub fn upgrade_stop_requested(&self) -> bool {
+ self.owned
+ .as_ref()
+ .is_some_and(|owned| owned.shutdown.is_none())
+ }
+ pub fn upgrade_status(
+ &mut self,
+ action: hiroute_host_runtime::UpgradeAction,
+ ) -> Result<hiroute_host_runtime::LauncherUpgradeStatus, String> {
+ let owned = self
+ .owned
+ .as_mut()
+ .filter(|owned| owned.authority_healthy)
+ .ok_or("UPGRADE_RESIDENT_NOT_OWNED")?;
+ let id = crate::random_id()?;
+ let mut bytes = serde_json::to_vec(&hiroute_host_runtime::LauncherUpgradeRequest {
+ schema: "hiroute.launcher-upgrade/v1".into(),
+ registration_id: id.clone(),
+ action,
+ })
+ .map_err(|_| "UPGRADE_FRAME_INVALID")?;
+ bytes.push(b'\n');
+ let exchange = (|| {
+ write_frame(&mut owned.capability, &bytes)?;
+ let bytes = read_frame(&mut owned.ack, 4096, Duration::from_secs(10), None)?;
+ let status: hiroute_host_runtime::LauncherUpgradeStatus =
+ serde_json::from_slice(&bytes).map_err(|_| "UPGRADE_ACK_INVALID")?;
+ if status.schema != "hiroute.launcher-upgrade-status/v1" || status.registration_id != id
+ {
+ return Err("UPGRADE_ACK_INVALID".into());
+ }
+ Ok(status)
+ })();
+ // A failed exchange can leave an unread reply in the shared protected channel.
+ // Do not let a later capability registration consume it as its own acknowledgement.
+ if exchange.is_err() {
+ owned.authority_healthy = false;
+ }
+ exchange
+ }
+
+ /// Upgrade never falls back to the ordinary exit path's bounded force-kill. Installation
+ /// remains blocked until the exact owned child has actually exited.
+ pub fn stop_for_upgrade(&mut self) -> Result<(), String> {
+ let shutdown_requested = self
+ .owned
+ .as_ref()
+ .ok_or("UPGRADE_RESIDENT_NOT_OWNED")?
+ .shutdown
+ .is_none();
+ // A timed-out orderly stop is still in progress. Retrying waits for that child;
+ // its protected channel is no longer usable after shutdown was requested.
+ if !shutdown_requested {
+ if !self
+ .upgrade_status(hiroute_host_runtime::UpgradeAction::Status)?
+ .drained()
+ {
+ return Err("UPGRADE_WORK_ACTIVE".into());
+ }
+ }
+ let owned = self.owned.as_mut().ok_or("UPGRADE_RESIDENT_NOT_OWNED")?;
+ drop(owned.shutdown.take());
+ let deadline = Instant::now() + Duration::from_secs(45);
+ loop {
+ if owned
+ .child
+ .try_wait()
+ .map_err(|_| "UPGRADE_STOP_FAILED")?
+ .is_some()
+ {
+ return Ok(());
+ }
+ if Instant::now() >= deadline {
+ return Err("UPGRADE_STOP_PENDING".into());
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
pub fn open(root: &Path, daemon: &Path) -> Result<Self, String> {
Self::open_managed(
root,
@@ -311,7 +392,7 @@ impl Resident {
Some(DAEMON_READY_TIMEOUT.as_millis() as u64),
);
let ready_started = Instant::now();
- let ready_read = read_frame(&mut stdout, 4096, DAEMON_READY_TIMEOUT, Some(cancelled));
+ let ready_read = startup_progress::read_ready(&mut stdout, cancelled, diagnostics);
stages
.handle()
.try_emit(DiagnosticEvent::ReadyRead(ReadyIo {
@@ -853,158 +934,4 @@ pub(crate) fn acquire_host_lock(root: &Path) -> Result<File, String> {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn shutdown_interrupts_a_pending_daemon_ready_read() {
- let (mut reader, _writer) = std::os::unix::net::UnixStream::pair().unwrap();
- reader.set_nonblocking(true).unwrap();
- let cancelled = AtomicBool::new(false);
- std::thread::scope(|scope| {
- scope.spawn(|| {
- std::thread::sleep(Duration::from_millis(20));
- cancelled.store(true, Ordering::SeqCst);
- });
- let started = Instant::now();
- assert_eq!(
- read_frame(&mut reader, 4096, DAEMON_READY_TIMEOUT, Some(&cancelled)).unwrap_err(),
- "DAEMON_START_CANCELLED"
- );
- assert!(started.elapsed() < Duration::from_secs(2));
- });
- }
-
- #[test]
- fn startup_failure_frame_maps_storage_without_accepting_extra_payload() {
- assert_eq!(
- decode_startup_failure(&serde_json::json!({
- "schema": "hiroute.daemon-startup-failure/v1",
- "code": "storage_unavailable"
- })),
- Ok(Some("DAEMON_STORAGE_UNREADABLE"))
- );
- assert_eq!(
- decode_startup_failure(&serde_json::json!({
- "schema": "hiroute.daemon-startup-failure/v1",
- "code": "storage_unavailable",
- "message": "/private/data/path"
- })),
- Err("DAEMON_READY_INVALID")
- );
- assert_eq!(
- decode_startup_failure(&serde_json::json!({
- "schema": "hiroute.daemon-ready/v1"
- })),
- Ok(None)
- );
- }
-
- #[test]
- fn cancelled_startup_does_not_create_state_or_launch_a_child() {
- let directory = tempfile::tempdir().unwrap();
- let root = directory.path().join("not-created");
- let result = Resident::open_managed(
- &root,
- &root.join("hirouted"),
- &AtomicBool::new(true),
- &NativeDiagnostics::disabled(),
- );
- assert_eq!(result.err().as_deref(), Some("DAEMON_START_CANCELLED"));
- assert!(!root.exists());
- }
-
- #[test]
- fn a_second_descriptor_of_a_held_host_lock_reports_the_duplicate() {
- // Parallel process tests may fork while this test holds a file lock. A child
- // retains the same open-file description until exec, even with CLOEXEC. Exercise
- // exact close/reclaim ordering in one isolated test process instead.
- const CASE: &str =
- "bootstrap::tests::a_second_descriptor_of_a_held_host_lock_reports_the_duplicate";
- const CHILD: &str = "HIROUTE_ISOLATED_LOCK_TEST";
- if std::env::var(CHILD).as_deref() != Ok(CASE) {
- let output = std::process::Command::new(std::env::current_exe().unwrap())
- .args(["--exact", CASE])
- .env(CHILD, CASE)
- .output()
- .unwrap();
- let stdout = String::from_utf8_lossy(&output.stdout);
- assert!(
- output.status.success()
- && stdout
- .lines()
- .any(|line| line == format!("test {CASE} ... ok")),
- "isolated lock test must execute its exact case: {stdout} {}",
- String::from_utf8_lossy(&output.stderr)
- );
- return;
- }
- let directory = tempfile::tempdir().unwrap();
- let root = directory.path().join("host");
- let held = acquire_host_lock(&root).unwrap();
- assert_eq!(
- acquire_host_lock(&root).unwrap_err(),
- "DESKTOP_ALREADY_RUNNING",
- "flock on a second descriptor of the same lock file conflicts within one process"
- );
- // A duplicated descriptor models the shared open-file description inherited
- // across fork. Closing one descriptor alone must not release the lease.
- let inherited = held.try_clone().unwrap();
- drop(held);
- assert_eq!(
- acquire_host_lock(&root).unwrap_err(),
- "DESKTOP_ALREADY_RUNNING"
- );
- drop(inherited);
- assert!(acquire_host_lock(&root).is_ok());
- }
-
- #[test]
- fn acknowledgement_requires_the_exact_successful_registration() {
- for (id, registered, expected) in [
- ("current", true, true),
- ("older", true, false),
- ("current", false, false),
- ] {
- let bytes = format!(
- "{{\"schema\":\"hiroute.protected-apply-ack/v2\",\"registration_id\":\"{id}\",\"registered\":{registered}}}\n"
- );
- assert_eq!(
- receive_ack(&mut bytes.as_bytes(), "current", Duration::from_secs(1)).is_ok(),
- expected
- );
- }
- for bytes in [b"".as_slice(), b"{}", b"{}\n", &[b'a'; 1026]] {
- let mut reader: &[u8] = bytes;
- assert!(receive_ack(&mut reader, "current", Duration::from_secs(1)).is_err());
- }
- }
- #[test]
- fn stalled_acknowledgement_and_registration_writes_have_absolute_deadlines() {
- struct Stalled;
- impl Read for Stalled {
- fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
- Err(std::io::ErrorKind::WouldBlock.into())
- }
- }
- let started = Instant::now();
- assert_eq!(
- receive_ack(&mut Stalled, "current", Duration::from_millis(20)).unwrap_err(),
- "PROTECTED_CHANNEL_TIMEOUT"
- );
- assert!(started.elapsed() < Duration::from_secs(1));
- struct Closed;
- impl Write for Closed {
- fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
- Ok(0)
- }
- fn flush(&mut self) -> std::io::Result<()> {
- Ok(())
- }
- }
- assert_eq!(
- write_frame(&mut Closed, b"registration").unwrap_err(),
- "PROTECTED_CHANNEL_CLOSED"
- );
- }
-}
+mod tests;
diff --git a/apps/desktop/src-tauri/src/bootstrap/startup_progress.rs b/apps/desktop/src-tauri/src/bootstrap/startup_progress.rs
new file mode 100644
index 00000000..630ad497
--- /dev/null
+++ b/apps/desktop/src-tauri/src/bootstrap/startup_progress.rs
@@ -0,0 +1,90 @@
+//! Bounded upgrade phases share the already inherited daemon readiness pipe.
+use super::*;
+use hiroute_host_runtime::StorageUpgradePhase;
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct Progress {
+ schema: String,
+ phase: StorageUpgradePhase,
+}
+const UPGRADE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
+
+pub(super) fn read_ready(
+ reader: &mut impl Read,
+ cancelled: &AtomicBool,
+ diagnostics: &NativeDiagnostics,
+) -> Result<Vec<u8>, String> {
+ let started = Instant::now();
+ let mut budget = DAEMON_READY_TIMEOUT;
+ let mut previous = None;
+ loop {
+ let remaining = budget
+ .checked_sub(started.elapsed())
+ .ok_or("PROTECTED_CHANNEL_TIMEOUT")?;
+ let bytes = read_frame(reader, 4096, remaining, Some(cancelled))?;
+ let value: serde_json::Value =
+ serde_json::from_slice(&bytes).map_err(|_| "DAEMON_READY_INVALID")?;
+ if value["schema"] != "hiroute.daemon-upgrade-progress/v1" {
+ return Ok(bytes);
+ }
+ let progress: Progress =
+ serde_json::from_value(value).map_err(|_| "DAEMON_READY_INVALID")?;
+ let index = match progress.phase {
+ StorageUpgradePhase::SourceCheck => 0,
+ StorageUpgradePhase::Backup => 1,
+ StorageUpgradePhase::Conversion => 2,
+ StorageUpgradePhase::Validation => 3,
+ StorageUpgradePhase::ServiceRecovery => 4,
+ };
+ if progress.schema != "hiroute.daemon-upgrade-progress/v1"
+ || previous.is_some_and(|last| index <= last)
+ {
+ return Err("DAEMON_READY_INVALID".into());
+ }
+ // At most five strictly advancing phases. The overall deadline never resets, so a
+ // child cannot keep the host waiting indefinitely by repeating progress frames.
+ previous = Some(index);
+ budget = UPGRADE_TIMEOUT;
+ diagnostics.report_upgrade(progress.phase);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn upgrade_progress_is_bounded_and_ready_is_still_the_final_authority() {
+ let state = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let diagnostics = NativeDiagnostics::disabled().with_upgrade_progress(state.clone());
+ let mut pipe = std::io::Cursor::new(concat!(
+ "{\"schema\":\"hiroute.daemon-upgrade-progress/v1\",\"phase\":\"source_check\"}\n",
+ "{\"schema\":\"hiroute.daemon-upgrade-progress/v1\",\"phase\":\"backup\"}\n",
+ "{\"schema\":\"hiroute.daemon-ready/v1\"}\n"
+ ));
+ let ready = read_ready(&mut pipe, &AtomicBool::new(false), &diagnostics).unwrap();
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&ready).unwrap()["schema"],
+ "hiroute.daemon-ready/v1"
+ );
+ assert_eq!(*state.lock().unwrap(), Some(StorageUpgradePhase::Backup));
+ for invalid in [
+ concat!(
+ "{\"schema\":\"hiroute.daemon-upgrade-progress/v1\",\"phase\":\"backup\"}\n",
+ "{\"schema\":\"hiroute.daemon-upgrade-progress/v1\",\"phase\":\"backup\"}\n"
+ ),
+ "{\"schema\":\"hiroute.daemon-upgrade-progress/v1\",\"phase\":\"unknown\"}\n",
+ "{\"schema\":\"hiroute.daemon-upgrade-progress/v1\",\"phase\":\"backup\",\"path\":\"untrusted\"}\n",
+ ] {
+ assert_eq!(
+ read_ready(
+ &mut std::io::Cursor::new(invalid),
+ &AtomicBool::new(false),
+ &diagnostics
+ )
+ .unwrap_err(),
+ "DAEMON_READY_INVALID"
+ );
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/bootstrap/tests.rs b/apps/desktop/src-tauri/src/bootstrap/tests.rs
new file mode 100644
index 00000000..60cad8d0
--- /dev/null
+++ b/apps/desktop/src-tauri/src/bootstrap/tests.rs
@@ -0,0 +1,219 @@
+use super::*;
+
+#[test]
+fn upgrade_prepare_status_cancel_exchange_complete_correlated_frames() {
+ use hiroute_host_runtime::{LauncherUpgradeRequest, LauncherUpgradeStatus, UpgradeAction};
+ let directory = tempfile::tempdir().unwrap();
+ let (shutdown_reader, shutdown_writer) = pipe().unwrap();
+ let (mut requests, capability) = pipe().unwrap();
+ let (ack, mut replies) = pipe().unwrap();
+ nonblocking(&requests).unwrap();
+ nonblocking(&ack).unwrap();
+ let child = Command::new("/bin/cat")
+ .stdin(Stdio::from(shutdown_reader))
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+ let mut resident = Resident {
+ client: Client::new(
+ "hiroute-desktop",
+ LocalEndpoint::from_runtime_root(directory.path().join("run")),
+ ),
+ owned: Some(OwnedChild {
+ child,
+ shutdown: Some(shutdown_writer),
+ capability,
+ ack,
+ authority_healthy: true,
+ manual_input_candidates: BTreeSet::new(),
+ diagnostics: None,
+ }),
+ _lock: acquire_host_lock(directory.path()).unwrap(),
+ };
+ std::thread::scope(|scope| {
+ let peer = scope.spawn(move || {
+ let mut registrations = BTreeSet::new();
+ for expected in ["prepare", "status", "cancel"] {
+ let bytes = read_frame(&mut requests, 4096, Duration::from_secs(2), None).unwrap();
+ let request: LauncherUpgradeRequest = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(request.schema, "hiroute.launcher-upgrade/v1");
+ assert_eq!(serde_json::to_value(request.action).unwrap(), expected);
+ assert!(registrations.insert(request.registration_id.clone()));
+ let mut reply = serde_json::to_vec(&LauncherUpgradeStatus {
+ schema: "hiroute.launcher-upgrade-status/v1".into(),
+ registration_id: request.registration_id,
+ paused: expected != "cancel",
+ active_calls: 0,
+ active_tasks: 0,
+ })
+ .unwrap();
+ reply.push(b'\n');
+ write_frame(&mut replies, &reply).unwrap();
+ }
+ });
+ for (action, paused) in [
+ (UpgradeAction::Prepare, true),
+ (UpgradeAction::Status, true),
+ (UpgradeAction::Cancel, false),
+ ] {
+ let response = resident.upgrade_status(action).unwrap();
+ assert_eq!(response.paused, paused);
+ assert_eq!(response.drained(), paused);
+ }
+ peer.join().unwrap();
+ });
+ assert!(resident.owned.as_ref().unwrap().authority_healthy);
+}
+
+#[test]
+fn shutdown_interrupts_a_pending_daemon_ready_read() {
+ let (mut reader, _writer) = std::os::unix::net::UnixStream::pair().unwrap();
+ reader.set_nonblocking(true).unwrap();
+ let cancelled = AtomicBool::new(false);
+ std::thread::scope(|scope| {
+ scope.spawn(|| {
+ std::thread::sleep(Duration::from_millis(20));
+ cancelled.store(true, Ordering::SeqCst);
+ });
+ let started = Instant::now();
+ assert_eq!(
+ read_frame(&mut reader, 4096, DAEMON_READY_TIMEOUT, Some(&cancelled)).unwrap_err(),
+ "DAEMON_START_CANCELLED"
+ );
+ assert!(started.elapsed() < Duration::from_secs(2));
+ });
+}
+
+#[test]
+fn startup_failure_frame_maps_storage_without_accepting_extra_payload() {
+ assert_eq!(
+ decode_startup_failure(&serde_json::json!({
+ "schema": "hiroute.daemon-startup-failure/v1",
+ "code": "storage_unavailable"
+ })),
+ Ok(Some("DAEMON_STORAGE_UNREADABLE"))
+ );
+ assert_eq!(
+ decode_startup_failure(&serde_json::json!({
+ "schema": "hiroute.daemon-startup-failure/v1",
+ "code": "storage_unavailable",
+ "message": "/private/data/path"
+ })),
+ Err("DAEMON_READY_INVALID")
+ );
+ assert_eq!(
+ decode_startup_failure(&serde_json::json!({
+ "schema": "hiroute.daemon-ready/v1"
+ })),
+ Ok(None)
+ );
+}
+
+#[test]
+fn cancelled_startup_does_not_create_state_or_launch_a_child() {
+ let directory = tempfile::tempdir().unwrap();
+ let root = directory.path().join("not-created");
+ let result = Resident::open_managed(
+ &root,
+ &root.join("hirouted"),
+ &AtomicBool::new(true),
+ &NativeDiagnostics::disabled(),
+ );
+ assert_eq!(result.err().as_deref(), Some("DAEMON_START_CANCELLED"));
+ assert!(!root.exists());
+}
+
+#[test]
+fn a_second_descriptor_of_a_held_host_lock_reports_the_duplicate() {
+ // Parallel process tests may fork while this test holds a file lock. A child
+ // retains the same open-file description until exec, even with CLOEXEC. Exercise
+ // exact close/reclaim ordering in one isolated test process instead.
+ const CASE: &str =
+ "bootstrap::tests::a_second_descriptor_of_a_held_host_lock_reports_the_duplicate";
+ const CHILD: &str = "HIROUTE_ISOLATED_LOCK_TEST";
+ if std::env::var(CHILD).as_deref() != Ok(CASE) {
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", CASE])
+ .env(CHILD, CASE)
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ output.status.success()
+ && stdout
+ .lines()
+ .any(|line| line == format!("test {CASE} ... ok")),
+ "isolated lock test must execute its exact case: {stdout} {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ return;
+ }
+ let directory = tempfile::tempdir().unwrap();
+ let root = directory.path().join("host");
+ let held = acquire_host_lock(&root).unwrap();
+ assert_eq!(
+ acquire_host_lock(&root).unwrap_err(),
+ "DESKTOP_ALREADY_RUNNING",
+ "flock on a second descriptor of the same lock file conflicts within one process"
+ );
+ // A duplicated descriptor models the shared open-file description inherited
+ // across fork. Closing one descriptor alone must not release the lease.
+ let inherited = held.try_clone().unwrap();
+ drop(held);
+ assert_eq!(
+ acquire_host_lock(&root).unwrap_err(),
+ "DESKTOP_ALREADY_RUNNING"
+ );
+ drop(inherited);
+ assert!(acquire_host_lock(&root).is_ok());
+}
+
+#[test]
+fn acknowledgement_requires_the_exact_successful_registration() {
+ for (id, registered, expected) in [
+ ("current", true, true),
+ ("older", true, false),
+ ("current", false, false),
+ ] {
+ let bytes = format!(
+ "{{\"schema\":\"hiroute.protected-apply-ack/v2\",\"registration_id\":\"{id}\",\"registered\":{registered}}}\n"
+ );
+ assert_eq!(
+ receive_ack(&mut bytes.as_bytes(), "current", Duration::from_secs(1)).is_ok(),
+ expected
+ );
+ }
+ for bytes in [b"".as_slice(), b"{}", b"{}\n", &[b'a'; 1026]] {
+ let mut reader: &[u8] = bytes;
+ assert!(receive_ack(&mut reader, "current", Duration::from_secs(1)).is_err());
+ }
+}
+#[test]
+fn stalled_acknowledgement_and_registration_writes_have_absolute_deadlines() {
+ struct Stalled;
+ impl Read for Stalled {
+ fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
+ Err(std::io::ErrorKind::WouldBlock.into())
+ }
+ }
+ let started = Instant::now();
+ assert_eq!(
+ receive_ack(&mut Stalled, "current", Duration::from_millis(20)).unwrap_err(),
+ "PROTECTED_CHANNEL_TIMEOUT"
+ );
+ assert!(started.elapsed() < Duration::from_secs(1));
+ struct Closed;
+ impl Write for Closed {
+ fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
+ Ok(0)
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+ assert_eq!(
+ write_frame(&mut Closed, b"registration").unwrap_err(),
+ "PROTECTED_CHANNEL_CLOSED"
+ );
+}
diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rs
index df95e38a..eb63836b 100644
--- a/apps/desktop/src-tauri/src/bridge.rs
+++ b/apps/desktop/src-tauri/src/bridge.rs
@@ -47,6 +47,9 @@ mod web_confirmation;
use web_confirmation::*;
mod window_behavior;
use window_behavior::*;
+mod updates;
+use updates::*;
+mod shutdown;
pub struct DesktopState(
pub Arc<Mutex<Option<Session>>>,
pub Arc<StartupState>,
@@ -837,6 +840,14 @@ pub fn run() {
app.manage(diagnostics);
app.manage(WebConfirmationState::default());
app.manage(WorkerDependencyConfirmationState::default());
+ #[cfg(target_os = "macos")]
+ app.manage(crate::updates::UpdateState::new(
+ app.config()
+ .version
+ .clone()
+ .unwrap_or_else(|| env!("CARGO_PKG_VERSION").into()),
+ root.clone().ok(),
+ ));
// The single-host desktop.lock is taken synchronously, before any window exists:
// a duplicate host hands off and exits here instead of presenting dead UI. Every
// other acquisition failure keeps its existing async startup diagnostics.
@@ -889,13 +900,15 @@ pub fn run() {
app.manage(start_session(
diagnostic_handle,
root.clone().ok(),
- move |cancelled| {
+ move |cancelled, upgrade_progress| {
if duplicate {
// The duplicate never touches the lock or starts a daemon again; its only
// job was the handoff above.
return Err("DESKTOP_ALREADY_RUNNING".into());
}
let root = root?;
+ let native_diagnostics =
+ native_diagnostics.with_upgrade_progress(upgrade_progress);
let diagnostics = &native_diagnostics;
let binary = std::env::current_exe()
.map_err(|_| "DAEMON_BINARY_UNAVAILABLE")?
@@ -1009,6 +1022,11 @@ pub fn run() {
diagnostic_status,
startup_status,
open_startup_recovery_directory,
+ update_status,
+ update_check,
+ update_download,
+ update_install,
+ update_cancel,
set_diagnostic_level,
open_diagnostic_directory,
open_external_url,
@@ -1047,15 +1065,7 @@ pub fn run() {
}
}
}
- if let tauri::RunEvent::Exit = event {
- let state = handle.state::<DesktopState>();
- state.1.cancelled.store(true, Ordering::SeqCst);
- tauri::async_runtime::block_on(async {
- drop(state.0.lock().await.take());
- });
- // The resident child is gone by now; flush this process's own bounded report.
- handle.state::<DiagnosticsState>().shutdown();
- }
+ shutdown::on_run_event(handle, &event);
});
}
diff --git a/apps/desktop/src-tauri/src/bridge/shutdown.rs b/apps/desktop/src-tauri/src/bridge/shutdown.rs
new file mode 100644
index 00000000..e995957b
--- /dev/null
+++ b/apps/desktop/src-tauri/src/bridge/shutdown.rs
@@ -0,0 +1,29 @@
+//! Release the resident while the macOS event loop can still complete pending IPC replies.
+use super::{DesktopState, DiagnosticsState};
+use std::sync::atomic::Ordering;
+use tauri::{AppHandle, Manager, RunEvent};
+
+pub(super) fn on_run_event(handle: &AppHandle, event: &RunEvent) {
+ match event {
+ RunEvent::ExitRequested { api, .. } => {
+ let state = handle.state::<DesktopState>();
+ if state.1.cancelled.swap(true, Ordering::SeqCst) {
+ // Another quit request cannot bypass the still-running shutdown. The final
+ // app.exit below is admitted only after the owned resident has been dropped.
+ if state.0.try_lock().map_or(true, |session| session.is_some()) {
+ api.prevent_exit();
+ }
+ return;
+ }
+ api.prevent_exit();
+ let sessions = state.0.clone();
+ let handle = handle.clone();
+ tauri::async_runtime::spawn(async move {
+ drop(sessions.lock().await.take());
+ handle.exit(0);
+ });
+ }
+ RunEvent::Exit => handle.state::<DiagnosticsState>().shutdown(),
+ _ => {}
+ }
+}
diff --git a/apps/desktop/src-tauri/src/bridge/startup.rs b/apps/desktop/src-tauri/src/bridge/startup.rs
index 9099af4a..dc5d3ea4 100644
--- a/apps/desktop/src-tauri/src/bridge/startup.rs
+++ b/apps/desktop/src-tauri/src/bridge/startup.rs
@@ -14,12 +14,19 @@ pub struct StartupState {
pub(super) error: OnceLock<String>,
pub(super) cancelled: AtomicBool,
pub(super) data_root: Option<PathBuf>,
+ pub(super) upgrade_progress:
+ Arc<std::sync::Mutex<Option<hiroute_host_runtime::StorageUpgradePhase>>>,
}
pub(super) fn start_session(
diagnostics: DiagnosticHandle,
data_root: Option<PathBuf>,
- initialize: impl FnOnce(&AtomicBool) -> Result<Session, String> + Send + 'static,
+ initialize: impl FnOnce(
+ &AtomicBool,
+ Arc<std::sync::Mutex<Option<hiroute_host_runtime::StorageUpgradePhase>>>,
+ ) -> Result<Session, String>
+ + Send
+ + 'static,
) -> DesktopState {
let state = DesktopState(
Arc::new(Mutex::new(None)),
@@ -33,10 +40,12 @@ pub(super) fn start_session(
// Commands must await initialization without holding the WebView event loop.
let mut session = state.0.clone().try_lock_owned().expect("new session lock");
let startup = state.1.clone();
- tauri::async_runtime::spawn_blocking(move || match initialize(&startup.cancelled) {
- Ok(ready) => *session = Some(ready),
- Err(error) => {
- let _ = startup.error.set(error);
+ tauri::async_runtime::spawn_blocking(move || {
+ match initialize(&startup.cancelled, startup.upgrade_progress.clone()) {
+ Ok(ready) => *session = Some(ready),
+ Err(error) => {
+ let _ = startup.error.set(error);
+ }
}
});
state
@@ -49,6 +58,26 @@ pub struct StartupReport {
#[serde(skip_serializing_if = "Option::is_none")]
code: Option<String>,
recovery_available: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ backup_directory: Option<PathBuf>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ upgrade_phase: Option<hiroute_host_runtime::StorageUpgradePhase>,
+}
+
+fn complete_upgrade_backup(root: &std::path::Path) -> Option<PathBuf> {
+ // The storage startup boundary publishes the source outside storage, under the host's
+ // existing private data root. No path from JSON or from the WebView is used for opening.
+ let backup = root.join("storage.upgrade-backups/migration-set/source");
+ let directory = hiroute_diagnostics::files::PrivateDir::open_existing(&backup).ok()?;
+ let mut manifest_file = directory.open_read("source-backup.json").ok()??;
+ if manifest_file.len() > 4 * 1024 * 1024 {
+ return None;
+ }
+ let manifest: serde_json::Value =
+ serde_json::from_slice(&manifest_file.read_prefix(4 * 1024 * 1024).ok()?).ok()?;
+ manifest_file.recheck().ok()?;
+ (manifest["schema"] == "hiroute.upgrade-source-backup/v1" && manifest["complete"] == true)
+ .then_some(backup)
}
#[tauri::command]
@@ -65,6 +94,12 @@ pub async fn startup_status(
root.is_absolute()
&& hiroute_diagnostics::files::PrivateDir::open_existing(root).is_ok()
}),
+ backup_directory: state
+ .1
+ .data_root
+ .as_deref()
+ .and_then(complete_upgrade_backup),
+ upgrade_phase: state.1.upgrade_progress.lock().ok().and_then(|p| *p),
});
}
let ready = state.0.try_lock().is_ok_and(|session| session.is_some());
@@ -72,6 +107,12 @@ pub async fn startup_status(
state: if ready { "ready" } else { "starting" },
code: None,
recovery_available: false,
+ backup_directory: None,
+ upgrade_phase: if ready {
+ None
+ } else {
+ state.1.upgrade_progress.lock().ok().and_then(|p| *p)
+ },
})
}
@@ -94,7 +135,8 @@ pub async fn open_startup_recovery_directory(
.ok_or("PRIVATE_PATH_UNAVAILABLE")?;
hiroute_diagnostics::files::PrivateDir::open_existing(&root)
.map_err(|_| "PRIVATE_PATH_INVALID")?;
- super::diagnostics::open_in_file_manager(&root)
+ let directory = complete_upgrade_backup(&root).unwrap_or(root);
+ super::diagnostics::open_in_file_manager(&directory)
.map_err(|_| "STARTUP_RECOVERY_OPEN_FAILED".into())
}
@@ -104,11 +146,40 @@ mod tests {
use std::sync::atomic::Ordering;
use std::time::Duration;
+ #[test]
+ #[cfg(unix)]
+ fn recovery_directory_requires_a_private_complete_published_source() {
+ use std::os::unix::fs::{PermissionsExt, symlink};
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().join("data");
+ let backup = root.join("storage.upgrade-backups/migration-set/source");
+ hiroute_diagnostics::files::PrivateDir::open_or_create(&backup).unwrap();
+ let manifest = backup.join("source-backup.json");
+ assert_eq!(complete_upgrade_backup(&root), None);
+ std::fs::write(
+ &manifest,
+ br#"{"schema":"hiroute.upgrade-source-backup/v1","complete":false}"#,
+ )
+ .unwrap();
+ std::fs::set_permissions(&manifest, std::fs::Permissions::from_mode(0o600)).unwrap();
+ assert_eq!(complete_upgrade_backup(&root), None);
+ std::fs::write(
+ &manifest,
+ br#"{"schema":"hiroute.upgrade-source-backup/v1","complete":true}"#,
+ )
+ .unwrap();
+ assert_eq!(complete_upgrade_backup(&root), Some(backup.clone()));
+ let other = backup.join("other.json");
+ std::fs::rename(&manifest, &other).unwrap();
+ symlink(&other, &manifest).unwrap();
+ assert_eq!(complete_upgrade_backup(&root), None);
+ }
+
#[tokio::test]
async fn startup_does_not_block_the_caller_or_expose_an_uninitialized_session() {
let (entered, started) = tokio::sync::oneshot::channel();
let (release, wait) = std::sync::mpsc::channel();
- let state = start_session(DiagnosticHandle::noop(), None, move |_| {
+ let state = start_session(DiagnosticHandle::noop(), None, move |_, _| {
let _ = entered.send(());
wait.recv().unwrap();
Err("DAEMON_READY_INVALID".into())
@@ -130,7 +201,7 @@ mod tests {
#[tokio::test]
async fn exit_can_cancel_pending_startup_before_waiting_for_session_cleanup() {
let (entered, started) = tokio::sync::oneshot::channel();
- let state = start_session(DiagnosticHandle::noop(), None, move |cancelled| {
+ let state = start_session(DiagnosticHandle::noop(), None, move |cancelled, _| {
let _ = entered.send(());
while !cancelled.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(1));
diff --git a/apps/desktop/src-tauri/src/bridge/updates.rs b/apps/desktop/src-tauri/src/bridge/updates.rs
new file mode 100644
index 00000000..cc2d5239
--- /dev/null
+++ b/apps/desktop/src-tauri/src/bridge/updates.rs
@@ -0,0 +1,33 @@
+#[cfg(target_os = "macos")]
+pub use crate::updates::*;
+
+#[cfg(not(target_os = "macos"))]
+mod unsupported {
+ use tauri::WebviewWindow;
+ fn denied(window: &WebviewWindow) -> Result<serde_json::Value, String> {
+ super::super::main_window(window)?;
+ Err("UPGRADE_PLATFORM_UNSUPPORTED".into())
+ }
+ #[tauri::command]
+ pub fn update_status(window: WebviewWindow) -> Result<serde_json::Value, String> {
+ denied(&window)
+ }
+ #[tauri::command]
+ pub fn update_check(window: WebviewWindow) -> Result<serde_json::Value, String> {
+ denied(&window)
+ }
+ #[tauri::command]
+ pub fn update_download(window: WebviewWindow) -> Result<serde_json::Value, String> {
+ denied(&window)
+ }
+ #[tauri::command]
+ pub fn update_install(window: WebviewWindow) -> Result<serde_json::Value, String> {
+ denied(&window)
+ }
+ #[tauri::command]
+ pub fn update_cancel(window: WebviewWindow) -> Result<serde_json::Value, String> {
+ denied(&window)
+ }
+}
+#[cfg(not(target_os = "macos"))]
+pub use unsupported::*;
diff --git a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs
index 480e1ec6..5184364d 100644
--- a/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs
+++ b/apps/desktop/src-tauri/src/bridge_command_acl_tests.rs
@@ -146,6 +146,16 @@ fn diagnostic_commands_are_exposed_to_the_main_window() {
fn startup_recovery_commands_are_exposed_to_the_main_window() {
assert_commands(STARTUP_COMMANDS);
}
+#[test]
+fn updater_commands_accept_only_native_actions_in_the_main_window() {
+ assert_commands(&[
+ "update_status",
+ "update_check",
+ "update_download",
+ "update_install",
+ "update_cancel",
+ ]);
+}
#[test]
fn external_urls_use_only_the_restricted_main_window_command() {
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index f4a64397..f510845e 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -23,6 +23,8 @@ pub mod operation_observation;
#[cfg(unix)]
mod resident_ownership;
pub mod session;
+#[cfg(all(target_os = "macos", feature = "desktop-runtime"))]
+pub mod updates;
pub fn random_id() -> Result<String, String> {
let mut bytes = zeroize::Zeroizing::new([0u8; 32]);
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index bbc0306e..3305ce7f 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -1,4 +1,8 @@
#![forbid(unsafe_code)]
fn main() {
+ #[cfg(target_os = "macos")]
+ if let Some(result) = hiroute_desktop::updates::finish_update_if_requested() {
+ std::process::exit(if result.is_ok() { 0 } else { 1 });
+ }
hiroute_desktop::bridge::run();
}
diff --git a/apps/desktop/src-tauri/src/native_diagnostics.rs b/apps/desktop/src-tauri/src/native_diagnostics.rs
index bb85b45d..36e3288a 100644
--- a/apps/desktop/src-tauri/src/native_diagnostics.rs
+++ b/apps/desktop/src-tauri/src/native_diagnostics.rs
@@ -38,6 +38,8 @@ pub struct NativeDiagnostics {
pub root: PathBuf,
pub parent_session: Option<SessionId>,
port: DiagnosticsPort,
+ upgrade_progress:
+ Option<std::sync::Arc<std::sync::Mutex<Option<hiroute_host_runtime::StorageUpgradePhase>>>>,
}
impl NativeDiagnostics {
@@ -46,6 +48,7 @@ impl NativeDiagnostics {
root,
parent_session,
port,
+ upgrade_progress: None,
}
}
@@ -58,6 +61,23 @@ impl NativeDiagnostics {
self.port.clone()
}
+ pub fn with_upgrade_progress(
+ mut self,
+ progress: std::sync::Arc<
+ std::sync::Mutex<Option<hiroute_host_runtime::StorageUpgradePhase>>,
+ >,
+ ) -> Self {
+ self.upgrade_progress = Some(progress);
+ self
+ }
+ pub(super) fn report_upgrade(&self, phase: hiroute_host_runtime::StorageUpgradePhase) {
+ if let Some(progress) = &self.upgrade_progress
+ && let Ok(mut current) = progress.lock()
+ {
+ *current = Some(phase);
+ }
+ }
+
/// A process-lifetime context for modules that need a diagnostic anchor, for example
/// the shared Local Control client. Long-lived callers derive per-unit-of-work children.
pub fn context(&self) -> hiroute_diagnostics::context::DiagnosticContext {
diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rs
new file mode 100644
index 00000000..60c1fc44
--- /dev/null
+++ b/apps/desktop/src-tauri/src/updates.rs
@@ -0,0 +1,392 @@
+//! Native updater lifecycle. WebView chooses actions; source, paths and trust stay native.
+use hiroute_host_runtime::{
+ DesktopPackageIdentity, DesktopRelease, UpgradeAction, verify_desktop_app,
+};
+use serde::Serialize;
+use std::{
+ path::PathBuf,
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+};
+use tauri::{Manager, State, WebviewWindow};
+mod download;
+mod installer;
+pub use installer::finish_update_if_requested;
+
+#[derive(Clone)]
+struct PreparedUpdate {
+ release: DesktopRelease,
+ current: PathBuf,
+ staged: PathBuf,
+ stage_root: PathBuf,
+ download_root: PathBuf,
+ old_identity: DesktopPackageIdentity,
+ new_identity: DesktopPackageIdentity,
+}
+impl PreparedUpdate {
+ fn revalidate(&self) -> Result<(), String> {
+ if verify_desktop_app(&self.current, "ai.hiroute.desktop", None, None)? != self.old_identity
+ || verify_desktop_app(
+ &self.staged,
+ "ai.hiroute.desktop",
+ Some(&self.release),
+ None,
+ )? != self.new_identity
+ {
+ return Err("UPGRADE_PACKAGE_CHANGED".into());
+ }
+ Ok(())
+ }
+}
+#[derive(Clone, Serialize)]
+pub struct UpdateView {
+ current_version: String,
+ phase: String,
+ available: Option<DesktopRelease>,
+ downloaded_bytes: u64,
+ active_calls: u64,
+ active_tasks: u64,
+ error: Option<String>,
+ can_install: bool,
+ package_ready: bool,
+}
+struct UpdateInner {
+ view: UpdateView,
+ prepared: Option<PreparedUpdate>,
+}
+pub struct Updates {
+ inner: Mutex<UpdateInner>,
+ cancelled: AtomicBool,
+ current_app: Option<PathBuf>,
+ data_root: Option<PathBuf>,
+}
+pub struct UpdateState(pub Arc<Updates>);
+impl UpdateState {
+ pub fn new(current_version: String, data_root: Option<PathBuf>) -> Self {
+ let current_app = std::env::current_exe().ok().and_then(|p| {
+ (p.file_name()? == "hiroute-desktop"
+ && p.parent()?.file_name()? == "MacOS"
+ && p.parent()?.parent()?.file_name()? == "Contents")
+ .then(|| {
+ p.parent()
+ .unwrap()
+ .parent()
+ .unwrap()
+ .parent()
+ .unwrap()
+ .to_path_buf()
+ })
+ .and_then(|app| std::fs::canonicalize(app).ok())
+ });
+ let current_version = current_app
+ .as_ref()
+ .and_then(|app| {
+ let output = std::process::Command::new("/usr/bin/plutil")
+ .args(["-extract", "CFBundleShortVersionString", "raw", "-o", "-"])
+ .arg(app.join("Contents/Info.plist"))
+ .output()
+ .ok()?;
+ output
+ .status
+ .success()
+ .then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned())
+ })
+ .unwrap_or(current_version);
+ Self(Arc::new(Updates {
+ inner: Mutex::new(UpdateInner {
+ view: UpdateView {
+ current_version,
+ phase: "idle".into(),
+ available: None,
+ downloaded_bytes: 0,
+ active_calls: 0,
+ active_tasks: 0,
+ error: None,
+ can_install: current_app.is_some(),
+ package_ready: false,
+ },
+ prepared: None,
+ }),
+ cancelled: AtomicBool::new(false),
+ current_app,
+ data_root,
+ }))
+ }
+}
+impl Updates {
+ fn edit(&self, update: impl FnOnce(&mut UpdateView)) -> Result<(), String> {
+ update(
+ &mut self
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?
+ .view,
+ );
+ Ok(())
+ }
+ fn view(&self) -> Result<UpdateView, String> {
+ Ok(self
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?
+ .view
+ .clone())
+ }
+ fn begin(&self, phase: &str) -> Result<UpdateView, String> {
+ let mut inner = self.inner.lock().map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;
+ if matches!(
+ inner.view.phase.as_str(),
+ "checking" | "downloading" | "verifying" | "waiting" | "installing"
+ ) {
+ return Err("UPGRADE_BUSY".into());
+ }
+ self.cancelled.store(false, Ordering::SeqCst);
+ inner.view.phase = phase.into();
+ inner.view.error = None;
+ Ok(inner.view.clone())
+ }
+ fn fail(&self, error: String) {
+ let _ = self.edit(|v| {
+ v.phase = "failed".into();
+ v.error = Some(error);
+ });
+ }
+}
+fn main_window(window: &WebviewWindow) -> Result<(), String> {
+ if window.label() == "main" {
+ Ok(())
+ } else {
+ Err("WINDOW_DENIED".into())
+ }
+}
+#[tauri::command]
+pub fn update_status(
+ window: WebviewWindow,
+ state: State<'_, UpdateState>,
+) -> Result<UpdateView, String> {
+ main_window(&window)?;
+ state.0.view()
+}
+#[tauri::command]
+pub async fn update_check(
+ window: WebviewWindow,
+ state: State<'_, UpdateState>,
+) -> Result<UpdateView, String> {
+ main_window(&window)?;
+ let view = state.0.begin("checking")?;
+ let arch = if cfg!(target_arch = "aarch64") {
+ "arm64"
+ } else {
+ "x86_64"
+ };
+ match download::check(&view.current_version, arch).await {
+ Ok(release) => {
+ let mut inner = state
+ .0
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;
+ let reusable = inner.prepared.as_ref().is_some_and(|p| {
+ release
+ .as_ref()
+ .is_some_and(|r| p.release.version == r.version && p.release.sha256 == r.sha256)
+ });
+ if !reusable {
+ inner.prepared = None;
+ }
+ inner.view.available = release;
+ inner.view.package_ready = reusable;
+ inner.view.phase = if reusable {
+ "ready"
+ } else if inner.view.available.is_some() {
+ "available"
+ } else {
+ "current"
+ }
+ .into();
+ }
+ Err(error) => state.0.fail(error),
+ }
+ state.0.view()
+}
+#[tauri::command]
+pub async fn update_download(
+ window: WebviewWindow,
+ state: State<'_, UpdateState>,
+) -> Result<UpdateView, String> {
+ main_window(&window)?;
+ let release = {
+ let mut inner = state
+ .0
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;
+ if !matches!(inner.view.phase.as_str(), "available" | "failed") || inner.prepared.is_some()
+ {
+ return Err("UPGRADE_DOWNLOAD_NOT_READY".into());
+ }
+ let release = inner
+ .view
+ .available
+ .clone()
+ .ok_or("UPGRADE_NOT_AVAILABLE")?;
+ inner.view.phase = "downloading".into();
+ inner.view.error = None;
+ inner.view.downloaded_bytes = 0;
+ state.0.cancelled.store(false, Ordering::SeqCst);
+ release
+ };
+ let result = download::prepare(&state.0, release).await;
+ match result {
+ Ok(prepared) => {
+ let mut inner = state
+ .0
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;
+ inner.prepared = Some(prepared);
+ inner.view.phase = "ready".into();
+ inner.view.package_ready = true;
+ }
+ Err(error) if error == "UPGRADE_CANCELLED" => {
+ state.0.edit(|v| v.phase = "available".into())?
+ }
+ Err(error) => state.0.fail(error),
+ }
+ state.0.view()
+}
+#[tauri::command]
+pub fn update_cancel(
+ window: WebviewWindow,
+ state: State<'_, UpdateState>,
+) -> Result<UpdateView, String> {
+ main_window(&window)?;
+ let inner = state
+ .0
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;
+ if !matches!(
+ inner.view.phase.as_str(),
+ "downloading" | "verifying" | "waiting"
+ ) {
+ return Err("UPGRADE_CANCEL_UNAVAILABLE".into());
+ }
+ state.0.cancelled.store(true, Ordering::SeqCst);
+ Ok(inner.view.clone())
+}
+#[tauri::command]
+pub async fn update_install(
+ window: WebviewWindow,
+ state: State<'_, UpdateState>,
+ desktop: State<'_, crate::bridge::DesktopState>,
+) -> Result<UpdateView, String> {
+ main_window(&window)?;
+ let prepared = {
+ let mut inner = state
+ .0
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;
+ if !matches!(inner.view.phase.as_str(), "ready" | "failed") {
+ return Err("UPGRADE_INSTALL_NOT_READY".into());
+ }
+ let prepared = inner.prepared.clone().ok_or("UPGRADE_INSTALL_NOT_READY")?;
+ inner.view.phase = "waiting".into();
+ inner.view.error = None;
+ state.0.cancelled.store(false, Ordering::SeqCst);
+ prepared
+ };
+ let updates = state.0.clone();
+ let sessions = desktop.0.clone();
+ let handle = window.app_handle().clone();
+ tauri::async_runtime::spawn(async move {
+ if let Err(error) = install(&updates, &sessions, &handle, prepared).await {
+ // Resume only while the owned daemon is still serving. An already requested
+ // orderly shutdown must finish; it cannot be converted into a new live session.
+ let _ = resident_call(&sessions, |r| {
+ if !r.upgrade_stop_requested() {
+ r.upgrade_status(UpgradeAction::Cancel)?;
+ }
+ Ok(())
+ })
+ .await;
+ updates.fail(error);
+ }
+ });
+ state.0.view()
+}
+type Sessions = Arc<tokio::sync::Mutex<Option<crate::session::Session>>>;
+async fn resident_call<T: Send + 'static>(
+ sessions: &Sessions,
+ call: impl FnOnce(&mut crate::bootstrap::Resident) -> Result<T, String> + Send + 'static,
+) -> Result<T, String> {
+ let mut session = sessions.clone().lock_owned().await;
+ tokio::task::spawn_blocking(move || {
+ call(&mut session.as_mut().ok_or("RESIDENT_UNAVAILABLE")?.resident)
+ })
+ .await
+ .map_err(|_| "UPGRADE_RESIDENT_UNAVAILABLE")?
+}
+async fn install(
+ updates: &Updates,
+ sessions: &Sessions,
+ app: &tauri::AppHandle,
+ prepared: PreparedUpdate,
+) -> Result<(), String> {
+ resident_call(sessions, |r| {
+ if r.upgrade_stop_requested() {
+ Err("UPGRADE_RESIDENT_STOPPING_RESTART_REQUIRED".into())
+ } else {
+ Ok(())
+ }
+ })
+ .await?;
+ let root = updates
+ .data_root
+ .clone()
+ .ok_or("PRIVATE_PATH_UNAVAILABLE")?;
+ let copy = prepared.clone();
+ let handoff = tokio::task::spawn_blocking(move || {
+ copy.revalidate()?;
+ installer::prepare(&root, &copy)
+ })
+ .await
+ .map_err(|_| "UPGRADE_VERIFY_FAILED")??;
+ resident_call(sessions, |r| r.upgrade_status(UpgradeAction::Prepare)).await?;
+ loop {
+ if updates.cancelled.load(Ordering::SeqCst) {
+ resident_call(sessions, |r| r.upgrade_status(UpgradeAction::Cancel)).await?;
+ updates.edit(|v| {
+ v.phase = "ready".into();
+ v.active_calls = 0;
+ v.active_tasks = 0;
+ })?;
+ return Ok(());
+ }
+ let status = resident_call(sessions, |r| r.upgrade_status(UpgradeAction::Status)).await?;
+ updates.edit(|v| {
+ v.active_calls = status.active_calls;
+ v.active_tasks = status.active_tasks;
+ })?;
+ if status.drained() {
+ let mut inner = updates
+ .inner
+ .lock()
+ .map_err(|_| "UPGRADE_STATE_UNAVAILABLE")?;
+ if !updates.cancelled.load(Ordering::SeqCst) {
+ inner.view.phase = "installing".into();
+ break;
+ }
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ }
+ resident_call(sessions, |r| r.stop_for_upgrade()).await?;
+ tokio::task::spawn_blocking(move || installer::launch(&handoff))
+ .await
+ .map_err(|_| "UPGRADE_INSTALLER_FAILED")??;
+ app.exit(0);
+ Ok(())
+}
diff --git a/apps/desktop/src-tauri/src/updates/download.rs b/apps/desktop/src-tauri/src/updates/download.rs
new file mode 100644
index 00000000..d60ef7ad
--- /dev/null
+++ b/apps/desktop/src-tauri/src/updates/download.rs
@@ -0,0 +1,244 @@
+//! Bounded native download and read-only DMG staging; existing work keeps running throughout.
+use super::{PreparedUpdate, Updates};
+use hiroute_host_runtime::{
+ DesktopRelease, MAX_RELEASE_FEED_BYTES, RELEASE_FEED, WebsiteReleasesV2, verify_desktop_app,
+};
+use sha2::{Digest, Sha256};
+use std::{
+ fs,
+ io::Write,
+ path::{Path, PathBuf},
+ process::Command,
+ sync::atomic::Ordering,
+ time::Duration,
+};
+
+fn url(production: &str) -> Result<String, String> {
+ #[cfg(all(feature = "desktop-pilot", debug_assertions))]
+ if let Ok(origin) = std::env::var("HIROUTE_PILOT_UPGRADE_ORIGIN") {
+ // Only the explicitly compiled Pilot can exercise a local unpublished candidate.
+ let parsed = reqwest::Url::parse(&origin).map_err(|_| "UPGRADE_PILOT_ORIGIN_INVALID")?;
+ if parsed.scheme() != "http"
+ || parsed.host_str() != Some("127.0.0.1")
+ || parsed.port().is_none()
+ || !parsed.username().is_empty()
+ || parsed.password().is_some()
+ || parsed.path() != "/"
+ || parsed.query().is_some()
+ || parsed.fragment().is_some()
+ {
+ return Err("UPGRADE_PILOT_ORIGIN_INVALID".into());
+ }
+ let path = production
+ .strip_prefix("https://hiroute.ai/")
+ .ok_or("UPGRADE_URL_INVALID")?;
+ return Ok(format!(
+ "{}{path}",
+ origin.trim_end_matches('/').to_owned() + "/"
+ ));
+ }
+ Ok(production.into())
+}
+fn client() -> Result<reqwest::Client, String> {
+ reqwest::Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .connect_timeout(Duration::from_secs(10))
+ .read_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(600))
+ .user_agent("HiRoute-Updater")
+ .build()
+ .map_err(|_| "UPGRADE_NETWORK_UNAVAILABLE".into())
+}
+pub(super) async fn check(
+ current: &str,
+ architecture: &str,
+) -> Result<Option<DesktopRelease>, String> {
+ let mut response = client()?
+ .get(url(RELEASE_FEED)?)
+ .send()
+ .await
+ .map_err(|_| "UPGRADE_CATALOG_UNAVAILABLE")?;
+ if !response.status().is_success()
+ || response
+ .content_length()
+ .is_some_and(|s| s > MAX_RELEASE_FEED_BYTES as u64)
+ {
+ return Err("UPGRADE_CATALOG_UNAVAILABLE".into());
+ }
+ let mut bytes = Vec::new();
+ while let Some(chunk) = response
+ .chunk()
+ .await
+ .map_err(|_| "UPGRADE_CATALOG_UNAVAILABLE")?
+ {
+ if bytes.len() + chunk.len() > MAX_RELEASE_FEED_BYTES {
+ return Err("UPGRADE_CATALOG_INVALID".into());
+ }
+ bytes.extend_from_slice(&chunk);
+ }
+ WebsiteReleasesV2::parse(&bytes)?
+ .desktop_update(current, architecture)
+ .map_err(Into::into)
+}
+
+pub(super) async fn prepare(
+ state: &Updates,
+ release: DesktopRelease,
+) -> Result<PreparedUpdate, String> {
+ release.revision_prefix()?;
+ let app = state
+ .current_app
+ .clone()
+ .ok_or("UPGRADE_INSTALLED_APP_REQUIRED")?;
+ let root = state.data_root.clone().ok_or("PRIVATE_PATH_UNAVAILABLE")?;
+ let parent = app.parent().ok_or("UPGRADE_APP_PATH_INVALID")?;
+ let id = crate::random_id()?;
+ let download_root = root.join("updates").join(&id);
+ crate::bootstrap::private_dir(&download_root)?;
+ let stage_root = parent.join(format!(".HiRoute-update-{id}"));
+ crate::bootstrap::private_dir(&stage_root)?;
+ let dmg = download_root.join("package.dmg");
+ let result = async {
+ let mut response = client()?
+ .get(url(&release.download_url())?)
+ .send()
+ .await
+ .map_err(|_| "UPGRADE_DOWNLOAD_FAILED")?;
+ if !response.status().is_success()
+ || response.content_length().is_some_and(|s| s != release.size)
+ {
+ return Err("UPGRADE_DOWNLOAD_SIZE_MISMATCH".to_owned());
+ }
+ use std::os::unix::fs::OpenOptionsExt;
+ let mut output = fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&dmg)
+ .map_err(|_| "UPGRADE_DOWNLOAD_WRITE_FAILED")?;
+ let mut hash = Sha256::new();
+ let mut downloaded = 0u64;
+ while let Some(chunk) = response
+ .chunk()
+ .await
+ .map_err(|_| "UPGRADE_DOWNLOAD_FAILED")?
+ {
+ if state.cancelled.load(Ordering::SeqCst) {
+ return Err("UPGRADE_CANCELLED".into());
+ }
+ downloaded += chunk.len() as u64;
+ if downloaded > release.size {
+ return Err("UPGRADE_DOWNLOAD_SIZE_MISMATCH".into());
+ }
+ output
+ .write_all(&chunk)
+ .map_err(|_| "UPGRADE_DOWNLOAD_WRITE_FAILED")?;
+ hash.update(&chunk);
+ state.edit(|view| view.downloaded_bytes = downloaded)?;
+ }
+ output
+ .sync_all()
+ .map_err(|_| "UPGRADE_DOWNLOAD_WRITE_FAILED")?;
+ if downloaded != release.size || format!("{:x}", hash.finalize()) != release.sha256 {
+ return Err("UPGRADE_DOWNLOAD_DIGEST_MISMATCH".into());
+ }
+ state.edit(|view| view.phase = "verifying".into())?;
+ let source = app.clone();
+ let staged = stage_root.join("HiRoute.app");
+ let next = staged.clone();
+ let image = dmg.clone();
+ let mount = download_root.join("volume");
+ let selected = release.clone();
+ let (old_identity, new_identity) = tokio::task::spawn_blocking(move || {
+ let old = verify_desktop_app(&source, "ai.hiroute.desktop", None, None)?;
+ let new = stage_dmg(&image, &mount, &next, &selected)?;
+ Ok::<_, String>((old, new))
+ })
+ .await
+ .map_err(|_| "UPGRADE_VERIFY_FAILED")??;
+ if state.cancelled.load(Ordering::SeqCst) {
+ return Err("UPGRADE_CANCELLED".into());
+ }
+ Ok(PreparedUpdate {
+ release,
+ current: app,
+ staged,
+ stage_root: stage_root.clone(),
+ download_root: download_root.clone(),
+ old_identity,
+ new_identity,
+ })
+ }
+ .await;
+ if result.is_err() {
+ // Only this attempt's random private staging directories are removed.
+ let _ = fs::remove_dir_all(&stage_root);
+ let _ = fs::remove_dir_all(&download_root);
+ }
+ result
+}
+fn command(program: &str, arguments: &[&std::ffi::OsStr]) -> Result<(), String> {
+ let result = Command::new(program)
+ .args(arguments)
+ .output()
+ .map_err(|_| "UPGRADE_VERIFY_FAILED")?;
+ if result.status.success() {
+ Ok(())
+ } else {
+ Err("UPGRADE_VERIFY_FAILED".into())
+ }
+}
+fn stage_dmg(
+ image: &Path,
+ mount: &Path,
+ staged: &Path,
+ release: &DesktopRelease,
+) -> Result<hiroute_host_runtime::DesktopPackageIdentity, String> {
+ use std::ffi::OsStr as O;
+ command("/usr/bin/hdiutil", &[O::new("verify"), image.as_os_str()])?;
+ command(
+ "/usr/bin/hdiutil",
+ &[
+ O::new("attach"),
+ O::new("-readonly"),
+ O::new("-nobrowse"),
+ O::new("-mountpoint"),
+ mount.as_os_str(),
+ image.as_os_str(),
+ ],
+ )?;
+ let result = (|| {
+ let visible = fs::read_dir(mount)
+ .map_err(|_| "UPGRADE_DMG_INVALID")?
+ .map(|e| e.map(|e| e.file_name()))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|_| "UPGRADE_DMG_INVALID")?;
+ let visible = visible
+ .into_iter()
+ .filter(|n| !n.to_string_lossy().starts_with('.'))
+ .collect::<std::collections::BTreeSet<_>>();
+ if visible
+ != ["HiRoute.app".into(), "Applications".into()]
+ .into_iter()
+ .collect()
+ || fs::read_link(mount.join("Applications")).map_err(|_| "UPGRADE_DMG_INVALID")?
+ != PathBuf::from("/Applications")
+ {
+ return Err("UPGRADE_DMG_INVALID".into());
+ }
+ let app = mount.join("HiRoute.app");
+ verify_desktop_app(&app, "ai.hiroute.desktop", Some(release), None)?;
+ command("/usr/bin/ditto", &[app.as_os_str(), staged.as_os_str()])?;
+ Ok(verify_desktop_app(
+ staged,
+ "ai.hiroute.desktop",
+ Some(release),
+ None,
+ )?)
+ })();
+ let detached = command("/usr/bin/hdiutil", &[O::new("detach"), mount.as_os_str()]);
+ if detached.is_err() {
+ return Err("UPGRADE_DMG_DETACH_FAILED".into());
+ }
+ result
+}
diff --git a/apps/desktop/src-tauri/src/updates/installer.rs b/apps/desktop/src-tauri/src/updates/installer.rs
new file mode 100644
index 00000000..e4d20c06
--- /dev/null
+++ b/apps/desktop/src-tauri/src/updates/installer.rs
@@ -0,0 +1,266 @@
+//! Same-package installer: no WebView paths, privilege escalation, or automatic data rollback.
+use super::PreparedUpdate;
+use hiroute_diagnostics::files::PrivateDir;
+use hiroute_host_runtime::{DesktopPackageIdentity, DesktopRelease};
+use serde::{Deserialize, Serialize};
+use std::{
+ fs,
+ io::Write,
+ path::{Path, PathBuf},
+ process::{Command, Stdio},
+ time::{Duration, Instant},
+};
+
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+struct Handoff {
+ schema: String,
+ parent_pid: u32,
+ data_root: PathBuf,
+ current: PathBuf,
+ staged: PathBuf,
+ previous: PathBuf,
+ release: DesktopRelease,
+ old_identity: DesktopPackageIdentity,
+ new_identity: DesktopPackageIdentity,
+}
+fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
+ use std::os::unix::fs::OpenOptionsExt;
+ let mut file = fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(path)
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
+ file.write_all(bytes)
+ .and_then(|_| file.sync_all())
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED".into())
+}
+pub(super) fn prepare(root: &Path, update: &PreparedUpdate) -> Result<PathBuf, String> {
+ let id = crate::random_id()?;
+ let directory = update.download_root.join(format!("install-{id}"));
+ crate::bootstrap::private_dir(&directory)?;
+ let previous = update
+ .current
+ .parent()
+ .ok_or("UPGRADE_APP_PATH_INVALID")?
+ .join(format!(
+ ".HiRoute-previous-{}-{id}.app",
+ &update.old_identity.revision[..12]
+ ));
+ let handoff = Handoff {
+ schema: "hiroute.desktop-upgrade-handoff/v1".into(),
+ parent_pid: std::process::id(),
+ data_root: root.to_path_buf(),
+ current: update.current.clone(),
+ staged: update.staged.clone(),
+ previous,
+ release: update.release.clone(),
+ old_identity: update.old_identity.clone(),
+ new_identity: update.new_identity.clone(),
+ };
+ let path = directory.join("handoff.json");
+ write_private(
+ &path,
+ &serde_json::to_vec(&handoff).map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?,
+ )?;
+ fs::File::open(&directory)
+ .and_then(|f| f.sync_all())
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
+ Ok(path)
+}
+pub(super) fn launch(path: &Path) -> Result<(), String> {
+ let directory = path.parent().ok_or("UPGRADE_INSTALLER_INVALID")?;
+ use std::os::unix::fs::OpenOptionsExt;
+ let log = fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(directory.join("installer.log"))
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
+ let mut child =
+ Command::new(std::env::current_exe().map_err(|_| "UPGRADE_INSTALLER_UNAVAILABLE")?)
+ .arg("--finish-upgrade")
+ .arg(path)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(log)
+ .spawn()
+ .map_err(|_| "UPGRADE_INSTALLER_UNAVAILABLE")?;
+ let deadline = Instant::now() + Duration::from_secs(10);
+ let private = PrivateDir::open_existing(directory).map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ loop {
+ if let Some(mut ack) = private
+ .open_read("started")
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
+ {
+ if ack
+ .read_prefix(64)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
+ == b"hiroute.upgrade-installer-started/v1\n"
+ {
+ return Ok(());
+ }
+ return Err("UPGRADE_INSTALLER_INVALID".into());
+ }
+ if child
+ .try_wait()
+ .map_err(|_| "UPGRADE_INSTALLER_FAILED")?
+ .is_some()
+ || Instant::now() >= deadline
+ {
+ return Err("UPGRADE_INSTALLER_FAILED".into());
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+}
+pub fn finish_update_if_requested() -> Option<Result<(), String>> {
+ let mut arguments = std::env::args_os().skip(1);
+ if arguments.next().as_deref() != Some(std::ffi::OsStr::new("--finish-upgrade")) {
+ return None;
+ }
+ Some((|| {
+ let path = PathBuf::from(arguments.next().ok_or("UPGRADE_INSTALLER_INVALID")?);
+ if arguments.next().is_some() {
+ return Err("UPGRADE_INSTALLER_INVALID".into());
+ }
+ // Invalid arguments never authorize creating files beside an arbitrary supplied path.
+ let record = load(&path)?;
+ let result = finish(&path, record);
+ if let Err(error) = &result {
+ // Preserve a small, private result beside the handoff. No credentials or database
+ // bytes are involved; the existing manual recovery procedure remains authoritative.
+ let _ = write_private(
+ &path.with_file_name("failed.json"),
+ &serde_json::to_vec(&serde_json::json!({"code":error})).unwrap(),
+ );
+ eprintln!("{error}");
+ }
+ result
+ })())
+}
+fn load(path: &Path) -> Result<Handoff, String> {
+ if !path.is_absolute() || path.file_name() != Some("handoff.json".as_ref()) {
+ return Err("UPGRADE_INSTALLER_INVALID".into());
+ }
+ let directory = PrivateDir::open_existing(path.parent().ok_or("UPGRADE_INSTALLER_INVALID")?)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ let mut file = directory
+ .open_read("handoff.json")
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
+ .ok_or("UPGRADE_INSTALLER_INVALID")?;
+ if file.len() > 256 * 1024 {
+ return Err("UPGRADE_INSTALLER_INVALID".into());
+ }
+ let record: Handoff = serde_json::from_slice(
+ &file
+ .read_prefix(256 * 1024)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?,
+ )
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ file.recheck().map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ if record.schema != "hiroute.desktop-upgrade-handoff/v1"
+ || record.parent_pid == 0
+ || !record.data_root.is_absolute()
+ || !path.starts_with(record.data_root.join("updates"))
+ || record.current
+ != fs::canonicalize(std::env::current_exe().map_err(|_| "UPGRADE_INSTALLER_INVALID")?)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
+ .parent()
+ .and_then(Path::parent)
+ .and_then(Path::parent)
+ .ok_or("UPGRADE_INSTALLER_INVALID")?
+ || record.old_identity.app_path != record.current
+ || record.new_identity.app_path != record.staged
+ || record.staged.file_name() != Some("HiRoute.app".as_ref())
+ || record.staged.parent().and_then(Path::parent) != record.current.parent()
+ || !record
+ .staged
+ .parent()
+ .and_then(Path::file_name)
+ .is_some_and(|n| n.to_string_lossy().starts_with(".HiRoute-update-"))
+ || record.previous.parent() != record.current.parent()
+ || !record.previous.file_name().is_some_and(|n| {
+ n.to_string_lossy().starts_with(".HiRoute-previous-")
+ && n.to_string_lossy().ends_with(".app")
+ })
+ || fs::symlink_metadata(&record.previous).is_ok()
+ {
+ return Err("UPGRADE_INSTALLER_INVALID".into());
+ }
+ PrivateDir::open_existing(&record.data_root).map_err(|_| "PRIVATE_PATH_INVALID")?;
+ PrivateDir::open_existing(record.staged.parent().unwrap())
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ record.release.revision_prefix()?;
+ Ok(record)
+}
+fn finish(path: &Path, record: Handoff) -> Result<(), String> {
+ if nix::unistd::getppid().as_raw() as u32 != record.parent_pid {
+ return Err("UPGRADE_INSTALLER_PARENT_MISMATCH".into());
+ }
+ write_private(
+ &path.with_file_name("started"),
+ b"hiroute.upgrade-installer-started/v1\n",
+ )?;
+ let pid = nix::unistd::Pid::from_raw(record.parent_pid as i32);
+ let deadline = Instant::now() + Duration::from_secs(45);
+ loop {
+ match nix::sys::signal::kill(pid, None) {
+ Err(nix::errno::Errno::ESRCH) => break,
+ Err(_) => return Err("UPGRADE_INSTALLER_PARENT_UNKNOWN".into()),
+ Ok(()) if Instant::now() >= deadline => {
+ return Err("UPGRADE_DESKTOP_STOP_PENDING".into());
+ }
+ Ok(()) => std::thread::sleep(Duration::from_millis(20)),
+ }
+ }
+ // A newly launched host wins the lock and prevents replacement. Never replace underneath it.
+ let _lock = crate::bootstrap::acquire_host_lock(&record.data_root)?;
+ if hiroute_host_runtime::verify_desktop_app(&record.current, "ai.hiroute.desktop", None, None)?
+ != record.old_identity
+ || hiroute_host_runtime::verify_desktop_app(
+ &record.staged,
+ "ai.hiroute.desktop",
+ Some(&record.release),
+ None,
+ )? != record.new_identity
+ {
+ return Err("UPGRADE_PACKAGE_CHANGED".into());
+ }
+ fs::rename(&record.current, &record.previous).map_err(|_| "UPGRADE_REPLACE_FAILED")?;
+ if fs::rename(&record.staged, &record.current).is_err() {
+ // The data has not been touched. Restore the displaced App name if the second rename
+ // itself fails, retaining all staging bytes and the manual recovery package.
+ fs::rename(&record.previous, &record.current).map_err(|_| "UPGRADE_APP_RESTORE_FAILED")?;
+ return Err("UPGRADE_REPLACE_FAILED".into());
+ }
+ fs::File::open(record.current.parent().unwrap())
+ .and_then(|f| f.sync_all())
+ .map_err(|_| "UPGRADE_REPLACE_SYNC_FAILED")?;
+ write_private(
+ &path.with_file_name("installed.json"),
+ &serde_json::to_vec(
+ &serde_json::json!({"version":record.release.version,"previous_app":record.previous}),
+ )
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?,
+ )?;
+ drop(_lock);
+ #[cfg(all(feature = "desktop-pilot", debug_assertions))]
+ let mut restart = Command::new(record.current.join("Contents/MacOS/hiroute-desktop"));
+ #[cfg(not(all(feature = "desktop-pilot", debug_assertions)))]
+ let mut restart = {
+ let mut command = Command::new("/usr/bin/open");
+ command.arg("-a").arg(&record.current);
+ command
+ };
+ restart
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .map_err(|_| "UPGRADE_RESTART_FAILED")?;
+ // Keep the installed handoff, DMG and previous App for explicit recovery. The empty owned
+ // stage directory is disposable and contains no user data.
+ let _ = fs::remove_dir(record.staged.parent().unwrap());
+ Ok(())
+}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index e7eb6558..2d4e0608 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "HiRoute",
- "version": "0.1.0",
+ "version": "0.2.0",
"identifier": "ai.hiroute.desktop",
"build": {"frontendDist": "../dist"},
"app": {
diff --git a/apps/desktop/src/features/UpdatesSettings.tsx b/apps/desktop/src/features/UpdatesSettings.tsx
new file mode 100644
index 00000000..aa2a7761
--- /dev/null
+++ b/apps/desktop/src/features/UpdatesSettings.tsx
@@ -0,0 +1,67 @@
+import { invoke } from '@tauri-apps/api/core';
+import { useEffect, useState } from 'react';
+import { safeDiagnosticCode } from '../error-code';
+import type { Language } from '../ui/preferences';
+
+type UpdateView = {
+ current_version: string;
+ phase: 'idle' | 'checking' | 'current' | 'available' | 'downloading' | 'verifying' | 'ready' | 'waiting' | 'installing' | 'failed';
+ available: { version: string; notes: { zh: string; en: string }; size: number } | null;
+ downloaded_bytes: number;
+ active_calls: number;
+ active_tasks: number;
+ error: string | null;
+ can_install: boolean;
+ package_ready: boolean;
+};
+const busyPhases = ['checking', 'downloading', 'verifying', 'waiting', 'installing'];
+export function UpdatesSettings({ active, language }: { active: boolean; language: Language }) {
+ const text = (zh: string, en: string) => language === 'zh' ? zh : en;
+ const [view, setView] = useState<UpdateView | null>(null);
+ const [error, setError] = useState('');
+ const [actionPending, setActionPending] = useState(false);
+ const busy = view !== null && busyPhases.includes(view.phase);
+ useEffect(() => {
+ if (!active && !busy) return;
+ let current = true;
+ const read = () => void invoke<UpdateView>('update_status').then(value => {
+ if (current) setView(value);
+ }).catch(failure => { if (current) setError(safeDiagnosticCode(failure, 'UPGRADE_STATUS_UNAVAILABLE')); });
+ read();
+ const timer = window.setInterval(read, 1000);
+ return () => { current = false; window.clearInterval(timer); };
+ }, [active, busy]);
+ const act = async (command: 'update_check' | 'update_download' | 'update_install' | 'update_cancel') => {
+ setActionPending(true); setError('');
+ try { setView(await invoke<UpdateView>(command)); }
+ catch (failure) { setError(safeDiagnosticCode(failure, 'UPGRADE_UNAVAILABLE')); }
+ finally { setActionPending(false); }
+ };
+ const status = !view ? text('正在读取版本信息…', 'Reading version information…')
+ : view.phase === 'checking' ? text('正在检查官网发布版本…', 'Checking official releases…')
+ : view.phase === 'current' ? text('已是最新稳定版本', 'The latest stable version is installed')
+ : view.phase === 'available' ? text(`可升级到 ${view.available?.version}`, `Version ${view.available?.version} is available`)
+ : view.phase === 'downloading' ? text(`正在下载 ${view.available?.version} · ${Math.min(100, Math.floor(view.downloaded_bytes / (view.available?.size || 1) * 100))}%`, `Downloading ${view.available?.version} · ${Math.min(100, Math.floor(view.downloaded_bytes / (view.available?.size || 1) * 100))}%`)
+ : view.phase === 'verifying' ? text('正在校验安装包…', 'Verifying the installation package…')
+ : view.phase === 'ready' ? text(`安装包已就绪:${view.available?.version}`, `Package ready: ${view.available?.version}`)
+ : view.phase === 'waiting' ? text(`等待 ${view.active_calls} 个调用、${view.active_tasks} 个任务结束;可取消升级继续使用。`, `Waiting for ${view.active_calls} call(s) and ${view.active_tasks} task(s); cancel to continue using HiRoute.`)
+ : view.phase === 'installing' ? text('正在停止服务并安装,完成后会重新打开 HiRoute。', 'Stopping the service and installing. HiRoute will reopen when complete.')
+ : view.phase === 'failed' ? text('升级未完成,请查看错误及启动页中的恢复说明。', 'The upgrade did not complete. See the error and startup recovery instructions.')
+ : text('从官网获取稳定版本', 'Stable releases from the official website');
+ const code = view?.error || error;
+ const canCancel = view && ['downloading', 'verifying', 'waiting'].includes(view.phase);
+ return <section className="settings-group"><h2>{text('版本升级', 'Updates')}</h2><div className="settings-list">
+ <div className="settings-row"><div className="settings-copy"><strong>HiRoute {view?.current_version ?? ''}</strong><span role="status">{status}</span></div>
+ <div className="worker-settings-control">
+ {!busy && <button className="btn" type="button" disabled={actionPending} onClick={() => void act('update_check')}>{text('检查更新', 'Check for updates')}</button>}
+ {view && !busy && view.available && !view.package_ready && <button className="btn" type="button" disabled={actionPending || !view.can_install} onClick={() => void act('update_download')}>{text('下载更新', 'Download update')}</button>}
+ {view?.package_ready && !busy && <button className="btn" type="button" disabled={actionPending} onClick={() => void act('update_install')}>{text('安装并重启', 'Install and restart')}</button>}
+ {canCancel && <button className="btn" type="button" onClick={() => void act('update_cancel')}>{text('取消升级', 'Cancel update')}</button>}
+ </div>
+ </div>
+ {view?.available && !busy && <div className="gateway-risk">{view.available.notes[language]}</div>}
+ {view?.phase === 'ready' && <div className="gateway-risk">{text('安装前会等待现有调用和任务结束。安装与首次启动期间,Agent 路由会暂时不可用;需要时可按备份目录中的说明恢复旧 App 和旧数据。', 'Installation waits for current calls and tasks. Agent routing is temporarily unavailable during installation and first startup. If needed, follow the backup instructions to restore the previous App and data.')}</div>}
+ {code && <div className="settings-inline-error" role="status">{text(`升级不可用(${code})。可重试检查,或从官网下载安装包并完全退出 HiRoute 后覆盖安装。`, `Update unavailable (${code}). Check again, or download from the official website and fully quit HiRoute before replacing the App.`)}</div>}
+ {view && !view.can_install && <div className="gateway-risk">{text('应用内安装需要使用完整的 HiRoute App。', 'In-app installation requires a complete HiRoute App.')}</div>}
+ </div></section>;
+}
diff --git a/apps/desktop/src/product/DesktopApp.tsx b/apps/desktop/src/product/DesktopApp.tsx
index 745e7510..dbc7e811 100644
--- a/apps/desktop/src/product/DesktopApp.tsx
+++ b/apps/desktop/src/product/DesktopApp.tsx
@@ -148,6 +148,14 @@ export function DesktopApp() {
const service = visibleData(home.reads.service);
const startupFailure = home.startup?.state === 'failed' ? home.startup : null;
+ const upgradePhase = home.startup?.state === 'starting' ? home.startup.upgrade_phase : undefined;
+ const upgradePhaseText = upgradePhase ? ({
+ source_check: language === 'zh' ? '正在校验存储格式' : 'Checking storage format',
+ backup: language === 'zh' ? '正在保存升级前的完整备份' : 'Saving the complete pre-upgrade backup',
+ conversion: language === 'zh' ? '正在升级本机数据' : 'Upgrading local data',
+ validation: language === 'zh' ? '正在校验升级结果' : 'Verifying upgraded data',
+ service_recovery: language === 'zh' ? '正在恢复本机服务' : 'Restoring the local service',
+ })[upgradePhase] : undefined;
const serviceLabel = service?.daemon === 'read_only'
? text.serviceReadOnly
: service?.daemon === 'unavailable'
@@ -574,16 +582,20 @@ export function DesktopApp() {
/>
<main className="main">
{notice && <div className="toast-stack" aria-live="polite"><div className="toast" role="status"><UiIcon name="info" /><span>{notice}</span></div></div>}
+ {upgradePhaseText && <div className="callout" role="status" aria-live="polite"><UiIcon name="info" /><div><strong>{upgradePhaseText}</strong><p>{language === 'zh' ? '请等待升级完成;请保留原数据与完整安装包。' : 'Wait for the upgrade to finish. Keep the original data and complete installation package.'}</p></div></div>}
{startupFailure && <div className="callout bad" role="alert" data-error-code={startupFailure.code}>
<UiIcon name="warning" />
<div>
<strong>{language === 'zh' ? '本机服务启动失败' : 'Local service failed to start'}</strong>
- <p>{startupFailure.code === 'DAEMON_STORAGE_UNREADABLE'
- ? (language === 'zh' ? 'HiRoute 数据无法读取或已损坏。原数据未被清空或迁移;请先备份恢复目录,再同时移走其中的 storage 和 gateway.lkg 后重启。' : 'HiRoute data is unreadable or damaged. It was not cleared or migrated. Back up the recovery directory, then move both storage and gateway.lkg aside before restarting.')
- : (language === 'zh' ? `启动阶段失败(${startupFailure.code ?? 'STARTUP_FAILED'})。原数据保持不变,可打开恢复目录查看日志并备份。` : `Startup failed (${startupFailure.code ?? 'STARTUP_FAILED'}). Existing data is unchanged; open the recovery directory to inspect logs and back it up.`)}</p>
+ <p>{startupFailure.code === 'DAEMON_UPGRADE_SOURCE_UNSUPPORTED'
+ ? (language === 'zh' ? '此数据格式尚无经过验证的升级与恢复路径。请保留原数据并使用对应旧版本,勿清空目录重试。' : 'This data format has no verified upgrade and recovery path. Keep the data and use its matching previous version.')
+ : startupFailure.backup_directory
+ ? (language === 'zh' ? '请保留当前数据目录,按升级备份中的《恢复说明.md》恢复整组数据,并覆盖安装说明指定的旧版本。恢复会舍弃备份之后的新数据。' : 'Keep the current data directory. Follow the recovery guide in the upgrade backup to restore the complete data set and install the specified previous version. Changes made after the backup will be lost.')
+ : (language === 'zh' ? `启动阶段失败(${startupFailure.code ?? 'STARTUP_FAILED'})。请保留现有数据,打开恢复目录查看日志并备份。` : `Startup failed (${startupFailure.code ?? 'STARTUP_FAILED'}). Keep the existing data; open the recovery directory to inspect logs and back it up.`)}</p>
+ {startupFailure.backup_directory && <p>{language === 'zh' ? '升级备份:' : 'Upgrade backup: '}{startupFailure.backup_directory}</p>}
{startupFailure.recovery_available && <button className="btn" type="button" onClick={() => {
void invoke('open_startup_recovery_directory').catch(() => setNotice(language === 'zh' ? '无法安全打开恢复目录,请检查目录权限后重试。' : 'The recovery directory could not be opened safely. Check its permissions and try again.'));
- }}>{language === 'zh' ? '打开恢复目录' : 'Open recovery directory'}</button>}
+ }}>{startupFailure.backup_directory ? (language === 'zh' ? '打开升级备份与恢复说明' : 'Open upgrade backup and recovery guide') : (language === 'zh' ? '打开恢复目录' : 'Open recovery directory')}</button>}
</div>
</div>}
diff --git a/apps/desktop/src/product/SettingsPage.tsx b/apps/desktop/src/product/SettingsPage.tsx
index eda41c52..565e6b56 100644
--- a/apps/desktop/src/product/SettingsPage.tsx
+++ b/apps/desktop/src/product/SettingsPage.tsx
@@ -1,6 +1,7 @@
import { invoke } from '@tauri-apps/api/core';
import { useEffect, useState } from 'react';
import { DiagnosticsSettings } from '../features/diagnostics/DiagnosticsSettings';
+import { UpdatesSettings } from '../features/UpdatesSettings';
import { safeDiagnosticCode } from '../error-code';
import { ProductPage } from '../ui';
import type { Language, LanguagePreference, TextScale, ThemePreference } from '../ui/preferences';
@@ -191,6 +192,7 @@ export function SettingsPage(props: SettingsPageProps) {
<button className="btn" type="button" onClick={() => props.onOpenSessions()}>{text('查看会话', 'View sessions')}</button>
</div></div></section>
<DiagnosticsSettings active={props.active} language={props.language} />
+ <UpdatesSettings active={props.active} language={props.language} />
<section className="settings-group"><h2>CLI</h2><div className="settings-list"><div className="settings-row">
<div className="settings-copy"><strong>{text('终端入口', 'Terminal entry')}</strong><span>{cliEntry === null
? text('正在检查 ~/.local/bin/hiroute', 'Checking ~/.local/bin/hiroute')
diff --git a/apps/desktop/src/product/use-desktop-home.ts b/apps/desktop/src/product/use-desktop-home.ts
index 39ee65ed..cde9f31e 100644
--- a/apps/desktop/src/product/use-desktop-home.ts
+++ b/apps/desktop/src/product/use-desktop-home.ts
@@ -51,7 +51,7 @@ function observationRequest(view: string, query: object) {
}
export function useDesktopHome() {
- const [startup, setStartup] = useState<{ state: 'starting' | 'ready' | 'failed'; code?: string; recovery_available: boolean } | null>(null);
+ const [startup, setStartup] = useState<{ state: 'starting' | 'ready' | 'failed'; code?: string; recovery_available: boolean; backup_directory?: string; upgrade_phase?: 'source_check' | 'backup' | 'conversion' | 'validation' | 'service_recovery' } | null>(null);
const [service, setService] = useState<DomainReadSlot<HomeService>>(loading);
const [compute, setCompute] = useState<DomainReadSlot<HomeCompute>>(loading);
const [plans, setPlans] = useState<DomainReadSlot<HomePlans>>(loading);
@@ -243,6 +243,23 @@ export function useDesktopHome() {
void refreshAll();
}, [refreshAll]);
+ useEffect(() => {
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const poll = async () => {
+ try {
+ const report = await invoke<NonNullable<typeof startup>>('startup_status');
+ if (cancelled) return;
+ setStartup(current => current?.state === 'ready' ? current : report);
+ if (report.state === 'starting') timer = setTimeout(() => void poll(), 500);
+ } catch {
+ if (!cancelled) timer = setTimeout(() => void poll(), 1000);
+ }
+ };
+ void poll();
+ return () => { cancelled = true; if (timer) clearTimeout(timer); };
+ }, []);
+
return {
startup,
reads: {
diff --git a/apps/desktop/tests/prepare_plan.py b/apps/desktop/tests/prepare_plan.py
index b2691f73..357e2d54 100644
--- a/apps/desktop/tests/prepare_plan.py
+++ b/apps/desktop/tests/prepare_plan.py
@@ -7,6 +7,7 @@ This is preparation evidence; it is not Desktop GUI acceptance.
"""
import hashlib, json, os, pathlib, secrets, select, socket, stat, statistics, subprocess, sys, time
REPO = pathlib.Path(__file__).resolve().parents[3]
+RELEASE_VERSION = json.loads((REPO / 'contracts/cli/local-control-hello.v2.schema.json').read_text())['properties']['client_version']['const']
BENCH_RUNS = int(os.environ.get('HIROUTE_PLAN_BENCHMARK_RUNS', '1'))
if BENCH_RUNS < 1 or BENCH_RUNS > 10: raise SystemExit('Benchmark runs must be 1..10')
BENCHMARK = 'HIROUTE_PLAN_BENCHMARK_RUNS' in os.environ
@@ -25,8 +26,10 @@ if build.returncode:
raise SystemExit(build.returncode)
ROOT = pathlib.Path(sys.argv[1]).resolve()
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
+ROOT.chmod(0o700)
if any(ROOT.iterdir()): raise SystemExit('Preparation requires an empty isolated directory')
-PROJECT = ROOT / 'agent-input'; (PROJECT / '.claude').mkdir(parents=True, mode=0o700)
+PROJECT = ROOT / 'agent-input'; PROJECT.mkdir(mode=0o700)
+(PROJECT / '.claude').mkdir(mode=0o700)
SENTINEL = 'hr02-isolated-not-a-provider-credential-' + secrets.token_hex(16)
settings = PROJECT / '.claude/settings.json'
settings.write_text(json.dumps({'env': {'ANTHROPIC_BASE_URL': 'https://open.bigmodel.cn/api/anthropic', 'ANTHROPIC_AUTH_TOKEN': SENTINEL, 'ANTHROPIC_MODEL': 'glm-5.3'}}))
@@ -50,6 +53,7 @@ record.chmod(0o600)
fds=[shutdown_r,capability_r,ack_w]
daemon_args=[str(REPO/'target/debug/hirouted'),'--role','all','--storage-root',str(ROOT/'storage'),'--runtime-root',str(ROOT/'run'),'--listen',f'127.0.0.1:{port}','--lkg',str(ROOT/'gateway.lkg'),'--shutdown-fd',str(fds[0]),'--capability-fd',str(fds[1]),'--capability-ack-fd',str(fds[2])]
if BENCHMARK: daemon_args += ['--diagnostics-root',str(ROOT/'diagnostics'),'--diagnostic-level-override','debug']
+startup_started=time.perf_counter_ns()
daemon=subprocess.Popen(daemon_args,cwd=PROJECT,env=environment,pass_fds=fds,stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
os.close(shutdown_r);os.close(capability_r);os.close(ack_w)
def call(command, payload=None, grant=None):
@@ -69,7 +73,7 @@ def control(operation,payload,grant=None):
if grant is not None: request['protected_grant']=grant
with socket.socket(socket.AF_UNIX) as sock:
sock.settimeout(35);sock.connect(str(ROOT/'run/hiroute/control.sock'));stream=sock.makefile('rwb')
- stream.write(encoded({'api_version':{'major':2,'minor':0},'machine_schema_version':{'major':2,'minor':0},'client_name':'desktop-e2e','client_version':'0.1.0'})+b'\n');stream.flush()
+ stream.write(encoded({'api_version':{'major':2,'minor':0},'machine_schema_version':{'major':2,'minor':0},'client_name':'desktop-e2e','client_version':RELEASE_VERSION})+b'\n');stream.flush()
hello=json.loads(stream.readline());assert 'local-control-v2' in hello['capabilities'],hello
stream.write(encoded(request)+b'\n');stream.flush();raw=stream.readline()
assert SENTINEL.encode() not in raw,'Secret escaped protected Local Control response'
@@ -102,6 +106,12 @@ try:
startup=json.loads(ready)
if 'process_id' not in startup: raise RuntimeError(f"daemon startup failed: {startup.get('code', 'unknown')}")
assert startup['process_id']==daemon.pid
+ if BENCHMARK:
+ startup_ms=round((time.perf_counter_ns()-startup_started)/1_000_000,3)
+ def daemon_rss_kib():
+ # Query only the live daemon, excluding Cargo and the Python driver.
+ return int(subprocess.check_output(['ps','-o','rss=','-p',str(daemon.pid)],text=True).strip())
+ ready_rss_kib=daemon_rss_kib()
# This preparation daemon stands in for the previously owned run. Seed its exact endpoint
# identities while they are live, so Desktop restart can verify the old served address.
endpoint_dir=ROOT/'run/hiroute'
@@ -157,6 +167,7 @@ try:
baseline=call(['routing','list'])
(ROOT/'baseline.json').write_text(json.dumps(baseline,indent=2))
print(json.dumps({'state':'prepared','operation_id':operation['operation_id'],'plans':len(baseline['plans']),'root':str(ROOT)}),flush=True)
+ if BENCHMARK: print(json.dumps({'benchmark':'startup_and_memory','startup_ready_ms':startup_ms,'ready_rss_kib':ready_rss_kib,'after_publish_rss_kib':daemon_rss_kib(),'profile':'debug','startup':'fresh_current_format','upstream_calls':0}),flush=True)
if BENCHMARK: print(json.dumps({'benchmark':'plan_apply','runs':BENCH_RUNS,'apply_ms':durations_ms,'median_ms':statistics.median(durations_ms)}),flush=True)
finally:
os.close(shutdown_w)
diff --git a/apps/website/.gitignore b/apps/website/.gitignore
index 30de806f..41285bb0 100644
--- a/apps/website/.gitignore
+++ b/apps/website/.gitignore
@@ -5,4 +5,5 @@ public/api/
public/decision-assets/
public/install/
public/install.sh
+public/releases.json
public/brand/app-icon.png
diff --git a/apps/website/scripts/prepare-content.mjs b/apps/website/scripts/prepare-content.mjs
index cbb19775..778634ef 100644
--- a/apps/website/scripts/prepare-content.mjs
+++ b/apps/website/scripts/prepare-content.mjs
@@ -29,4 +29,5 @@ for (const entry of await fs.readdir(path.join(source, 'assets'), { withFileType
}
await fs.copyFile(path.join(repository, 'scripts/install-standalone.py'), path.join(installDirectory, 'standalone.py'));
await fs.writeFile(path.join(publicDirectory, 'install.sh'), generateLinuxInstallScript(releaseManifest), { mode: 0o755 });
+await fs.writeFile(path.join(publicDirectory, 'releases.json'), JSON.stringify(releaseManifest, null, 2) + '\n');
console.log('Prepared canonical Decision API, illustrations, and Linux installer entry.');
diff --git a/apps/website/scripts/validate-build.mjs b/apps/website/scripts/validate-build.mjs
index bfa32f38..a3c9dbcd 100644
--- a/apps/website/scripts/validate-build.mjs
+++ b/apps/website/scripts/validate-build.mjs
@@ -16,7 +16,7 @@ const required = [
'docs/decision-api/index.html', 'en/docs/decision-api/index.html',
'docs/jev-decider/index.html', 'en/docs/jev-decider/index.html',
'api/decision.openapi.json', 'api/jev-policy.default.json',
- 'install.sh', 'install/standalone.py', '404.html', 'sitemap-index.xml',
+ 'install.sh', 'install/standalone.py', 'releases.json', '404.html', 'sitemap-index.xml',
];
for (const relative of required) {
if (!fs.existsSync(path.join(dist, relative))) throw new Error(`missing website output: ${relative}`);
diff --git a/apps/website/tests/releases.test.mjs b/apps/website/tests/releases.test.mjs
index 13b230cc..26ac49db 100644
--- a/apps/website/tests/releases.test.mjs
+++ b/apps/website/tests/releases.test.mjs
@@ -22,6 +22,11 @@ const release = {
notes: { zh: '正式版本。', en: 'Stable release.' }, artifacts: [artifact],
};
const manifest = { schema: 'hiroute.website.releases/v2', releases: [release] };
+test('Desktop update endpoint publishes the same validated website catalog', () => {
+ const generated = JSON.parse(fs.readFileSync(new URL('../public/releases.json', import.meta.url), 'utf8'));
+ const source = JSON.parse(fs.readFileSync(new URL('../data/releases.json', import.meta.url), 'utf8'));
+ assert.deepEqual(generated, validateReleaseManifest(source));
+});
const standalone = {
kind: 'standalone', platform: 'Linux', architecture: 'x86_64', target: 'x86_64-unknown-linux-gnu',
format: 'tar.gz', distribution: 'unsigned',
diff --git a/contracts/cli/contract-set.v1.json b/contracts/cli/contract-set.v1.json
index 49e1b186..8200cc0a 100644
--- a/contracts/cli/contract-set.v1.json
+++ b/contracts/cli/contract-set.v1.json
@@ -13,7 +13,7 @@
"delegation-start-request.v1.schema.json": "sha256:033885686bf77cb03344c8ccc5ae245e9407e5c8010bf94e59d2232fb0b3a7b4",
"delegation-wait-request.v1.schema.json": "sha256:9aba6c969923f455ea376a5d8bc034efb4acd103d5b79df1d0d3aebb3d57b9e9",
"empty-request.v1.schema.json": "sha256:44d40c4601343ddfb543fd04751cc0a0a994fe8d7963adc541fe4a245ceba2b1",
- "local-control-hello.v2.schema.json": "sha256:001b164e383a50764d97d4cce01aa296ec821b01532c2f9e951d8da8e061fca1",
+ "local-control-hello.v2.schema.json": "sha256:169b944fd7d6a6c48e6615e875ec1dfe7b0045e09186312fd2c2b7cc92b56aa6",
"local-control.v2.schema.json": "sha256:4b654de90cd6e333b3953379e5b2e1c5125f1dcbe307b7c7c73f12bb2032d18c",
"machine-envelope.v2.schema.json": "sha256:5a0b47ce1fd80628f760a3da5a88de7dc01f6df83cb6eef47fd4a6c8289070ba",
"manifest.v1.json": "sha256:c602e9b661621403bc05405674f5522604be0e716a886673776199492f686f75",
diff --git a/contracts/cli/local-control-hello.v2.schema.json b/contracts/cli/local-control-hello.v2.schema.json
index 1c4f58fe..a2c070e9 100644
--- a/contracts/cli/local-control-hello.v2.schema.json
+++ b/contracts/cli/local-control-hello.v2.schema.json
@@ -12,7 +12,7 @@
"type": "string"
},
"client_version": {
- "const": "0.1.0"
+ "const": "0.2.0"
},
"machine_schema_version": {
"$ref": "local-control.v2.schema.json#/properties/schema_version"
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index f03f3341..0eb3c72c 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -23,7 +23,7 @@
"hiroute.agent-launch-descriptor-request/v1",
"hiroute.agent-live-check-evidence/v1",
"hiroute.agent-live-check-receipt/v1",
- "hiroute.agent-model-grant/v2",
+ "hiroute.agent-model-grant/v3",
"hiroute.agent-model-settings-status/v2",
"hiroute.agent-plan-alias-registry/v1",
"hiroute.agent-plan-catalog-query/v2",
@@ -67,7 +67,7 @@
"hiroute.collaboration-credential/v1",
"hiroute.command-result/v1",
"hiroute.compiled-agent-plan/v1",
- "hiroute.compiled-agent-plan/v2",
+ "hiroute.compiled-agent-plan/v3",
"hiroute.compiled-planner-policy/v1",
"hiroute.compute-connection-apply-request/v1",
"hiroute.compute-connection-authorization-request/v1",
@@ -128,6 +128,7 @@
"hiroute.created-plan/v2",
"hiroute.daemon-ready/v1",
"hiroute.daemon-startup-failure/v1",
+ "hiroute.daemon-upgrade-progress/v1",
"hiroute.delegation-accepted/v1",
"hiroute.delegation-cancel-request/v1",
"hiroute.delegation-cancel/v1",
@@ -151,6 +152,7 @@
"hiroute.desktop-price-intent/v1",
"hiroute.desktop-rename-intent/v1",
"hiroute.desktop-subscription-check-intent/v1",
+ "hiroute.desktop-upgrade-handoff/v1",
"hiroute.desktop-worker-dependency-selection-intent/v1",
"hiroute.desktop.cpa-artifacts/v1",
"hiroute.diagnostic-event/v1",
@@ -161,6 +163,7 @@
"hiroute.fixed-local-id/v2",
"hiroute.frozen-candidate-ledger/v1",
"hiroute.gateway-access-grant/v1",
+ "hiroute.gateway-cache-compiler/v1",
"hiroute.gateway-candidate-local-id/v1",
"hiroute.gateway-catalog-renderer/v1",
"hiroute.gateway-listener-status/v1",
@@ -182,6 +185,7 @@
"hiroute.gateway.port.lifecycle-fact/v2",
"hiroute.gateway.port.runtime-publication/v1",
"hiroute.gateway.port.runtime-state/v1",
+ "hiroute.gateway.publication-cache/v1",
"hiroute.gateway.publication-snapshot/v1",
"hiroute.gateway.publication-snapshot/v3",
"hiroute.gateway.ready/v1",
@@ -189,6 +193,8 @@
"hiroute.gateway.request-authority/v2",
"hiroute.gateway.sealed-candidate-execution/v1",
"hiroute.header-secret-lease-request/v1",
+ "hiroute.launcher-upgrade-status/v1",
+ "hiroute.launcher-upgrade/v1",
"hiroute.machine-envelope/v2",
"hiroute.managed-artifact-backup/v2",
"hiroute.managed-artifact-compensation/v1",
@@ -200,7 +206,6 @@
"hiroute.managed-launch-observation/v1",
"hiroute.managed-launch-warning/v1",
"hiroute.materialized-route-digest/v1",
- "hiroute.materialized-route-digest/v2",
"hiroute.migration-store/v1",
"hiroute.model-catalog-query/v1",
"hiroute.model-catalog-view/v1",
@@ -229,7 +234,9 @@
"hiroute.operation-event/v1",
"hiroute.operation-idempotency-lookup/v1",
"hiroute.operation-idempotency-result/v1",
+ "hiroute.operation-input/v1",
"hiroute.operation-lookup/v1",
+ "hiroute.operation-step-input/v1",
"hiroute.operation-step/v1",
"hiroute.operation-view/v1",
"hiroute.otel.gen-ai-mapping/v1",
@@ -246,7 +253,7 @@
"hiroute.plan-lifecycle-change/v1",
"hiroute.plan-lifecycle-preview/v1",
"hiroute.plan-quality-samples-page/v1",
- "hiroute.plan-version/v1",
+ "hiroute.plan-version/v2",
"hiroute.planner-candidate-facts/v1",
"hiroute.planner-input-facts-digest/v1",
"hiroute.planner-input/v1",
@@ -288,7 +295,8 @@
"hiroute.settings-codex-model-file/v1",
"hiroute.settings-login-item/v1",
"hiroute.settings-model-publication/v1",
- "hiroute.settings-service-completion/v1",
+ "hiroute.settings-service-completion/v2",
+ "hiroute.settings-service-proof/v2",
"hiroute.settings-skill-file/v1",
"hiroute.settings-skill-reference/v1",
"hiroute.setup-apply-request/v1",
@@ -301,18 +309,24 @@
"hiroute.sqlite-backup-manifest/v2",
"hiroute.sqlite-backup-set/v2",
"hiroute.sqlite-logical-state/v1",
+ "hiroute.stable-route/v1",
"hiroute.standalone-install/v1",
"hiroute.standalone-protected-input-request/v1",
"hiroute.standalone-protected-input-response/v1",
"hiroute.standalone-service-doctor/v1",
"hiroute.standalone-service-logs/v1",
"hiroute.standalone-service-status/v1",
+ "hiroute.stored-plan/v1",
+ "hiroute.stored-publication/v1",
"hiroute.subscription-maintenance/v2",
"hiroute.system-status/v1",
+ "hiroute.upgrade-installer-started/v1",
+ "hiroute.upgrade-source-backup/v1",
"hiroute.value-ledger-entry/v1",
"hiroute.value-query/v1",
"hiroute.value-view/v1",
"hiroute.web-confirmation/v1",
+ "hiroute.website.releases/v2",
"hiroute.work-plan-list-request/v1",
"hiroute.work-plan-list/v1",
"hiroute.worker-cancel-request/v1",
@@ -337,10 +351,38 @@
"hiroute.worker-wait-request/v1"
],
"subjects": [
+ {
+ "subject": "operation_canonical_fixture",
+ "audited_prefixes": [
+ "hiroute.operation-input",
+ "hiroute.pre-fix-default-canonical-records"
+ ],
+ "current_contracts": [
+ "hiroute.operation-input/v1"
+ ],
+ "legacy_support": [
+ {
+ "contract": "hiroute.pre-fix-default-canonical-records/v1",
+ "mode": "frozen_fixture",
+ "owner": "local-storage",
+ "reason": "Preserve the unmodified pre-MVP canonical Operation journal, alias-only model scope and six original step proofs as algorithm regression evidence. It is not a supported schema22 migration source or production recovery decoder; a schema23 store rejects its raw journal.",
+ "removal_condition": "Remove only with the historical canonical digest regression suite; never regenerate the frozen bytes from a current producer.",
+ "allowed_paths": [
+ "crates/local-storage/tests/canonical_compat.rs",
+ "crates/local-storage/tests/canonical_compat/default-records.v1.json",
+ "crates/local-storage/tests/canonical_compat/README.md"
+ ]
+ }
+ ]
+ },
{
"subject": "terminal_classification_retired_quotas",
- "audited_prefixes": ["hiroute.candidate-capability"],
- "current_contracts": ["hiroute.candidate-capability/v1"],
+ "audited_prefixes": [
+ "hiroute.candidate-capability"
+ ],
+ "current_contracts": [
+ "hiroute.candidate-capability/v1"
+ ],
"legacy_support": [
{
"contract": "hiroute.candidate-capability/v1",
@@ -352,10 +394,12 @@
"crates/application/src/compiler/test_fixtures.rs",
"crates/daemon/src/control/runtime/candidate_protocol_profiles.rs",
"crates/domain/src/routing/gateway_execution.rs",
+ "crates/domain/src/routing/capability_compiler.rs",
"crates/gateway/src/profiles/capability.rs",
"crates/gateway/src/planning/eligibility.rs",
"crates/gateway/src/runtime/driver/response.rs",
- "e2e/product/golden/routing/compiled-publication.v2.json"
+ "e2e/product/golden/routing/compiled-publication.v2.json",
+ "e2e/product/fixtures/routing/current-publication.v3.json"
]
}
]
@@ -429,11 +473,13 @@
"subject": "routing_publication",
"audited_prefixes": [
"hiroute.gateway-publication",
- "hiroute.gateway.publication-snapshot"
+ "hiroute.gateway.publication-snapshot",
+ "hiroute.stored-publication"
],
"current_contracts": [
"hiroute.gateway-publication/v3",
- "hiroute.gateway.publication-snapshot/v3"
+ "hiroute.gateway.publication-snapshot/v3",
+ "hiroute.stored-publication/v1"
],
"legacy_support": [
{
@@ -482,15 +528,18 @@
"hiroute.plan-content-change",
"hiroute.routing-control-change",
"hiroute.routing-control",
- "hiroute.routing-publication-effect"
+ "hiroute.routing-publication-effect",
+ "hiroute.stored-plan",
+ "hiroute.stable-route"
],
"current_contracts": [
- "agent-plan-compiler/v2",
- "hiroute.compiled-agent-plan/v2",
- "hiroute.materialized-route-digest/v2",
+ "agent-plan-compiler/v3",
+ "hiroute.compiled-agent-plan/v3",
+ "hiroute.stable-route/v1",
"hiroute.plan-content-change/v2",
"hiroute.routing-control/v2",
- "hiroute.routing-publication-effect/v2"
+ "hiroute.routing-publication-effect/v2",
+ "hiroute.stored-plan/v1"
],
"legacy_support": [
{
@@ -498,7 +547,7 @@
"mode": "recovery_read_only",
"owner": "routing-compiler",
"reason": "Authenticate and convert the frozen V1 compiled-plan fixture; current authoring emits compiler V2.",
- "removal_condition": "Remove only when publication and recovery-journal inventories, including every still-supported backup, report zero compiler-V1 aggregates and zero compiled-plan-V1 bodies.",
+ "removal_condition": "An explicit announced end-of-support decision and a validated upgrade or bridge path for all remaining supported sources and backups, with synchronized specs and release documentation.",
"allowed_paths": [
"crates/domain/src/routing/mod.rs",
"e2e/product/golden/routing/compiled-publication.v2.json"
@@ -509,7 +558,7 @@
"mode": "recovery_read_only",
"owner": "routing-compiler",
"reason": "Authenticate persisted V1 plans and reseal their unchanged executable arrays as V2.",
- "removal_condition": "Remove only when active, prepared, and last-known-good publications, recovery journals, and every still-supported backup report zero compiled-plan-V1 bodies.",
+ "removal_condition": "An explicit announced end-of-support decision and a validated upgrade or bridge path for all remaining supported sources and backups, with synchronized specs and release documentation.",
"allowed_paths": [
"crates/domain/src/routing/mod.rs",
"e2e/product/golden/routing/compiled-publication.v2.json"
@@ -520,7 +569,7 @@
"mode": "recovery_read_only",
"owner": "routing-compiler",
"reason": "Verify a V1 compiled plan before converting it; current compilation uses the V2 executable-only digest.",
- "removal_condition": "Remove only with the compiled-plan-V1 reader after the same publication, journal, and backup inventory reports zero V1 materialized-route digests.",
+ "removal_condition": "An explicit announced end-of-support decision and a validated upgrade or bridge path for all remaining supported sources and backups, with synchronized specs and release documentation.",
"allowed_paths": [
"crates/domain/src/routing/materialized.rs"
]
@@ -737,6 +786,88 @@
"hiroute.worker-settings/v1"
],
"legacy_support": []
+ },
+ {
+ "subject": "stable_model_grant",
+ "audited_prefixes": [
+ "hiroute.agent-model-grant"
+ ],
+ "current_contracts": [
+ "hiroute.agent-model-grant/v3"
+ ],
+ "legacy_support": []
+ },
+ {
+ "subject": "stable_plan_version",
+ "audited_prefixes": [
+ "hiroute.plan-version"
+ ],
+ "current_contracts": [
+ "hiroute.plan-version/v2"
+ ],
+ "legacy_support": []
+ },
+ {
+ "subject": "settings_service_completion",
+ "audited_prefixes": [
+ "hiroute.settings-service-completion"
+ ],
+ "current_contracts": [
+ "hiroute.settings-service-completion/v2"
+ ],
+ "legacy_support": []
+ },
+ {
+ "subject": "gateway_publication_cache",
+ "audited_prefixes": [
+ "hiroute.gateway.publication-cache",
+ "hiroute.gateway.durable-publication"
+ ],
+ "current_contracts": [
+ "hiroute.gateway.publication-cache/v1"
+ ],
+ "legacy_support": [
+ {
+ "contract": "hiroute.gateway.durable-publication/v1",
+ "mode": "recovery_read_only",
+ "owner": "gateway-publication",
+ "reason": "Retain the standalone aggregate-feed fixture recovery reader. Product startup ignores the cache and reconciles control.db installation decisions before admission.",
+ "removal_condition": "Only after explicit retirement of this source with a retained bridge for still-supported aggregate-feed inputs and sealed fixtures.",
+ "allowed_paths": [
+ "crates/gateway/src/publication/installer.rs"
+ ]
+ }
+ ]
+ },
+ {
+ "subject": "launcher_upgrade",
+ "audited_prefixes": [
+ "hiroute.launcher-upgrade",
+ "hiroute.launcher-upgrade-status"
+ ],
+ "current_contracts": [
+ "hiroute.launcher-upgrade/v1",
+ "hiroute.launcher-upgrade-status/v1"
+ ],
+ "legacy_support": []
+ },
+ {
+ "subject": "desktop_update",
+ "audited_prefixes": [
+ "hiroute.website.releases",
+ "hiroute.desktop-upgrade-handoff",
+ "hiroute.upgrade-recovery-package",
+ "hiroute.upgrade-installer-started",
+ "hiroute.daemon-upgrade-progress",
+ "hiroute.upgrade-recovery-catalog"
+ ],
+ "current_contracts": [
+ "hiroute.website.releases/v2",
+ "hiroute.desktop-upgrade-handoff/v1",
+ "hiroute.upgrade-installer-started/v1",
+ "hiroute.daemon-upgrade-progress/v1"
+ ],
+ "legacy_support": []
}
],
"forbidden_contracts": [
diff --git a/contracts/releases/index.v1.json b/contracts/releases/index.v1.json
new file mode 100644
index 00000000..b6b09a50
--- /dev/null
+++ b/contracts/releases/index.v1.json
@@ -0,0 +1,13 @@
+{
+ "latest_stable": "v0.1.0",
+ "releases": [
+ {
+ "channel": "stable",
+ "file": "v0.1.0.json",
+ "revision": "5f3ee7c96f4f6a02c1a730008055d413c28e1d5e",
+ "sha256": "bf13db620715f65ac3c893f87b264b66e79ff790b52e894e0ba0669a8f167880",
+ "tag": "v0.1.0"
+ }
+ ],
+ "schema": "hiroute.release-contract-index/v1"
+}
diff --git a/contracts/releases/v0.1.0.json b/contracts/releases/v0.1.0.json
new file mode 100644
index 00000000..f3abb68a
--- /dev/null
+++ b/contracts/releases/v0.1.0.json
@@ -0,0 +1,828 @@
+{
+ "contracts": {
+ "cli_contract_set": {
+ "content": {
+ "descriptor_digest": "sha256:977c6c3de2ed68f4437db403b16db9b0684616acd41124abfe2ff06caf364022",
+ "files": {
+ "agent-check-request.v1.schema.json": "sha256:fbd9e9b19282a5ed8c3e30b5ae16538bc01318a70e4bb7c7a55e8e0472553feb",
+ "agent-launch-descriptor-request.v1.schema.json": "sha256:28f2f9d2d7f9a1618bea0f13383002429bc9e0ff56166cbee86958a245d0fd48",
+ "agent-plan-catalog-query.v2.schema.json": "sha256:c9dab9d3152c36449467f67de229836cff18cc3c5e7cdcdea719361aa9724676",
+ "coverage-manifest.v1.json": "sha256:76d8776f13d953fd0b1c0387ba877c30fba7ecf564d927d131cb7e76b3f5a822",
+ "delegation-cancel-request.v1.schema.json": "sha256:0822c53fc16acfcd618fbef66410939f33f634313389a6df4705f414a468b878",
+ "delegation-continue-request.v1.schema.json": "sha256:da2f81607f37d154a0fa698a107b37d4b0e9d5a03693dcbcc41e0b7e65db5b93",
+ "delegation-get-request.v1.schema.json": "sha256:85b29839c1c508018ebe40e4b2bb5c1dce7c3a87c27efa30b196b2d1b6658471",
+ "delegation-list-request.v1.schema.json": "sha256:b5f94da911750d9360f52ad9ca9d93e97950f77297dbbe2fb430eb1064077c52",
+ "delegation-result-request.v1.schema.json": "sha256:8b369bc1475707c537591ca0838e28bef382647996007c4fd2b8274629a7634f",
+ "delegation-start-request.v1.schema.json": "sha256:033885686bf77cb03344c8ccc5ae245e9407e5c8010bf94e59d2232fb0b3a7b4",
+ "delegation-wait-request.v1.schema.json": "sha256:9aba6c969923f455ea376a5d8bc034efb4acd103d5b79df1d0d3aebb3d57b9e9",
+ "empty-request.v1.schema.json": "sha256:44d40c4601343ddfb543fd04751cc0a0a994fe8d7963adc541fe4a245ceba2b1",
+ "local-control-hello.v2.schema.json": "sha256:001b164e383a50764d97d4cce01aa296ec821b01532c2f9e951d8da8e061fca1",
+ "local-control.v2.schema.json": "sha256:4b654de90cd6e333b3953379e5b2e1c5125f1dcbe307b7c7c73f12bb2032d18c",
+ "machine-envelope.v2.schema.json": "sha256:5a0b47ce1fd80628f760a3da5a88de7dc01f6df83cb6eef47fd4a6c8289070ba",
+ "manifest.v1.json": "sha256:c602e9b661621403bc05405674f5522604be0e716a886673776199492f686f75",
+ "operation-cancel-request.v1.schema.json": "sha256:0071cbcf27de3bfb7f6644478fe2b73bb5387ebe33db93629ff5672959e8495f",
+ "operation-lookup.v1.schema.json": "sha256:0fbaaa15b0e75b4186979bdd856bed0485d55a4bd33a33f3caf3bd92e01a7850",
+ "plan-content-change.v2.schema.json": "sha256:1706ccfd7aa0abe34b1253bcf43d746b01af059ded980cc2dc430633569c20ca",
+ "plan-draft-change.v1.schema.json": "sha256:8f3cf4a330260b241e8a751f99d706043e946b344f8d18e09d1081d47d3554b9",
+ "plan-editor.v2.schema.json": "sha256:8e1dc12e825826e1703664b7124d291ffd6ec2061dd49660f763609511319ff5",
+ "plan-lifecycle-change.v1.schema.json": "sha256:ff8ec4ff9bbf32fac6584b0a8dbd46e8724c4b55b6c09dd375ab2995af393132",
+ "planned-manifest.v1.json": "sha256:eac0c7583245a881de141f9b8d853a86efb3f9ef8fa9a3ffb3ed75d759467072",
+ "session-list-query.v1.schema.json": "sha256:1f71a89fc019b59c3499708c0760b694b8cb8532028b56d98702cd3b2721cd44",
+ "session-lookup.v1.schema.json": "sha256:0c9e0ea31bdde7f720a9a17e8dc175902a20b3fb92abc21ce4bdae9fc3d97587",
+ "setup-apply-request.v1.schema.json": "sha256:b44377ecb53e609574cd2e1d49624d6bc8e148f7b60a99c2ea9db861e0c2cabd",
+ "setup-request.v1.schema.json": "sha256:e7fb0a57d7cbe41caf90b4a57e56b8434aa01b91054935447666cb2af5bc98fd",
+ "value-query.v1.schema.json": "sha256:7dbc91344f1b1f9635a8b62c010567cad9e6f29207d8f1d89f5b4abb80fdbfae",
+ "work-plan-list-request.v1.schema.json": "sha256:d50adc8e139cbed719fcec6412c796a7cf4d4f280dd7a56c525619f72c26c58d",
+ "worker-cancel-request.v1.schema.json": "sha256:f731e6a6be762d409a53afe9697be105d0debb89fe5e28be96b15ae03b31dfdc",
+ "worker-continue-request.v1.schema.json": "sha256:cfe89487d3524061dd277a97b11291fcd0db4a0a0ca333118023628ab7d61b3b",
+ "worker-dependencies-discover-request.v1.schema.json": "sha256:cde9509210a2a2605fc95ed19d9c4a3aa754241dd49e6522124f77236dac44e4",
+ "worker-dependencies-select-request.v1.schema.json": "sha256:d6a0454d125ea368f6b205fe7f360b14963fdd6fc94080bc2e19daf2aef6b972",
+ "worker-exec-request.v1.schema.json": "sha256:78bfea83b08e595ad4d4b5a5a20884ad9ebb34bb05e5ceed966f9e8e16f4d0fa",
+ "worker-list-request.v1.schema.json": "sha256:f1a2b5900b0412d8d561a5925a6f9489b495e74c41f386a3504175b2be3aff64",
+ "worker-plans-request.v1.schema.json": "sha256:a7f2d13869ab542223bf51eef4f0c1a05a4c8afef43f202165fd3025a2ab72c1",
+ "worker-read-request.v1.schema.json": "sha256:9821ee686f0e6c58b187b7c1addf0d3703954995f6081389370c1b5f599922ba",
+ "worker-result-request.v1.schema.json": "sha256:af6a9f65eb32e9d85b95b8b643af8d9bbe3fe88d8093e7e06c4353fadf332c8f",
+ "worker-status-request.v1.schema.json": "sha256:d2a03db6c4e064c2b1948520a37143e2d224b2d9af4d1a015b009988be6473d2",
+ "worker-wait-request.v1.schema.json": "sha256:6d72ac0dcee361d7240cebbf02a6290a47c765a80d7dcd1c7d795b245923702b"
+ },
+ "product_contract_revision": "487a807c8dc25cfb24e8b097882cd3bb9716a009",
+ "proposal_map_revision": "ab4da93cc49c6ec56a01e046230411ff1ca82300",
+ "schema_version": {
+ "major": 1,
+ "minor": 0
+ }
+ },
+ "path": "contracts/cli/contract-set.v1.json",
+ "sha256": "411753848cff5dba071c861f81440db21bf90a87686cecb51b499c601faad5de"
+ },
+ "compatibility_register": {
+ "content": {
+ "forbidden_contracts": [
+ "hiroute.agent-plan-catalog/v1",
+ "hiroute.gateway.port.execution-fact/v2",
+ "hiroute.local-control/v1",
+ "hiroute.machine-envelope/v1",
+ "hiroute.observation.product-execution-envelope/v1",
+ "hiroute.protected-apply-ack/v1",
+ "hiroute.routing-change/v1",
+ "hiroute.routing-control-preview/v1",
+ "hiroute.routing-preview/v1"
+ ],
+ "production_contracts": [
+ "hiroute.agent-access-grant-effect/v1",
+ "hiroute.agent-access-grant-entry/v1",
+ "hiroute.agent-check-request/v1",
+ "hiroute.agent-check/v1",
+ "hiroute.agent-collaboration-credential/v1",
+ "hiroute.agent-collaboration-grant/v1",
+ "hiroute.agent-collaboration-settings-status/v2",
+ "hiroute.agent-config-change/v1",
+ "hiroute.agent-config-permission-control/v1",
+ "hiroute.agent-config-permission-effect/v1",
+ "hiroute.agent-config-permission-marker/v1",
+ "hiroute.agent-config-restore/v1",
+ "hiroute.agent-connection-control/v1",
+ "hiroute.agent-connection-effect/v1",
+ "hiroute.agent-connection-preview/v1",
+ "hiroute.agent-connection-restore-point/v1",
+ "hiroute.agent-connection-status/v1",
+ "hiroute.agent-connection/v1",
+ "hiroute.agent-discovery-list/v1",
+ "hiroute.agent-launch-descriptor-request/v1",
+ "hiroute.agent-live-check-evidence/v1",
+ "hiroute.agent-live-check-receipt/v1",
+ "hiroute.agent-model-grant/v2",
+ "hiroute.agent-model-settings-status/v2",
+ "hiroute.agent-plan-alias-registry/v1",
+ "hiroute.agent-plan-catalog-query/v2",
+ "hiroute.agent-plan-catalog/v2",
+ "hiroute.agent-plan-desired/v1",
+ "hiroute.agent-plan-facts/v1",
+ "hiroute.agent-plan-grant/v1",
+ "hiroute.agent-plan-lookup/v1",
+ "hiroute.agent-plan-status/v2",
+ "hiroute.agent-profile/v1",
+ "hiroute.agent-profiles-artifact/v1",
+ "hiroute.agent-routing-catalog/v1",
+ "hiroute.agent-routing-overlay/v1",
+ "hiroute.agent-scan-observation/v1",
+ "hiroute.agent-settings-preview/v2",
+ "hiroute.agent-surface-check/v1",
+ "hiroute.borrowed-codex-access-lease/v1",
+ "hiroute.borrowed-codex-binding-evidence/v1",
+ "hiroute.borrowed-codex-evidence/v1",
+ "hiroute.borrowed-codex-revision/v1",
+ "hiroute.borrowed-codex-source-path/v1",
+ "hiroute.candidate-capability/v1",
+ "hiroute.candidate-protocol-profile/v1",
+ "hiroute.change-preview-consent/v1",
+ "hiroute.change-preview/v1",
+ "hiroute.classifier-decision-test-result/v1",
+ "hiroute.classifier-decision-test/v1",
+ "hiroute.claude-native-layers/v1",
+ "hiroute.claude-native-messages/v1",
+ "hiroute.client-protocol-profile/v1",
+ "hiroute.client-service-status/v1",
+ "hiroute.codex-catalog-artifact/v1",
+ "hiroute.codex-catalog/v1",
+ "hiroute.codex-collaboration/v1",
+ "hiroute.codex-field-restore/v1",
+ "hiroute.codex-native-files/v2",
+ "hiroute.codex-native-responses/v1",
+ "hiroute.codex-subscription-candidate/v1",
+ "hiroute.codex-subscription-discovery-evidence/v2",
+ "hiroute.codex-subscription-source/v1",
+ "hiroute.collaboration-credential/v1",
+ "hiroute.command-result/v1",
+ "hiroute.compiled-agent-plan/v1",
+ "hiroute.compiled-agent-plan/v2",
+ "hiroute.compiled-planner-policy/v1",
+ "hiroute.compute-connection-apply-request/v1",
+ "hiroute.compute-connection-authorization-request/v1",
+ "hiroute.compute-connection-change/v1",
+ "hiroute.compute-connection-options/v1",
+ "hiroute.compute-connection-preview/v1",
+ "hiroute.compute-connection-test-request/v1",
+ "hiroute.compute-control-projection/v1",
+ "hiroute.compute-discovery-evidence/v1",
+ "hiroute.compute-management-binding/v2",
+ "hiroute.compute-management-change/v2",
+ "hiroute.compute-management-key/v2",
+ "hiroute.compute-management-lineage/v2",
+ "hiroute.compute-management-mutation/v2",
+ "hiroute.compute-management-preview/v2",
+ "hiroute.compute-management-query/v2",
+ "hiroute.compute-management-snapshot/v2",
+ "hiroute.compute-management-source/v2",
+ "hiroute.compute-management-target/v2",
+ "hiroute.compute-probe-lease/v1",
+ "hiroute.compute-projection-control/v1",
+ "hiroute.compute-projection-effect-state/v1",
+ "hiroute.compute-projection-identity/v1",
+ "hiroute.compute-runtime-identity/v1",
+ "hiroute.compute-runtime-state/v1",
+ "hiroute.compute-scan-result/v1",
+ "hiroute.compute-scanner-evidence/v1",
+ "hiroute.compute-source-binding-identity/v1",
+ "hiroute.compute-source-control/v1",
+ "hiroute.compute-source-semantic-identity/v1",
+ "hiroute.compute-state/v1",
+ "hiroute.compute-subscription-check-result/v2",
+ "hiroute.compute-subscription-check/v2",
+ "hiroute.compute-subscription-checked-input/v2",
+ "hiroute.compute-subscription-control/v2",
+ "hiroute.compute-subscription-effect-marker/v1",
+ "hiroute.compute-subscription-effect/v2",
+ "hiroute.compute-subscription-preview/v2",
+ "hiroute.compute-subscription-target/v2",
+ "hiroute.compute-subscription-validation-record/v1",
+ "hiroute.connector-owned-credential/v1",
+ "hiroute.connector-owned-runtime-fallback/v1",
+ "hiroute.connector-profile/v1",
+ "hiroute.connector-registry/v1",
+ "hiroute.connector-runtime-fallback/v1",
+ "hiroute.control-compensation/v1",
+ "hiroute.control-desired/v1",
+ "hiroute.cpa-account-attestation/v1",
+ "hiroute.cpa-account-state/v1",
+ "hiroute.cpa-account/v1",
+ "hiroute.cpa-owner/v1",
+ "hiroute.cpa-source-binding-identity/v1",
+ "hiroute.cpa-subscription-catalog-capability/v1",
+ "hiroute.cpa-subscription-inventory/v1",
+ "hiroute.cpa-subscription-observed-model/v1",
+ "hiroute.cpa-subscription-runtime-fallback/v1",
+ "hiroute.cpa-subscription-validation/v1",
+ "hiroute.created-plan/v2",
+ "hiroute.daemon-ready/v1",
+ "hiroute.daemon-startup-failure/v1",
+ "hiroute.delegation-accepted/v1",
+ "hiroute.delegation-cancel-request/v1",
+ "hiroute.delegation-cancel/v1",
+ "hiroute.delegation-continue-request/v1",
+ "hiroute.delegation-get-request/v1",
+ "hiroute.delegation-get/v1",
+ "hiroute.delegation-list-request/v1",
+ "hiroute.delegation-list/v1",
+ "hiroute.delegation-native-root/v1",
+ "hiroute.delegation-persistent-journal/v1",
+ "hiroute.delegation-result-request/v1",
+ "hiroute.delegation-result/v1",
+ "hiroute.delegation-run/v1",
+ "hiroute.delegation-start-request/v1",
+ "hiroute.delegation-tool-continuation-scope/v1",
+ "hiroute.delegation-wait-request/v1",
+ "hiroute.delegation-wait/v1",
+ "hiroute.desktop-agent-settings-intent/v2",
+ "hiroute.desktop-model-save-intent/v1",
+ "hiroute.desktop-plan-intent/v1",
+ "hiroute.desktop-price-intent/v1",
+ "hiroute.desktop-rename-intent/v1",
+ "hiroute.desktop-subscription-check-intent/v1",
+ "hiroute.desktop-worker-dependency-selection-intent/v1",
+ "hiroute.desktop.cpa-artifacts/v1",
+ "hiroute.diagnostic-event/v1",
+ "hiroute.diagnostic-settings/v1",
+ "hiroute.diagnostic-status/v1",
+ "hiroute.discovered-model-candidate/v1",
+ "hiroute.empty-request/v1",
+ "hiroute.fixed-local-id/v2",
+ "hiroute.frozen-candidate-ledger/v1",
+ "hiroute.gateway-access-grant/v1",
+ "hiroute.gateway-candidate-local-id/v1",
+ "hiroute.gateway-catalog-renderer/v1",
+ "hiroute.gateway-listener-status/v1",
+ "hiroute.gateway-listener/v1",
+ "hiroute.gateway-operational-target/v1",
+ "hiroute.gateway-publication/v2",
+ "hiroute.gateway-publication/v3",
+ "hiroute.gateway.agent-plan-semantics/v1",
+ "hiroute.gateway.credential-leases/v1",
+ "hiroute.gateway.credentials/v1",
+ "hiroute.gateway.durable-publication/v1",
+ "hiroute.gateway.e2e-fixture/v2",
+ "hiroute.gateway.error/v1",
+ "hiroute.gateway.external-port-set/v2",
+ "hiroute.gateway.lifecycle-fact-envelope/v2",
+ "hiroute.gateway.port.conversation-content/v2",
+ "hiroute.gateway.port.credential/v1",
+ "hiroute.gateway.port.execution-fact/v3",
+ "hiroute.gateway.port.lifecycle-fact/v2",
+ "hiroute.gateway.port.runtime-publication/v1",
+ "hiroute.gateway.port.runtime-state/v1",
+ "hiroute.gateway.publication-snapshot/v1",
+ "hiroute.gateway.publication-snapshot/v3",
+ "hiroute.gateway.ready/v1",
+ "hiroute.gateway.ready/v2",
+ "hiroute.gateway.request-authority/v2",
+ "hiroute.gateway.sealed-candidate-execution/v1",
+ "hiroute.header-secret-lease-request/v1",
+ "hiroute.machine-envelope/v2",
+ "hiroute.managed-artifact-backup/v2",
+ "hiroute.managed-artifact-compensation/v1",
+ "hiroute.managed-artifact-marker/v2",
+ "hiroute.managed-artifact-marker/v3",
+ "hiroute.managed-artifact-marker/v4",
+ "hiroute.managed-claude-launch-descriptor/v2",
+ "hiroute.managed-collaboration-skill/v2",
+ "hiroute.managed-launch-observation/v1",
+ "hiroute.managed-launch-warning/v1",
+ "hiroute.materialized-route-digest/v1",
+ "hiroute.materialized-route-digest/v2",
+ "hiroute.migration-store/v1",
+ "hiroute.model-catalog-query/v1",
+ "hiroute.model-catalog-view/v1",
+ "hiroute.model-data/v1",
+ "hiroute.model-metadata-catalog/v1",
+ "hiroute.model-request-ir/v1",
+ "hiroute.model-stream-event/v1",
+ "hiroute.native-credential-lease-request/v1",
+ "hiroute.native-field-restore/v1",
+ "hiroute.native-files/v1",
+ "hiroute.native-observation/v2",
+ "hiroute.observation-retention/v1",
+ "hiroute.observation.ack/v2",
+ "hiroute.observation.conversation-content-envelope/v2",
+ "hiroute.observation.execution-fact-envelope/v1",
+ "hiroute.observation.execution-fact-envelope/v3",
+ "hiroute.observation.execution-pricing/v1",
+ "hiroute.observation.gap-heartbeat/v1",
+ "hiroute.observation.nack/v1",
+ "hiroute.observation.product-execution-envelope/v2",
+ "hiroute.observation.query/v2",
+ "hiroute.observation.run-link/v1",
+ "hiroute.observation.serialization-failure/v1",
+ "hiroute.observation.valuation-summary/v2",
+ "hiroute.operation-cancel-request/v1",
+ "hiroute.operation-event/v1",
+ "hiroute.operation-idempotency-lookup/v1",
+ "hiroute.operation-idempotency-result/v1",
+ "hiroute.operation-lookup/v1",
+ "hiroute.operation-step/v1",
+ "hiroute.operation-view/v1",
+ "hiroute.otel.gen-ai-mapping/v1",
+ "hiroute.plan-authoring/v2",
+ "hiroute.plan-content-change/v2",
+ "hiroute.plan-content-preview/v2",
+ "hiroute.plan-draft-change/v1",
+ "hiroute.plan-draft-control/v1",
+ "hiroute.plan-draft-preview/v1",
+ "hiroute.plan-draft/v1",
+ "hiroute.plan-editor-options-request/v1",
+ "hiroute.plan-editor-options/v1",
+ "hiroute.plan-editor/v2",
+ "hiroute.plan-lifecycle-change/v1",
+ "hiroute.plan-lifecycle-preview/v1",
+ "hiroute.plan-quality-samples-page/v1",
+ "hiroute.plan-version/v1",
+ "hiroute.planner-candidate-facts/v1",
+ "hiroute.planner-input-facts-digest/v1",
+ "hiroute.planner-input/v1",
+ "hiroute.planner-output/v1",
+ "hiroute.posix-artifact-fingerprint/v1",
+ "hiroute.prepared-discovery-input/v1",
+ "hiroute.product-publication-marker/v1",
+ "hiroute.product-publication-marker/v2",
+ "hiroute.protected-apply-ack/v2",
+ "hiroute.protected-apply-grant/v2",
+ "hiroute.protected-input-result/v1",
+ "hiroute.protected-input/v1",
+ "hiroute.rating-snapshot/v2",
+ "hiroute.registered-compute-discovery-fact/v1",
+ "hiroute.release-facts-compiler-input/v2",
+ "hiroute.release-facts-cross-reference/v2",
+ "hiroute.release-facts/v2",
+ "hiroute.release-model-data/v2",
+ "hiroute.routing-control/v1",
+ "hiroute.routing-control/v2",
+ "hiroute.routing-publication-effect/v1",
+ "hiroute.routing-publication-effect/v2",
+ "hiroute.routing-receipt/v1",
+ "hiroute.routing-skill/v1",
+ "hiroute.runtime-compensation/v1",
+ "hiroute.runtime-fallback-candidate/v1",
+ "hiroute.runtime-state/v1",
+ "hiroute.sealed-collaboration-bootstrap/v1",
+ "hiroute.secret-compensation/v1",
+ "hiroute.secret-entry/v1",
+ "hiroute.secret-entry/v2",
+ "hiroute.semantic-ledger/v1",
+ "hiroute.session-detail/v1",
+ "hiroute.session-list-query/v1",
+ "hiroute.session-list/v1",
+ "hiroute.session-lookup/v1",
+ "hiroute.session-store-status/v1",
+ "hiroute.settings-claude-model-file/v1",
+ "hiroute.settings-codex-model-file/v1",
+ "hiroute.settings-login-item/v1",
+ "hiroute.settings-model-publication/v1",
+ "hiroute.settings-service-completion/v1",
+ "hiroute.settings-skill-file/v1",
+ "hiroute.settings-skill-reference/v1",
+ "hiroute.setup-apply-request/v1",
+ "hiroute.setup-apply-result/v1",
+ "hiroute.setup-preview-digest/v1",
+ "hiroute.setup-request/v1",
+ "hiroute.setup-status/v1",
+ "hiroute.source-local-candidate/v2",
+ "hiroute.source-price-change/v2",
+ "hiroute.sqlite-backup-manifest/v2",
+ "hiroute.sqlite-backup-set/v2",
+ "hiroute.sqlite-logical-state/v1",
+ "hiroute.standalone-install/v1",
+ "hiroute.standalone-protected-input-request/v1",
+ "hiroute.standalone-protected-input-response/v1",
+ "hiroute.standalone-service-doctor/v1",
+ "hiroute.standalone-service-logs/v1",
+ "hiroute.standalone-service-status/v1",
+ "hiroute.subscription-maintenance/v2",
+ "hiroute.system-status/v1",
+ "hiroute.value-ledger-entry/v1",
+ "hiroute.value-query/v1",
+ "hiroute.value-view/v1",
+ "hiroute.web-confirmation/v1",
+ "hiroute.work-plan-list-request/v1",
+ "hiroute.work-plan-list/v1",
+ "hiroute.worker-cancel-request/v1",
+ "hiroute.worker-command-data/v1",
+ "hiroute.worker-continue-request/v1",
+ "hiroute.worker-dependencies-discover-request/v1",
+ "hiroute.worker-dependencies-select-request/v1",
+ "hiroute.worker-dependencies-view/v1",
+ "hiroute.worker-dependency-selection-compensation/v1",
+ "hiroute.worker-dependency-selection-confirmation/v1",
+ "hiroute.worker-exec-request/v1",
+ "hiroute.worker-executor-availability-list/v1",
+ "hiroute.worker-list-request/v1",
+ "hiroute.worker-plans-request/v1",
+ "hiroute.worker-read-data/v1",
+ "hiroute.worker-read-request/v1",
+ "hiroute.worker-receipt/v1",
+ "hiroute.worker-result-request/v1",
+ "hiroute.worker-settings/v1",
+ "hiroute.worker-status-request/v1",
+ "hiroute.worker-submission-receipt/v1",
+ "hiroute.worker-wait-request/v1"
+ ],
+ "rejection_paths": [
+ "crates/domain/src/publication/mod.rs",
+ "crates/gateway/src/publication/tests.rs",
+ "tools/e2e-harness/tests/p0_gateway_request_authority.rs"
+ ],
+ "schema": "hiroute.contract-compatibility-support/v1",
+ "subjects": [
+ {
+ "audited_prefixes": [
+ "hiroute.e2e.sut-build-attestation"
+ ],
+ "current_contracts": [
+ "hiroute.e2e.sut-build-attestation/v3"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "e2e/schema/p0-production-launcher.schema.json",
+ "tools/e2e-harness/src/p0/production/types.rs",
+ "tools/e2e-harness/tests/p0_gateway_oracle.rs"
+ ],
+ "contract": "hiroute.e2e.sut-build-attestation/v1",
+ "mode": "frozen_fixture",
+ "owner": "gateway-e2e-oracle",
+ "reason": "Keep the sealed historical Gateway Oracle build proof isolated from current candidate preparation.",
+ "removal_condition": "Remove only with the sealed Oracle launcher schema, frozen attestation type, and its dedicated historical test."
+ }
+ ],
+ "subject": "gateway_e2e_build_attestation"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.gateway.port.execution-fact",
+ "hiroute.observation.execution-fact-envelope",
+ "hiroute.observation.product-execution-envelope"
+ ],
+ "current_contracts": [
+ "hiroute.gateway.port.execution-fact/v3",
+ "hiroute.observation.execution-fact-envelope/v3",
+ "hiroute.observation.product-execution-envelope/v2"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/domain/src/observation/execution_validation.rs",
+ "crates/domain/src/observation/execution_tests.rs",
+ "e2e/golden/p0-gateway-golden.json",
+ "e2e/schema/p0-execution-fact.schema.json",
+ "tools/e2e-harness/src/p0/types.rs"
+ ],
+ "contract": "hiroute.observation.execution-fact-envelope/v1",
+ "mode": "recovery_read_only",
+ "owner": "observation-storage",
+ "reason": "Authenticate already-persisted V1 observations during read and backfill; live ingestion rejects them.",
+ "removal_condition": "Remove only when an inventory of every active activity.db and every still-supported backup reports zero V1 observation rows; a backup containing V1 must either retain the authenticated reader or be explicitly retired by its retention owner."
+ },
+ {
+ "allowed_paths": [
+ "e2e/schema/p0-production-collector.schema.json",
+ "tools/e2e-harness/src/p0/production/collector.rs",
+ "tools/e2e-harness/src/p0/production/types.rs",
+ "tools/e2e-harness/tests/p0_gateway_oracle.rs"
+ ],
+ "contract": "hiroute.observation.execution-fact-envelope/v2",
+ "mode": "frozen_fixture",
+ "owner": "gateway-e2e-oracle",
+ "reason": "Preserve the prior production collector and its explicit incompatibility assertion outside current candidate smoke.",
+ "removal_condition": "Remove only in the same change that deletes the sealed Oracle collector schema, its frozen types, and its dedicated historical test."
+ }
+ ],
+ "subject": "execution_observation"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.gateway-publication",
+ "hiroute.gateway.publication-snapshot"
+ ],
+ "current_contracts": [
+ "hiroute.gateway-publication/v3",
+ "hiroute.gateway.publication-snapshot/v3"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/domain/src/publication/mod.rs",
+ "e2e/product/golden/routing/compiled-publication.v2.json",
+ "e2e/product/golden/routing/routing-boundary.v1.json",
+ "tools/product-e2e/tests/routing_plans.rs"
+ ],
+ "contract": "hiroute.gateway-publication/v2",
+ "mode": "recovery_read_only",
+ "owner": "routing-publication",
+ "reason": "Authenticate persisted Product publications and the frozen deterministic fixture, then convert them to V3 before a new write.",
+ "removal_condition": "Remove only when inventories of active, prepared, and last-known-good publication slots, recovery journals, and every still-supported backup report zero V2 aggregates; a backup containing V2 must retain conversion or be explicitly retired."
+ },
+ {
+ "allowed_paths": [
+ "crates/gateway/src/server.rs",
+ "e2e/schema/p0-gateway-publication.schema.json",
+ "tools/e2e-harness/src/p0/types.rs"
+ ],
+ "contract": "hiroute.gateway.publication-snapshot/v1",
+ "mode": "frozen_fixture",
+ "owner": "gateway-e2e-oracle",
+ "reason": "Preserve the sealed historical Oracle launcher and its schema; current candidate smoke uses V3 inputs.",
+ "removal_condition": "Remove only in the same change that deletes the sealed Oracle launcher, the V1 publication schema, and the dedicated historical scenario; never remove it from current-smoke work alone."
+ },
+ {
+ "allowed_paths": [
+ "tools/e2e-harness/src/p0/production/legacy_inputs.rs"
+ ],
+ "contract": "hiroute.gateway.publication-snapshot/v2",
+ "mode": "frozen_fixture",
+ "owner": "gateway-e2e-oracle",
+ "reason": "Seed only the historical sealed Oracle before its current-input adapter replaces the publication with V3.",
+ "removal_condition": "Remove only in the same change that deletes the historical Oracle input adapter and its sealed V2 seed fixture."
+ }
+ ],
+ "subject": "routing_publication"
+ },
+ {
+ "audited_prefixes": [
+ "agent-plan-compiler",
+ "hiroute.compiled-agent-plan",
+ "hiroute.materialized-route-digest",
+ "hiroute.plan-content-change",
+ "hiroute.routing-control-change",
+ "hiroute.routing-control",
+ "hiroute.routing-publication-effect"
+ ],
+ "current_contracts": [
+ "agent-plan-compiler/v2",
+ "hiroute.compiled-agent-plan/v2",
+ "hiroute.materialized-route-digest/v2",
+ "hiroute.plan-content-change/v2",
+ "hiroute.routing-control/v2",
+ "hiroute.routing-publication-effect/v2"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/domain/src/routing/mod.rs",
+ "e2e/product/golden/routing/compiled-publication.v2.json"
+ ],
+ "contract": "agent-plan-compiler/v1",
+ "mode": "recovery_read_only",
+ "owner": "routing-compiler",
+ "reason": "Authenticate and convert the frozen V1 compiled-plan fixture; current authoring emits compiler V2.",
+ "removal_condition": "Remove only when publication and recovery-journal inventories, including every still-supported backup, report zero compiler-V1 aggregates and zero compiled-plan-V1 bodies."
+ },
+ {
+ "allowed_paths": [
+ "crates/domain/src/routing/mod.rs",
+ "e2e/product/golden/routing/compiled-publication.v2.json"
+ ],
+ "contract": "hiroute.compiled-agent-plan/v1",
+ "mode": "recovery_read_only",
+ "owner": "routing-compiler",
+ "reason": "Authenticate persisted V1 plans and reseal their unchanged executable arrays as V2.",
+ "removal_condition": "Remove only when active, prepared, and last-known-good publications, recovery journals, and every still-supported backup report zero compiled-plan-V1 bodies."
+ },
+ {
+ "allowed_paths": [
+ "crates/domain/src/routing/materialized.rs"
+ ],
+ "contract": "hiroute.materialized-route-digest/v1",
+ "mode": "recovery_read_only",
+ "owner": "routing-compiler",
+ "reason": "Verify a V1 compiled plan before converting it; current compilation uses the V2 executable-only digest.",
+ "removal_condition": "Remove only with the compiled-plan-V1 reader after the same publication, journal, and backup inventory reports zero V1 materialized-route digests."
+ },
+ {
+ "allowed_paths": [
+ "crates/application/src/control_plane/tests.rs",
+ "crates/daemon/tests/support/plan_content_process.py"
+ ],
+ "contract": "hiroute.routing-control-change/v1",
+ "mode": "rejection_fixture",
+ "owner": "routing-authoring",
+ "reason": "Prove direct Local Control and product clients reject the retired create/update authoring shape without reading facts or admitting an Operation.",
+ "removal_condition": "Remove only when the minimum supported client version can no longer emit the retired shape and the Local Control rejection assertion is deliberately retired in the same change."
+ },
+ {
+ "allowed_paths": [
+ "crates/domain/src/operation/routing.rs"
+ ],
+ "contract": "hiroute.routing-control/v1",
+ "mode": "recovery_read_only",
+ "owner": "operation-journal",
+ "reason": "Decode and validate already-durable V1 routing operations during crash recovery.",
+ "removal_condition": "Remove only when active and retained operation journals plus every still-supported backup report zero V1 routing-control records; a backup containing one must retain recovery or be explicitly retired."
+ },
+ {
+ "allowed_paths": [
+ "crates/domain/src/operation/routing.rs"
+ ],
+ "contract": "hiroute.routing-publication-effect/v1",
+ "mode": "recovery_read_only",
+ "owner": "operation-journal",
+ "reason": "Decode and validate the publication effect paired with a durable V1 routing operation.",
+ "removal_condition": "Remove only when the routing-control-V1 gate is satisfied and the same journal and backup inventory reports zero paired V1 publication effects."
+ }
+ ],
+ "subject": "compiled_routing"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.machine-envelope",
+ "hiroute.protected-apply-ack",
+ "hiroute.protected-apply-grant"
+ ],
+ "current_contracts": [
+ "hiroute.machine-envelope/v2",
+ "hiroute.protected-apply-ack/v2",
+ "hiroute.protected-apply-grant/v2"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/daemon/src/control/bin.rs"
+ ],
+ "contract": "hiroute.protected-apply-grant/v1",
+ "mode": "rejection_fixture",
+ "owner": "local-control",
+ "reason": "Prove the protected launcher rejects an uncorrelated V1 grant.",
+ "removal_condition": "Remove only when the minimum supported protected launcher emits correlated V2 grants and the explicit V1 rejection assertion is retired in the same change."
+ }
+ ],
+ "subject": "protected_local_control"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.managed-artifact-marker"
+ ],
+ "current_contracts": [
+ "hiroute.managed-artifact-marker/v4"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/local-storage/src/control/mod.rs",
+ "crates/local-storage/src/control/agent_transaction_tests.rs"
+ ],
+ "contract": "hiroute.managed-artifact-marker/v2",
+ "mode": "recovery_read_only",
+ "owner": "local-storage",
+ "reason": "Authenticate legacy exists/write compensation and migrate its marker metadata to V4 before recovery.",
+ "removal_condition": "Remove only when every active restore directory contains zero V2 markers after open-time migration and each still-supported backup either restores through V4 successfully or is explicitly retired."
+ },
+ {
+ "allowed_paths": [
+ "crates/local-storage/src/control/mod.rs",
+ "crates/local-storage/src/control/agent_transaction_tests.rs"
+ ],
+ "contract": "hiroute.managed-artifact-marker/v3",
+ "mode": "recovery_read_only",
+ "owner": "local-storage",
+ "reason": "Authenticate legacy delete compensation and migrate its marker metadata to V4 before recovery.",
+ "removal_condition": "Remove only when every active restore directory contains zero V3 markers after open-time migration and each still-supported backup either restores through V4 successfully or is explicitly retired."
+ }
+ ],
+ "subject": "managed_artifact_marker"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.model-metadata-catalog",
+ "hiroute.rating-snapshot",
+ "hiroute.release-facts-compiler-input",
+ "hiroute.release-model-data"
+ ],
+ "current_contracts": [
+ "hiroute.model-metadata-catalog/v1",
+ "hiroute.rating-snapshot/v2",
+ "hiroute.release-facts-compiler-input/v2",
+ "hiroute.release-model-data/v2"
+ ],
+ "legacy_support": [],
+ "subject": "release_model_data"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.secret-entry"
+ ],
+ "current_contracts": [
+ "hiroute.secret-entry/v2"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/local-storage/src/secrets/mod.rs"
+ ],
+ "contract": "hiroute.secret-entry/v1",
+ "mode": "recovery_read_only",
+ "owner": "secret-storage",
+ "reason": "Authenticate fully identified legacy entries and journal images inside the atomic V17 rewrap migration.",
+ "removal_condition": "Remove only when every active V17 store reports zero V1 secret-entry and before/staged journal slots, and every still-supported pre-V17 backup has either passed authenticated restore-to-V2 testing or been explicitly retired."
+ }
+ ],
+ "subject": "secret_entry_aad"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.product-publication-marker"
+ ],
+ "current_contracts": [
+ "hiroute.product-publication-marker/v2"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/daemon/src/control/runtime/effects/tests/publication_validation.rs",
+ "crates/daemon/src/control/runtime/publication.rs"
+ ],
+ "contract": "hiroute.product-publication-marker/v1",
+ "mode": "recovery_read_only",
+ "owner": "operation-journal",
+ "reason": "Authenticate an already-durable publication effect, reconstruct its exact Product record from the owning Operation and intent, and normalize it to V2 before the next recovery checkpoint.",
+ "removal_condition": "Remove only when active and retained operation journals report zero V1 publication markers and every still-supported backup has either passed exact V1-to-V2 recovery or been explicitly retired."
+ }
+ ],
+ "subject": "product_publication_marker"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.gateway.ready"
+ ],
+ "current_contracts": [
+ "hiroute.gateway.ready/v2"
+ ],
+ "legacy_support": [
+ {
+ "allowed_paths": [
+ "crates/gateway/src/server.rs",
+ "e2e/schema/p0-production-readiness.schema.json",
+ "tools/e2e-harness/src/p0/types.rs"
+ ],
+ "contract": "hiroute.gateway.ready/v1",
+ "mode": "frozen_fixture",
+ "owner": "gateway-e2e-oracle",
+ "reason": "Keep the sealed pre-product Gateway Oracle readiness response isolated from the managed current runtime, which emits and probes V2 only.",
+ "removal_condition": "Remove only in the same change that deletes the sealed historical Oracle launcher, its V1 readiness schema, and the dedicated readiness assertion."
+ }
+ ],
+ "subject": "gateway_process_readiness"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.release-facts-cross-reference"
+ ],
+ "current_contracts": [
+ "hiroute.release-facts-cross-reference/v2"
+ ],
+ "legacy_support": [],
+ "subject": "release_facts_cross_reference"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.agent-routing-catalog"
+ ],
+ "current_contracts": [
+ "hiroute.agent-routing-catalog/v1"
+ ],
+ "legacy_support": [],
+ "subject": "agent_routing_catalog"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.web-confirmation"
+ ],
+ "current_contracts": [
+ "hiroute.web-confirmation/v1"
+ ],
+ "legacy_support": [],
+ "subject": "desktop_web_confirmation"
+ },
+ {
+ "audited_prefixes": [
+ "hiroute.worker-settings"
+ ],
+ "current_contracts": [
+ "hiroute.worker-settings/v1"
+ ],
+ "legacy_support": [],
+ "subject": "worker_settings"
+ }
+ ]
+ },
+ "path": "contracts/compatibility-support.v1.json",
+ "sha256": "5d79765b6e5c6ad39463e5e3747074b9c97226e27b5c5b9b36429514d439696b"
+ }
+ },
+ "release": {
+ "artifacts": [
+ {
+ "filename": "HiRoute-0.1.0-5f3ee7c96f4f-macos-arm64-trial.dmg",
+ "sha256": "6f3babf6ba3c16bb760cff6c5afa664c326dd651728f7cd36f54b27268a643b1",
+ "size": 73383351
+ },
+ {
+ "filename": "hiroute-0.1.0-5f3ee7c96f4f-x86_64-unknown-linux-gnu.tar.gz",
+ "sha256": "b54b62e48d9576d382a29e6c99e0903ecaed8cabd2b5a3d9c74f8f3ea19bdf94",
+ "size": 62812169
+ },
+ {
+ "filename": "hiroute-0.1.0-5f3ee7c96f4f-x86_64-unknown-linux-gnu.tar.gz.json",
+ "sha256": "d3e2b5a41d6624b48bf14c72670fd4c4ce6870a6247bdc785e7253cfc9935bba",
+ "size": 2123
+ }
+ ],
+ "channel": "stable",
+ "published_at": "2026-09-22T08:20:13Z",
+ "repository": "higress-group/HiRoute",
+ "revision": "5f3ee7c96f4f6a02c1a730008055d413c28e1d5e",
+ "tag": "v0.1.0"
+ },
+ "schema": "hiroute.release-contract-snapshot/v1",
+ "storage": {
+ "source_path": "crates/local-storage/src/migrations/mod.rs",
+ "source_sha256": "c020c555d67b739395c142cd073104232b244f10f3aeda44af3e9f8c97b51a52",
+ "sql_schema_version": 22
+ }
+}
diff --git a/crates/application-api/Cargo.toml b/crates/application-api/Cargo.toml
index 792abf23..d061c2b9 100644
--- a/crates/application-api/Cargo.toml
+++ b/crates/application-api/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "hiroute-application-api"
-version = "0.1.0"
+version = "0.2.0"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
diff --git a/crates/application-api/src/generated.rs b/crates/application-api/src/generated.rs
index a6692cac..e29aacea 100644
--- a/crates/application-api/src/generated.rs
+++ b/crates/application-api/src/generated.rs
@@ -179,7 +179,7 @@ fn client_hello_v2_schema() -> Value {
"api_version": { "$ref": "local-control.v2.schema.json#/properties/schema_version" },
"machine_schema_version": { "$ref": "local-control.v2.schema.json#/properties/schema_version" },
"client_name": { "type": "string", "minLength": 1, "maxLength": 128 },
- "client_version": { "const": env!("CARGO_PKG_VERSION") }
+ "client_version": { "const": crate::LOCAL_CONTROL_RELEASE_VERSION }
}
})
}
diff --git a/crates/application-api/src/lib.rs b/crates/application-api/src/lib.rs
index 5d7dd80d..903a2c4b 100644
--- a/crates/application-api/src/lib.rs
+++ b/crates/application-api/src/lib.rs
@@ -66,12 +66,12 @@ pub use hiroute_domain::{
pub use protocol::{
AgentCheckRequestV1, AgentCheckScopeV1, AgentCheckSuiteV1, AgentModelCheckTargetV2,
ApplyRequestV1, ApplyResultV1, ClientHelloV1, ErrorCategory, ErrorCode, ErrorV1,
- FallbackPolicyV1, FreePoolModeV1, LOCAL_CONTROL_MAX_FRAME_BYTES, LOCAL_CONTROL_SCHEMA_V2,
- LocalControlRequestV2, LocalControlWireRequestV2, MACHINE_ENVELOPE_SCHEMA_V2,
- MachineEnvelopeV2, MachineErrorV1, MachineNextActionV1, MachineStatus, NextActionV1,
- OperationCancelRequestV1, OperationLookupV1, OperationReferenceV1, PreviewRequestV1,
- PreviewResultV1, PrincipalKind, PrincipalV1, ProtectedClientGrantV2, RoutingModeV1,
- SETUP_REQUEST_SCHEMA_V1, ServerHelloV1, SessionContentModeV1, SessionListPageV1,
+ FallbackPolicyV1, FreePoolModeV1, LOCAL_CONTROL_MAX_FRAME_BYTES, LOCAL_CONTROL_RELEASE_VERSION,
+ LOCAL_CONTROL_SCHEMA_V2, LocalControlRequestV2, LocalControlWireRequestV2,
+ MACHINE_ENVELOPE_SCHEMA_V2, MachineEnvelopeV2, MachineErrorV1, MachineNextActionV1,
+ MachineStatus, NextActionV1, OperationCancelRequestV1, OperationLookupV1, OperationReferenceV1,
+ PreviewRequestV1, PreviewResultV1, PrincipalKind, PrincipalV1, ProtectedClientGrantV2,
+ RoutingModeV1, SETUP_REQUEST_SCHEMA_V1, ServerHelloV1, SessionContentModeV1, SessionListPageV1,
SessionListRequestV1, SessionLookupV1, SetupApplyRequestV1, SetupPreviewV1, SetupRequestV1,
SetupSelectionV1, SystemStatusV1, ValuePeriodV1, ValueRequestV1, ValueScopeViewV1, WarningV1,
negotiate_hello,
diff --git a/crates/application-api/src/protocol.rs b/crates/application-api/src/protocol.rs
index 94df731c..36152c90 100644
--- a/crates/application-api/src/protocol.rs
+++ b/crates/application-api/src/protocol.rs
@@ -9,6 +9,9 @@ use crate::commands::CoverageState;
pub const LOCAL_CONTROL_SCHEMA_V2: SchemaVersion = SchemaVersion::new(2, 0);
pub const MACHINE_ENVELOPE_SCHEMA_V2: SchemaVersion = SchemaVersion::new(2, 0);
+/// Product release used by the same-release Local Control handshake, independent
+/// of the package versions of client transport and implementation libraries.
+pub const LOCAL_CONTROL_RELEASE_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Maximum newline-delimited JSON frame size, including the trailing newline.
pub const LOCAL_CONTROL_MAX_FRAME_BYTES: usize = 10 * 1024 * 1024;
@@ -87,15 +90,15 @@ pub fn negotiate_hello(client: &ClientHelloV1) -> Result<ServerHelloV1, ErrorV1>
}
if client.client_name.is_empty()
|| client.client_name.len() > 128
- || client.client_version != env!("CARGO_PKG_VERSION")
+ || client.client_version != LOCAL_CONTROL_RELEASE_VERSION
{
return Err(ErrorV1::new(ErrorCode::InvalidArguments));
}
Ok(ServerHelloV1 {
api_version: LOCAL_CONTROL_SCHEMA_V2,
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
- daemon_version: env!("CARGO_PKG_VERSION").to_owned(),
- release_version: env!("CARGO_PKG_VERSION").to_owned(),
+ daemon_version: LOCAL_CONTROL_RELEASE_VERSION.to_owned(),
+ release_version: LOCAL_CONTROL_RELEASE_VERSION.to_owned(),
capabilities: vec![
"local-control-v2".to_owned(),
"client-access-v1".to_owned(),
diff --git a/crates/application/src/agent_connection/claude_model_journal.rs b/crates/application/src/agent_connection/claude_model_journal.rs
index 932a003e..cc8a4315 100644
--- a/crates/application/src/agent_connection/claude_model_journal.rs
+++ b/crates/application/src/agent_connection/claude_model_journal.rs
@@ -1,8 +1,9 @@
use hiroute_domain::{
AgentClaudePresetValuesV2, AgentConfigChangeV1, AgentConnectionControlIntentV1,
AgentConnectionEffectRoleV1, AgentConnectionTransactionKindV1, AgentFacetIntent,
- AgentModelGrantV2, AgentSettingsSpecV2, CanonicalDigest, ExternalEffectIntentV1, OperationId,
- OperationV1, OperationValidationError, PortError, PortErrorCode, PortResult,
+ AgentModelGrantV2, AgentOperationRead, AgentSettingsSpecV2, CanonicalDigest,
+ ExternalEffectIntentV1, OperationId, OperationValidationError, PortError, PortErrorCode,
+ PortResult,
};
use serde::{Deserialize, Serialize};
use std::path::Path;
@@ -103,22 +104,22 @@ pub fn decode_settings_claude_model_file(
}
pub fn settings_claude_model_file_for_operation(
- operation: &OperationV1,
+ operation: &(impl AgentOperationRead + ?Sized),
intent: &ExternalEffectIntentV1,
) -> PortResult<ClaudeModelFilePayload> {
let payload = decode_settings_claude_model_file(intent)?;
let spec: AgentSettingsSpecV2 =
- serde_json::from_value(operation.plan.spec().desired_state.clone())
+ serde_json::from_value(operation.agent_input().spec.desired_state.clone())
.map_err(|_| invalid())?;
- if operation.plan.spec().command_id != "agents.settings.apply"
+ if operation.agent_input().spec.command_id != "agents.settings.apply"
|| spec.context_id != payload.context_id
- || !operation.plan.external().contains(intent)
+ || !operation.agent_input().external.contains(intent)
{
return Err(invalid());
}
- let state = &operation.plan.control()["payload"]["state"];
+ let state = &operation.agent_input().control["payload"]["state"];
if state["accept_digest"]
- != serde_json::to_value(&operation.accepted_digest).map_err(|_| invalid())?
+ != serde_json::to_value(operation.accepted_digest()).map_err(|_| invalid())?
{
return Err(invalid());
}
@@ -133,12 +134,12 @@ pub fn settings_claude_model_file_for_operation(
) => {
let grant: AgentModelGrantV2 =
serde_json::from_value(state["model_grant"].clone()).map_err(|_| invalid())?;
- let [mutation] = operation.plan.agent_access_grants() else {
+ let [mutation] = operation.agent_input().grants else {
return Err(invalid());
};
let scope = mutation.desired_scope().ok_or_else(invalid)?;
if scope.model_grant() != &grant
- || previous_operation.as_ref() == Some(&operation.operation_id)
+ || previous_operation.as_ref() == Some(operation.operation_id())
|| grant
.claude_preset_values(settings, &snapshot.native_presets)
.map_err(|_| invalid())?
@@ -150,7 +151,7 @@ pub fn settings_claude_model_file_for_operation(
(
AgentFacetIntent::Restore { restore_point_ref },
ClaudeModelFileAction::Restore { original_operation },
- ) if original_operation != &operation.operation_id
+ ) if original_operation != operation.operation_id()
&& *restore_point_ref == super::codex_model_restore_point_ref(original_operation) => {}
_ => return Err(invalid()),
}
diff --git a/crates/application/src/agent_connection/model_journal.rs b/crates/application/src/agent_connection/model_journal.rs
index aa0b129c..14ee6549 100644
--- a/crates/application/src/agent_connection/model_journal.rs
+++ b/crates/application/src/agent_connection/model_journal.rs
@@ -1,8 +1,8 @@
//! Non-secret native model file intent, bound to the original settings Operation.
use hiroute_domain::{
AgentConnectionControlIntentV1, AgentConnectionEffectRoleV1, AgentConnectionTransactionKindV1,
- AgentConnectionTransactionSubjectV1, AgentFacetIntent, AgentSettingsSpecV2, CanonicalDigest,
- ExternalEffectIntentV1, OperationId, OperationV1, OperationValidationError, PortError,
+ AgentConnectionTransactionSubjectV1, AgentFacetIntent, AgentOperationRead, AgentSettingsSpecV2,
+ CanonicalDigest, ExternalEffectIntentV1, OperationId, OperationValidationError, PortError,
PortErrorCode, PortResult,
};
use serde::{Deserialize, Serialize};
@@ -240,22 +240,22 @@ pub fn decode_settings_codex_model_file(
/// Validate membership and facet again when consuming a persisted journal during execution.
/// The original payload, not a new current-state preview, supplies recovery inputs.
pub fn settings_codex_model_file_for_operation(
- operation: &OperationV1,
+ operation: &(impl AgentOperationRead + ?Sized),
intent: &ExternalEffectIntentV1,
) -> PortResult<CodexModelFilePayload> {
let payload = decode_settings_codex_model_file(intent)?;
let spec: AgentSettingsSpecV2 =
- serde_json::from_value(operation.plan.spec().desired_state.clone())
+ serde_json::from_value(operation.agent_input().spec.desired_state.clone())
.map_err(|_| invalid())?;
- if operation.plan.spec().command_id != "agents.settings.apply"
+ if operation.agent_input().spec.command_id != "agents.settings.apply"
|| spec.context_id != payload.context_id
- || !operation.plan.external().contains(intent)
+ || !operation.agent_input().external.contains(intent)
{
return Err(invalid());
}
- let state = &operation.plan.control()["payload"]["state"];
+ let state = &operation.agent_input().control["payload"]["state"];
if state["accept_digest"]
- != serde_json::to_value(&operation.accepted_digest).map_err(|_| invalid())?
+ != serde_json::to_value(operation.accepted_digest()).map_err(|_| invalid())?
{
return Err(invalid());
}
@@ -271,7 +271,7 @@ pub fn settings_codex_model_file_for_operation(
) => {
let grant: hiroute_domain::AgentModelGrantV2 =
serde_json::from_value(state["model_grant"].clone()).map_err(|_| invalid())?;
- let [mutation] = operation.plan.agent_access_grants() else {
+ let [mutation] = operation.agent_input().grants else {
return Err(invalid());
};
let scope = mutation.desired_scope().ok_or_else(invalid)?;
@@ -282,7 +282,7 @@ pub fn settings_codex_model_file_for_operation(
.codex_default_override(settings)
.map_err(|_| invalid())?
!= *model
- || previous_operation.as_ref() == Some(&operation.operation_id)
+ || previous_operation.as_ref() == Some(operation.operation_id())
{
return Err(invalid());
}
@@ -291,7 +291,7 @@ pub fn settings_codex_model_file_for_operation(
return Err(invalid());
}
if let Some(digest) = model_catalog
- && !operation.plan.external().iter().any(|intent| {
+ && !operation.agent_input().external.iter().any(|intent| {
decode_settings_codex_catalog(intent)
.is_ok_and(|catalog| &catalog.content_digest == digest)
})
@@ -305,7 +305,7 @@ pub fn settings_codex_model_file_for_operation(
original_operation,
native_model,
},
- ) if original_operation != &operation.operation_id
+ ) if original_operation != operation.operation_id()
&& *restore_point_ref == codex_model_restore_point_ref(original_operation)
&& &spec.restore_native_model == native_model => {}
_ => return Err(invalid()),
diff --git a/crates/application/src/compiler/explicit.rs b/crates/application/src/compiler/explicit.rs
index fd99c95f..e7d5fb22 100644
--- a/crates/application/src/compiler/explicit.rs
+++ b/crates/application/src/compiler/explicit.rs
@@ -148,8 +148,8 @@ pub fn compile_agent_plan_v2(
.route_digest()
.map_err(|_| AgentPlanCompilerError::InvalidCompiledPlan)?;
CompiledAgentPlanV1::seal_current(CompiledAgentPlanBodyV1 {
- schema: AGENT_PLAN_COMPILED_SCHEMA_V2.into(),
- compiler_revision: AGENT_PLAN_COMPILER_REVISION_V2.into(),
+ schema: AGENT_PLAN_COMPILED_SCHEMA_V3.into(),
+ compiler_revision: AGENT_PLAN_COMPILER_REVISION_V3.into(),
identity,
agent_plan_revision: revision,
materialized_route_digest,
diff --git a/crates/application/src/compiler/test_fixtures.rs b/crates/application/src/compiler/test_fixtures.rs
index 5b48c499..a9c4efb9 100644
--- a/crates/application/src/compiler/test_fixtures.rs
+++ b/crates/application/src/compiler/test_fixtures.rs
@@ -257,6 +257,10 @@ fn fixture_protocol_profile(
upstream_protocol: UpstreamProtocol::Responses,
model_configuration_id: model_configuration_id.into(),
native_model: native_model.into(),
+ model_support: StoredModelSupportV1 {
+ tools: GatewayCriticalFactV1::Exact(true),
+ vision: GatewayCriticalFactV1::Exact(true),
+ },
request: GatewayRequestFeatureProfileV1 {
text: exact,
initial_instructions: exact,
diff --git a/crates/application/src/compiler/tests.rs b/crates/application/src/compiler/tests.rs
index 68ea2f45..cb3cf51f 100644
--- a/crates/application/src/compiler/tests.rs
+++ b/crates/application/src/compiler/tests.rs
@@ -264,7 +264,7 @@ fn compiler_preserves_exact_ordered_credential_refs_and_rejects_duplicates() {
fn compiler_unknown_fact_revision_and_unqualified_capability_fail_closed() {
let desired = smart_desired();
let mut facts = compilation_facts();
- facts.compiler_revision = "agent-plan-compiler/v2".into();
+ facts.compiler_revision = "agent-plan-compiler/v3".into();
assert!(matches!(
materialize_agent_plan(&desired, &facts).unwrap_err(),
AgentPlanCompilerError::Facts(CompilerFactError::UnsupportedCompilerRevision)
@@ -329,7 +329,7 @@ fn compiler_compiled_revision_is_immutable_and_unknown_compiler_revision_is_reje
let plan = &mut publication.plans[0];
assert_eq!(
plan.body.compiler_revision,
- hiroute_domain::AGENT_PLAN_COMPILER_REVISION_V2
+ hiroute_domain::AGENT_PLAN_COMPILER_REVISION_V3
);
std::sync::Arc::make_mut(&mut plan.body).compiler_revision =
"unsupported-compiler-revision".into();
@@ -548,7 +548,7 @@ fn compiler_publication_bytes_are_current_deterministic_and_secret_free() {
assert!(!lowercase.contains("ordering_price_version"));
assert!(!lowercase.contains("price_rate_id"));
assert!(lowercase.contains("\"bearer_token_sha256\""));
- assert!(lowercase.contains("\"catalog_renderer_revision\""));
+ assert!(!lowercase.contains("\"catalog_renderer_revision\""));
assert!(lowercase.contains("\"credential_refs\""));
assert!(lowercase.contains("\"endpoint\""));
assert!(!lowercase.contains("\"authorization\":"));
@@ -568,9 +568,11 @@ fn compiler_publication_bytes_are_current_deterministic_and_secret_free() {
);
}
+ let restored = hiroute_domain::GatewayPublicationV1::decode(&bytes).unwrap();
+ assert_eq!(restored.canonical_bytes().unwrap(), bytes);
assert_eq!(
- hiroute_domain::GatewayPublicationV1::decode(&bytes).unwrap(),
- first
+ hiroute_domain::StoredPublicationV1::freeze(&restored).unwrap(),
+ hiroute_domain::StoredPublicationV1::freeze(&first).unwrap()
);
}
diff --git a/crates/application/src/operations/mod.rs b/crates/application/src/operations/mod.rs
index c74a36c5..16fa9e60 100644
--- a/crates/application/src/operations/mod.rs
+++ b/crates/application/src/operations/mod.rs
@@ -816,11 +816,14 @@ fn settings_service_completion_digest(
publication_digest: &CanonicalDigest,
) -> Result<CanonicalDigest, TransactionError> {
CanonicalDigest::of(&(
+ "hiroute.settings-service-proof/v2",
operation.operation_id.as_str(),
&operation.accepted_digest,
publication_revision,
publication_digest,
- &operation.plan,
+ operation
+ .stable_input_digest()
+ .map_err(|_| TransactionError::InvalidArguments)?,
))
.map_err(|_| TransactionError::InvalidArguments)
}
diff --git a/crates/application/src/operations/tests/settings_tail.rs b/crates/application/src/operations/tests/settings_tail.rs
index 063e20f5..514467fe 100644
--- a/crates/application/src/operations/tests/settings_tail.rs
+++ b/crates/application/src/operations/tests/settings_tail.rs
@@ -460,7 +460,7 @@ fn settings_receipt_parse_accepts_only_the_registered_schema() {
);
let mut wrong_schema = receipt.clone();
- wrong_schema.schema = "hiroute.settings-service-completion/v2".to_owned();
+ wrong_schema.schema = format!("hiroute.settings-service-completion/v{}", 999);
assert_eq!(
SettingsServiceCompletionV1::parse(&serde_json::to_string(&wrong_schema).unwrap()),
None
diff --git a/crates/application/src/publication/tests.rs b/crates/application/src/publication/tests.rs
index f803c525..034db190 100644
--- a/crates/application/src/publication/tests.rs
+++ b/crates/application/src/publication/tests.rs
@@ -253,7 +253,7 @@ fn publication_revision_and_grant_generation_invariants_are_independent() {
activator.publish(&first, None).unwrap();
let mut same_revision = compiled_publication(11);
- same_revision.catalog_renderer_revision = "hiroute.gateway-catalog-renderer/v2".into();
+ same_revision.authority_epoch += 1;
same_revision.validate().unwrap();
let same_record =
PublicationRecordV1::from_publication(workspace.clone(), &same_revision).unwrap();
diff --git a/crates/application/src/routing/lifecycle/tests.rs b/crates/application/src/routing/lifecycle/tests.rs
index b41eb022..d4eb1688 100644
--- a/crates/application/src/routing/lifecycle/tests.rs
+++ b/crates/application/src/routing/lifecycle/tests.rs
@@ -1,17 +1,19 @@
use super::*;
fn state() -> PlanLifecycleSnapshotV1 {
- let legacy = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let legacy = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
let versions = legacy
.plans
.iter()
.map(|compiled| {
- let recovered =
- PlanVersionV1::from_legacy_compiled(legacy.workspace_id.clone(), compiled.clone())
- .unwrap();
+ let recovered = PlanVersionV1::from_unversioned_compiled_recovery(
+ legacy.workspace_id.clone(),
+ compiled.clone(),
+ )
+ .unwrap();
PlanVersionV1::new(
legacy.workspace_id.clone(),
recovered.configuration,
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index ed926001..851a2d08 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "hiroute-cli"
-version = "0.1.0"
+version = "0.2.0"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
diff --git a/crates/cli/tests/work_plans.rs b/crates/cli/tests/work_plans.rs
index 3b2901f7..0ffe32a0 100644
--- a/crates/cli/tests/work_plans.rs
+++ b/crates/cli/tests/work_plans.rs
@@ -1,69 +1,9 @@
#![cfg(unix)]
-use hiroute_application::ApplicationService;
-use hiroute_application::delegation::work_plans::*;
-use hiroute_application_api::*;
-use hiroute_daemon::control::{ProductionControlRuntime, start_control};
-use hiroute_domain::delegation::WorkerHarnessV1;
-use hiroute_domain::{
- AgentCollaborationCredential, AgentCollaborationGrant, AgentCollaborationRevocationStorePort,
- AgentIngressProtocolV1, WorkspaceId,
-};
-use hiroute_integrations::TrustedReleaseCatalog;
-use hiroute_local_storage::LocalStorageSet;
use serde_json::{Value, json};
-use std::collections::BTreeSet;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::process::{Command, Stdio};
-use std::sync::{Arc, Mutex};
-use std::time::Duration;
-#[path = "work_plans/support.rs"]
-mod support;
-#[derive(Default)]
-struct Metadata(Mutex<Vec<WorkPlanMetadataV1>>);
-impl WorkPlanMetadataPort for Metadata {
- fn current_plans(
- &self,
- _: &WorkspaceId,
- _: &BTreeSet<AgentPlanId>,
- ) -> Result<Vec<WorkPlanMetadataV1>, ErrorCode> {
- // Intentionally includes unauthorized, unpublished and unbound rows: Application must
- // perform its own filtering rather than trusting an overly broad backend projection.
- Ok(self.0.lock().unwrap().clone())
- }
-}
-fn plan(
- id: &str,
- published: bool,
- bound: bool,
- availability: WorkPlanAvailabilityV1,
-) -> WorkPlanMetadataV1 {
- WorkPlanMetadataV1 {
- agent_plan_id: AgentPlanId::parse(id).unwrap(),
- alias: format!("work-{id}"),
- display_name: format!("Worker {id}"),
- purpose: "published purpose".into(),
- published,
- work: bound.then_some((WorkerHarnessV1::CodexCli, AgentIngressProtocolV1::Responses)),
- availability,
- reason: (availability != WorkPlanAvailabilityV1::Ready)
- .then(|| "harness_not_observed".into()),
- }
-}
-fn catalog() -> TrustedReleaseCatalog {
- const MANIFEST: &[u8] =
- include_bytes!("../../../assets/release-facts/current/bundle/manifest.json");
- const REGISTRY: &[u8] =
- include_bytes!("../../../assets/release-facts/current/bundle/connector-registry.json");
- const MODEL_DATA: &[u8] =
- include_bytes!("../../../assets/release-facts/current/bundle/model-data.json");
- TrustedReleaseCatalog::load_bundled_release_facts(MANIFEST, MANIFEST, REGISTRY, MODEL_DATA)
- .unwrap()
-}
-fn query() -> Value {
- json!({"workspace_id": WorkspaceId::default(), "context_id": "owner", "grant_id": "collaboration-grant/directory"})
-}
fn cli(root: &std::path::Path, payload: Value, secret: Option<&[u8]>) -> (i32, Value) {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_hiroute"));
cmd.args(["work-plans", "list", "--request-stdin", "--output", "json"])
@@ -101,190 +41,15 @@ fn cli(root: &std::path::Path, payload: Value, secret: Option<&[u8]>) -> (i32, V
)
}
-fn internal_control(root: &std::path::Path, payload: Value, secret: Option<&[u8]>) -> Value {
- let client = hiroute_cli::LocalControlClient::new("hiroute-cli", root);
- let response = client
- .call(LocalControlWireRequestV2 {
- schema_version: LOCAL_CONTROL_SCHEMA_V2,
- request_id: "work-plans-internal-control".into(),
- operation_id: "ListWorkPlans".into(),
- payload,
- protected_grant: secret.map(|secret| ProtectedClientGrantV2 {
- principal_kind: PrincipalKind::Skill,
- capability: String::from_utf8(secret.to_vec()).unwrap(),
- }),
- })
- .unwrap();
- serde_json::to_value(response).unwrap()
-}
-
-fn store_grant(
- stores: &LocalStorageSet,
- generation: u64,
- ids: &[&str],
- secret: &AgentCollaborationCredential,
-) -> AgentCollaborationGrant {
- let op = support::begin(stores, &format!("directory-{generation}"));
- let grant = AgentCollaborationGrant::issue(
- WorkspaceId::default(),
- "owner".into(),
- "collaboration-grant/directory".into(),
- generation,
- ids.iter()
- .map(|id| AgentPlanId::parse(*id).unwrap())
- .collect(),
- secret,
- )
- .unwrap();
- stores
- .control()
- .store_collaboration_grant(&op.operation_id, generation - 1, &grant)
- .unwrap();
- support::finish(stores, op);
- grant
-}
-
#[test]
-fn work_plans_production_cli_current_authority_and_metadata() {
- const CHILD: &str = "HIROUTE_DIRECTORY_TEST_CHILD";
- if std::env::var_os(CHILD).is_none() {
- let home = tempfile::tempdir().unwrap();
- use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
- std::fs::set_permissions(home.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
- // This fixture models a private Agent HOME, independently of the caller's umask.
- std::fs::DirBuilder::new()
- .mode(0o700)
- .create(home.path().join(".claude"))
- .unwrap();
- let status = Command::new(std::env::current_exe().unwrap())
- .args([
- "--exact",
- "work_plans_production_cli_current_authority_and_metadata",
- "--nocapture",
- ])
- .env(CHILD, "1")
- .env("HOME", home.path())
- .env("PATH", "/usr/bin:/bin")
- .env_remove("CODEX_HOME")
- .env_remove("CLAUDE_CONFIG_DIR")
- .env_remove("ANTHROPIC_AUTH_TOKEN")
- .env_remove("ANTHROPIC_BASE_URL")
- .status()
- .unwrap();
- assert!(status.success());
- return;
- }
- use std::os::unix::fs::PermissionsExt;
- let root = tempfile::Builder::new()
- .permissions(std::fs::Permissions::from_mode(0o700))
- .tempdir()
- .unwrap();
- let runtime =
- ProductionControlRuntime::open_with_release_catalog(root.path().join("storage"), catalog())
- .unwrap();
- let stores = LocalStorageSet::open_for_daemon_startup(root.path().join("storage")).unwrap();
- let secret = AgentCollaborationCredential::from_csprng_entropy([42; 32]);
- store_grant(&stores, 1, &["a", "b", "draft", "unbound"], &secret);
- let metadata = Arc::new(Metadata(Mutex::new(vec![
- plan("a", true, true, WorkPlanAvailabilityV1::Ready),
- plan("b", true, true, WorkPlanAvailabilityV1::Unknown),
- plan("draft", false, true, WorkPlanAvailabilityV1::Ready),
- plan("unbound", true, false, WorkPlanAvailabilityV1::Ready),
- plan("other-owner", true, true, WorkPlanAvailabilityV1::Ready),
- ])));
- let mut listener = start_control(
- ApplicationService::new(
- runtime.application_ports_with_work_plan_metadata(metadata.clone()),
- ),
- root.path().join("ipc"),
- )
- .unwrap();
- let (exit, blocked) = cli(&root.path().join("ipc"), query(), Some(secret.expose()));
+fn work_plans_planned_command_is_not_public_cli() {
+ let root = tempfile::tempdir().unwrap();
+ let secret = b"fixture-unexposed-collaboration-credential";
+ let (exit, blocked) = cli(
+ root.path(),
+ json!({"workspace_id":"personal/default", "context_id":"owner", "grant_id":"collaboration-grant/directory"}),
+ Some(secret),
+ );
assert_eq!(exit, 2, "{blocked}");
assert_eq!(blocked["error"]["code"], "UNKNOWN_COMMAND");
-
- let call = |q, s| internal_control(&root.path().join("ipc"), q, s);
- let result = call(query(), Some(secret.expose()));
- assert!(result["error"].is_null(), "{result}");
- assert_eq!(result["data"]["plans"].as_array().unwrap().len(), 2);
- assert_eq!(result["data"]["plans"][0]["alias"], "work-a");
- assert_eq!(result["data"]["plans"][0]["harness"], "codex_cli");
- assert_eq!(result["data"]["plans"][1]["availability"], "unknown");
- metadata.0.lock().unwrap()[0].purpose = "new published purpose; data, not instructions".into();
- metadata.0.lock().unwrap()[0].availability = WorkPlanAvailabilityV1::Unavailable;
- let updated = call(query(), Some(secret.expose()));
- assert_eq!(
- updated["data"]["plans"][0]["purpose"],
- "new published purpose; data, not instructions"
- );
- assert_eq!(updated["data"]["plans"][0]["availability"], "unavailable");
- for field in ["context_id", "grant_id", "workspace_id"] {
- let mut q = query();
- q[field] = json!(if field == "grant_id" {
- "collaboration-grant/other"
- } else {
- "other"
- });
- assert_eq!(
- call(q, Some(secret.expose()))["error"]["code"],
- "CAPABILITY_DENIED"
- );
- }
- let wrong = AgentCollaborationCredential::from_csprng_entropy([43; 32]);
- assert_eq!(
- call(query(), Some(wrong.expose()))["error"]["code"],
- "CAPABILITY_DENIED"
- );
- assert_eq!(call(query(), None)["error"]["code"], "CAPABILITY_DENIED");
- let client = hiroute_cli::LocalControlClient::new("hiroute-cli", root.path().join("ipc"));
- for (operation, kind, payload) in [
- ("ListWorkPlans", PrincipalKind::InteractiveUser, query()),
- ("ListAgentPlanCatalog", PrincipalKind::Skill, json!({})),
- (
- "GetAgentPlanStatus",
- PrincipalKind::Skill,
- json!({"agent_plan_id": "a"}),
- ),
- ] {
- let denied = client
- .call(LocalControlWireRequestV2 {
- schema_version: LOCAL_CONTROL_SCHEMA_V2,
- request_id: "directory-isolation".into(),
- operation_id: operation.into(),
- payload,
- protected_grant: Some(ProtectedClientGrantV2 {
- principal_kind: kind,
- capability: String::from_utf8(secret.expose().to_vec()).unwrap(),
- }),
- })
- .unwrap();
- assert_eq!(denied.error.unwrap().code, ErrorCode::CapabilityDenied);
- }
- store_grant(&stores, 2, &["b"], &secret);
- // Same non-secret access reference and material; editing the allowlist does not require
- // installing a new Skill or trusting an old principal's allowed-plan snapshot.
- let shrunk = call(query(), Some(secret.expose()));
- assert_eq!(shrunk["data"]["plans"].as_array().unwrap().len(), 1);
- assert_eq!(shrunk["data"]["plans"][0]["agent_plan_id"], "b");
- let rotated = AgentCollaborationCredential::from_csprng_entropy([44; 32]);
- let grant = store_grant(&stores, 3, &["b"], &rotated);
- assert_eq!(
- call(query(), Some(secret.expose()))["error"]["code"],
- "CAPABILITY_DENIED"
- );
- assert!(call(query(), Some(rotated.expose()))["error"].is_null());
- let op = support::begin(&stores, "directory-revoke");
- stores
- .control()
- .persist_collaboration_revocation(
- &grant.plan_revocation(op.operation_id.clone(), 3).unwrap(),
- )
- .unwrap();
- support::finish(&stores, op);
- assert_eq!(
- call(query(), Some(rotated.expose()))["error"]["code"],
- "CAPABILITY_DENIED"
- );
- listener.shutdown();
- listener.join(Duration::from_secs(10)).unwrap();
}
diff --git a/crates/client-core/src/lib.rs b/crates/client-core/src/lib.rs
index 8221100d..9b3b23a9 100644
--- a/crates/client-core/src/lib.rs
+++ b/crates/client-core/src/lib.rs
@@ -17,8 +17,9 @@ pub use error::{ClientFailure, FailureCode, SubmissionState};
pub use observation::ObservationCursor;
use hiroute_application_api::{
- ClientHelloV1, ErrorCode, LOCAL_CONTROL_SCHEMA_V2, LocalControlWireRequestV2,
- MACHINE_ENVELOPE_SCHEMA_V2, MachineEnvelopeV2, PrincipalKind, ServerHelloV1,
+ ClientHelloV1, ErrorCode, LOCAL_CONTROL_RELEASE_VERSION, LOCAL_CONTROL_SCHEMA_V2,
+ LocalControlWireRequestV2, MACHINE_ENVELOPE_SCHEMA_V2, MachineEnvelopeV2, PrincipalKind,
+ ServerHelloV1,
};
use hiroute_diagnostics::context::DiagnosticContext;
use hiroute_diagnostics::correlation::CorrelationDomain;
@@ -181,7 +182,7 @@ impl Client {
api_version: LOCAL_CONTROL_SCHEMA_V2,
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
client_name: self.name.clone(),
- client_version: env!("CARGO_PKG_VERSION").into(),
+ client_version: LOCAL_CONTROL_RELEASE_VERSION.into(),
};
let handshake = async {
stream
@@ -194,8 +195,8 @@ impl Client {
Ok(hello)
if hello.api_version == LOCAL_CONTROL_SCHEMA_V2
&& hello.machine_schema_version == MACHINE_ENVELOPE_SCHEMA_V2
- && hello.daemon_version == env!("CARGO_PKG_VERSION")
- && hello.release_version == env!("CARGO_PKG_VERSION")
+ && hello.daemon_version == LOCAL_CONTROL_RELEASE_VERSION
+ && hello.release_version == LOCAL_CONTROL_RELEASE_VERSION
&& hello.capabilities.iter().any(|c| c == "local-control-v2")
&& (!matches!(
request.0.operation_id.as_str(),
diff --git a/crates/cpa-bridge/src/runtime/tests.rs b/crates/cpa-bridge/src/runtime/tests.rs
index 44facc4d..2a279952 100644
--- a/crates/cpa-bridge/src/runtime/tests.rs
+++ b/crates/cpa-bridge/src/runtime/tests.rs
@@ -837,10 +837,14 @@ fn failed_orphan_authentication_restores_stale_owner_for_bounded_retry() {
control.set_fail_probes(true);
let failed = fixture_runtime(&root, Arc::clone(&backend), Arc::clone(&control), 2);
- assert!(matches!(
- failed.start(),
- Err(CpaLifecycleError::ControlUnavailable)
- ));
+ let outcome = failed.start();
+ if !matches!(outcome, Err(CpaLifecycleError::ControlUnavailable)) {
+ let evidence = root.keep();
+ panic!(
+ "orphan authentication returned {outcome:?}; retained fixture: {}",
+ evidence.display()
+ );
+ }
let restored: serde_json::Value =
serde_json::from_slice(&std::fs::read(&owner_path).unwrap()).unwrap();
assert_eq!(restored["owner_pid"], json!(u32::MAX - 1));
diff --git a/crates/daemon/Cargo.toml b/crates/daemon/Cargo.toml
index 88615248..eec392c2 100644
--- a/crates/daemon/Cargo.toml
+++ b/crates/daemon/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "hiroute-daemon"
-version = "0.1.0"
+version = "0.2.0"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
diff --git a/crates/daemon/src/control/bin.rs b/crates/daemon/src/control/bin.rs
index ccaa50c5..2575fd29 100644
--- a/crates/daemon/src/control/bin.rs
+++ b/crates/daemon/src/control/bin.rs
@@ -148,7 +148,14 @@ fn classify_role_all_error(error: &RoleAllError) -> StartupFailureCode {
match error {
RoleAllError::InvalidConfiguration => StartupFailureCode::InvalidConfiguration,
RoleAllError::JoinTimeout(_) => StartupFailureCode::Internal,
- RoleAllError::Component(component, _) => match *component {
+ RoleAllError::Component(component, detail) => match *component {
+ "Storage" if detail.starts_with("UPGRADE_SOURCE_UNSUPPORTED") => {
+ StartupFailureCode::UpgradeSourceUnsupported
+ }
+
+ "Storage" if detail.starts_with("stable storage upgrade failed") => {
+ StartupFailureCode::UpgradeStorageFailed
+ }
"Storage" | "Gateway publication" | "Runtime state" => {
StartupFailureCode::StorageUnavailable
}
@@ -247,7 +254,38 @@ fn run_all(arguments: Arguments, diagnostics: &DiagnosticRuntime) -> Result<(),
if let Some(engine) = arguments.codex_desktop_engine {
config = config.with_codex_desktop_engine(engine);
}
- let mut role = start_role_all(config)
+ let (progress, phases) = std::sync::mpsc::channel();
+ config.upgrade_progress = Some(progress);
+ let progress_writer = std::thread::spawn(move || -> Result<(), String> {
+ let mut stdout = std::io::stdout().lock();
+ for phase in phases {
+ serde_json::to_writer(
+ &mut stdout,
+ &serde_json::json!({
+ "schema":"hiroute.daemon-upgrade-progress/v1", "phase":phase
+ }),
+ )
+ .map_err(|_| "upgrade progress write failed")?;
+ stdout
+ .write_all(b"\n")
+ .and_then(|_| stdout.flush())
+ .map_err(|_| "upgrade progress write failed")?;
+ }
+ Ok(())
+ });
+ let result = start_role_all(config);
+ // Drain progress before writing ready/failure. No second listener or business writer is
+ // started to report migration, and frames cannot be interleaved with readiness.
+ progress_writer
+ .join()
+ .map_err(|_| {
+ StartupError::new(
+ StartupFailureCode::ReadyChannelFailed,
+ "upgrade progress writer stopped",
+ )
+ })?
+ .map_err(|error| StartupError::new(StartupFailureCode::ReadyChannelFailed, error))?;
+ let mut role = result
.map_err(|error| StartupError::new(classify_role_all_error(&error), error.to_string()))?;
write_ready(&role, diagnostics)
.map_err(|error| StartupError::new(StartupFailureCode::ReadyChannelFailed, error))?;
@@ -268,6 +306,20 @@ fn run_all(arguments: Arguments, diagnostics: &DiagnosticRuntime) -> Result<(),
);
}
match frame {
+ ProtectedChannelFrame::Upgrade(request) => {
+ let status = role.upgrade_status(request.action, request.registration_id)?;
+ let writer = acknowledgements.as_mut().expect("checked channel");
+ serde_json::to_writer(&mut *writer, &status)
+ .map_err(|_| "upgrade acknowledgement failed")?;
+ use std::io::Write;
+ writer
+ .write_all(b"\n")
+ .map_err(|_| "upgrade acknowledgement failed")?;
+ writer
+ .flush()
+ .map_err(|_| "upgrade acknowledgement failed")?;
+ continue;
+ }
ProtectedChannelFrame::Apply { registration, .. } => {
role.register_apply_capability(registration)?;
}
@@ -681,6 +733,7 @@ impl Drop for ProtectedCapabilityFrameV1 {
}
enum ProtectedChannelFrame {
+ Upgrade(hiroute_host_runtime::LauncherUpgradeRequest),
Apply {
registration_id: String,
registration: ApplyCapabilityRegistrationV1,
@@ -699,6 +752,7 @@ enum ProtectedChannelFrame {
impl ProtectedChannelFrame {
fn registration_id(&self) -> String {
match self {
+ Self::Upgrade(request) => request.registration_id.clone(),
Self::Apply {
registration_id, ..
} => registration_id.clone(),
@@ -713,6 +767,21 @@ impl ProtectedChannelFrame {
}
fn parse_capability_frame(bytes: &[u8]) -> Result<ProtectedChannelFrame, String> {
+ let schema: serde_json::Value =
+ serde_json::from_slice(bytes).map_err(|_| "protected frame is invalid")?;
+ if schema["schema"] == "hiroute.launcher-upgrade/v1" {
+ let request: hiroute_host_runtime::LauncherUpgradeRequest =
+ serde_json::from_slice(bytes).map_err(|_| "upgrade frame is invalid")?;
+ if request.registration_id.len() != 64
+ || !request
+ .registration_id
+ .bytes()
+ .all(|b| b.is_ascii_hexdigit())
+ {
+ return Err("upgrade registration id is invalid".into());
+ }
+ return Ok(ProtectedChannelFrame::Upgrade(request));
+ }
let mut frame: ProtectedCapabilityFrameV1 =
serde_json::from_slice(bytes).map_err(|_| "capability frame is invalid".to_owned())?;
let valid_id = |id: &str| id.len() == 64 && id.bytes().all(|b| b.is_ascii_hexdigit());
@@ -817,6 +886,24 @@ fn parse_capability_frame(bytes: &[u8]) -> Result<ProtectedChannelFrame, String>
.map_err(|error| error.to_string())
}
+#[cfg(test)]
+mod upgrade_frame_tests {
+ use super::*;
+ #[test]
+ fn upgrade_frame_is_exact_and_cannot_carry_business_authority() {
+ let mut value = serde_json::json!({"schema":"hiroute.launcher-upgrade/v1","registration_id":"a".repeat(64),"action":"prepare"});
+ assert!(matches!(
+ parse_capability_frame(&serde_json::to_vec(&value).unwrap()).unwrap(),
+ ProtectedChannelFrame::Upgrade(_)
+ ));
+ value["capability"] = serde_json::json!("not an upgrade field");
+ assert!(parse_capability_frame(&serde_json::to_vec(&value).unwrap()).is_err());
+ value.as_object_mut().unwrap().remove("capability");
+ value["action"] = serde_json::json!("force_stop");
+ assert!(parse_capability_frame(&serde_json::to_vec(&value).unwrap()).is_err());
+ }
+}
+
#[cfg(unix)]
fn protected_inherited_writer(fd: i32) -> Result<std::fs::File, String> {
use std::os::unix::fs::FileTypeExt;
diff --git a/crates/daemon/src/control/managed.rs b/crates/daemon/src/control/managed.rs
index a8a472de..bbbcf232 100644
--- a/crates/daemon/src/control/managed.rs
+++ b/crates/daemon/src/control/managed.rs
@@ -87,7 +87,7 @@ pub fn start_control(
application: ApplicationService,
runtime_root: impl AsRef<Path>,
) -> Result<ManagedControlHandle, ManagedControlError> {
- start_control_inner(application, runtime_root.as_ref(), None, false)
+ start_control_inner(application, runtime_root.as_ref(), None, false, None)
}
pub(crate) fn start_control_with_agent_grants(
@@ -95,12 +95,14 @@ pub(crate) fn start_control_with_agent_grants(
runtime_root: impl AsRef<Path>,
resolver: Arc<dyn AgentGrantResolverPort>,
released_commands_only: bool,
+ upgrade: Option<Arc<hiroute_host_runtime::UpgradeDrain>>,
) -> Result<ManagedControlHandle, ManagedControlError> {
start_control_inner(
application,
runtime_root.as_ref(),
Some(resolver),
released_commands_only,
+ upgrade,
)
}
@@ -109,6 +111,7 @@ fn start_control_inner(
runtime_root: &Path,
resolver: Option<Arc<dyn AgentGrantResolverPort>>,
released_commands_only: bool,
+ upgrade: Option<Arc<hiroute_host_runtime::UpgradeDrain>>,
) -> Result<ManagedControlHandle, ManagedControlError> {
let (listener, guard, endpoint) =
bind_listener(runtime_root).map_err(ManagedControlError::Start)?;
@@ -130,6 +133,11 @@ fn start_control_inner(
} else {
LocalControlDaemon::new(application)
};
+ let daemon = if let Some(upgrade) = upgrade {
+ daemon.with_upgrade_drain(upgrade)
+ } else {
+ daemon
+ };
let phase = Arc::new(std::sync::Mutex::new(ManagedControlPhase::Ready));
let shutdown = Arc::new(AtomicBool::new(false));
let worker_phase = Arc::clone(&phase);
@@ -401,6 +409,7 @@ mod tests {
root.path(),
Arc::new(FixtureGrantResolver),
false,
+ None,
)
.unwrap();
let protected = root.path().join("hiroute");
diff --git a/crates/daemon/src/control/mod.rs b/crates/daemon/src/control/mod.rs
index 0acc28cd..f1856213 100644
--- a/crates/daemon/src/control/mod.rs
+++ b/crates/daemon/src/control/mod.rs
@@ -201,6 +201,7 @@ fn category_event_code(category: hiroute_application_api::ErrorCategory) -> Even
#[derive(Clone)]
pub struct LocalControlDaemon {
+ upgrade: Arc<hiroute_host_runtime::UpgradeDrain>,
application: ApplicationService,
released_commands_only: bool,
/// Receive-side diagnostics; a no-op handle keeps every existing host unchanged.
@@ -210,6 +211,7 @@ pub struct LocalControlDaemon {
impl LocalControlDaemon {
pub fn new(application: ApplicationService) -> Self {
Self {
+ upgrade: Arc::new(hiroute_host_runtime::UpgradeDrain::default()),
application,
released_commands_only: false,
diagnostics: DiagnosticHandle::noop(),
@@ -221,6 +223,14 @@ impl LocalControlDaemon {
self
}
+ pub(crate) fn with_upgrade_drain(
+ mut self,
+ upgrade: Arc<hiroute_host_runtime::UpgradeDrain>,
+ ) -> Self {
+ self.upgrade = upgrade;
+ self
+ }
+
/// Record one bounded control-call outcome per dispatch on the receiving side. The
/// token is derived from the wire request id, never stored as text.
pub fn with_diagnostics(mut self, diagnostics: DiagnosticHandle) -> Self {
@@ -483,6 +493,14 @@ fn serve_connection(
return Ok(());
}
};
+ let Some(_upgrade_call) = daemon.upgrade.enter(false) else {
+ write_negotiated_error(
+ &mut stream,
+ ErrorV1::new(ErrorCode::DaemonUnavailable),
+ Some(request.request_id),
+ )?;
+ return Ok(());
+ };
let _wait_permit = match admission.classify(&request.operation_id) {
Ok(permit) => permit,
Err(error) => {
@@ -1207,7 +1225,10 @@ mod tests {
)
.unwrap();
let mut reader = BufReader::new(healthy.try_clone().unwrap());
- let _ = read_frame(&mut reader, Instant::now() + Duration::from_secs(1)).unwrap();
+ let hello = read_frame(&mut reader, Instant::now() + Duration::from_secs(1)).unwrap();
+ let hello: hiroute_application_api::ServerHelloV1 = serde_json::from_str(&hello).unwrap();
+ assert_eq!(hello.daemon_version, env!("CARGO_PKG_VERSION"));
+ assert_eq!(hello.release_version, env!("CARGO_PKG_VERSION"));
write_frame(
&mut healthy,
&LocalControlWireRequestV2 {
diff --git a/crates/daemon/src/control/runtime.rs b/crates/daemon/src/control/runtime.rs
index 4a0dac85..40e38ea9 100644
--- a/crates/daemon/src/control/runtime.rs
+++ b/crates/daemon/src/control/runtime.rs
@@ -2,7 +2,8 @@ use std::collections::BTreeMap;
use std::fs::{self, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, Weak};
use std::time::{SystemTime, UNIX_EPOCH};
use hiroute_application::control::{
@@ -107,9 +108,26 @@ struct RuntimeOpenOverrides {
scanner: Option<FilesystemAgentScannerV1>,
model_transport: Option<Arc<dyn hiroute_integrations::ModelDirectoryTransportV1>>,
codex_desktop_engine: Option<PathBuf>,
+ storage_startup: hiroute_local_storage::StorageStartupOptions,
}
impl ProductionControlRuntime {
+ pub(crate) fn upgrade_active_tasks(&self) -> Result<u64, String> {
+ let occupied = self
+ .adapter
+ .stores
+ .lock()
+ .map_err(|_| "upgrade task storage unavailable".to_owned())?
+ .runtime()
+ .upgrade_occupied_tasks()
+ .map_err(|_| "upgrade task storage unavailable".to_owned())?;
+ let executing = self
+ .delegation_executor
+ .upgrade_active_count()
+ .map_err(|_| "upgrade task executor unavailable".to_owned())?;
+ Ok(occupied.max(executing))
+ }
+
pub fn open(storage_root: impl AsRef<Path>) -> Result<Self, String> {
let catalog = crate::release_catalog::load_production_release_catalog()?;
Self::open_inner(storage_root.as_ref(), catalog)
@@ -175,7 +193,13 @@ impl ProductionControlRuntime {
catalog: TrustedReleaseCatalog,
cpa: Option<Arc<ManagedCpaRuntime>>,
) -> Result<Self, String> {
- Self::prepare_for_role_all_with_codex_desktop_engine(storage_root, catalog, cpa, None)
+ Self::prepare_for_role_all_with_codex_desktop_engine(
+ storage_root,
+ catalog,
+ cpa,
+ None,
+ Default::default(),
+ )
}
pub(crate) fn prepare_for_role_all_with_codex_desktop_engine(
@@ -183,6 +207,7 @@ impl ProductionControlRuntime {
catalog: TrustedReleaseCatalog,
cpa: Option<Arc<ManagedCpaRuntime>>,
codex_desktop_engine: Option<PathBuf>,
+ storage_startup: hiroute_local_storage::StorageStartupOptions,
) -> Result<Self, String> {
let sources = cpa
.as_ref()
@@ -195,6 +220,7 @@ impl ProductionControlRuntime {
false,
RuntimeOpenOverrides {
codex_desktop_engine,
+ storage_startup,
..RuntimeOpenOverrides::default()
},
)
@@ -248,8 +274,11 @@ impl ProductionControlRuntime {
recover: bool,
overrides: RuntimeOpenOverrides,
) -> Result<Self, String> {
- let stores = LocalStorageSet::open_for_daemon_startup(storage_root)
- .map_err(|error| error.to_string())?;
+ let stores = LocalStorageSet::open_for_daemon_startup_with_options(
+ storage_root,
+ &overrides.storage_startup,
+ )
+ .map_err(|error| error.to_string())?;
stores
.control()
.begin_plan_version_recovery()
@@ -369,6 +398,7 @@ impl ProductionControlRuntime {
subscription_maintenance: Mutex::new(subscriptions::SubscriptionMaintenance::new()?),
managed_agent_runtime: Mutex::new(None),
publication_target: Mutex::new(None),
+ startup_recovery_complete: AtomicBool::new(false),
delegation_native_cleanup_cursor: Mutex::new(None),
delegation_task_maintenance_cursor: Mutex::new(None),
});
@@ -397,6 +427,9 @@ impl ProductionControlRuntime {
adapter.reconcile_delegation_plan_versions()?;
adapter.recover_delegation_authorizations()?;
adapter.enable_subscription_maintenance();
+ adapter
+ .finish_startup_publication_recovery()
+ .map_err(|error| error.to_string())?;
}
Ok(Self {
_observation_maintenance:
@@ -493,6 +526,19 @@ impl ProductionControlRuntime {
publication_target: Option<Arc<dyn PublicationTargetPort + Send + Sync>>,
resident_service_ready: bool,
) -> Result<(), String> {
+ self.adapter
+ .startup_recovery_complete
+ .store(false, Ordering::Release);
+ if let Some(target) = self
+ .adapter
+ .publication_target()
+ .map_err(|e| e.to_string())?
+ {
+ target.suspend_requests().map_err(|e| e.to_string())?;
+ }
+ if let Some(target) = &publication_target {
+ target.suspend_requests().map_err(|e| e.to_string())?;
+ }
let worker_gateway = gateway_base_url
.strip_prefix("http://")
.and_then(|value| value.strip_suffix("/v1"))
@@ -502,7 +548,10 @@ impl ProductionControlRuntime {
self.delegation_executor
.set_gateway(worker_gateway)
.map_err(|error| error.to_string())?;
- let selection_source: Arc<dyn WorkerInstallationSelectionSource> = self.adapter.clone();
+ // Availability is retained by the adapter, so its selection callback must not
+ // own that adapter in return. The enclosing runtime owns the live adapter.
+ let selection_source: Arc<dyn WorkerInstallationSelectionSource> =
+ Arc::new(WorkerSelections(Arc::downgrade(&self.adapter)));
let managed = managed_profile_source(
&self.delegation_storage_root,
selection_source,
@@ -547,13 +596,16 @@ impl ProductionControlRuntime {
.publication_target
.lock()
.map_err(|_| "publication target is unavailable".to_owned())? = publication_target;
+ self.adapter
+ .restore_active_publication()
+ .map_err(|error| error.to_string())?;
self.adapter.reconcile_startup_and_open()?;
self.adapter.reconcile_cpa_runtime_from_management()?;
self.adapter.reconcile_delegation_plan_versions()?;
self.adapter.recover_delegation_authorizations()?;
self.adapter.enable_subscription_maintenance();
self.adapter
- .reconcile_active_publication()
+ .finish_startup_publication_recovery()
.map_err(|error| error.to_string())?;
Ok(())
}
@@ -653,6 +705,7 @@ struct LocalControlAdapter {
subscription_maintenance: Mutex<subscriptions::SubscriptionMaintenance>,
managed_agent_runtime: Mutex<Option<ManagedAgentRuntimeV1>>,
publication_target: Mutex<Option<Arc<dyn PublicationTargetPort + Send + Sync>>>,
+ startup_recovery_complete: AtomicBool,
delegation_native_cleanup_cursor:
Mutex<Option<hiroute_observation::managed_text::ManagedTextNativeCleanupCursor>>,
delegation_task_maintenance_cursor:
@@ -797,6 +850,21 @@ struct ManagedAgentRuntimeV1 {
resident_service_ready: bool,
}
+struct WorkerSelections(Weak<LocalControlAdapter>);
+
+impl WorkerInstallationSelectionSource for WorkerSelections {
+ fn selection(
+ &self,
+ harness: hiroute_domain::delegation::WorkerHarnessV1,
+ ) -> Result<Option<WorkerInstallationSelection>, hiroute_domain::delegation::DelegationErrorV1>
+ {
+ self.0
+ .upgrade()
+ .ok_or(hiroute_domain::delegation::DelegationErrorV1::StorageUnavailable)?
+ .selection(harness)
+ }
+}
+
impl WorkerInstallationSelectionSource for LocalControlAdapter {
fn selection(
&self,
diff --git a/crates/daemon/src/control/runtime/agent_connection.rs b/crates/daemon/src/control/runtime/agent_connection.rs
index 1fbfda90..7bc626a7 100644
--- a/crates/daemon/src/control/runtime/agent_connection.rs
+++ b/crates/daemon/src/control/runtime/agent_connection.rs
@@ -562,9 +562,8 @@ mod tests {
use hiroute_application_api::AGENT_CONNECT_SPEC_SCHEMA_V1;
use hiroute_domain::{
AgentConfigRestorePointV1, AgentPlanAllowedScopeV1, BeginOperationOutcome,
- ConnectorRegistryBundleV1, GatewayPublicationRevision, GatewayPublicationV1,
- IdempotencyScopeV1, OperationId, OperationV1, ProtectedApplyCapability,
- PublicationRecordV1, ReleaseModelDataBundleV2,
+ ConnectorRegistryBundleV1, GatewayPublicationRevision, IdempotencyScopeV1, OperationId,
+ OperationV1, ProtectedApplyCapability, PublicationRecordV1, ReleaseModelDataBundleV2,
};
use hiroute_integrations::{
AgentFilesystemLayoutV1, ClaudeRegistrationIndexV1, FilesystemAgentScannerV1,
@@ -627,10 +626,11 @@ mod tests {
let artifacts = stores
.open_managed_artifacts(storage.join("artifacts"), storage.join("restores"))
.unwrap();
- let mut publication = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
+ let mut publication =
+ serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
publication.publication_revision = GatewayPublicationRevision::new(1).unwrap();
publication.aliases.clear();
publication.grants.clear();
@@ -711,6 +711,7 @@ mod tests {
resident_service_ready: false,
})),
publication_target: Mutex::new(Some(target.clone())),
+ startup_recovery_complete: std::sync::atomic::AtomicBool::new(true),
delegation_native_cleanup_cursor: Mutex::new(None),
delegation_task_maintenance_cursor: Mutex::new(None),
};
diff --git a/crates/daemon/src/control/runtime/agent_connection_discovery.rs b/crates/daemon/src/control/runtime/agent_connection_discovery.rs
index 3dbe971b..2ac0a8e2 100644
--- a/crates/daemon/src/control/runtime/agent_connection_discovery.rs
+++ b/crates/daemon/src/control/runtime/agent_connection_discovery.rs
@@ -1,5 +1,5 @@
use hiroute_application::control::ControlReadError;
-use hiroute_domain::{ActiveAgentConnectionV1, OperationV1, WorkspaceId};
+use hiroute_domain::{ActiveAgentConnectionV1, WorkspaceId};
use hiroute_integrations::{AgentDiscoveryOutcomeV1, FilesystemAgentDiscoveryV1};
use super::{APPLY_OPERATION, LocalControlAdapter};
@@ -8,14 +8,20 @@ impl LocalControlAdapter {
pub(super) fn latest_connection_operation(
&self,
connection_id: &str,
- ) -> Result<(ActiveAgentConnectionV1, OperationV1), ControlReadError> {
+ ) -> Result<
+ (
+ ActiveAgentConnectionV1,
+ hiroute_local_storage::SucceededAgentOperationV1,
+ ),
+ ControlReadError,
+ > {
let stores = self
.stores
.lock()
.map_err(|_| ControlReadError::Unavailable)?;
for operation in stores
.control()
- .succeeded_operations_for_kind(&WorkspaceId::default(), APPLY_OPERATION)
+ .succeeded_agent_operations_for_kind(&WorkspaceId::default(), APPLY_OPERATION)
.map_err(super::super::map_port)?
{
let projection = operation
diff --git a/crates/daemon/src/control/runtime/candidate_protocol_profiles.rs b/crates/daemon/src/control/runtime/candidate_protocol_profiles.rs
index ad06cda5..649d4f13 100644
--- a/crates/daemon/src/control/runtime/candidate_protocol_profiles.rs
+++ b/crates/daemon/src/control/runtime/candidate_protocol_profiles.rs
@@ -1,14 +1,12 @@
use hiroute_domain::{
- ConnectorRuntimeKind, GatewayAuthenticationSemanticsV1, GatewayCandidateCapabilityProfileV1,
- GatewayCandidateProtocolProfileV1, GatewayConnectorProfileV1, GatewayContextLimitsV1,
- GatewayCriticalFactV1, GatewayErrorSemanticsV1, GatewayFidelityV1, GatewayHeaderSemanticsV1,
- GatewayNativeProviderStateEmissionV1, GatewayNativeReasoningFieldAssignmentV1,
+ ConnectorRuntimeKind, GatewayAuthenticationSemanticsV1, GatewayCandidateProtocolProfileV1,
+ GatewayConnectorProfileV1, GatewayCriticalFactV1, GatewayErrorSemanticsV1,
+ GatewayHeaderSemanticsV1, GatewayNativeReasoningFieldAssignmentV1,
GatewayNativeReasoningRenderV1, GatewayNativeReasoningValueV1, GatewayReasoningAccountingV1,
- GatewayReasoningControlKindV1, GatewayReasoningProfileCapabilityV1,
- GatewayRequestFeatureProfileV1, GatewayResponseFeatureProfileV1,
- GatewayStreamingRefusalSemanticsV1, GatewayTokenEstimatorProfileV1, ModelDefinitionV1,
+ GatewayReasoningControlKindV1, GatewayReasoningProfileCapabilityV1, ModelDefinitionV1,
ModelEndpointCapabilityV1, ModelNativeReasoningV1, NativeReasoningCapabilityV1,
- NativeReasoningRenderConventionV1, UpstreamProtocol,
+ NativeReasoningRenderConventionV1, StoredModelCapabilitiesV1, StoredModelSupportV1,
+ StoredNativeReasoningV1, UpstreamProtocol,
};
use super::{ProtocolConnectorFacts, ProtocolFace, protocol_label};
@@ -76,22 +74,6 @@ pub(super) fn protocol_profiles(
else {
continue;
};
- let exact_provider_state = matches!(
- upstream_protocol,
- UpstreamProtocol::Responses | UpstreamProtocol::Messages
- );
- let exact = GatewayFidelityV1::Exact;
- let unsupported = GatewayFidelityV1::Unsupported;
- let tool = if model.capabilities.tool {
- exact
- } else {
- unsupported
- };
- let vision = if model.capabilities.vision {
- exact
- } else {
- unsupported
- };
profiles.push(GatewayCandidateProtocolProfileV1 {
schema_version: "hiroute.candidate-protocol-profile/v1".into(),
native_target: face.native_target.clone(),
@@ -112,114 +94,33 @@ pub(super) fn protocol_profiles(
),
serializer_revision: "hiroute-target-json/v1".into(),
decoder_revision: "hiroute-native-response/v1".into(),
- capability: GatewayCandidateCapabilityProfileV1 {
- schema_version: "hiroute.candidate-capability/v1".into(),
+ capability: StoredModelCapabilitiesV1 {
capability_id: capability.capability_id.clone(),
capability_revision: capability.revision.to_string(),
- upstream_protocol,
model_configuration_id: capability.model_configuration_id.clone(),
native_model: native_transport_model.to_owned(),
- request: GatewayRequestFeatureProfileV1 {
- text: exact,
- initial_instructions: exact,
- mid_conversation_instructions: if upstream_protocol
- == UpstreamProtocol::Messages
- {
- unsupported
- } else {
- exact
- },
- image_url: vision,
- image_base64: vision,
- image_base64_media_types: GatewayCriticalFactV1::Exact(
- if model.capabilities.vision {
- vec![
- "image/gif".into(),
- "image/jpeg".into(),
- "image/png".into(),
- "image/webp".into(),
- ]
- } else {
- Vec::new()
- },
- ),
- function_tools: tool,
- strict_tools: if upstream_protocol == UpstreamProtocol::Messages {
- unsupported
- } else {
- tool
- },
- tool_choice_none: if upstream_protocol == UpstreamProtocol::Messages {
- unsupported
- } else {
- tool
- },
- tool_choice_auto: tool,
- tool_choice_required_any: tool,
- tool_choice_required_named: tool,
- parallel_tools: tool,
- tool_roundtrip: tool,
- tool_result_text: tool,
- tool_result_json: tool,
- logical_tool_id_mapping: tool,
- provider_state: if exact_provider_state {
- exact
- } else {
- unsupported
- },
- },
- response: GatewayResponseFeatureProfileV1 {
- text: exact,
- reasoning: exact,
- refusal: exact,
- tool_calls: tool,
- logical_tool_id_mapping: tool,
- usage: exact,
- finish_reason: exact,
- typed_error: exact,
- provider_state: if exact_provider_state {
- exact
- } else {
- unsupported
- },
- stream_refusal: if upstream_protocol == UpstreamProtocol::Messages {
- GatewayStreamingRefusalSemanticsV1::TerminalClassified
- } else {
- GatewayStreamingRefusalSemanticsV1::ExactDelta
- },
- stream_text_delta: exact,
- stream_tool_argument_delta: tool,
- stream_reasoning_delta: exact,
- stream_usage: exact,
- },
- reasoning_profiles: reasoning_profiles.clone(),
- selected_reasoning_profile_id: selected_reasoning_profile_id.clone(),
- context: GatewayContextLimitsV1 {
- max_input_tokens: GatewayCriticalFactV1::Exact(
- model.capabilities.context_tokens,
- ),
- max_output_tokens: GatewayCriticalFactV1::Exact(
- model.capabilities.max_output_tokens,
- ),
- max_total_tokens: GatewayCriticalFactV1::Exact(
- model
- .capabilities
- .context_tokens
- .checked_add(model.capabilities.max_output_tokens),
- ),
- estimator: GatewayCriticalFactV1::Exact(GatewayTokenEstimatorProfileV1 {
- revision: "byte-upper-bound/v1".into(),
- bytes_per_token: 1,
- fixed_overhead_tokens: 0,
- }),
+ model_support: StoredModelSupportV1 {
+ tools: GatewayCriticalFactV1::Exact(model.capabilities.tool),
+ vision: GatewayCriticalFactV1::Exact(model.capabilities.vision),
},
+ max_input_tokens: GatewayCriticalFactV1::Exact(model.capabilities.context_tokens),
+ max_output_tokens: GatewayCriticalFactV1::Exact(
+ model.capabilities.max_output_tokens,
+ ),
+ max_total_tokens: GatewayCriticalFactV1::Exact(
+ model
+ .capabilities
+ .context_tokens
+ .checked_add(model.capabilities.max_output_tokens),
+ ),
native_streaming: GatewayCriticalFactV1::Exact(model.capabilities.streaming),
- native_provider_state: if exact_provider_state {
- GatewayNativeProviderStateEmissionV1::Native
- } else {
- GatewayNativeProviderStateEmissionV1::Never
- },
- },
+ reasoning_profiles: reasoning_profiles
+ .iter()
+ .map(StoredNativeReasoningV1::freeze)
+ .collect(),
+ selected_reasoning_profile_id,
+ }
+ .compile(upstream_protocol),
connector: GatewayConnectorProfileV1 {
schema_version: "hiroute.connector-profile/v1".into(),
provider_id: connector.provider_id.clone(),
diff --git a/crates/daemon/src/control/runtime/collaboration_status.rs b/crates/daemon/src/control/runtime/collaboration_status.rs
index 56e7e190..3cc95a34 100644
--- a/crates/daemon/src/control/runtime/collaboration_status.rs
+++ b/crates/daemon/src/control/runtime/collaboration_status.rs
@@ -8,8 +8,8 @@ use hiroute_application_api::{
AgentSettingsStatusRequestV2,
};
use hiroute_domain::{
- AgentFacetIntent, AgentSettingsSpecV2, CanonicalDigest, NativeAgentArtifactPort,
- OperationState, OperationV1, WorkspaceId,
+ AgentFacetIntent, AgentOperationRead, AgentSettingsSpecV2, CanonicalDigest,
+ NativeAgentArtifactPort, OperationState, WorkspaceId,
};
impl LocalControlAdapter {
@@ -22,17 +22,19 @@ impl LocalControlAdapter {
.ok_or(ControlReadError::NotFound)?;
let mut status = empty_status();
let stores = self.stores_lock().map_err(super::map_port)?;
- let belongs = |operation: &OperationV1| -> Result<bool, ControlReadError> {
- if operation.plan.spec().command_id != "agents.settings.apply"
- || operation.plan.spec().resource_id.as_deref() != Some(&request.context_id)
- {
- return Ok(false);
- }
- let spec: AgentSettingsSpecV2 =
- serde_json::from_value(operation.plan.spec().desired_state.clone())
- .map_err(|_| ControlReadError::Corrupt)?;
- Ok(!matches!(spec.collaboration, AgentFacetIntent::Keep))
- };
+ let belongs =
+ |operation: &dyn hiroute_domain::AgentOperationRead| -> Result<bool, ControlReadError> {
+ if operation.agent_input().spec.command_id != "agents.settings.apply"
+ || operation.agent_input().spec.resource_id.as_deref()
+ != Some(&request.context_id)
+ {
+ return Ok(false);
+ }
+ let spec: AgentSettingsSpecV2 =
+ serde_json::from_value(operation.agent_input().spec.desired_state.clone())
+ .map_err(|_| ControlReadError::Corrupt)?;
+ Ok(!matches!(spec.collaboration, AgentFacetIntent::Keep))
+ };
if let Some(pending) = stores
.control()
.writer_claim_operation()
@@ -50,7 +52,7 @@ impl LocalControlAdapter {
}
let operations = stores
.control()
- .succeeded_operations_for_kinds(
+ .succeeded_agent_operations_for_kinds(
&WorkspaceId::default(),
&["ApplyAgentConnectionChange", "ApplyAgentConnectionRestore"],
)
@@ -66,7 +68,7 @@ impl LocalControlAdapter {
return Ok(status);
};
let spec: AgentSettingsSpecV2 =
- serde_json::from_value(operation.plan.spec().desired_state.clone())
+ serde_json::from_value(operation.agent_input().spec.desired_state.clone())
.map_err(|_| ControlReadError::Corrupt)?;
status.operation_id = Some(operation.operation_id.to_string());
status.operation_state = Some(operation.state.as_str().into());
diff --git a/crates/daemon/src/control/runtime/compute_routing/tests.rs b/crates/daemon/src/control/runtime/compute_routing/tests.rs
index 84bd47b8..756deae5 100644
--- a/crates/daemon/src/control/runtime/compute_routing/tests.rs
+++ b/crates/daemon/src/control/runtime/compute_routing/tests.rs
@@ -383,6 +383,7 @@ fn current_catalog_drift_excludes_only_stale_projection_from_routing_snapshot()
),
managed_agent_runtime: Mutex::new(None),
publication_target: Mutex::new(None),
+ startup_recovery_complete: std::sync::atomic::AtomicBool::new(true),
delegation_native_cleanup_cursor: Mutex::new(None),
delegation_task_maintenance_cursor: Mutex::new(None),
};
diff --git a/crates/daemon/src/control/runtime/effects/tests.rs b/crates/daemon/src/control/runtime/effects/tests.rs
index 2c1494ae..31d773cf 100644
--- a/crates/daemon/src/control/runtime/effects/tests.rs
+++ b/crates/daemon/src/control/runtime/effects/tests.rs
@@ -59,10 +59,11 @@ fn publication_restart_reconciles_every_persisted_install_window() {
GatewayPublicationInstaller::open(&lkg).unwrap(),
)));
*runtime.adapter.publication_target.lock().unwrap() = Some(target.clone());
- let desired = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
+ let desired =
+ serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
let (mut operation, intent, record) = routing_operation(
&runtime.adapter,
desired,
@@ -156,6 +157,25 @@ fn publication_restart_reconciles_every_persisted_install_window() {
GatewayPublicationInstaller::open(&lkg).unwrap(),
)));
assert!(RuntimePublicationFeed::pin(target.as_ref()).is_none());
+ *recovered.adapter.publication_target.lock().unwrap() = Some(target.clone());
+ recovered.adapter.restore_active_publication().unwrap();
+ recovered.adapter.reconcile_startup_and_open().unwrap();
+ assert_eq!(
+ recovered
+ .adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .load_operation(&operation_id)
+ .unwrap()
+ .unwrap()
+ .state,
+ hiroute_domain::OperationState::Succeeded
+ );
+ assert!(
+ RuntimePublicationFeed::pin(target.as_ref()).is_none(),
+ "journal completion must not admit requests before remaining startup recovery"
+ );
recovered
.configure_managed_agent_runtime(
"http://127.0.0.1:5837/v1".into(),
@@ -192,6 +212,21 @@ fn publication_restart_reconciles_every_persisted_install_window() {
.len(),
1
);
+ drop(stores);
+ assert!(
+ recovered
+ .configure_managed_agent_runtime(
+ "invalid-gateway".into(),
+ "/test/hiroute".into(),
+ Some(target.clone()),
+ )
+ .is_err()
+ );
+ recovered.adapter.reconcile_active_publication().unwrap();
+ assert!(
+ RuntimePublicationFeed::pin(target.as_ref()).is_none(),
+ "failed startup configuration must keep admission suspended"
+ );
}
}
use crate::control::runtime::LocalControlAdapter;
@@ -210,7 +245,9 @@ fn current_publication(
.iter()
.cloned()
.map(|compiled| {
- let legacy = PlanVersionV1::from_legacy_compiled(workspace.clone(), compiled).unwrap();
+ let legacy =
+ PlanVersionV1::from_unversioned_compiled_recovery(workspace.clone(), compiled)
+ .unwrap();
PlanVersionV1::new(
workspace.clone(),
legacy.configuration,
@@ -522,6 +559,7 @@ fn permission_effect_hardens_only_pinned_identity_and_never_reverts_mode() {
),
managed_agent_runtime: Mutex::new(None),
publication_target: Mutex::new(None),
+ startup_recovery_complete: std::sync::atomic::AtomicBool::new(true),
delegation_native_cleanup_cursor: Mutex::new(None),
delegation_task_maintenance_cursor: Mutex::new(None),
};
@@ -621,10 +659,11 @@ fn product_plan_only_publication_installs_identified_no_new_calls_state() {
crate::release_catalog::fixture_catalog(),
)
.unwrap();
- let mut desired = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
+ let mut desired =
+ serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
desired.aliases.clear();
desired.grants.clear();
let (operation, intent, desired_record) =
@@ -714,8 +753,8 @@ fn executable_publication_without_gateway_target_rejects_admission_and_install_d
crate::release_catalog::fixture_catalog(),
)
.unwrap();
- let desired = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let desired = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
let mut prior = desired.clone();
diff --git a/crates/daemon/src/control/runtime/effects/tests/publication_validation.rs b/crates/daemon/src/control/runtime/effects/tests/publication_validation.rs
index 790060c7..7bc56ea4 100644
--- a/crates/daemon/src/control/runtime/effects/tests/publication_validation.rs
+++ b/crates/daemon/src/control/runtime/effects/tests/publication_validation.rs
@@ -103,10 +103,11 @@ fn publication_recovery_rejects_corrupt_markers_and_upgrades_verified_legacy() {
GatewayPublicationInstaller::open(directory.path().join("gateway-lkg.json")).unwrap(),
)));
*runtime.adapter.publication_target.lock().unwrap() = Some(target);
- let mut desired = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
+ let mut desired =
+ serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
desired.aliases.clear();
desired.grants.clear();
let (mut operation, intent, record) =
@@ -239,9 +240,9 @@ fn publication_recovery_rejects_corrupt_markers_and_upgrades_verified_legacy() {
}
#[test]
-fn master_authored_v2_plan_is_recovered_from_durable_compiler_v1_publication() {
+fn authored_plan_is_recovered_from_stable_publication_and_updated() {
if crate::test_support::isolated_agent_home(
- "control::runtime::effects::tests::publication_validation::master_authored_v2_plan_is_recovered_from_durable_compiler_v1_publication",
+ "control::runtime::effects::tests::publication_validation::authored_plan_is_recovered_from_stable_publication_and_updated",
) {
return;
}
@@ -290,31 +291,23 @@ fn master_authored_v2_plan_is_recovered_from_durable_compiler_v1_publication() {
let authored = preview_plan_content(&create, &authoring).unwrap();
assert_eq!(
authored.plan_version.compiled.body.schema,
- hiroute_domain::AGENT_PLAN_COMPILED_SCHEMA_V2
+ hiroute_domain::AGENT_PLAN_COMPILED_SCHEMA_V3
);
assert_eq!(
authored.plan_version.compiled.body.compiler_revision,
- hiroute_domain::AGENT_PLAN_COMPILER_REVISION_V2
+ hiroute_domain::AGENT_PLAN_COMPILER_REVISION_V3
);
- // Reproduce master's bootstrap writer: its empty V2/compiler-V1 seed was promoted to V3,
- // but `preview_plan_content` supplied the already-current compiled Plan V2 unchanged.
- let legacy_schema = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap()
- .schema;
+ // The current writer stores frozen facts. Reopening must reconstruct the same
+ // confirmed plan, permit a content update, and keep the stored bytes unchanged.
let revision_one = GatewayPublicationRevision::new(1).unwrap();
- let mut seed = GatewayPublicationV1::new(
+ let seed = GatewayPublicationV1::new(
workspace.clone(),
revision_one,
hiroute_domain::AliasRegistryV1::default(),
vec![],
)
.unwrap();
- seed.schema = legacy_schema;
- seed.compiler_revision = hiroute_domain::AGENT_PLAN_COMPILER_REVISION_V1.into();
- seed.validate().unwrap();
let mut aliases = seed.alias_registry.clone();
assert_eq!(
aliases
@@ -396,7 +389,10 @@ fn master_authored_v2_plan_is_recovered_from_durable_compiler_v1_publication() {
let recovered_authoring =
RoutingFactsPort::plan_authoring_snapshot(recovered.adapter.as_ref(), &workspace, &update)
.unwrap();
- assert_eq!(recovered_authoring.active_publication, Some(historical));
+ assert_eq!(
+ recovered_authoring.active_publication,
+ Some(historical_record.verify_current().unwrap())
+ );
assert_eq!(
recovered_authoring
.legacy_source
@@ -497,8 +493,8 @@ fn publication_no_new_calls_replaces_servable_before_with_identified_denial() {
crate::release_catalog::fixture_catalog(),
)
.unwrap();
- let prior = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let prior = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
let mut desired = prior.clone();
diff --git a/crates/daemon/src/control/runtime/effects/tests/service_status.rs b/crates/daemon/src/control/runtime/effects/tests/service_status.rs
index 8ef403db..55d16b8b 100644
--- a/crates/daemon/src/control/runtime/effects/tests/service_status.rs
+++ b/crates/daemon/src/control/runtime/effects/tests/service_status.rs
@@ -37,10 +37,11 @@ fn service_status_requires_resumed_target_and_no_retained_writer_claim() {
runtime.adapter.service_status().unwrap().gateway,
ClientGatewayStateV1::Empty
);
- let publication = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
+ let publication =
+ serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
let record =
PublicationRecordV1::from_publication(publication.workspace_id.clone(), &publication)
.unwrap();
diff --git a/crates/daemon/src/control/runtime/native_model_lifecycle_tests.rs b/crates/daemon/src/control/runtime/native_model_lifecycle_tests.rs
index 0dcd53ab..26bad658 100644
--- a/crates/daemon/src/control/runtime/native_model_lifecycle_tests.rs
+++ b/crates/daemon/src/control/runtime/native_model_lifecycle_tests.rs
@@ -98,13 +98,7 @@ fn settings_codex_daemon_stages_real_grant_reopens_and_restores_native_file() {
.iter()
.any(|grant| grant.grant_id == reference.grant_id())
);
- install.state = OperationState::Succeeded;
- adapter
- .stores_lock()
- .unwrap()
- .control()
- .finish_operation(&mut install)
- .unwrap();
+ super::finish_fixture_operation(adapter, &mut install);
drop(runtime);
let runtime = open(root.path());
diff --git a/crates/daemon/src/control/runtime/native_model_tests.rs b/crates/daemon/src/control/runtime/native_model_tests.rs
index c5e56646..ef6963a3 100644
--- a/crates/daemon/src/control/runtime/native_model_tests.rs
+++ b/crates/daemon/src/control/runtime/native_model_tests.rs
@@ -18,6 +18,8 @@ use std::{collections::BTreeSet, fs, os::unix::fs::PermissionsExt};
mod codex_cache;
#[path = "native_model_lifecycle_tests.rs"]
mod lifecycle;
+#[path = "native_model_tests/recovery_admission.rs"]
+mod recovery_admission;
#[test]
fn settings_status_joins_surface_checks_with_the_active_publication_revision() {
@@ -80,13 +82,7 @@ fn settings_status_joins_surface_checks_with_the_active_publication_revision() {
"the activated configuration must point at the immutable catalog artifact: {configured}"
);
publish(adapter, &mut install);
- install.state = OperationState::Succeeded;
- adapter
- .stores_lock()
- .unwrap()
- .control()
- .finish_operation(&mut install)
- .unwrap();
+ finish_fixture_operation(adapter, &mut install);
let revision = adapter
.stores_lock()
.unwrap()
@@ -307,13 +303,7 @@ fn settings_status_joins_surface_checks_with_the_active_publication_revision() {
.unwrap();
adapter.activate_external(&update, &update_file).unwrap();
publish(adapter, &mut update);
- update.state = OperationState::Succeeded;
- adapter
- .stores_lock()
- .unwrap()
- .control()
- .finish_operation(&mut update)
- .unwrap();
+ finish_fixture_operation(adapter, &mut update);
let next_revision = adapter
.stores_lock()
.unwrap()
@@ -673,6 +663,7 @@ fn open_with_codex_fixture_surfaces(
root: &std::path::Path,
) -> (ProductionControlRuntime, std::path::PathBuf) {
fs::set_permissions(root, fs::Permissions::from_mode(0o700)).unwrap();
+ drop(hiroute_local_storage::LocalStorageSet::open_for_daemon_startup(root).unwrap());
let cli = root.join("codex-cli-fixture");
let desktop = root.join("codex-desktop-fixture");
write_codex_fixture(&cli);
@@ -722,30 +713,26 @@ fn open_without_fixture_grants(root: &std::path::Path) -> ProductionControlRunti
)
}
-/// The golden still carries its pre-migration executable sections and legacy Plan contract;
-/// their fixture/decoder convergence is a pending adjudication and this test needs only the
-/// compiled plans, so the disputed sections are emptied and the domain's own deterministic
-/// current-contract upgrade is applied in this in-test view instead of adjudicating here.
+/// Validate the complete frozen source before projecting a current plan-only publication.
fn golden_publication_plans_only() -> GatewayPublicationV1 {
- let mut value: serde_json::Value = serde_json::from_slice(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let source = serde_json::from_slice::<serde_json::Value>(include_bytes!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
- let object = value.as_object_mut().unwrap();
- object.insert("grants".into(), serde_json::json!([]));
- object.insert("aliases".into(), serde_json::json!([]));
- serde_json::from_value::<GatewayPublicationV1>(value)
- .unwrap()
- .into_current()
- .unwrap()
+ let mut publication =
+ serde_json::from_value::<hiroute_domain::GatewayPublicationV1>(source.clone()).unwrap();
+ publication.grants.clear();
+ publication.aliases.clear();
+ publication.validate_current_contract().unwrap();
+ publication
}
fn configure_runtime(
root: &std::path::Path,
runtime: ProductionControlRuntime,
) -> ProductionControlRuntime {
- let initial = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let initial = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
configure_runtime_with_initial(root, runtime, initial)
@@ -756,6 +743,8 @@ fn configure_runtime_with_initial(
runtime: ProductionControlRuntime,
initial: GatewayPublicationV1,
) -> ProductionControlRuntime {
+ // This frozen V2 aggregate is test input; current producers publish stable facts.
+ let initial = initial.into_current().unwrap();
*runtime.adapter.managed_agent_runtime.lock().unwrap() = Some(ManagedAgentRuntimeV1 {
gateway_base_url: "http://127.0.0.1:5837/v1".into(),
trusted_hiroute_executable: "/test/hiroute".into(),
@@ -879,6 +868,48 @@ fn record_agent_effect(
.unwrap();
}
+fn finish_fixture_operation(adapter: &LocalControlAdapter, operation: &mut OperationV1) {
+ // These adapter tests apply effects manually. Seal the same completed journal shape as
+ // the coordinator, so read-only status verifies all six steps and the service receipt.
+ let effect = operation
+ .step(OperationStepKind::CompilePublication)
+ .effects
+ .iter()
+ .find(|effect| effect.kind == OwnedEffectKind::Publication)
+ .unwrap();
+ let revision = effect.compensation["publication_revision"]
+ .as_u64()
+ .unwrap();
+ let digest = effect.after_fingerprint.clone().unwrap();
+ let receipt = SettingsServiceCompletionV1 {
+ schema: SETTINGS_SERVICE_COMPLETION_SCHEMA.into(),
+ publication_revision: revision,
+ publication_digest: digest.clone(),
+ completed_effects_digest: CanonicalDigest::of(&(
+ "hiroute.settings-service-proof/v2",
+ operation.operation_id.as_str(),
+ &operation.accepted_digest,
+ revision,
+ &digest,
+ operation.stable_input_digest().unwrap(),
+ ))
+ .unwrap(),
+ };
+ operation
+ .step_mut(OperationStepKind::Activate)
+ .terminal_result = Some(serde_json::to_string(&receipt).unwrap());
+ for step in &mut operation.steps {
+ step.status = OperationStepStatus::Applied;
+ }
+ operation.state = OperationState::Succeeded;
+ adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .finish_operation(operation)
+ .unwrap();
+}
+
fn operation(
adapter: &LocalControlAdapter,
key: &str,
@@ -886,9 +917,11 @@ fn operation(
original: Option<&OperationId>,
) -> OperationV1 {
ensure_target_cache(adapter);
- let publication = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
+ let publication = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(
+ include_bytes!("../../../../../e2e/product/fixtures/routing/current-publication.v3.json"),
+ )
+ .unwrap()
+ .into_current()
.unwrap();
let plans = publication.published_agent_plans().unwrap();
let plan = plans
diff --git a/crates/daemon/src/control/runtime/native_model_tests/recovery_admission.rs b/crates/daemon/src/control/runtime/native_model_tests/recovery_admission.rs
new file mode 100644
index 00000000..a92aa7ec
--- /dev/null
+++ b/crates/daemon/src/control/runtime/native_model_tests/recovery_admission.rs
@@ -0,0 +1,164 @@
+//! Recover the durable publication-compensated / Secret-active crash window.
+use super::*;
+use hiroute_gateway::server::composition::RuntimePublicationFeed;
+
+#[test]
+fn startup_recovers_publication_compensated_before_secret_rollback() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::native_model::tests::recovery_admission::startup_recovers_publication_compensated_before_secret_rollback",
+ ) {
+ return;
+ }
+ let root = tempfile::tempdir().unwrap();
+ let runtime = open_without_fixture_grants(root.path());
+ let adapter = &runtime.adapter;
+ let path = adapter.scanner.codex_user_config_target();
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::set_permissions(path.parent().unwrap(), fs::Permissions::from_mode(0o700)).unwrap();
+ let before = b"# retained user configuration\n";
+ fs::write(&path, before).unwrap();
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
+ let mut operation = operation(adapter, "rollback-crash", before, None);
+ let mutation = &operation.plan.agent_access_grants()[0];
+ let grant = adapter
+ .stores_lock()
+ .unwrap()
+ .secrets()
+ .apply_agent_access_grant(&operation.operation_id, mutation, None)
+ .unwrap();
+ let reference = AgentAccessGrantRefV1::from_ensure_effect(&grant, mutation).unwrap();
+ operation.step_mut(OperationStepKind::ApplySecrets).effects = vec![grant.clone()];
+ adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .save_operation(&mut operation)
+ .unwrap();
+ let intent = operation
+ .plan
+ .external()
+ .iter()
+ .find(|intent| intent.kind() == OwnedEffectKind::Publication)
+ .unwrap()
+ .clone();
+ let publication = adapter.apply_external(&operation, &intent).unwrap();
+ operation
+ .step_mut(OperationStepKind::CompilePublication)
+ .effects = vec![publication.clone()];
+ adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .save_operation(&mut operation)
+ .unwrap();
+ adapter
+ .stores_lock()
+ .unwrap()
+ .secrets()
+ .activate_agent_access_grant(&grant)
+ .unwrap();
+ let aborted = adapter
+ .prepare_publication_rollback(&operation, &publication)
+ .unwrap();
+ operation
+ .step_mut(OperationStepKind::CompilePublication)
+ .effects = vec![aborted.clone()];
+ operation.state = OperationState::RollingBack;
+ adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .save_operation(&mut operation)
+ .unwrap();
+ assert_eq!(
+ adapter.compensate_external(&operation, &aborted).unwrap(),
+ CompensationOutcome::Compensated
+ );
+ operation
+ .step_mut(OperationStepKind::CompilePublication)
+ .status = OperationStepStatus::Compensated;
+ adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .save_operation(&mut operation)
+ .unwrap();
+ assert!(
+ adapter
+ .stores_lock()
+ .unwrap()
+ .control()
+ .prepared_publication(&WorkspaceId::default())
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ adapter
+ .stores_lock()
+ .unwrap()
+ .secrets()
+ .resolve_agent_access_grant(&reference)
+ .is_ok()
+ );
+ let id = operation.operation_id.clone();
+ drop(runtime);
+
+ // Reopen the exact persisted checkpoint through the production startup entry.
+ let recovered = ProductionControlRuntime::prepare_for_role_all(
+ root.path(),
+ crate::release_catalog::fixture_catalog(),
+ None,
+ )
+ .expect("a recoverable rollback must reach journal recovery");
+ let target = std::sync::Arc::new(crate::gateway_ports::GatewayPublicationAdapter::new(
+ std::sync::Arc::new(
+ hiroute_gateway::server::publication::GatewayPublicationInstaller::open(
+ root.path().join("gateway-lkg.json"),
+ )
+ .unwrap(),
+ ),
+ ));
+ *recovered.adapter.publication_target.lock().unwrap() = Some(target.clone());
+ assert!(RuntimePublicationFeed::pin(target.as_ref()).is_none());
+ // A caller cannot skip recovery and expose the inconsistent grant as serving state.
+ assert!(
+ recovered
+ .adapter
+ .finish_startup_publication_recovery()
+ .is_err()
+ );
+ assert!(RuntimePublicationFeed::pin(target.as_ref()).is_none());
+ assert!(
+ !recovered
+ .adapter
+ .startup_recovery_complete
+ .load(std::sync::atomic::Ordering::Acquire)
+ );
+ recovered
+ .configure_managed_agent_runtime(
+ "http://127.0.0.1:5837/v1".into(),
+ "/test/hiroute".into(),
+ Some(target.clone()),
+ )
+ .unwrap();
+ let stores = recovered.adapter.stores_lock().unwrap();
+ assert_eq!(
+ stores.control().load_operation(&id).unwrap().unwrap().state,
+ OperationState::RolledBack
+ );
+ assert!(
+ stores
+ .secrets()
+ .resolve_agent_access_grant(&reference)
+ .is_err()
+ );
+ assert!(
+ stores
+ .control()
+ .prepared_publication(&WorkspaceId::default())
+ .unwrap()
+ .is_none()
+ );
+ assert!(RuntimePublicationFeed::pin(target.as_ref()).is_some());
+ assert_eq!(fs::read(path).unwrap(), before);
+}
diff --git a/crates/daemon/src/control/runtime/publication.rs b/crates/daemon/src/control/runtime/publication.rs
index 570fb8d5..cc735981 100644
--- a/crates/daemon/src/control/runtime/publication.rs
+++ b/crates/daemon/src/control/runtime/publication.rs
@@ -55,10 +55,10 @@ impl LocalControlAdapter {
connection_id: &str,
) -> PortResult<AgentAccessGrantRefV1> {
let stores = self.stores_lock()?;
- for operation in stores
- .control()
- .succeeded_operations_for_kind(&WorkspaceId::default(), "ApplyAgentConnectionChange")?
- {
+ for operation in stores.control().succeeded_agent_operations_for_kind(
+ &WorkspaceId::default(),
+ "ApplyAgentConnectionChange",
+ )? {
let projection = operation
.plan
.agent_connection_projection()
@@ -480,7 +480,10 @@ impl LocalControlAdapter {
|| {
let target = self.required_publication_target()?;
if !target.verify_installed(record).map_err(target_error)? {
- target.activate_verified(record).map_err(target_error)?;
+ crate::publication_failpoint::during_operation_install(|| {
+ target.activate_verified(record)
+ })
+ .map_err(target_error)?;
}
if !target.verify_installed(record).map_err(target_error)? {
return Err(invalid("publication.activate.target-mismatch"));
diff --git a/crates/daemon/src/control/runtime/publication/lifecycle.rs b/crates/daemon/src/control/runtime/publication/lifecycle.rs
index 47c45c88..55e1110f 100644
--- a/crates/daemon/src/control/runtime/publication/lifecycle.rs
+++ b/crates/daemon/src/control/runtime/publication/lifecycle.rs
@@ -35,7 +35,7 @@ impl LocalControlAdapter {
self.required_publication_target()?;
Ok(())
}
- pub(super) fn publication_target(
+ pub(in crate::control::runtime) fn publication_target(
&self,
) -> PortResult<Option<Arc<dyn PublicationTargetPort + Send + Sync>>> {
self.publication_target
@@ -232,6 +232,48 @@ impl LocalControlAdapter {
}
pub(in crate::control::runtime) fn reconcile_active_publication(&self) -> PortResult<()> {
+ self.restore_active_publication()?;
+ if !self
+ .startup_recovery_complete
+ .load(std::sync::atomic::Ordering::Acquire)
+ {
+ return Ok(());
+ }
+ self.resume_active_publication()
+ }
+
+ pub(in crate::control::runtime) fn finish_startup_publication_recovery(
+ &self,
+ ) -> PortResult<()> {
+ self.stores_lock()?
+ .validate_recovered_grant_publications()
+ .map_err(|_| invalid("publication.startup.grant-integrity"))?;
+ self.restore_active_publication()?;
+ self.resume_active_publication()?;
+ self.startup_recovery_complete
+ .store(true, std::sync::atomic::Ordering::Release);
+ Ok(())
+ }
+
+ fn resume_active_publication(&self) -> PortResult<()> {
+ if let Some(target) = self.publication_target()? {
+ if self
+ .stores_lock()?
+ .control()
+ .active_publication(&WorkspaceId::default())?
+ .is_none()
+ && !target.is_empty().map_err(target_error)?
+ {
+ return Err(invalid("publication.startup.orphan-target"));
+ }
+ target.resume_requests().map_err(target_error)?;
+ }
+ Ok(())
+ }
+
+ /// Reconstruct committed authority before journal recovery observes service receipts.
+ /// Admission remains suspended until the complete startup recovery succeeds.
+ pub(in crate::control::runtime) fn restore_active_publication(&self) -> PortResult<()> {
let record = self
.stores_lock()?
.control()
@@ -247,16 +289,14 @@ impl LocalControlAdapter {
}
return Ok(());
};
- if let Some(record) = record {
+ if let Some(record) = record
+ && !self.publication_is_installed(&record)?
+ {
+ target.activate_verified(&record).map_err(target_error)?;
if !self.publication_is_installed(&record)? {
- target.activate_verified(&record).map_err(target_error)?;
- if !self.publication_is_installed(&record)? {
- return Err(invalid("publication.startup.identity"));
- }
+ return Err(invalid("publication.startup.identity"));
}
- } else if !target.is_empty().map_err(target_error)? {
- return Err(invalid("publication.startup.orphan-target"));
}
- target.resume_requests().map_err(target_error)
+ Ok(())
}
}
diff --git a/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rs b/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rs
index 948ead16..03bf3171 100644
--- a/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_collaboration_tests.rs
@@ -9,6 +9,7 @@ fn v2_settings_skill_only_enable_change_and_disable_keep_model_untouched() {
}
let root = tempfile::tempdir().unwrap();
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ drop(hiroute_local_storage::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap());
let executable = root.path().join("codex-fixture");
fs::write(&executable, b"#!/bin/sh\nprintf 'codex-cli 99.99.99\\n'\n").unwrap();
fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
@@ -209,6 +210,7 @@ fn v2_settings_releases_borrowed_skill_after_user_file_drift() {
let root = tempfile::tempdir().unwrap();
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ drop(hiroute_local_storage::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap());
let executable = root.path().join("codex-fixture");
fs::write(&executable, b"#!/bin/sh\nprintf 'codex-cli 99.99.99\\n'\n").unwrap();
fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
diff --git a/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs b/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs
index 7766eaa4..97b3cdbc 100644
--- a/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_facets_tests.rs
@@ -11,6 +11,7 @@ fn v2_settings_skill_only_works_before_the_first_publication() {
}
let root = tempfile::tempdir().unwrap();
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ drop(hiroute_local_storage::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap());
let executable = root.path().join("codex-fixture");
fs::write(&executable, b"#!/bin/sh\nprintf 'codex-cli 99.99.99\\n'\n").unwrap();
fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
@@ -116,6 +117,7 @@ fn v2_settings_dispatch_claude_configures_and_formally_restores_owned_user_file(
}
let root = tempfile::tempdir().unwrap();
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ drop(hiroute_local_storage::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap());
let home = root.path().join("agent-home");
fs::create_dir(&home).unwrap();
let settings = home.join(".claude/settings.json");
diff --git a/crates/daemon/src/control/runtime/settings_entry_tests.rs b/crates/daemon/src/control/runtime/settings_entry_tests.rs
index b94e2b09..e1fa74f4 100644
--- a/crates/daemon/src/control/runtime/settings_entry_tests.rs
+++ b/crates/daemon/src/control/runtime/settings_entry_tests.rs
@@ -28,6 +28,7 @@ fn v2_settings_first_save_without_native_probe_and_reenable_identical_catalog()
let root = tempfile::tempdir().unwrap();
#[cfg(unix)]
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ drop(hiroute_local_storage::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap());
let executable = root.path().join("codex-fixture");
fs::write(&executable, b"#!/bin/sh\nprintf 'codex-cli 99.99.99\\n'\n").unwrap();
fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
@@ -491,6 +492,7 @@ fn exercise_settings_entry() {
let root = tempfile::tempdir().unwrap();
#[cfg(unix)]
fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ drop(hiroute_local_storage::LocalStorageSet::open_for_daemon_startup(root.path()).unwrap());
let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap());
let mut layout = AgentFilesystemLayoutV1::from_process(&home, root.path());
layout.codex_executable = std::path::PathBuf::from(
diff --git a/crates/daemon/src/control/runtime/settings_facts.rs b/crates/daemon/src/control/runtime/settings_facts.rs
index bba42d62..d415b945 100644
--- a/crates/daemon/src/control/runtime/settings_facts.rs
+++ b/crates/daemon/src/control/runtime/settings_facts.rs
@@ -380,7 +380,7 @@ impl LocalControlAdapter {
let mut selected_collaboration_restore = None;
for original in stores
.control()
- .succeeded_operations_for_kind(&workspace, "ApplyAgentConnectionChange")
+ .succeeded_agent_operations_for_kind(&workspace, "ApplyAgentConnectionChange")
.map_err(super::map_port)?
{
if original.plan.spec().command_id != "agents.settings.apply" {
@@ -913,7 +913,7 @@ fn login_item_owned_by_this_feature(
) -> Result<bool, ControlReadError> {
for original in stores
.control()
- .succeeded_operations_for_kinds(
+ .succeeded_agent_operations_for_kinds(
workspace,
&["ApplyAgentConnectionChange", "ApplyAgentConnectionRestore"],
)
diff --git a/crates/daemon/src/control/runtime/settings_status.rs b/crates/daemon/src/control/runtime/settings_status.rs
index 372c6ffb..7d3fdc9c 100644
--- a/crates/daemon/src/control/runtime/settings_status.rs
+++ b/crates/daemon/src/control/runtime/settings_status.rs
@@ -139,9 +139,9 @@ impl LocalControlAdapter {
collaboration: None,
};
let stores = self.stores_lock().map_err(super::map_port)?;
- let belongs = |operation: &OperationV1| {
- operation.plan.spec().command_id == "agents.settings.apply"
- && operation.plan.spec().resource_id.as_deref() == Some(&request.context_id)
+ let belongs = |operation: &dyn hiroute_domain::AgentOperationRead| {
+ operation.agent_input().spec.command_id == "agents.settings.apply"
+ && operation.agent_input().spec.resource_id.as_deref() == Some(&request.context_id)
&& model_intent(class, operation).is_some()
};
if let Some(pending) = stores
@@ -161,12 +161,12 @@ impl LocalControlAdapter {
}
let operations = stores
.control()
- .succeeded_operations_for_kinds(
+ .succeeded_agent_operations_for_kinds(
&WorkspaceId::default(),
&["ApplyAgentConnectionChange", "ApplyAgentConnectionRestore"],
)
.map_err(super::map_port)?;
- let Some(operation) = operations.into_iter().find(belongs) else {
+ let Some(operation) = operations.into_iter().find(|operation| belongs(operation)) else {
return Ok((status, None, None));
};
let intent = model_intent(class, &operation).ok_or(ControlReadError::Corrupt)?;
@@ -398,21 +398,25 @@ impl LocalControlAdapter {
fn model_intent(
class: super::settings_facts::SettingsAgentClass,
- operation: &OperationV1,
+ operation: &(impl hiroute_domain::AgentOperationRead + ?Sized),
) -> Option<&hiroute_domain::ExternalEffectIntentV1> {
- operation.plan.external().iter().find(|intent| match class {
- super::settings_facts::SettingsAgentClass::Codex => {
- super::native_model::is_settings_codex_model(intent)
- }
- super::settings_facts::SettingsAgentClass::Claude => {
- super::native_claude_model::is_settings_claude_model(intent)
- }
- })
+ operation
+ .agent_input()
+ .external
+ .iter()
+ .find(|intent| match class {
+ super::settings_facts::SettingsAgentClass::Codex => {
+ super::native_model::is_settings_codex_model(intent)
+ }
+ super::settings_facts::SettingsAgentClass::Claude => {
+ super::native_claude_model::is_settings_claude_model(intent)
+ }
+ })
}
fn model_action(
class: super::settings_facts::SettingsAgentClass,
- operation: &OperationV1,
+ operation: &(impl hiroute_domain::AgentOperationRead + ?Sized),
intent: &hiroute_domain::ExternalEffectIntentV1,
) -> hiroute_domain::PortResult<ModelAction> {
match class {
diff --git a/crates/daemon/src/control/runtime/work_plans.rs b/crates/daemon/src/control/runtime/work_plans.rs
index 4e2ed76c..b9805344 100644
--- a/crates/daemon/src/control/runtime/work_plans.rs
+++ b/crates/daemon/src/control/runtime/work_plans.rs
@@ -205,6 +205,10 @@ impl ProductionControlRuntime {
}
}
+#[cfg(all(test, unix))]
+#[path = "work_plans/current_authority_tests.rs"]
+mod current_authority_tests;
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/daemon/src/control/runtime/work_plans/current_authority_support.rs b/crates/daemon/src/control/runtime/work_plans/current_authority_support.rs
new file mode 100644
index 00000000..d88f6276
--- /dev/null
+++ b/crates/daemon/src/control/runtime/work_plans/current_authority_support.rs
@@ -0,0 +1,127 @@
+#![allow(dead_code)]
+use hiroute_domain::*;
+use hiroute_local_storage::{ApplyCapabilityRegistrationV1, LocalStorageSet};
+use serde_json::json;
+
+fn agent_transaction_plan(
+ transaction: AgentConnectionTransactionKindV1,
+ before: Option<CanonicalDigest>,
+) -> TransactionPlanV1 {
+ let spec = ChangeSpecV1 {
+ schema_version: hiroute_domain::CHANGE_SPEC_SCHEMA_V1,
+ command_id: transaction.command_id().to_owned(),
+ resource_id: Some("agent-connection/codex-default".to_owned()),
+ desired_state: match transaction {
+ AgentConnectionTransactionKindV1::Settings => {
+ panic!("legacy fixture does not model independent settings")
+ }
+ AgentConnectionTransactionKindV1::Apply => json!({
+ "agent_id": "agent.codex",
+ "profile_id": "default",
+ "default_agent_plan_id": "plan.primary"
+ }),
+ AgentConnectionTransactionKindV1::Restore => json!({
+ "agent_id": "agent.codex",
+ "profile_id": "default",
+ "restore_point_ref": "restore.codex.1"
+ }),
+ },
+ };
+ let subject = AgentConnectionTransactionSubjectV1::from_registered_profile(
+ "agent.codex",
+ "default",
+ "codex.profile.v1",
+ )
+ .unwrap();
+ let control = AgentConnectionControlIntentV1::from_registered_planner(
+ transaction,
+ subject,
+ &spec,
+ &json!({"connection_revision": 4, "desired_digest": "connection.digest.v4"}),
+ )
+ .unwrap();
+ let external = [
+ AgentConnectionEffectRoleV1::GrantScopedPublication,
+ AgentConnectionEffectRoleV1::ManagedConfiguration,
+ ]
+ .into_iter()
+ .map(|role| {
+ ExternalEffectIntentV1::from_agent_connection_planner(
+ &control,
+ role,
+ if role == AgentConnectionEffectRoleV1::ManagedConfiguration {
+ before.clone()
+ } else {
+ None
+ },
+ &json!({"role": format!("{role:?}"), "content_digest": "sha256:fixture"}),
+ if role == AgentConnectionEffectRoleV1::ManagedConfiguration {
+ 0o640
+ } else {
+ 0o644
+ },
+ )
+ .unwrap()
+ })
+ .collect();
+ TransactionPlanV1::from_agent_connection_planner(spec, control, external).unwrap()
+}
+
+pub fn begin(stores: &LocalStorageSet, key: &str) -> OperationV1 {
+ let workspace = WorkspaceId::default();
+ let scope =
+ IdempotencyScopeV1::new("interactive-user", "ApplyAgentConnectionChange", key).unwrap();
+ let digest = CanonicalDigest::of_bytes(key.as_bytes());
+ let revisions = stores.control().current_revisions(&workspace).unwrap();
+ let operation = OperationV1::new(
+ OperationId::derive(&workspace, &scope, &digest),
+ workspace.clone(),
+ scope,
+ digest.clone(),
+ digest.clone(),
+ revisions.clone(),
+ agent_transaction_plan(AgentConnectionTransactionKindV1::Apply, None),
+ )
+ .unwrap();
+ let capability = format!("fixture-exact-apply-capability-{key}-0123456789");
+ let expires = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs() as i64
+ + 120;
+ stores
+ .apply_capability_registrar()
+ .register(
+ ApplyCapabilityRegistrationV1::from_protected_launcher(
+ capability.clone(),
+ "interactive-user",
+ workspace.clone(),
+ "ApplyAgentConnectionChange",
+ digest,
+ revisions,
+ expires,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let auth = 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, &auth).unwrap(),
+ BeginOperationOutcome::Created
+ );
+ operation
+}
+pub fn finish(stores: &LocalStorageSet, mut operation: OperationV1) {
+ operation.state = OperationState::Succeeded;
+ stores.control().finish_operation(&mut operation).unwrap();
+}
diff --git a/crates/daemon/src/control/runtime/work_plans/current_authority_tests.rs b/crates/daemon/src/control/runtime/work_plans/current_authority_tests.rs
new file mode 100644
index 00000000..92ffa986
--- /dev/null
+++ b/crates/daemon/src/control/runtime/work_plans/current_authority_tests.rs
@@ -0,0 +1,230 @@
+#![cfg(unix)]
+use super::super::ProductionControlRuntime;
+use crate::control::start_control;
+use hiroute_application::ApplicationService;
+use hiroute_application::delegation::work_plans::*;
+use hiroute_application_api::*;
+use hiroute_client_core::{Client, LocalEndpoint};
+use hiroute_domain::delegation::WorkerHarnessV1;
+use hiroute_domain::{
+ AgentCollaborationCredential, AgentCollaborationGrant, AgentCollaborationRevocationStorePort,
+ AgentIngressProtocolV1, WorkspaceId,
+};
+use hiroute_local_storage::LocalStorageSet;
+use serde_json::{Value, json};
+use std::collections::BTreeSet;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+#[path = "current_authority_support.rs"]
+mod support;
+
+#[derive(Default)]
+struct Metadata(Mutex<Vec<WorkPlanMetadataV1>>);
+impl WorkPlanMetadataPort for Metadata {
+ fn current_plans(
+ &self,
+ _: &WorkspaceId,
+ _: &BTreeSet<AgentPlanId>,
+ ) -> Result<Vec<WorkPlanMetadataV1>, ErrorCode> {
+ // Intentionally includes unauthorized, unpublished and unbound rows: Application must
+ // perform its own filtering rather than trusting an overly broad backend projection.
+ Ok(self.0.lock().unwrap().clone())
+ }
+}
+fn plan(
+ id: &str,
+ published: bool,
+ bound: bool,
+ availability: WorkPlanAvailabilityV1,
+) -> WorkPlanMetadataV1 {
+ WorkPlanMetadataV1 {
+ agent_plan_id: AgentPlanId::parse(id).unwrap(),
+ alias: format!("work-{id}"),
+ display_name: format!("Worker {id}"),
+ purpose: "published purpose".into(),
+ published,
+ work: bound.then_some((WorkerHarnessV1::CodexCli, AgentIngressProtocolV1::Responses)),
+ availability,
+ reason: (availability != WorkPlanAvailabilityV1::Ready)
+ .then(|| "harness_not_observed".into()),
+ }
+}
+fn query() -> Value {
+ json!({"workspace_id": WorkspaceId::default(), "context_id": "owner", "grant_id": "collaboration-grant/directory"})
+}
+fn internal_control(
+ client: &Client,
+ executor: &tokio::runtime::Runtime,
+ payload: Value,
+ secret: Option<&[u8]>,
+) -> Value {
+ let response = executor
+ .block_on(client.call_wire(LocalControlWireRequestV2 {
+ schema_version: LOCAL_CONTROL_SCHEMA_V2,
+ request_id: "work-plans-internal-control".into(),
+ operation_id: "ListWorkPlans".into(),
+ payload,
+ protected_grant: secret.map(|secret| ProtectedClientGrantV2 {
+ principal_kind: PrincipalKind::Skill,
+ capability: String::from_utf8(secret.to_vec()).unwrap(),
+ }),
+ }))
+ .unwrap();
+ serde_json::to_value(response).unwrap()
+}
+
+fn store_grant(
+ stores: &LocalStorageSet,
+ generation: u64,
+ ids: &[&str],
+ secret: &AgentCollaborationCredential,
+) -> AgentCollaborationGrant {
+ let op = support::begin(stores, &format!("directory-{generation}"));
+ let grant = AgentCollaborationGrant::issue(
+ WorkspaceId::default(),
+ "owner".into(),
+ "collaboration-grant/directory".into(),
+ generation,
+ ids.iter()
+ .map(|id| AgentPlanId::parse(*id).unwrap())
+ .collect(),
+ secret,
+ )
+ .unwrap();
+ stores
+ .control()
+ .store_collaboration_grant(&op.operation_id, generation - 1, &grant)
+ .unwrap();
+ support::finish(stores, op);
+ grant
+}
+
+#[test]
+fn current_authority_and_metadata_changes_apply_without_restart() {
+ if crate::test_support::isolated_agent_home(
+ "control::runtime::work_plans::current_authority_tests::current_authority_and_metadata_changes_apply_without_restart",
+ ) {
+ return;
+ }
+ let root = crate::test_support::private_tempdir();
+ let runtime = ProductionControlRuntime::open_with_release_catalog(
+ root.path().join("storage"),
+ crate::release_catalog::fixture_catalog(),
+ )
+ .unwrap();
+ let secret = AgentCollaborationCredential::from_csprng_entropy([42; 32]);
+ store_grant(
+ &runtime.adapter.stores_lock().unwrap(),
+ 1,
+ &["a", "b", "draft", "unbound"],
+ &secret,
+ );
+ let metadata = Arc::new(Metadata(Mutex::new(vec![
+ plan("a", true, true, WorkPlanAvailabilityV1::Ready),
+ plan("b", true, true, WorkPlanAvailabilityV1::Unknown),
+ plan("draft", false, true, WorkPlanAvailabilityV1::Ready),
+ plan("unbound", true, false, WorkPlanAvailabilityV1::Ready),
+ plan("other-owner", true, true, WorkPlanAvailabilityV1::Ready),
+ ])));
+ let mut listener = start_control(
+ ApplicationService::new(
+ runtime.application_ports_with_work_plan_metadata(metadata.clone()),
+ ),
+ root.path().join("ipc"),
+ )
+ .unwrap();
+ let client = Client::new(
+ "work-plans-test",
+ LocalEndpoint::from_runtime_root(root.path().join("ipc")),
+ );
+ let executor = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let call = |q, s| internal_control(&client, &executor, q, s);
+ let result = call(query(), Some(secret.expose()));
+ assert!(result["error"].is_null(), "{result}");
+ assert_eq!(result["data"]["plans"].as_array().unwrap().len(), 2);
+ assert_eq!(result["data"]["plans"][0]["alias"], "work-a");
+ assert_eq!(result["data"]["plans"][0]["harness"], "codex_cli");
+ assert_eq!(result["data"]["plans"][1]["availability"], "unknown");
+ metadata.0.lock().unwrap()[0].purpose = "new published purpose; data, not instructions".into();
+ metadata.0.lock().unwrap()[0].availability = WorkPlanAvailabilityV1::Unavailable;
+ let updated = call(query(), Some(secret.expose()));
+ assert_eq!(
+ updated["data"]["plans"][0]["purpose"],
+ "new published purpose; data, not instructions"
+ );
+ assert_eq!(updated["data"]["plans"][0]["availability"], "unavailable");
+ for field in ["context_id", "grant_id", "workspace_id"] {
+ let mut q = query();
+ q[field] = json!(if field == "grant_id" {
+ "collaboration-grant/other"
+ } else {
+ "other"
+ });
+ assert_eq!(
+ call(q, Some(secret.expose()))["error"]["code"],
+ "CAPABILITY_DENIED"
+ );
+ }
+ let wrong = AgentCollaborationCredential::from_csprng_entropy([43; 32]);
+ assert_eq!(
+ call(query(), Some(wrong.expose()))["error"]["code"],
+ "CAPABILITY_DENIED"
+ );
+ assert_eq!(call(query(), None)["error"]["code"], "CAPABILITY_DENIED");
+ for (operation, kind, payload) in [
+ ("ListWorkPlans", PrincipalKind::InteractiveUser, query()),
+ ("ListAgentPlanCatalog", PrincipalKind::Skill, json!({})),
+ (
+ "GetAgentPlanStatus",
+ PrincipalKind::Skill,
+ json!({"agent_plan_id": "a"}),
+ ),
+ ] {
+ let denied = executor
+ .block_on(client.call_wire(LocalControlWireRequestV2 {
+ schema_version: LOCAL_CONTROL_SCHEMA_V2,
+ request_id: "directory-isolation".into(),
+ operation_id: operation.into(),
+ payload,
+ protected_grant: Some(ProtectedClientGrantV2 {
+ principal_kind: kind,
+ capability: String::from_utf8(secret.expose().to_vec()).unwrap(),
+ }),
+ }))
+ .unwrap();
+ assert_eq!(denied.error.unwrap().code, ErrorCode::CapabilityDenied);
+ }
+ store_grant(&runtime.adapter.stores_lock().unwrap(), 2, &["b"], &secret);
+ // Same non-secret access reference and material; editing the allowlist does not require
+ // installing a new Skill or trusting an old principal's allowed-plan snapshot.
+ let shrunk = call(query(), Some(secret.expose()));
+ assert_eq!(shrunk["data"]["plans"].as_array().unwrap().len(), 1);
+ assert_eq!(shrunk["data"]["plans"][0]["agent_plan_id"], "b");
+ let rotated = AgentCollaborationCredential::from_csprng_entropy([44; 32]);
+ let grant = store_grant(&runtime.adapter.stores_lock().unwrap(), 3, &["b"], &rotated);
+ assert_eq!(
+ call(query(), Some(secret.expose()))["error"]["code"],
+ "CAPABILITY_DENIED"
+ );
+ assert!(call(query(), Some(rotated.expose()))["error"].is_null());
+ {
+ let stores = runtime.adapter.stores_lock().unwrap();
+ let op = support::begin(&stores, "directory-revoke");
+ stores
+ .control()
+ .persist_collaboration_revocation(
+ &grant.plan_revocation(op.operation_id.clone(), 3).unwrap(),
+ )
+ .unwrap();
+ support::finish(&stores, op);
+ }
+ assert_eq!(
+ call(query(), Some(rotated.expose()))["error"]["code"],
+ "CAPABILITY_DENIED"
+ );
+ listener.shutdown();
+ listener.join(Duration::from_secs(10)).unwrap();
+}
diff --git a/crates/daemon/src/delegation/executor.rs b/crates/daemon/src/delegation/executor.rs
index e7becb88..4c3ee520 100644
--- a/crates/daemon/src/delegation/executor.rs
+++ b/crates/daemon/src/delegation/executor.rs
@@ -141,6 +141,13 @@ impl DelegationRunExecutor {
/// The process entry point installs the diagnostic port once the runtime exists; a
/// missing port keeps worker/task diagnostics inert instead of failing execution.
+ pub(crate) fn upgrade_active_count(&self) -> Result<u64, DelegationErrorV1> {
+ self.active
+ .lock()
+ .map(|active| active.len() as u64)
+ .map_err(|_| DelegationErrorV1::StorageUnavailable)
+ }
+
pub fn set_diagnostics(&self, diagnostics: DiagnosticsPort) {
if let Ok(mut current) = self.diagnostics.write() {
*current = diagnostics;
diff --git a/crates/daemon/src/delegation/profile/capability_tests.rs b/crates/daemon/src/delegation/profile/capability_tests.rs
index bc646042..7caf42c3 100644
--- a/crates/daemon/src/delegation/profile/capability_tests.rs
+++ b/crates/daemon/src/delegation/profile/capability_tests.rs
@@ -7,8 +7,8 @@ fn missing_worker_dependencies_leave_normal_gateway_publication_available() {
use hiroute_gateway::server::publication::GatewayPublicationInstaller;
use std::sync::Arc;
- let publication = hiroute_domain::GatewayPublicationV1::decode_persisted(
- include_str!("../../../../../e2e/product/golden/routing/compiled-publication.v2.json")
+ let publication = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(
+ include_str!("../../../../../e2e/product/fixtures/routing/current-publication.v3.json")
.as_bytes(),
)
.unwrap();
diff --git a/crates/daemon/src/gateway_ports/publication_tests.rs b/crates/daemon/src/gateway_ports/publication_tests.rs
index 2d90ada2..956f47f8 100644
--- a/crates/daemon/src/gateway_ports/publication_tests.rs
+++ b/crates/daemon/src/gateway_ports/publication_tests.rs
@@ -1,12 +1,12 @@
use super::*;
-use hiroute_domain::{GatewayPublicationRevision, GatewayPublicationV1};
+use hiroute_domain::GatewayPublicationRevision;
use hiroute_gateway::server::publication::PublicationFailpoint;
use hiroute_gateway::server::{dispatch::GatewayRequestAuthority, request_plan::IngressProtocol};
fn record(revision: u64) -> PublicationRecordV1 {
- let mut publication = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
+ let mut publication = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(
+ include_bytes!("../../../../e2e/product/fixtures/routing/current-publication.v3.json"),
+ )
.unwrap();
publication.publication_revision = GatewayPublicationRevision::new(revision).unwrap();
PublicationRecordV1::from_publication(publication.workspace_id.clone(), &publication).unwrap()
diff --git a/crates/daemon/src/gateway_ports/tests.rs b/crates/daemon/src/gateway_ports/tests.rs
index 5f06c2ce..98cb4d38 100644
--- a/crates/daemon/src/gateway_ports/tests.rs
+++ b/crates/daemon/src/gateway_ports/tests.rs
@@ -44,11 +44,11 @@ fn scope() -> ExecutionScope {
fn gateway_ports_publication_installs_one_verified_aggregate_and_pins_it() {
let golden = std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
- .join("../../e2e/product/golden/routing/compiled-publication.v2.json"),
+ .join("../../e2e/product/fixtures/routing/current-publication.v3.json"),
)
.unwrap();
let publication =
- hiroute_domain::GatewayPublicationV1::decode_persisted(golden.as_bytes()).unwrap();
+ serde_json::from_str::<hiroute_domain::GatewayPublicationV1>(&golden).unwrap();
let record = hiroute_domain::PublicationRecordV1::from_publication(
publication.workspace_id.clone(),
&publication,
diff --git a/crates/daemon/src/gateway_ports/tests/publication_scope.rs b/crates/daemon/src/gateway_ports/tests/publication_scope.rs
index 76d413d2..2538d8a9 100644
--- a/crates/daemon/src/gateway_ports/tests/publication_scope.rs
+++ b/crates/daemon/src/gateway_ports/tests/publication_scope.rs
@@ -1,15 +1,13 @@
use super::*;
-use hiroute_domain::{
- CompiledAgentPlanV1, GatewayPublicationRevision, GatewayPublicationV1, PublicationRecordV1,
-};
+use hiroute_domain::{CompiledAgentPlanV1, GatewayPublicationRevision, PublicationRecordV1};
use hiroute_gateway::server::dispatch::GatewayRequestAuthority;
use hiroute_gateway::server::publication::GatewayCatalog;
#[test]
fn publication_plan_update_preserves_two_independent_agent_scopes_and_old_request_pin() {
- let mut publication = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
+ let mut publication = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(
+ include_bytes!("../../../../../e2e/product/fixtures/routing/current-publication.v3.json"),
+ )
.unwrap()
.into_current()
.unwrap();
diff --git a/crates/daemon/src/publication_failpoint.rs b/crates/daemon/src/publication_failpoint.rs
index 1cd22035..09273f0f 100644
--- a/crates/daemon/src/publication_failpoint.rs
+++ b/crates/daemon/src/publication_failpoint.rs
@@ -1,8 +1,30 @@
//! Process-exit injection for the real-binary recovery suite. Absent in normal builds.
+#[cfg(feature = "integration-test-hooks")]
+thread_local! {
+ static OPERATION_INSTALL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+pub(crate) fn during_operation_install<T>(install: impl FnOnce() -> T) -> T {
+ #[cfg(feature = "integration-test-hooks")]
+ {
+ struct Reset(bool);
+ impl Drop for Reset {
+ fn drop(&mut self) {
+ OPERATION_INSTALL.with(|armed| armed.set(self.0));
+ }
+ }
+ let _reset = Reset(OPERATION_INSTALL.with(|armed| armed.replace(true)));
+ install()
+ }
+ #[cfg(not(feature = "integration-test-hooks"))]
+ install()
+}
+
pub(crate) fn requested(boundary: &str) -> bool {
#[cfg(feature = "integration-test-hooks")]
{
std::env::var("HIROUTE_TEST_PUBLICATION_CRASH_AT").as_deref() == Ok(boundary)
+ && (boundary != "after_gateway_durable" || OPERATION_INSTALL.with(std::cell::Cell::get))
}
#[cfg(not(feature = "integration-test-hooks"))]
{
diff --git a/crates/daemon/src/role_all.rs b/crates/daemon/src/role_all.rs
index ccf45132..6eeb173f 100644
--- a/crates/daemon/src/role_all.rs
+++ b/crates/daemon/src/role_all.rs
@@ -58,6 +58,9 @@ pub struct RoleAllConfig {
pub diagnostics: DiagnosticsPort,
/// Standalone exposes only the current public release manifest at Local Control.
pub released_commands_only: bool,
+ /// Progress only on the inherited native readiness pipe; it grants no control authority.
+ pub upgrade_progress:
+ Option<std::sync::mpsc::Sender<hiroute_host_runtime::StorageUpgradePhase>>,
}
#[derive(Clone, Debug)]
@@ -82,6 +85,7 @@ impl RoleAllConfig {
codex_desktop_engine: None,
diagnostics: DiagnosticsPort::default(),
released_commands_only: false,
+ upgrade_progress: None,
}
}
@@ -111,6 +115,7 @@ pub struct RoleAllHandle {
gateway: ManagedGatewayHandle,
cpa: Option<Arc<ManagedCpaRuntime>>,
_runtime: ProductionControlRuntime,
+ upgrade: Arc<hiroute_host_runtime::UpgradeDrain>,
}
struct GatewayClassifierDiagnostic {
@@ -185,6 +190,26 @@ impl RoleAllHandle {
self._runtime.release_manual_protected_input(candidate_ref)
}
+ pub fn upgrade_status(
+ &self,
+ action: hiroute_host_runtime::UpgradeAction,
+ registration_id: String,
+ ) -> Result<hiroute_host_runtime::LauncherUpgradeStatus, String> {
+ use hiroute_host_runtime::UpgradeAction;
+ match action {
+ UpgradeAction::Prepare => self.upgrade.pause(),
+ UpgradeAction::Cancel => self.upgrade.resume(),
+ UpgradeAction::Status => {}
+ }
+ Ok(hiroute_host_runtime::LauncherUpgradeStatus {
+ schema: "hiroute.launcher-upgrade-status/v1".into(),
+ registration_id,
+ paused: self.upgrade.paused(),
+ active_calls: self.upgrade.active(),
+ active_tasks: self._runtime.upgrade_active_tasks()?,
+ })
+ }
+
pub fn shutdown(&self) {
// Reverse startup order: reject new control work before stopping request traffic. The
// Gateway-owned bounded observation producers drain as their runtime is dropped.
@@ -279,6 +304,10 @@ pub fn start_role_all(config: RoleAllConfig) -> Result<RoleAllHandle, RoleAllErr
catalog,
cpa.clone(),
config.codex_desktop_engine.clone(),
+ hiroute_local_storage::StorageStartupOptions {
+ gateway_lkg: Some(config.gateway_lkg.clone()),
+ upgrade_progress: config.upgrade_progress.clone(),
+ },
)
.map_err(|error| RoleAllError::Component("Storage", error));
let runtime = match runtime {
@@ -311,7 +340,7 @@ fn start_role_all_with_runtime(
cpa: Option<Arc<ManagedCpaRuntime>>,
) -> Result<RoleAllHandle, RoleAllError> {
let installer = Arc::new(
- GatewayPublicationInstaller::open(&config.gateway_lkg)
+ GatewayPublicationInstaller::open_for_product_authority(&config.gateway_lkg)
.map_err(|error| RoleAllError::Component("Gateway publication", error.to_string()))?,
);
let publications = Arc::new(GatewayPublicationAdapter::new(installer));
@@ -366,13 +395,15 @@ fn start_role_all_with_runtime(
execution_facts: execution_sink,
conversation_content: content_sink,
};
+ let upgrade = Arc::new(hiroute_host_runtime::UpgradeDrain::default());
let gateway_runtime = Arc::new(
ProductionGatewayRuntime::compose_with_planner_and_observation(
ports,
Arc::new(PublicationPlannerInputAuthority),
observation,
)
- .with_run_request_authority(runtime.delegation_run_authority()),
+ .with_run_request_authority(runtime.delegation_run_authority())
+ .with_upgrade_drain(upgrade.clone()),
);
config.diagnostics.stage_begin(StartupStage::GatewayStart);
let gateway =
@@ -442,6 +473,7 @@ fn start_role_all_with_runtime(
&config.runtime_root,
runtime.agent_grant_resolver(),
config.released_commands_only,
+ Some(upgrade.clone()),
) {
Ok(control) => {
config
@@ -467,6 +499,7 @@ fn start_role_all_with_runtime(
gateway,
cpa,
_runtime: runtime,
+ upgrade,
})
}
diff --git a/crates/daemon/tests/pre_gateway_compute_routing.rs b/crates/daemon/tests/pre_gateway_compute_routing.rs
index 4e16360c..9ef6f798 100644
--- a/crates/daemon/tests/pre_gateway_compute_routing.rs
+++ b/crates/daemon/tests/pre_gateway_compute_routing.rs
@@ -541,6 +541,7 @@ fn run_production_path(root: &Path) {
assert_eq!(denied.error.unwrap().code, ErrorCode::CapabilityDenied);
assert_eq!(semantic_database_snapshot(&storage_root), before_denied);
+ drop(routing_port);
drop(application);
drop(runtime);
let stores = LocalStorageSet::open_for_daemon_startup(&storage_root).unwrap();
diff --git a/crates/daemon/tests/publication_process.rs b/crates/daemon/tests/publication_process.rs
index 24e6fdb4..4435a2d7 100644
--- a/crates/daemon/tests/publication_process.rs
+++ b/crates/daemon/tests/publication_process.rs
@@ -16,6 +16,11 @@ fn real_gateway_requests_retain_their_publication_across_installation() {
run_script("publication_requests.py");
}
+#[test]
+fn real_gateway_upgrade_wait_cancels_and_rebuilds_untrusted_cache() {
+ run_script("upgrade_requests.py");
+}
+
#[test]
fn real_process_recovery_preserves_independent_agent_edits() {
run_script("publication_agent_conflict.py");
diff --git a/crates/daemon/tests/support/model_connections_product.py b/crates/daemon/tests/support/model_connections_product.py
index a8343691..c5c94ba4 100644
--- a/crates/daemon/tests/support/model_connections_product.py
+++ b/crates/daemon/tests/support/model_connections_product.py
@@ -111,7 +111,7 @@ def control(product, operation, payload, protected_grant=None, expected_error=No
'api_version': V2,
'machine_schema_version': V2,
'client_name': 'native-product-test',
- 'client_version': '0.1.0',
+ 'client_version': product.release_version,
}) + b'\n')
stream.flush()
hello = json.loads(stream.readline())
@@ -426,11 +426,11 @@ def publish_plan_and_agent(product, binding_id):
preview = product.preview('routing preview', {'change': change})
# The second source has the same upstream ID but unknown capabilities. Its facts must
# not replace those of the explicitly selected binding.
- candidate = preview['plan_version']['compiled']['body']['materialized']['attempt_owned']['groups'][0]['candidates'][0]
- profile = next(profile for profile in candidate['protocol_profiles']
+ candidate = preview['plan_version']['compiled']['groups'][0]['candidates'][0]
+ profile = next(profile for profile in candidate['protocols']
if profile['ingress_protocol'] == 'responses')
assert profile['capability']['native_model'] == MODEL
- assert profile['capability']['request']['function_tools'] == 'exact'
+ assert profile['capability']['model_support']['tools'] == {'state': 'exact', 'value': True}
assert profile['capability']['native_streaming'] == {'state': 'exact', 'value': True}
product.apply('routing apply', 'ApplyAgentPlanChange', preview,
{'change': change}, 'native-product-plan')
diff --git a/crates/daemon/tests/support/plan_content_process.py b/crates/daemon/tests/support/plan_content_process.py
index a438b30f..8eebbc1c 100644
--- a/crates/daemon/tests/support/plan_content_process.py
+++ b/crates/daemon/tests/support/plan_content_process.py
@@ -54,7 +54,7 @@ def scenario(repository, boundary):
assert product.catalog()[0] == catalog, 'Preview changed the installed catalog'
assert preview['plan_head']['model_alias'] == product.model_alias
assert preview['plan_version']['configuration']['work'] == editor['work']
- assert preview['plan_version']['compiled']['body']['materialized']['attempt_owned']['limits']['context_window_tokens'] == 16384
+ assert preview['plan_version']['compiled']['limits']['context_window_tokens'] == 16384
result, body, capability = product.apply('routing apply', 'ApplyAgentPlanChange', preview,
{'change': change}, 'content-two', crash=bool(boundary))
if boundary:
diff --git a/crates/daemon/tests/support/publication_agent_conflict.py b/crates/daemon/tests/support/publication_agent_conflict.py
index 4bd32615..0cbe4805 100644
--- a/crates/daemon/tests/support/publication_agent_conflict.py
+++ b/crates/daemon/tests/support/publication_agent_conflict.py
@@ -50,6 +50,9 @@ def run(repository):
assert operation['state'] == 'activating', operation['state']
assert operation['safe_error_code'] == 'EFFECT_OWNERSHIP_LOST'
assert operation['steps'][-1]['status'] == 'started'
+ receipt = next(step['terminal_result'] for step in operation['steps']
+ if step['kind'] == 'activate')
+ assert json.loads(receipt)['schema'] == 'hiroute.settings-service-completion/v2'
operation_generation = operation['generation']
# The service segment is committed, so startup stays available; the independently edited
# native file remains a parked tail and its unfinalized grant is not re-exported.
@@ -60,26 +63,41 @@ def run(repository):
raise AssertionError('pending Agent grant became externally available')
except AssertionError as error:
assert str(error) == 'protected Agent grant unavailable'
- product.stop()
- product.start()
- assert settings.read_bytes() == independent
- with sqlite3.connect(f'file:{product.storage}/live/control.db?mode=rw', uri=True) as db:
- db.execute('PRAGMA query_only=ON')
- replayed = [json.loads(row[0]) for row in db.execute(
- 'SELECT operation_json FROM operations')]
- replayed = [op for op in replayed if op['operation_id'] == operation['operation_id']]
- assert len(replayed) == 1
- assert replayed[0]['state'] == 'activating'
- assert replayed[0]['safe_error_code'] == 'SETTINGS_TAIL_PENDING'
- assert replayed[0]['generation'] > operation_generation
- assert replayed[0]['steps'] == operation['steps'], 'startup retried the native file tail'
- with socket.socket() as sock:
- assert sock.connect_ex(('127.0.0.1', product.port)) == 0, 'service did not reopen'
+ for cache_state in ('present', 'missing', 'corrupt'):
+ product.stop()
+ cache = product.root / 'gateway-lkg'
+ if cache_state == 'missing':
+ cache.unlink()
+ elif cache_state == 'corrupt':
+ cache.write_bytes(b'not authoritative publication data')
+ product.start()
+ assert settings.read_bytes() == independent
+ with sqlite3.connect(f'file:{product.storage}/live/control.db?mode=rw', uri=True) as db:
+ db.execute('PRAGMA query_only=ON')
+ replayed = [json.loads(row[0]) for row in db.execute(
+ 'SELECT operation_json FROM operations')]
+ replayed = [op for op in replayed if op['operation_id'] == operation['operation_id']]
+ assert len(replayed) == 1
+ assert replayed[0]['state'] == 'activating'
+ assert replayed[0]['safe_error_code'] == 'SETTINGS_TAIL_PENDING'
+ assert replayed[0]['generation'] > operation_generation
+ assert replayed[0]['steps'] == operation['steps'], 'startup retried the native file tail'
+ assert next(step['terminal_result'] for step in replayed[0]['steps']
+ if step['kind'] == 'activate') == receipt, 'startup discarded the committed receipt'
+ operation_generation = replayed[0]['generation']
+ with socket.socket() as sock:
+ assert sock.connect_ex(('127.0.0.1', product.port)) == 0, 'service did not reopen'
+ try:
+ product.bearer(product.agent_connection)
+ raise AssertionError('pending Agent grant became externally available')
+ except AssertionError as error:
+ assert str(error) == 'protected Agent grant unavailable'
assert not (product.cpa_fixture / 'attempts.jsonl').exists(), 'recovery issued a model attempt'
print(json.dumps({'scenario': 'agent-user-edit-recovery', 'state': 'green',
'operation_state': replayed[0]['state'],
'safe_error_code': replayed[0]['safe_error_code'],
- 'user_file_preserved': True, 'upstream_attempts': 0}), flush=True)
+ 'user_file_preserved': True, 'cold_restart_cache_cases': 3,
+ 'service_receipt_preserved': True, 'upstream_attempts': 0}), flush=True)
finally:
product.close()
diff --git a/crates/daemon/tests/support/publication_product.py b/crates/daemon/tests/support/publication_product.py
index dfc2dcda..91ce8395 100644
--- a/crates/daemon/tests/support/publication_product.py
+++ b/crates/daemon/tests/support/publication_product.py
@@ -11,6 +11,7 @@ import select
import shutil
import socket
import subprocess
+import sys
import tempfile
import time
@@ -24,9 +25,34 @@ def encoded(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
+def startup_frame(process, timeout):
+ deadline = time.monotonic() + timeout
+ previous = -1
+ phases = ('source_check', 'backup', 'conversion', 'validation', 'service_recovery')
+ while True:
+ frame = b''
+ while not frame.endswith(b'\n'):
+ remaining = deadline - time.monotonic()
+ assert remaining > 0 and select.select([process.stdout], [], [], remaining)[0], 'daemon readiness timeout'
+ byte = os.read(process.stdout.fileno(), 1)
+ if not byte:
+ assert not frame, 'partial readiness frame'
+ return b''
+ frame += byte
+ assert len(frame) <= 4096, 'oversized readiness frame'
+ value = json.loads(frame)
+ if value.get('schema') != 'hiroute.daemon-upgrade-progress/v1':
+ return frame
+ assert set(value) == {'schema', 'phase'}, 'unknown progress fields'
+ index = phases.index(value['phase'])
+ assert index > previous, 'repeated or reversed progress'
+ previous = index
+
+
class Product:
def __init__(self, repository, project_source=False, root=None):
self.repo = Path(repository)
+ self.release_version = json.loads((self.repo / 'contracts/cli/local-control-hello.v2.schema.json').read_text())['properties']['client_version']['const']
self.project_source = project_source
self.bin = Path(os.environ.get('HIROUTE_VALIDATION_PRODUCT_BIN_DIR',
str(self.repo / 'target/debug')))
@@ -253,10 +279,9 @@ finally:
env=env, cwd=self.project,
pass_fds=(self.shutdown_r, self.cap_r, self.cap_ack_w), stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
- assert select.select([self.process.stdout], [], [], getattr(self, 'startup_timeout', 45))[0], 'daemon readiness timeout'
- ready = self.process.stdout.readline()
+ ready = startup_frame(self.process, getattr(self, 'startup_timeout', 45))
if expected_failure:
- assert not ready, 'unsafe recovery opened product service'
+ assert not ready or json.loads(ready).get('schema') == 'hiroute.daemon-startup-failure/v1', 'unsafe recovery opened product service'
status = self.process.wait(timeout=40)
self.outputs.append(self.process.stderr.read())
for fd in (self.shutdown_r, self.shutdown_w, self.cap_r, self.cap_w,
@@ -265,11 +290,11 @@ finally:
self.process = None
assert status != 0, 'failed recovery must not report successful startup'
return status
- assert ready, 'daemon did not become ready: ' + self.process.stderr.read().decode()
- assert json.loads(ready)['role'] == 'all'
self.outputs.append(ready)
+ assert ready, 'daemon did not become ready'
+ assert json.loads(ready).get('role') == 'all', 'daemon returned a startup failure frame'
- def stop(self, crash=False):
+ def stop(self, crash=False, diagnostic_failure=False):
if self.process is None:
return
os.close(self.shutdown_w)
@@ -284,7 +309,8 @@ finally:
self.cap_ack_r, self.cap_ack_w):
os.close(fd)
self.process = None
- assert status == (86 if crash else 0), ('daemon exit', status)
+ if not diagnostic_failure:
+ assert status == (86 if crash else 0), ('daemon exit', status)
def cli(self, command, payload=None, capability=None, success=True):
"""Use command notation to exercise Planned operations over internal Local Control.
@@ -395,7 +421,7 @@ finally:
'api_version': V2,
'machine_schema_version': V2,
'client_name': 'publication-product-test',
- 'client_version': '0.1.0',
+ 'client_version': self.release_version,
}) + b'\n')
stream.flush()
hello = json.loads(stream.readline())
@@ -559,10 +585,20 @@ finally:
return self.diagnostics_snapshot(destination)
def close(self):
+ failed = sys.exc_info()[0] is not None
try:
- self.stop()
+ self.stop(diagnostic_failure=failed)
assert all(secret.encode() not in output for secret in self.secrets
for output in self.outputs), 'public secret leak'
finally:
- if self.temporary is not None:
+ if failed and self.temporary is not None:
+ # Keep failed frames, stderr and data private; do not replace the original
+ # assertion with a shutdown error or erase the evidence in finally.
+ evidence = self.root / 'harness-failure.bin'
+ evidence.write_bytes(b'\n'.join(self.outputs))
+ evidence.chmod(0o600)
+ self.temporary._finalizer.detach()
+ print(json.dumps({'scenario': 'product-harness-failure',
+ 'state': 'red', 'evidence_root': str(self.root)}), flush=True)
+ elif self.temporary is not None:
self.temporary.cleanup()
diff --git a/crates/daemon/tests/support/upgrade_requests.py b/crates/daemon/tests/support/upgrade_requests.py
new file mode 100644
index 00000000..52d27339
--- /dev/null
+++ b/crates/daemon/tests/support/upgrade_requests.py
@@ -0,0 +1,107 @@
+"""Real role-all pause/drain/cancel, followed by authoritative cache rebuild and requests."""
+import concurrent.futures
+import json
+import os
+import select
+import secrets
+import subprocess
+import sys
+import time
+from publication_product import Product, encoded
+from publication_process import bootstrap
+from publication_requests import request, attempts
+
+
+def upgrade(product, action):
+ registration = secrets.token_hex(32)
+ os.write(product.cap_w, encoded({
+ 'schema': 'hiroute.launcher-upgrade/v1',
+ 'registration_id': registration, 'action': action,
+ }) + b'\n')
+ deadline = time.monotonic() + 5
+ frame = b''
+ while not frame.endswith(b'\n'):
+ remaining = deadline - time.monotonic()
+ assert remaining > 0 and select.select([product.cap_ack_r], [], [], remaining)[0], 'upgrade acknowledgement timeout'
+ byte = os.read(product.cap_ack_r, 1)
+ assert byte, 'upgrade channel closed'
+ frame += byte
+ assert len(frame) <= 4096
+ result = json.loads(frame)
+ assert set(result) == {'schema', 'registration_id', 'paused', 'active_calls', 'active_tasks'}
+ assert result['schema'] == 'hiroute.launcher-upgrade-status/v1'
+ assert result['registration_id'] == registration
+ return result
+
+
+def run(repository):
+ candidate = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repository, text=True).strip()
+ product = Product(repository)
+ try:
+ product.enable_debug_diagnostics()
+ product.enable_cpa()
+ bootstrap(product)
+ token = product.bearer(product.agent_connection)
+ alias = product.model_alias
+ initial_native = product.codex_settings.read_bytes()
+ catalog, _ = product.catalog()
+ pid = product.process.pid
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ old = executor.submit(request, product, alias, 'hold-old-request', token)
+ deadline = time.monotonic() + 10
+ while not (product.cpa_fixture / 'held').exists():
+ assert not old.done(), old.result()
+ assert time.monotonic() < deadline
+ time.sleep(.02)
+ waiting = upgrade(product, 'prepare')
+ assert waiting['paused'] and waiting['active_calls'] >= 1
+ status, _ = request(product, alias, 'must wait', token)
+ assert status == 503, status
+ response = product.control('ListAgentPlans', {}, success=False)
+ assert response['status'] == 'unavailable', response
+ assert product.process.poll() is None and product.process.pid == pid
+ assert attempts(product) == 1, 'paused call reached the upstream'
+ resumed = upgrade(product, 'cancel')
+ assert not resumed['paused'] and resumed['active_calls'] >= 1
+ status, body = request(product, alias, 'cancel restores admission', token)
+ assert status == 200 and b'fixture answer' in body
+ (product.cpa_fixture / 'release').touch()
+ status, body = old.result(timeout=15)
+ assert status == 200 and b'fixture answer' in body, (status, body)
+ drained = upgrade(product, 'prepare')
+ assert drained['paused'] and drained['active_calls'] == 0 and drained['active_tasks'] == 0
+ product.stop()
+ assert product.process is None, 'exact daemon did not exit'
+ cache = product.root / 'gateway-lkg'
+ current = cache.read_bytes()
+ assert cache.stat().st_mode & 0o777 == 0o600, 'new cache is not private'
+ for state in ['corrupt', 'missing', 'stale']:
+ if state == 'missing':
+ cache.unlink()
+ elif state == 'corrupt':
+ cache.write_bytes(b'invalid cache; no business authority')
+ else:
+ value = json.loads(current)
+ assert 'source_publication_digest' in value
+ value['source_publication_digest'] = 'sha256:' + '0' * 64
+ cache.write_bytes(encoded(value))
+ product.start()
+ rebuilt, _ = product.catalog()
+ assert rebuilt == catalog, 'catalog authority changed with the cache'
+ assert product.codex_settings.read_bytes() == initial_native, 'restart rewrote native configuration'
+ status, body = request(product, alias, 'same grant after cache rebuild', token)
+ assert status == 200 and b'fixture answer' in body
+ assert cache.read_bytes() == current, 'authoritative cache was not rebuilt'
+ product.stop()
+ print(json.dumps({'scenario': 'upgrade-drain-and-cache-rebuild', 'state': 'green',
+ 'candidate': candidate, 'in_flight_request_completed': True,
+ 'cancel_restored_admission': True, 'replacement_waited_for_exact_exit': True,
+ 'cache_cases': 3, 'original_grant_and_native_files_retained': True}), flush=True)
+ finally:
+ if hasattr(product, 'cpa_fixture'):
+ (product.cpa_fixture / 'release').touch()
+ product.close()
+
+
+if __name__ == '__main__':
+ run(sys.argv[1])
diff --git a/crates/diagnostics/src/event/startup.rs b/crates/diagnostics/src/event/startup.rs
index 396bd79a..e470d29f 100644
--- a/crates/diagnostics/src/event/startup.rs
+++ b/crates/diagnostics/src/event/startup.rs
@@ -31,6 +31,8 @@ pub enum StartupOutcome {
pub enum StartupFailureCode {
InvalidConfiguration,
StorageUnavailable,
+ UpgradeSourceUnsupported,
+ UpgradeStorageFailed,
ReleaseFactsInvalid,
DependencyUnavailable,
WorkerRejected,
diff --git a/crates/domain/src/agent_plan/legacy.rs b/crates/domain/src/agent_plan/legacy.rs
index 7f4429f3..9eeada71 100644
--- a/crates/domain/src/agent_plan/legacy.rs
+++ b/crates/domain/src/agent_plan/legacy.rs
@@ -22,7 +22,7 @@ impl PlanVersionV1 {
) -> Result<Self, PlanVersionError> {
compiled.validate().map_err(|_| PlanVersionError::Invalid)?;
if compiled.body.schema != AGENT_PLAN_COMPILED_SCHEMA_V1
- && compiled.body.schema != AGENT_PLAN_COMPILED_SCHEMA_V2
+ && compiled.body.schema != AGENT_PLAN_COMPILED_SCHEMA_V3
{
return Err(PlanVersionError::Invalid);
}
@@ -130,23 +130,31 @@ mod tests {
#[test]
fn unversioned_recovery_accepts_currentized_legacy_without_reopening_legacy_authoring() {
- let publication: GatewayPublicationV1 = GatewayPublicationV1::decode_persisted(
- include_bytes!("../../../../e2e/product/golden/routing/compiled-publication.v2.json"),
+ let source: serde_json::Value = serde_json::from_slice::<serde_json::Value>(
+ include_bytes!("../../../../e2e/product/fixtures/routing/current-publication.v3.json"),
)
.unwrap();
- let legacy = publication.plans[0].clone();
- let legacy_version =
- PlanVersionV1::from_legacy_compiled(publication.workspace_id.clone(), legacy.clone())
- .unwrap();
- let current = legacy.into_current().unwrap();
+ let publication =
+ serde_json::from_value::<crate::GatewayPublicationV1>(source.clone()).unwrap();
+ let current = publication.plans[0].clone();
let recovered = PlanVersionV1::from_unversioned_compiled_recovery(
publication.workspace_id,
current.clone(),
)
.unwrap();
- assert_eq!(recovered.configuration, legacy_version.configuration);
- assert_eq!(recovered.compiled, current);
+ assert_eq!(
+ recovered.configuration.display_name,
+ current.body.identity.display_name
+ );
+ assert_eq!(
+ recovered.configuration.purpose,
+ current.body.identity.purpose
+ );
+ assert_eq!(
+ crate::StoredPlanV1::freeze(&recovered.compiled).unwrap(),
+ crate::StoredPlanV1::freeze(&current).unwrap()
+ );
recovered.validate().unwrap();
assert!(
PlanVersionV1::from_legacy_compiled(
diff --git a/crates/domain/src/agent_plan/version.rs b/crates/domain/src/agent_plan/version.rs
index 18e34297..aa67bf19 100644
--- a/crates/domain/src/agent_plan/version.rs
+++ b/crates/domain/src/agent_plan/version.rs
@@ -6,7 +6,7 @@ use thiserror::Error;
use super::{AgentPlanId, ModelAlias};
use crate::{AgentPlanAuthoringV2, CanonicalDigest, CompiledAgentPlanV1, WorkspaceId};
-pub const PLAN_VERSION_SCHEMA_V1: &str = "hiroute.plan-version/v1";
+pub const PLAN_VERSION_SCHEMA_V1: &str = "hiroute.plan-version/v2";
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
@@ -36,6 +36,7 @@ pub struct PlanVersionV1 {
pub schema: String,
pub reference: PlanExecutionRef,
pub configuration: AgentPlanAuthoringV2,
+ #[serde(with = "crate::plan_codec")]
pub compiled: CompiledAgentPlanV1,
}
@@ -45,11 +46,19 @@ impl PlanVersionV1 {
configuration: AgentPlanAuthoringV2,
compiled: CompiledAgentPlanV1,
) -> Result<Self, PlanVersionError> {
+ // Authenticated unversioned recovery retains candidate order, then removes the retired
+ // rating-order evidence before sealing the current stable representation.
+ let compiled = compiled
+ .into_current()
+ .map_err(|_| PlanVersionError::Invalid)?;
+ let compiled = crate::StoredPlanV1::freeze(&compiled)
+ .and_then(|p| p.build())
+ .map_err(|_| PlanVersionError::Invalid)?;
let content_digest = CanonicalDigest::of(&(
PLAN_VERSION_SCHEMA_V1,
&workspace,
&configuration,
- &compiled,
+ &crate::StoredPlanV1::freeze(&compiled).map_err(|_| PlanVersionError::Invalid)?,
))
.map_err(|_| PlanVersionError::Invalid)?;
let value = Self {
@@ -79,7 +88,7 @@ impl PlanVersionV1 {
PLAN_VERSION_SCHEMA_V1,
&self.reference.workspace_id,
&self.configuration,
- &self.compiled,
+ &crate::StoredPlanV1::freeze(&self.compiled).map_err(|_| PlanVersionError::Invalid)?,
))
.map_err(|_| PlanVersionError::Invalid)?;
if self.schema != PLAN_VERSION_SCHEMA_V1
diff --git a/crates/domain/src/agents/model_grant.rs b/crates/domain/src/agents/model_grant.rs
index 3d96a980..6a97ace9 100644
--- a/crates/domain/src/agents/model_grant.rs
+++ b/crates/domain/src/agents/model_grant.rs
@@ -19,6 +19,7 @@ pub enum AgentModelRouteV2 {
},
Fixed {
candidate: CandidateSelectionV1,
+ #[serde(with = "crate::binding_codec")]
binding: Box<AttemptOwnedCandidateV1>,
},
}
@@ -167,9 +168,16 @@ impl AgentModelGrantV2 {
pub fn seal(
protocol: AgentIngressProtocolV1,
- routes: BTreeMap<String, AgentModelRouteV2>,
+ mut routes: BTreeMap<String, AgentModelRouteV2>,
) -> Result<Self, AgentConnectionError> {
- let digest = CanonicalDigest::of(&("hiroute.agent-model-grant/v2", protocol, &routes))
+ for route in routes.values_mut() {
+ if let AgentModelRouteV2::Fixed { binding, .. } = route {
+ **binding = crate::StoredCandidateV1::freeze(binding)
+ .and_then(|c| c.build())
+ .map_err(|_| AgentConnectionError::InvalidGrant)?;
+ }
+ }
+ let digest = CanonicalDigest::of(&("hiroute.agent-model-grant/v3", protocol, &routes))
.map_err(|_| AgentConnectionError::Encoding)?;
let grant = Self {
protocol,
@@ -225,7 +233,7 @@ impl AgentModelGrantV2 {
}
}
}
- if CanonicalDigest::of(&("hiroute.agent-model-grant/v2", self.protocol, &self.routes))
+ if CanonicalDigest::of(&("hiroute.agent-model-grant/v3", self.protocol, &self.routes))
.map_err(|_| AgentConnectionError::Encoding)?
!= self.digest
{
diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs
index 1a510272..8a1ceff0 100644
--- a/crates/domain/src/lib.rs
+++ b/crates/domain/src/lib.rs
@@ -39,16 +39,17 @@ pub use operation::{
AgentAccessGrantMaterialActionV1, AgentAccessGrantMutationKindV1, AgentAccessGrantMutationV1,
AgentAccessGrantRefV1, AgentAccessGrantScopeV1, AgentConfigPermissionIntentV1,
AgentConnectionControlIntentV1, AgentConnectionEffectRoleV1, AgentConnectionTransactionKindV1,
- AgentConnectionTransactionSubjectV1, BeginOperationOutcome,
- COMPUTE_SUBSCRIPTION_CHECK_COMMAND_ID_V2, COMPUTE_SUBSCRIPTION_EFFECT_ID_V2,
- CompensationOutcome, ComputeSourceControlPort, ComputeSourceMutationV1, ConsumedPlanDraftV1,
- ControlRepositoryPort, CredentialPoolControlPort, CredentialRefV1, EffectReconciliation,
- ExternalEffectIntentV1, ExternalEffectPort, IdempotencyScopeV1, OPERATION_SCHEMA_VERSION,
- OperationId, OperationState, OperationStatus, OperationStepKind, OperationStepStatus,
- OperationStepV1, OperationV1, OperationValidationError, OwnedEffectKind, OwnedEffectV1,
- PlanContentControlV2, ProtectedApplyCapability, ProtectedSecret, RuntimeMutationV1,
- RuntimeStatePort, SETTINGS_SERVICE_COMPLETION_SCHEMA, SecretFingerprintAlgorithm,
- SecretMutationKind, SecretMutationV1, SecretStorePort, SettingsServiceCompletionV1,
+ AgentConnectionTransactionSubjectV1, AgentOperationInputView, AgentOperationRead,
+ AgentPlanReadV1, BeginOperationOutcome, COMPUTE_SUBSCRIPTION_CHECK_COMMAND_ID_V2,
+ COMPUTE_SUBSCRIPTION_EFFECT_ID_V2, CompensationOutcome, ComputeSourceControlPort,
+ ComputeSourceMutationV1, ConsumedPlanDraftV1, ControlRepositoryPort, CredentialPoolControlPort,
+ CredentialRefV1, EffectReconciliation, ExternalEffectIntentV1, ExternalEffectPort,
+ IdempotencyScopeV1, OPERATION_INPUT_SCHEMA, OPERATION_SCHEMA_VERSION, OperationId,
+ OperationState, OperationStatus, OperationStepKind, OperationStepStatus, OperationStepV1,
+ OperationV1, OperationValidationError, OwnedEffectKind, OwnedEffectV1, PlanContentControlV2,
+ ProtectedApplyCapability, ProtectedSecret, RuntimeMutationV1, RuntimeStatePort,
+ SETTINGS_SERVICE_COMPLETION_SCHEMA, SecretFingerprintAlgorithm, SecretMutationKind,
+ SecretMutationV1, SecretStorePort, SettingsServiceCompletionV1, StoredOperationInputV1,
SubscriptionCheckIntentV2, TransactionPlanV1, VerifiedApplyAuthorizationV1,
VerifiedSecretSubjectV1, WorkerDependencySelectionChangeV1, WorkerDependencySelectionRecordV1,
agent_connection_publication_record, agent_connection_restore_publication_record,
diff --git a/crates/domain/src/operation/agent_connection.rs b/crates/domain/src/operation/agent_connection.rs
index 5be27636..08766324 100644
--- a/crates/domain/src/operation/agent_connection.rs
+++ b/crates/domain/src/operation/agent_connection.rs
@@ -298,7 +298,7 @@ pub fn is_settings_publication(intent: &ExternalEffectIntentV1) -> bool {
intent.kind() == OwnedEffectKind::Publication && intent.desired()["transaction"] == "settings"
}
-pub const SETTINGS_SERVICE_COMPLETION_SCHEMA: &str = "hiroute.settings-service-completion/v1";
+pub const SETTINGS_SERVICE_COMPLETION_SCHEMA: &str = "hiroute.settings-service-completion/v2";
/// Durable proof that a settings operation's service segment (secrets, control, runtime,
/// non-client artifacts, publication and protected revocations) finished. It authorizes the
@@ -445,67 +445,75 @@ impl TransactionPlanV1 {
&self.runtime,
&self.external,
)?;
- let control = decode_control(&self.control)?;
- let subject = decode_subject(control.subject)?;
- let payload: DurableAgentConnectionPayloadV1 = serde_json::from_value(control.payload)
- .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
- payload
- .connection
- .validate()
- .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
- let desired = self
- .spec
- .desired_state
- .as_object()
- .ok_or(OperationValidationError::UnregisteredEffectPlan)?;
- let connection_id = self
- .spec
- .resource_id
- .clone()
- .ok_or(OperationValidationError::UnregisteredEffectPlan)?;
- let installed_version = desired
- .get("installed_version")
+ connection_projection(&self.spec, &self.control)
+ }
+}
+
+pub(super) fn connection_projection(
+ spec: &ChangeSpecV1,
+ control: &Value,
+) -> Result<Option<ActiveAgentConnectionV1>, OperationValidationError> {
+ if spec.command_id != AgentConnectionTransactionKindV1::Apply.command_id() {
+ return Ok(None);
+ }
+ let control = decode_control(control)?;
+ let subject = decode_subject(control.subject)?;
+ let payload: DurableAgentConnectionPayloadV1 = serde_json::from_value(control.payload)
+ .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
+ payload
+ .connection
+ .validate()
+ .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
+ let desired = spec
+ .desired_state
+ .as_object()
+ .ok_or(OperationValidationError::UnregisteredEffectPlan)?;
+ let connection_id = spec
+ .resource_id
+ .clone()
+ .ok_or(OperationValidationError::UnregisteredEffectPlan)?;
+ let installed_version = desired
+ .get("installed_version")
+ .and_then(Value::as_str)
+ .ok_or(OperationValidationError::UnregisteredEffectPlan)?
+ .to_owned();
+ let desired_digest = |field: &str| {
+ desired
+ .get(field)
.and_then(Value::as_str)
- .ok_or(OperationValidationError::UnregisteredEffectPlan)?
- .to_owned();
- let desired_digest = |field: &str| {
- desired
- .get(field)
- .and_then(Value::as_str)
- .and_then(|value| CanonicalDigest::parse(value.to_owned()).ok())
- .ok_or(OperationValidationError::UnregisteredEffectPlan)
- };
- let observation_digest = desired_digest("observation_digest")?;
- if connection_id
- != format!(
- "agent-connection/{}/{}",
- payload.connection.agent_id, payload.connection.profile_id
- )
- || subject.agent_id() != payload.connection.agent_id
- || subject.profile_id() != payload.connection.profile_id
- || subject.integration_profile_ref() != payload.connection.integration_profile_ref
- || desired.get("agent_id").and_then(Value::as_str)
- != Some(payload.connection.agent_id.as_str())
- || desired.get("profile_id").and_then(Value::as_str)
- != Some(payload.connection.profile_id.as_str())
- || desired
- .get("integration_profile_ref")
- .and_then(Value::as_str)
- != Some(payload.connection.integration_profile_ref.as_str())
- || desired_digest("grant_digest")? != payload.connection.grant.digest
- || desired_digest("publication_digest")? != payload.publication_digest
- || desired_digest("config_change_digest")? != payload.config_change_digest
- {
- return Err(OperationValidationError::UnregisteredEffectPlan);
- }
- Ok(Some(ActiveAgentConnectionV1 {
- connection_id,
- installed_version,
- observation_digest,
- source_publication_digest: payload.publication_digest,
- connection: payload.connection,
- }))
+ .and_then(|value| CanonicalDigest::parse(value.to_owned()).ok())
+ .ok_or(OperationValidationError::UnregisteredEffectPlan)
+ };
+ let observation_digest = desired_digest("observation_digest")?;
+ if connection_id
+ != format!(
+ "agent-connection/{}/{}",
+ payload.connection.agent_id, payload.connection.profile_id
+ )
+ || subject.agent_id() != payload.connection.agent_id
+ || subject.profile_id() != payload.connection.profile_id
+ || subject.integration_profile_ref() != payload.connection.integration_profile_ref
+ || desired.get("agent_id").and_then(Value::as_str)
+ != Some(payload.connection.agent_id.as_str())
+ || desired.get("profile_id").and_then(Value::as_str)
+ != Some(payload.connection.profile_id.as_str())
+ || desired
+ .get("integration_profile_ref")
+ .and_then(Value::as_str)
+ != Some(payload.connection.integration_profile_ref.as_str())
+ || desired_digest("grant_digest")? != payload.connection.grant.digest
+ || desired_digest("publication_digest")? != payload.publication_digest
+ || desired_digest("config_change_digest")? != payload.config_change_digest
+ {
+ return Err(OperationValidationError::UnregisteredEffectPlan);
}
+ Ok(Some(ActiveAgentConnectionV1 {
+ connection_id,
+ installed_version,
+ observation_digest,
+ source_publication_digest: payload.publication_digest,
+ connection: payload.connection,
+ }))
}
/// Durable non-secret view used by daemon status, descriptor, and raw-grant joins.
diff --git a/crates/domain/src/operation/agent_read.rs b/crates/domain/src/operation/agent_read.rs
new file mode 100644
index 00000000..09226a67
--- /dev/null
+++ b/crates/domain/src/operation/agent_read.rs
@@ -0,0 +1,115 @@
+//! Borrowed business facts for Agent status. This view cannot enter the transaction executor.
+use super::*;
+
+pub struct AgentOperationInputView<'a> {
+ pub spec: &'a ChangeSpecV1,
+ pub control: &'a Value,
+ pub external: &'a [ExternalEffectIntentV1],
+ pub grants: &'a [AgentAccessGrantMutationV1],
+}
+
+pub trait AgentOperationRead {
+ fn agent_input(&self) -> AgentOperationInputView<'_>;
+ fn operation_id(&self) -> &OperationId;
+ fn accepted_digest(&self) -> &CanonicalDigest;
+ fn state(&self) -> OperationState;
+}
+
+impl AgentOperationRead for OperationV1 {
+ fn agent_input(&self) -> AgentOperationInputView<'_> {
+ AgentOperationInputView {
+ spec: self.plan.spec(),
+ control: self.plan.control(),
+ external: self.plan.external(),
+ grants: self.plan.agent_access_grants(),
+ }
+ }
+ fn operation_id(&self) -> &OperationId {
+ &self.operation_id
+ }
+ fn accepted_digest(&self) -> &CanonicalDigest {
+ &self.accepted_digest
+ }
+ fn state(&self) -> OperationState {
+ self.state
+ }
+}
+
+/// Validated command facts, with no routing compiler, journal writer or execution plan.
+#[derive(Clone, Debug)]
+pub struct AgentPlanReadV1 {
+ spec: ChangeSpecV1,
+ control: Value,
+ external: Vec<ExternalEffectIntentV1>,
+ grants: Vec<AgentAccessGrantMutationV1>,
+}
+
+impl AgentPlanReadV1 {
+ pub fn from_stored(input: &StoredOperationInputV1) -> Result<Self, OperationValidationError> {
+ if input.schema != OPERATION_INPUT_SCHEMA
+ || input.credential_pool.is_some()
+ || input.worker_dependency_selection.is_some()
+ || !input.secrets.is_empty()
+ || !input.runtime.is_empty()
+ {
+ return Err(OperationValidationError::UnregisteredEffectPlan);
+ }
+ let external = input
+ .external
+ .iter()
+ .map(|intent| {
+ ExternalEffectIntentV1::from_registered_adapter(
+ intent.effect_id.clone(),
+ intent.kind,
+ intent.target.clone(),
+ intent.before_fingerprint.clone(),
+ intent.desired.clone(),
+ intent.desired_mode,
+ intent.sensitive,
+ )
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ agent_connection::validate_plan(&input.spec, &input.control, &[], &[], &external)?;
+ let grants = agent_connection::agent_access_grants_from_control(&input.control)?;
+ Ok(Self {
+ spec: input.spec.clone(),
+ control: input.control.clone(),
+ external,
+ grants,
+ })
+ }
+ pub fn spec(&self) -> &ChangeSpecV1 {
+ &self.spec
+ }
+ pub fn operation_kind(&self) -> Result<&'static str, OperationValidationError> {
+ match self.spec.command_id.as_str() {
+ "agents.connect.apply" => Ok("ApplyAgentConnectionChange"),
+ "agents.restore.apply" => Ok("ApplyAgentConnectionRestore"),
+ "agents.settings.apply" => {
+ let settings: crate::AgentSettingsSpecV2 =
+ serde_json::from_value(self.spec.desired_state.clone())
+ .map_err(|_| OperationValidationError::UnregisteredEffectPlan)?;
+ Ok(if settings.is_restore_only() {
+ "ApplyAgentConnectionRestore"
+ } else {
+ "ApplyAgentConnectionChange"
+ })
+ }
+ _ => Err(OperationValidationError::UnregisteredEffectPlan),
+ }
+ }
+ pub fn control(&self) -> &Value {
+ &self.control
+ }
+ pub fn external(&self) -> &[ExternalEffectIntentV1] {
+ &self.external
+ }
+ pub fn agent_access_grants(&self) -> &[AgentAccessGrantMutationV1] {
+ &self.grants
+ }
+ pub fn agent_connection_projection(
+ &self,
+ ) -> Result<Option<ActiveAgentConnectionV1>, OperationValidationError> {
+ agent_connection::connection_projection(&self.spec, &self.control)
+ }
+}
diff --git a/crates/domain/src/operation/journal.rs b/crates/domain/src/operation/journal.rs
index 5c551eab..3664d20e 100644
--- a/crates/domain/src/operation/journal.rs
+++ b/crates/domain/src/operation/journal.rs
@@ -38,7 +38,9 @@ impl OperationV1 {
self.journal_checkpoint = Some(Arc::new(JournalCheckpoint {
identity: self.immutable_identity()?,
plan: self.plan.clone(),
- plan_json: serde_json::to_string(self.plan.as_ref())?.into(),
+ plan_json: StoredOperationInputV1::freeze(&self.plan)?
+ .canonical_json()?
+ .into(),
generation: self.generation,
steps: self.steps.clone(),
state: self.state,
diff --git a/crates/domain/src/operation/mod.rs b/crates/domain/src/operation/mod.rs
index 222fb459..882cd04f 100644
--- a/crates/domain/src/operation/mod.rs
+++ b/crates/domain/src/operation/mod.rs
@@ -23,6 +23,10 @@ mod routing_content;
mod routing_draft;
pub use routing_content::{ConsumedPlanDraftV1, PlanContentControlV2};
mod journal;
+mod stored;
+pub use stored::*;
+mod agent_read;
+pub use agent_read::*;
pub(crate) mod shared_input;
pub use journal::OperationJournalUpdate;
mod source_price;
@@ -49,7 +53,7 @@ pub use subscription_check::{
SubscriptionCheckIntentV2, decode_subscription_check_intent, is_subscription_check_effect,
};
-pub const OPERATION_SCHEMA_VERSION: u16 = 1;
+pub const OPERATION_SCHEMA_VERSION: u16 = 2;
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(transparent)]
@@ -1326,7 +1330,7 @@ pub struct OperationV1 {
pub request_digest: CanonicalDigest,
pub accepted_digest: CanonicalDigest,
pub expected_revisions: RevisionSetV1,
- #[serde(serialize_with = "shared_input::serialize")]
+ #[serde(serialize_with = "stored::serialize_plan")]
pub plan: Arc<TransactionPlanV1>,
pub state: OperationState,
pub generation: u64,
@@ -1356,33 +1360,12 @@ impl OperationV1 {
expected_revisions: RevisionSetV1,
plan: TransactionPlanV1,
) -> Result<Self, OperationValidationError> {
- let control_step_input = if let Some(selection) = &plan.worker_dependency_selection {
- serde_json::to_value((&plan.control, &plan.credential_pool, selection))?
- } else {
- serde_json::to_value((&plan.control, &plan.credential_pool))?
- };
- let step_inputs = [
- json!({
- "spec": &plan.spec,
- "accepted_digest": &accepted_digest,
- "expected_revisions": &expected_revisions,
- }),
- serde_json::to_value((&plan.secrets, &plan.agent_access_grants))?,
- control_step_input,
- serde_json::to_value(
- plan.external
- .iter()
- .filter(|effect| effect.kind == OwnedEffectKind::Publication)
- .collect::<Vec<_>>(),
- )?,
- serde_json::to_value(
- plan.external
- .iter()
- .filter(|effect| effect.kind == OwnedEffectKind::AgentArtifact)
- .collect::<Vec<_>>(),
- )?,
- serde_json::to_value(&plan.runtime)?,
- ];
+ let facts = StoredOperationInputV1::freeze(&plan)?;
+ let step_inputs = facts.step_inputs(
+ &accepted_digest,
+ &expected_revisions,
+ &plan.agent_access_grants,
+ )?;
let steps = OperationStepKind::ALL
.into_iter()
.zip(step_inputs)
@@ -1391,7 +1374,11 @@ impl OperationV1 {
Ok(OperationStepV1 {
sequence: u16::try_from(index).expect("six steps fit in u16"),
kind,
- deterministic_input_digest: CanonicalDigest::of(&input)?,
+ deterministic_input_digest: CanonicalDigest::of(&(
+ "hiroute.operation-step-input/v1",
+ kind,
+ input,
+ ))?,
status: OperationStepStatus::Pending,
attempts: 0,
effects: Vec::new(),
@@ -1418,6 +1405,10 @@ impl OperationV1 {
Ok(operation)
}
+ pub fn stable_input_digest(&self) -> Result<CanonicalDigest, OperationValidationError> {
+ StoredOperationInputV1::freeze(&self.plan)?.digest()
+ }
+
pub fn transition(&mut self, next: OperationState) -> Result<(), OperationValidationError> {
if !self.state.can_transition_to(next) {
return Err(OperationValidationError::InvalidTransition {
diff --git a/crates/domain/src/operation/routing.rs b/crates/domain/src/operation/routing.rs
index 9e64992a..0b4a7c88 100644
--- a/crates/domain/src/operation/routing.rs
+++ b/crates/domain/src/operation/routing.rs
@@ -407,8 +407,27 @@ mod tests {
crate::PublicationRecordV1,
) {
let bytes =
- include_bytes!("../../../../e2e/product/golden/routing/compiled-publication.v2.json");
- let publication = crate::GatewayPublicationV1::decode_persisted(bytes).unwrap();
+ include_bytes!("../../../../e2e/product/fixtures/routing/current-publication.v3.json");
+ let mut publication = serde_json::from_value::<crate::GatewayPublicationV1>(
+ serde_json::from_slice::<serde_json::Value>(bytes).unwrap(),
+ )
+ .unwrap();
+ // This retired typed-reader seam requires an authenticated V1 compiled body.
+ // The untouched historical source is authenticated by the source-22 reader above;
+ // this normalized fixture exercises effect ownership, not a source-format claim.
+ for plan in &mut publication.plans {
+ let mut body = plan.body.as_ref().clone();
+ body.schema = crate::AGENT_PLAN_COMPILED_SCHEMA_V1.into();
+ body.compiler_revision = crate::AGENT_PLAN_COMPILER_REVISION_V1.into();
+ body.materialized_route_digest = body.materialized.legacy_route_digest().unwrap();
+ let digest = CanonicalDigest::of(&body).unwrap();
+ *plan = crate::CompiledAgentPlanV1::authenticate_persisted(body, digest).unwrap();
+ }
+ publication.schema = crate::publication::LEGACY_GATEWAY_PUBLICATION_SCHEMA_V2.into();
+ publication.compiler_revision = crate::AGENT_PLAN_COMPILER_REVISION_V1.into();
+ publication.grants.clear();
+ publication.aliases.clear();
+ publication.validate().unwrap();
let compiled = publication
.plans
.iter()
@@ -422,13 +441,14 @@ mod tests {
resource_id: Some(format!("agent-plan/{}", compiled.agent_plan_id().as_str())),
desired_state: json!({"agent_plan_id": compiled.agent_plan_id()}),
};
- // The exact historical persisted record: the golden bytes are the durable V2
- // aggregate this recovery decoder must authenticate unchanged.
+ // Exercise the authenticated pre-stable runtime representation. Genuine source-22
+ // bytes are separately authenticated by the storage migration reader.
+ let bytes = serde_json::to_vec(&publication).unwrap();
let record = crate::PublicationRecordV1::from_parts(
publication.workspace_id.clone(),
publication.publication_revision,
- CanonicalDigest::of_bytes(bytes),
- bytes.to_vec(),
+ CanonicalDigest::of_bytes(&bytes),
+ bytes,
)
.unwrap();
(spec, intent, compiled, record)
diff --git a/crates/domain/src/operation/routing_content.rs b/crates/domain/src/operation/routing_content.rs
index 9c4a62a4..b5c8bc92 100644
--- a/crates/domain/src/operation/routing_content.rs
+++ b/crates/domain/src/operation/routing_content.rs
@@ -147,7 +147,7 @@ fn validate_inputs(
head.validate().map_err(|_| invalid())?;
if spec.command_id != "routing.apply"
|| control.schema != CONTROL_SCHEMA
- || version.compiled.body.schema != crate::AGENT_PLAN_COMPILED_SCHEMA_V2
+ || version.compiled.body.schema != crate::AGENT_PLAN_COMPILED_SCHEMA_V3
|| control.change_spec_digest != CanonicalDigest::of(spec)?
|| spec.resource_id.as_deref()
!= Some(&format!(
diff --git a/crates/domain/src/operation/stored.rs b/crates/domain/src/operation/stored.rs
new file mode 100644
index 00000000..cabb7147
--- /dev/null
+++ b/crates/domain/src/operation/stored.rs
@@ -0,0 +1,279 @@
+//! Versioned admission facts. Only validated command codecs can create an execution view.
+use super::*;
+
+pub const OPERATION_INPUT_SCHEMA: &str = "hiroute.operation-input/v1";
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredOperationInputV1 {
+ pub schema: String,
+ pub spec: ChangeSpecV1,
+ pub control: Value,
+ pub credential_pool: Option<CredentialPoolMutationV1>,
+ pub worker_dependency_selection: Option<WorkerDependencySelectionChangeV1>,
+ pub secrets: Vec<StoredSecretMutationV1>,
+ pub runtime: Vec<StoredRuntimeMutationV1>,
+ pub external: Vec<StoredExternalIntentV1>,
+}
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredSecretMutationV1 {
+ kind: SecretMutationKind,
+ credential: CredentialRefV1,
+ expected_generation: u64,
+ fingerprint_algorithm: SecretFingerprintAlgorithm,
+ input_slot: Option<String>,
+ fingerprint: Option<CanonicalDigest>,
+ new_allowed_destinations: Option<BTreeSet<String>>,
+}
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredRuntimeMutationV1 {
+ key: String,
+ value: Value,
+ expected_generation: u64,
+}
+
+#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredExternalIntentV1 {
+ pub(super) effect_id: String,
+ pub(super) kind: OwnedEffectKind,
+ pub(super) target: String,
+ pub(super) before_fingerprint: Option<CanonicalDigest>,
+ pub(super) desired: Value,
+ pub(super) desired_mode: u32,
+ pub(super) sensitive: bool,
+}
+
+impl StoredOperationInputV1 {
+ pub fn freeze(plan: &TransactionPlanV1) -> Result<Self, OperationValidationError> {
+ let stored = Self {
+ schema: OPERATION_INPUT_SCHEMA.into(),
+ spec: plan.spec.clone(),
+ control: plan.control.clone(),
+ credential_pool: plan.credential_pool.clone(),
+ worker_dependency_selection: plan.worker_dependency_selection.clone(),
+ secrets: plan
+ .secrets
+ .iter()
+ .map(|s| StoredSecretMutationV1 {
+ kind: s.kind,
+ credential: s.credential.clone(),
+ expected_generation: s.expected_generation,
+ fingerprint_algorithm: s.fingerprint_algorithm,
+ input_slot: s.input_slot.clone(),
+ fingerprint: s.fingerprint.clone(),
+ new_allowed_destinations: s.new_allowed_destinations.clone(),
+ })
+ .collect(),
+ runtime: plan
+ .runtime
+ .iter()
+ .map(|m| StoredRuntimeMutationV1 {
+ key: m.key.clone(),
+ value: m.value.clone(),
+ expected_generation: m.expected_generation,
+ })
+ .collect(),
+ external: plan
+ .external
+ .iter()
+ .map(|e| StoredExternalIntentV1 {
+ effect_id: e.effect_id.clone(),
+ kind: e.kind,
+ target: e.target.clone(),
+ before_fingerprint: e.before_fingerprint.clone(),
+ desired: (*e.desired).clone(),
+ desired_mode: e.desired_mode,
+ sensitive: e.sensitive,
+ })
+ .collect(),
+ };
+ Ok(stored)
+ }
+
+ pub fn build(&self) -> Result<TransactionPlanV1, OperationValidationError> {
+ if self.schema != OPERATION_INPUT_SCHEMA {
+ return Err(OperationValidationError::UnregisteredEffectPlan);
+ }
+ let secrets = self
+ .secrets
+ .iter()
+ .map(|s| {
+ if s.fingerprint_algorithm != SecretFingerprintAlgorithm::HmacSha256V1 {
+ return Err(OperationValidationError::UnregisteredEffectPlan);
+ }
+ match s.kind {
+ SecretMutationKind::Upsert if s.new_allowed_destinations.is_none() => {
+ SecretMutationV1::upsert(
+ s.credential.clone(),
+ s.expected_generation,
+ s.input_slot
+ .clone()
+ .ok_or(OperationValidationError::UnregisteredEffectPlan)?,
+ s.fingerprint.clone(),
+ )
+ }
+ SecretMutationKind::Delete
+ if s.input_slot.is_none()
+ && s.fingerprint.is_none()
+ && s.new_allowed_destinations.is_none() =>
+ {
+ SecretMutationV1::delete(s.credential.clone(), s.expected_generation)
+ }
+ SecretMutationKind::Rebind if s.input_slot.is_none() => {
+ SecretMutationV1::rebind(
+ s.credential.clone(),
+ s.new_allowed_destinations
+ .clone()
+ .ok_or(OperationValidationError::UnregisteredEffectPlan)?,
+ s.fingerprint
+ .clone()
+ .ok_or(OperationValidationError::UnregisteredEffectPlan)?,
+ )
+ }
+ _ => Err(OperationValidationError::UnregisteredEffectPlan),
+ }
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ let runtime = self
+ .runtime
+ .iter()
+ .map(|m| {
+ RuntimeMutationV1::from_registered_planner(
+ m.key.clone(),
+ m.value.clone(),
+ m.expected_generation,
+ )
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ let external = self
+ .external
+ .iter()
+ .map(|e| {
+ ExternalEffectIntentV1::from_registered_adapter(
+ e.effect_id.clone(),
+ e.kind,
+ e.target.clone(),
+ e.before_fingerprint.clone(),
+ e.desired.clone(),
+ e.desired_mode,
+ e.sensitive,
+ )
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ let plan = if let Some(selection) = &self.worker_dependency_selection {
+ if self.control != json!({})
+ || self.credential_pool.is_some()
+ || !secrets.is_empty()
+ || !runtime.is_empty()
+ || !external.is_empty()
+ {
+ return Err(OperationValidationError::UnregisteredEffectPlan);
+ }
+ let selection = WorkerDependencySelectionChangeV1::new(
+ selection.before_revision,
+ WorkerDependencySelectionRecordV1::new(
+ selection.after_selection.harness,
+ selection.after_selection.adapter_path.clone(),
+ selection.after_selection.cli_path.clone(),
+ selection.after_selection.node_path.clone(),
+ )?,
+ )?;
+ TransactionPlanV1::from_worker_dependency_selection_planner(
+ self.spec.clone(),
+ selection,
+ )?
+ } else {
+ // The command's existing typed codec strictly validates every control/effect payload.
+ TransactionPlanV1::from_registered_typed_planner(
+ self.spec.clone(),
+ self.control.clone(),
+ self.credential_pool.clone(),
+ secrets,
+ runtime,
+ external,
+ )?
+ };
+ if Self::freeze(&plan)? != *self {
+ return Err(OperationValidationError::UnregisteredEffectPlan);
+ }
+ Ok(plan)
+ }
+
+ pub(super) fn step_inputs(
+ &self,
+ accepted_digest: &CanonicalDigest,
+ expected_revisions: &RevisionSetV1,
+ grants: &[AgentAccessGrantMutationV1],
+ ) -> Result<[Value; 6], OperationValidationError> {
+ Ok([
+ json!({"spec": &self.spec, "accepted_digest": accepted_digest, "expected_revisions": expected_revisions}),
+ serde_json::to_value((&self.secrets, grants))?,
+ serde_json::to_value((
+ &self.control,
+ &self.credential_pool,
+ &self.worker_dependency_selection,
+ ))?,
+ serde_json::to_value(
+ self.external
+ .iter()
+ .filter(|effect| effect.kind == OwnedEffectKind::Publication)
+ .collect::<Vec<_>>(),
+ )?,
+ serde_json::to_value(
+ self.external
+ .iter()
+ .filter(|effect| effect.kind == OwnedEffectKind::AgentArtifact)
+ .collect::<Vec<_>>(),
+ )?,
+ serde_json::to_value(&self.runtime)?,
+ ])
+ }
+
+ pub fn validate_step_proofs(
+ &self,
+ accepted_digest: &CanonicalDigest,
+ expected_revisions: &RevisionSetV1,
+ grants: &[AgentAccessGrantMutationV1],
+ steps: &[OperationStepV1],
+ ) -> Result<(), OperationValidationError> {
+ if steps.len() != 6 {
+ return Err(OperationValidationError::InvalidDurableJournal);
+ }
+ for (index, ((step, kind), input)) in steps
+ .iter()
+ .zip(OperationStepKind::ALL)
+ .zip(self.step_inputs(accepted_digest, expected_revisions, grants)?)
+ .enumerate()
+ {
+ if usize::from(step.sequence) != index
+ || step.kind != kind
+ || step.deterministic_input_digest
+ != CanonicalDigest::of(&("hiroute.operation-step-input/v1", kind, input))?
+ {
+ return Err(OperationValidationError::InvalidDurableJournal);
+ }
+ }
+ Ok(())
+ }
+
+ pub fn canonical_json(&self) -> Result<String, OperationValidationError> {
+ Ok(crate::canonicalize_json(serde_json::to_value(self)?).to_string())
+ }
+ pub fn digest(&self) -> Result<CanonicalDigest, OperationValidationError> {
+ Ok(CanonicalDigest::of(&(OPERATION_INPUT_SCHEMA, self))?)
+ }
+}
+
+pub(super) fn serialize_plan<S: serde::Serializer>(
+ plan: &Arc<TransactionPlanV1>,
+ s: S,
+) -> Result<S::Ok, S::Error> {
+ let facts = StoredOperationInputV1::freeze(plan).map_err(serde::ser::Error::custom)?;
+ crate::canonicalize_json(serde_json::to_value(facts).map_err(serde::ser::Error::custom)?)
+ .serialize(s)
+}
diff --git a/crates/domain/src/publication/mod.rs b/crates/domain/src/publication/mod.rs
index 83b8293a..39f255af 100644
--- a/crates/domain/src/publication/mod.rs
+++ b/crates/domain/src/publication/mod.rs
@@ -9,8 +9,8 @@ use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
- AGENT_PLAN_COMPILED_SCHEMA_V2, AGENT_PLAN_COMPILER_REVISION_V1,
- AGENT_PLAN_COMPILER_REVISION_V2, AgentIngressProtocolV1, AliasRegistryV1,
+ AGENT_PLAN_COMPILED_SCHEMA_V3, AGENT_PLAN_COMPILER_REVISION_V1,
+ AGENT_PLAN_COMPILER_REVISION_V3, AgentIngressProtocolV1, AliasRegistryV1,
AttemptOwnedCandidateV1, CanonicalDigest, CompiledAgentPlanV1, ConnectorRuntimeKind,
GatewayAccessGrantV1, GatewayCandidateProtocolProfileV1, GatewayOperationalTargetV1,
MaterializedGroupId, ModelAlias, PortResult, PublishedAgentPlanV1, RequestOwnedRouteV1,
@@ -20,7 +20,9 @@ use crate::{
mod plan_state;
mod projection;
mod record;
+mod stored;
pub use record::PublicationRecordV1;
+pub use stored::*;
mod snapshot;
#[cfg(test)]
mod validation_tests;
@@ -31,7 +33,7 @@ pub use snapshot::{
GatewayPublicationSnapshotProjectionV3,
};
-const LEGACY_GATEWAY_PUBLICATION_SCHEMA_V2: &str = "hiroute.gateway-publication/v2";
+pub(crate) const LEGACY_GATEWAY_PUBLICATION_SCHEMA_V2: &str = "hiroute.gateway-publication/v2";
#[cfg(test)]
const UNSUPPORTED_GATEWAY_PUBLICATION_SCHEMA_V1: &str = "hiroute.gateway-publication/v1";
pub const GATEWAY_SNAPSHOT_SCHEMA_V3: &str = "hiroute.gateway.publication-snapshot/v3";
@@ -342,7 +344,7 @@ impl GatewayPublicationV1 {
let aliases = materialize_aliases(&plans, &grants)?;
let value = Self {
schema: GATEWAY_PUBLICATION_SCHEMA_V3.to_owned(),
- compiler_revision: AGENT_PLAN_COMPILER_REVISION_V2.to_owned(),
+ compiler_revision: AGENT_PLAN_COMPILER_REVISION_V3.to_owned(),
workspace_id,
authority_id,
authority_epoch,
@@ -365,22 +367,21 @@ impl GatewayPublicationV1 {
return Err(PublicationError::UnsupportedSchema);
}
let current_contract = self.schema == GATEWAY_PUBLICATION_SCHEMA_V3
- && self.compiler_revision == AGENT_PLAN_COMPILER_REVISION_V2
+ && self.compiler_revision == AGENT_PLAN_COMPILER_REVISION_V3
&& self
.plans
.iter()
- .all(|plan| plan.body.schema == AGENT_PLAN_COMPILED_SCHEMA_V2);
- // Master retained aggregate compiler V1 while the explicit editor compiled V2 Plans.
- // Unedited V1 Plans could coexist with edited V2 Plans in either persisted aggregate.
- // Authenticate every nested Plan's own schema/compiler/digest below; new writes still
- // require the sole V3/compiler V2/Plan V2 contract.
- let persisted_compatibility = self.compiler_revision == AGENT_PLAN_COMPILER_REVISION_V1
- && self.plans.iter().all(|plan| {
- matches!(
- plan.body.schema.as_str(),
- crate::AGENT_PLAN_COMPILED_SCHEMA_V1 | AGENT_PLAN_COMPILED_SCHEMA_V2
- )
- });
+ .all(|plan| plan.body.schema == AGENT_PLAN_COMPILED_SCHEMA_V3);
+ // Preserve the separately registered unversioned publication recovery boundary.
+ let persisted_compatibility = matches!(
+ self.compiler_revision.as_str(),
+ AGENT_PLAN_COMPILER_REVISION_V1
+ ) && self.plans.iter().all(|plan| {
+ matches!(
+ plan.body.schema.as_str(),
+ crate::AGENT_PLAN_COMPILED_SCHEMA_V1 | AGENT_PLAN_COMPILED_SCHEMA_V3
+ )
+ });
if !current_contract && !persisted_compatibility {
return Err(PublicationError::UnsupportedCompilerRevision);
}
@@ -464,11 +465,11 @@ impl GatewayPublicationV1 {
fn check_current_schema(&self) -> Result<(), PublicationError> {
if self.schema != GATEWAY_PUBLICATION_SCHEMA_V3
- || self.compiler_revision != AGENT_PLAN_COMPILER_REVISION_V2
+ || self.compiler_revision != AGENT_PLAN_COMPILER_REVISION_V3
|| self
.plans
.iter()
- .any(|plan| plan.body.schema != AGENT_PLAN_COMPILED_SCHEMA_V2)
+ .any(|plan| plan.body.schema != AGENT_PLAN_COMPILED_SCHEMA_V3)
{
return Err(PublicationError::UnsupportedSchema);
}
@@ -512,7 +513,7 @@ impl GatewayPublicationV1 {
return Ok(self);
}
self.schema = GATEWAY_PUBLICATION_SCHEMA_V3.to_owned();
- self.compiler_revision = AGENT_PLAN_COMPILER_REVISION_V2.to_owned();
+ self.compiler_revision = AGENT_PLAN_COMPILER_REVISION_V3.to_owned();
self.plans = self
.plans
.into_iter()
@@ -533,7 +534,8 @@ impl GatewayPublicationV1 {
pub fn canonical_bytes(&self) -> Result<Vec<u8>, PublicationError> {
self.validate()?;
- serde_json::to_vec(self).map_err(|_| PublicationError::Encoding)
+ serde_json::to_vec(&StoredPublicationV1::freeze(self)?)
+ .map_err(|_| PublicationError::Encoding)
}
/// Validates publication, authority, grant-generation, and per-Plan revision monotonicity
@@ -577,11 +579,12 @@ impl GatewayPublicationV1 {
return Err(PublicationError::InvalidTransition);
}
if plan.body.agent_plan_revision == previous.body.agent_plan_revision
- && plan.digest != previous.digest
- && previous
- .clone()
- .into_current()
- .map_or(true, |migrated| migrated != *plan)
+ && crate::StoredPlanV1::freeze(plan).ok()
+ != previous
+ .clone()
+ .into_current()
+ .ok()
+ .and_then(|p| crate::StoredPlanV1::freeze(&p).ok())
{
return Err(PublicationError::ImmutablePlanRevisionConflict);
}
@@ -625,18 +628,13 @@ impl GatewayPublicationV1 {
}
pub fn decode(bytes: &[u8]) -> Result<Self, PublicationError> {
- let value: Self = serde_json::from_slice(bytes).map_err(|_| PublicationError::Decoding)?;
- value.validate()?;
- // No mutation occurred after validation. Check canonical bytes without traversing all
- // nested Plans a second time through canonical_bytes().
- if serde_json::to_vec(&value)
- .map_err(|_| PublicationError::Encoding)?
- .as_slice()
- != bytes
- {
+ let stored: StoredPublicationV1 =
+ serde_json::from_slice(bytes).map_err(|_| PublicationError::Decoding)?;
+ let publication = stored.build()?;
+ if publication.canonical_bytes()?.as_slice() != bytes {
return Err(PublicationError::NonCanonicalEncoding);
}
- Ok(value)
+ Ok(publication)
}
/// Recovery reader for a persisted publication aggregate. Current bodies use the strict
@@ -647,6 +645,17 @@ impl GatewayPublicationV1 {
if let Ok(current) = Self::decode(bytes) {
return Ok(current);
}
+ if let Ok(persisted) = serde_json::from_slice::<Self>(bytes) {
+ persisted.validate()?;
+ if serde_json::to_vec(&persisted)
+ .map_err(|_| PublicationError::Encoding)?
+ .as_slice()
+ != bytes
+ {
+ return Err(PublicationError::NonCanonicalEncoding);
+ }
+ return Ok(persisted);
+ }
let legacy: LegacyGatewayPublicationV2 =
serde_json::from_slice(bytes).map_err(|_| PublicationError::Decoding)?;
let plans = legacy.plans;
diff --git a/crates/domain/src/publication/plan_state.rs b/crates/domain/src/publication/plan_state.rs
index f02a2dc3..25666725 100644
--- a/crates/domain/src/publication/plan_state.rs
+++ b/crates/domain/src/publication/plan_state.rs
@@ -15,7 +15,7 @@ impl GatewayPublicationV1 {
self.validate()?;
let mut next = self.clone();
next.schema = GATEWAY_PUBLICATION_SCHEMA_V3.into();
- next.compiler_revision = crate::AGENT_PLAN_COMPILER_REVISION_V2.into();
+ next.compiler_revision = crate::AGENT_PLAN_COMPILER_REVISION_V3.into();
next.publication_revision = revision;
next.alias_registry = aliases;
next.plans
@@ -72,7 +72,7 @@ impl GatewayPublicationV1 {
}
let mut next = self.clone();
next.schema = GATEWAY_PUBLICATION_SCHEMA_V3.into();
- next.compiler_revision = crate::AGENT_PLAN_COMPILER_REVISION_V2.into();
+ next.compiler_revision = crate::AGENT_PLAN_COMPILER_REVISION_V3.into();
next.plans = next
.plans
.into_iter()
@@ -222,239 +222,9 @@ impl GatewayPublicationV1 {
mod tests {
use super::*;
- /// Replays the aggregate update from master 501453a2. The aggregate kept compiler V1,
- /// while edited Plans could already be V2. This is a persisted-record fixture, not a writer.
- fn master_501453a2_plan_content_publication() -> GatewayPublicationV1 {
- let source: GatewayPublicationV1 = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
- let plan = source.plans[0].clone();
- let heads = source
- .plans
- .iter()
- .cloned()
- .map(|plan| {
- let version =
- crate::PlanVersionV1::from_legacy_compiled(source.workspace_id.clone(), plan)
- .unwrap();
- PlanHeadV1 {
- head_revision: version.reference.content_revision,
- model_alias: version.compiled.model_alias().clone(),
- reference: version.reference,
- status: PlanLifecycleV1::Enabled,
- }
- })
- .collect::<Vec<_>>();
-
- let mut next = source.clone();
- next.schema = GATEWAY_PUBLICATION_SCHEMA_V3.into();
- next.publication_revision = GatewayPublicationRevision::new(12).unwrap();
- next.alias_registry = source.alias_registry.clone();
- next.plans
- .retain(|candidate| candidate.agent_plan_id() != plan.agent_plan_id());
- next.plans.push(plan);
- next.plans
- .sort_by(|left, right| left.agent_plan_id().cmp(right.agent_plan_id()));
- next.plan_heads = heads;
- next.plan_heads
- .sort_by(|left, right| left.reference.plan_id.cmp(&right.reference.plan_id));
- next.aliases = materialize_aliases(&next.plans, &next.enabled_grants().unwrap()).unwrap();
- next.validate_transition_from(&source).unwrap();
- next
- }
-
- #[test]
- fn master_v3_compiler_v1_record_authenticates_migrates_and_republishes_current() {
- let persisted = master_501453a2_plan_content_publication();
- assert_eq!(persisted.schema, GATEWAY_PUBLICATION_SCHEMA_V3);
- assert_eq!(
- persisted.compiler_revision,
- crate::AGENT_PLAN_COMPILER_REVISION_V1
- );
- assert!(
- persisted
- .plans
- .iter()
- .all(|plan| { plan.body.schema == crate::AGENT_PLAN_COMPILED_SCHEMA_V1 })
- );
-
- let original_heads = persisted.plan_heads.clone();
- let original_grants = persisted.grants.clone();
- let original_materialized = persisted
- .plans
- .iter()
- .map(|plan| plan.body.materialized.clone())
- .collect::<Vec<_>>();
- let original_snapshot = persisted.gateway_snapshot().unwrap();
- let old_record =
- PublicationRecordV1::from_publication(persisted.workspace_id.clone(), &persisted)
- .unwrap();
-
- // The old digest is authenticated before any migration changes the covered bytes.
- let authenticated = old_record.verify().unwrap();
- assert_eq!(authenticated, persisted);
- // A persisted aggregate with one already-currentized Plan keeps its legacy name-set
- // grants; recovery derives the route bindings from the Plans exactly as persisted.
- let mut raw: serde_json::Value = serde_json::from_slice(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
- let upgraded_plan = serde_json::to_value(
- serde_json::from_value::<crate::CompiledAgentPlanV1>(raw["plans"][0].clone())
- .unwrap()
- .into_current()
- .unwrap(),
- )
- .unwrap();
- raw["plans"][0] = upgraded_plan;
- let mixed =
- GatewayPublicationV1::decode_persisted(&serde_json::to_vec(&raw).unwrap()).unwrap();
- mixed.validate().unwrap();
- mixed
- .clone()
- .into_current()
- .unwrap()
- .validate_current_contract()
- .unwrap();
- let mut invalid = mixed.clone();
- invalid.compiler_revision = "unsupported-compiler".into();
- assert_eq!(
- invalid.validate(),
- Err(PublicationError::UnsupportedCompilerRevision)
- );
- let mut tampered = mixed;
- std::sync::Arc::make_mut(&mut tampered.plans[0].body).compiler_revision =
- crate::AGENT_PLAN_COMPILER_REVISION_V1.into();
- assert!(tampered.validate().is_err());
- let current = authenticated.into_current().unwrap();
- current.validate_current_contract().unwrap();
- assert_eq!(current.plan_heads, original_heads);
- // The plan upgrade re-binds grant route digests to the current compiled form; grant
- // identities, generations and route coverage stay sealed, and the upgrade is
- // idempotent over the current aggregate.
- for (current_grant, original_grant) in current.grants.iter().zip(&original_grants) {
- assert_eq!(current_grant.grant_id, original_grant.grant_id);
- assert_eq!(current_grant.generation, original_grant.generation);
- assert_eq!(
- current_grant.bearer_token_sha256,
- original_grant.bearer_token_sha256
- );
- assert_eq!(
- current_grant.model_grant.protocol,
- original_grant.model_grant.protocol
- );
- assert_eq!(
- current_grant.model_grant.routes.keys().collect::<Vec<_>>(),
- original_grant.model_grant.routes.keys().collect::<Vec<_>>()
- );
- }
- assert_eq!(current.clone().into_current().unwrap(), current);
- assert_eq!(current.gateway_snapshot().unwrap(), original_snapshot);
- assert_eq!(
- current
- .plans
- .iter()
- .map(|plan| plan.body.materialized.clone())
- .collect::<Vec<_>>(),
- original_materialized
- .into_iter()
- .map(|mut materialized| {
- // Only obsolete ordering provenance changes; compare all remaining fields,
- // including candidate order, limits and exact execution configuration.
- for group in &mut materialized.attempt_owned.groups {
- group.ordering_evidence = crate::MaterializedOrderingV1::ExplicitOrder;
- group.pinned_ratings.clear();
- }
- materialized
- })
- .collect::<Vec<_>>()
- );
-
- // Re-emission stores only current bytes. A subsequent lifecycle write retains the Plan,
- // grant and immutable content identities while using the current compiler contract.
- let current_record =
- PublicationRecordV1::from_publication(current.workspace_id.clone(), &current).unwrap();
- let recovered = current_record.verify().unwrap();
- recovered.validate_current_contract().unwrap();
- let mut disabled = recovered.plan_heads[0].clone();
- disabled.head_revision += 1;
- disabled.status = PlanLifecycleV1::Disabled;
- let republished = recovered
- .next_with_plan_lifecycle(GatewayPublicationRevision::new(13).unwrap(), disabled)
- .unwrap();
- republished.validate_current_contract().unwrap();
- assert_eq!(republished.plans, recovered.plans);
- assert_eq!(republished.grants, recovered.grants);
- assert_eq!(
- republished.plan_heads[0].reference,
- recovered.plan_heads[0].reference
- );
- }
-
- #[test]
- fn persisted_master_accepts_v2_and_mixed_plans_without_rewriting_before_verification() {
- let source = master_501453a2_plan_content_publication();
- for converted_count in 0..=source.plans.len() {
- // Rebuild the aggregate exactly as the era's writer persisted it: legacy
- // name-set grants around a plan set that may already contain currentized Plans.
- let mut body = serde_json::to_value(&source).unwrap();
- body["grants"] = serde_json::Value::Array(
- source
- .grants
- .iter()
- .map(|grant| {
- serde_json::json!({
- "grant_id": grant.grant_id,
- "generation": grant.generation,
- "bearer_token_sha256": grant.bearer_token_sha256,
- "allowed_protocols": [grant.model_grant.protocol],
- "allowed_aliases": grant
- .model_grant
- .routes
- .keys()
- .collect::<Vec<_>>(),
- })
- })
- .collect(),
- );
- for plan in body["plans"]
- .as_array_mut()
- .unwrap()
- .iter_mut()
- .take(converted_count)
- {
- let compiled =
- serde_json::from_value::<crate::CompiledAgentPlanV1>(plan.clone()).unwrap();
- *plan = serde_json::to_value(compiled.into_current().unwrap()).unwrap();
- }
- let persisted =
- GatewayPublicationV1::decode_persisted(&serde_json::to_vec(&body).unwrap())
- .unwrap();
- let record =
- PublicationRecordV1::from_publication(persisted.workspace_id.clone(), &persisted)
- .unwrap();
- let authenticated = record.verify().unwrap();
- assert_eq!(authenticated, persisted);
- let current = authenticated.into_current().unwrap();
- current.validate_current_contract().unwrap();
- assert_eq!(current.plan_heads, persisted.plan_heads);
- assert_eq!(
- current.gateway_snapshot().unwrap(),
- persisted.gateway_snapshot().unwrap()
- );
- // Upgrading the remaining legacy Plans deterministically re-binds grant route
- // digests; once every Plan is current the grants pass through unchanged.
- assert_eq!(current.clone().into_current().unwrap(), current);
- if converted_count == source.plans.len() {
- assert_eq!(current.grants, persisted.grants);
- }
- }
- }
-
- fn migrated_publication_with_heads() -> GatewayPublicationV1 {
- let legacy: GatewayPublicationV1 = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ fn current_publication_with_heads() -> GatewayPublicationV1 {
+ let legacy: GatewayPublicationV1 = serde_json::from_str(include_str!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
let heads = legacy
@@ -462,9 +232,11 @@ mod tests {
.iter()
.cloned()
.map(|plan| {
- let version =
- crate::PlanVersionV1::from_legacy_compiled(legacy.workspace_id.clone(), plan)
- .unwrap();
+ let version = crate::PlanVersionV1::from_unversioned_compiled_recovery(
+ legacy.workspace_id.clone(),
+ plan,
+ )
+ .unwrap();
PlanHeadV1 {
head_revision: version.reference.content_revision,
model_alias: version.compiled.model_alias().clone(),
@@ -479,7 +251,7 @@ mod tests {
current
}
fn publication() -> GatewayPublicationV1 {
- let current = migrated_publication_with_heads();
+ let current = current_publication_with_heads();
current
.next_with_plan_content(
GatewayPublicationRevision::new(12).unwrap(),
@@ -491,7 +263,7 @@ mod tests {
}
#[test]
fn lifecycle_write_keeps_every_compiled_plan_current() {
- let current = migrated_publication_with_heads();
+ let current = current_publication_with_heads();
let mut head = current.plan_heads[0].clone();
head.head_revision += 1;
head.status = PlanLifecycleV1::Disabled;
@@ -502,7 +274,7 @@ mod tests {
assert!(
next.plans
.iter()
- .all(|plan| plan.body.schema == crate::AGENT_PLAN_COMPILED_SCHEMA_V2)
+ .all(|plan| plan.body.schema == crate::AGENT_PLAN_COMPILED_SCHEMA_V3)
);
}
#[test]
diff --git a/crates/domain/src/publication/record.rs b/crates/domain/src/publication/record.rs
index 7558ce96..5afdf21a 100644
--- a/crates/domain/src/publication/record.rs
+++ b/crates/domain/src/publication/record.rs
@@ -60,8 +60,9 @@ impl PublicationRecordV1 {
if workspace_id != publication.workspace_id {
return Err(PublicationError::InvalidWorkspace);
}
+ let publication = super::StoredPublicationV1::freeze(publication)?.build()?;
let bytes = publication.canonical_bytes()?;
- Ok(Self::from_verified(bytes, publication.clone()))
+ Ok(Self::from_verified(bytes, publication))
}
/// Storage and untrusted inputs always enter through complete authentication.
diff --git a/crates/domain/src/publication/routing_publication_tests.rs b/crates/domain/src/publication/routing_publication_tests.rs
index 3fb6d09e..e14cefdd 100644
--- a/crates/domain/src/publication/routing_publication_tests.rs
+++ b/crates/domain/src/publication/routing_publication_tests.rs
@@ -11,7 +11,8 @@ fn routing_publication_unknown_schema_and_revision_fail_closed() {
Vec::new(),
)
.unwrap();
- let mut value = serde_json::to_value(publication).unwrap();
+ let mut value =
+ serde_json::from_slice::<Value>(&publication.canonical_bytes().unwrap()).unwrap();
value["schema"] = serde_json::json!(UNSUPPORTED_GATEWAY_PUBLICATION_SCHEMA_V1);
let bytes = serde_json::to_vec(&value).unwrap();
assert_eq!(
@@ -20,7 +21,7 @@ fn routing_publication_unknown_schema_and_revision_fail_closed() {
);
let mut value: Value = serde_json::from_slice(&bytes).unwrap();
- value["schema"] = serde_json::json!(GATEWAY_PUBLICATION_SCHEMA_V3);
+ value["schema"] = serde_json::json!(STORED_PUBLICATION_SCHEMA);
value["publication_revision"] = serde_json::json!(0);
let bytes = serde_json::to_vec(&value).unwrap();
assert_eq!(
@@ -31,11 +32,12 @@ fn routing_publication_unknown_schema_and_revision_fail_closed() {
#[test]
fn model_grant_projection_rejects_conflicting_or_future_plan_provenance() {
- let fixture: Value = serde_json::from_slice(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let fixture: Value = serde_json::from_slice::<serde_json::Value>(include_bytes!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
- let plan: CompiledAgentPlanV1 = serde_json::from_value(fixture["plans"][0].clone()).unwrap();
+ let plan =
+ serde_json::from_value::<crate::CompiledAgentPlanV1>(fixture["plans"][0].clone()).unwrap();
let plan = plan.into_current().unwrap();
let revision = plan.body.agent_plan_revision;
let accepted_digest = plan.body.materialized_route_digest.clone();
@@ -105,9 +107,9 @@ fn routing_publication_record_is_bound_to_its_workspace() {
#[test]
fn adding_first_grant_does_not_mutate_the_independent_plan_revision() {
- let granted: GatewayPublicationV1 = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
+ let granted: GatewayPublicationV1 = serde_json::from_slice::<crate::GatewayPublicationV1>(
+ include_bytes!("../../../../e2e/product/fixtures/routing/current-publication.v3.json"),
+ )
.unwrap();
let mut plan_only = granted.clone();
plan_only.publication_revision = GatewayPublicationRevision::new(10).unwrap();
@@ -154,9 +156,9 @@ fn adding_first_grant_does_not_mutate_the_independent_plan_revision() {
#[test]
fn revoking_last_grant_preserves_the_independent_plan_publication() {
- let granted: GatewayPublicationV1 = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
+ let granted: GatewayPublicationV1 = serde_json::from_slice::<crate::GatewayPublicationV1>(
+ include_bytes!("../../../../e2e/product/fixtures/routing/current-publication.v3.json"),
+ )
.unwrap();
let first_grant_id = granted.grants[0].grant_id.clone();
let last_grant_id = granted.grants[1].grant_id.clone();
@@ -172,7 +174,7 @@ fn revoking_last_grant_preserves_the_independent_plan_publication() {
revoked
.plans
.iter()
- .all(|plan| plan.body.schema == AGENT_PLAN_COMPILED_SCHEMA_V2)
+ .all(|plan| plan.body.schema == AGENT_PLAN_COMPILED_SCHEMA_V3)
);
for (current, legacy) in revoked.plans.iter().zip(&granted.plans) {
assert_eq!(current.agent_plan_id(), legacy.agent_plan_id());
@@ -196,90 +198,3 @@ fn revoking_last_grant_preserves_the_independent_plan_publication() {
assert!(revoked_projection.grants.is_empty());
revoked.validate_transition_from(&one_grant).unwrap();
}
-
-#[test]
-fn legacy_publication_recovery_rederives_route_mapping_from_persisted_name_sets() {
- let raw: Value = serde_json::from_slice(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
- let recovered = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
- // Recovery reads an exact legacy record; only a new publish upgrades the tag.
- assert_eq!(recovered.schema, LEGACY_GATEWAY_PUBLICATION_SCHEMA_V2);
- let raw_grants = raw["grants"].as_array().unwrap();
- assert_eq!(recovered.grants.len(), raw_grants.len());
- for (grant, raw_grant) in recovered.grants.iter().zip(raw_grants) {
- assert_eq!(grant.grant_id, raw_grant["grant_id"].as_str().unwrap());
- let protocol: AgentIngressProtocolV1 =
- serde_json::from_value(raw_grant["allowed_protocols"][0].clone()).unwrap();
- assert_eq!(grant.model_grant.protocol, protocol);
- let aliases: Vec<ModelAlias> = raw_grant["allowed_aliases"]
- .as_array()
- .unwrap()
- .iter()
- .map(|value| serde_json::from_value(value.clone()).unwrap())
- .collect();
- for alias in &aliases {
- let plan = recovered
- .plans
- .iter()
- .find(|plan| plan.model_alias() == alias)
- .unwrap();
- match grant.model_grant.routes.get(alias.as_str()).unwrap() {
- crate::AgentModelRouteV2::Plan {
- plan_id,
- alias: route_alias,
- revision,
- semantic_digest,
- } => {
- assert_eq!(plan_id, plan.agent_plan_id());
- assert_eq!(route_alias, alias);
- assert_eq!(*revision, plan.body.agent_plan_revision);
- assert_eq!(semantic_digest, &plan.body.materialized_route_digest);
- }
- crate::AgentModelRouteV2::Fixed { .. } => {
- panic!("a V2 grant carries only published plan aliases");
- }
- }
- }
- }
- assert!(recovered.clone().into_current().is_ok());
-}
-
-#[test]
-fn legacy_publication_recovery_rejects_grant_shapes_the_v2_writer_never_sealed() {
- let mut raw: Value = serde_json::from_slice(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
- ))
- .unwrap();
- let mut two_protocols = raw.clone();
- two_protocols["grants"][0]["allowed_protocols"] = serde_json::json!(["messages", "responses"]);
- assert_eq!(
- GatewayPublicationV1::decode_persisted(&serde_json::to_vec(&two_protocols).unwrap())
- .unwrap_err(),
- PublicationError::InvalidGrant
- );
- let mut unknown_alias = raw.clone();
- unknown_alias["grants"][0]["allowed_aliases"] = serde_json::json!(["hiroute/not-published"]);
- assert_eq!(
- GatewayPublicationV1::decode_persisted(&serde_json::to_vec(&unknown_alias).unwrap())
- .unwrap_err(),
- PublicationError::InvalidGrant
- );
- let mut duplicate_alias = raw.clone();
- duplicate_alias["grants"][0]["allowed_aliases"] =
- serde_json::json!(["hiroute/2590c10eeae4f930", "hiroute/2590c10eeae4f930"]);
- assert_eq!(
- GatewayPublicationV1::decode_persisted(&serde_json::to_vec(&duplicate_alias).unwrap())
- .unwrap_err(),
- PublicationError::InvalidGrant
- );
- raw["schema"] = serde_json::json!(UNSUPPORTED_GATEWAY_PUBLICATION_SCHEMA_V1);
- assert_eq!(
- GatewayPublicationV1::decode_persisted(&serde_json::to_vec(&raw).unwrap()).unwrap_err(),
- PublicationError::UnsupportedSchema
- );
-}
diff --git a/crates/domain/src/publication/stored.rs b/crates/domain/src/publication/stored.rs
new file mode 100644
index 00000000..3c256dc4
--- /dev/null
+++ b/crates/domain/src/publication/stored.rs
@@ -0,0 +1,101 @@
+//! The durable publication contains choices and grants; executable aliases are projections.
+use super::*;
+
+pub const STORED_PUBLICATION_SCHEMA: &str = "hiroute.stored-publication/v1";
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredPublicationV1 {
+ pub schema: String,
+ pub workspace_id: WorkspaceId,
+ pub authority_id: String,
+ pub authority_epoch: u64,
+ pub publication_revision: GatewayPublicationRevision,
+ pub alias_registry: AliasRegistryV1,
+ pub plans: Vec<crate::StoredPlanV1>,
+ pub plan_heads: Vec<crate::PlanHeadV1>,
+ pub grants: Vec<GatewayExecutableGrantV2>,
+}
+
+impl StoredPublicationV1 {
+ pub fn freeze(publication: &GatewayPublicationV1) -> Result<Self, PublicationError> {
+ publication.validate()?;
+ Ok(Self {
+ schema: STORED_PUBLICATION_SCHEMA.into(),
+ workspace_id: publication.workspace_id.clone(),
+ authority_id: publication.authority_id.clone(),
+ authority_epoch: publication.authority_epoch,
+ publication_revision: publication.publication_revision,
+ alias_registry: publication.alias_registry.clone(),
+ plans: publication
+ .plans
+ .iter()
+ .map(|p| crate::StoredPlanV1::freeze(p).map_err(|_| PublicationError::InvalidPlan))
+ .collect::<Result<_, _>>()?,
+ plan_heads: publication.plan_heads.clone(),
+ grants: publication.grants.clone(),
+ })
+ }
+
+ pub fn build(&self) -> Result<GatewayPublicationV1, PublicationError> {
+ if self.schema != STORED_PUBLICATION_SCHEMA {
+ return Err(PublicationError::UnsupportedSchema);
+ }
+ let plans = self
+ .plans
+ .iter()
+ .map(|p| p.build().map_err(|_| PublicationError::InvalidPlan))
+ .collect::<Result<_, _>>()?;
+ // Do not silently rebind stored grants. A current writer already freezes the exact routes.
+ let mut publication = GatewayPublicationV1::from_parts(
+ self.workspace_id.clone(),
+ self.authority_id.clone(),
+ self.authority_epoch,
+ self.publication_revision,
+ DEFAULT_CATALOG_RENDERER_REVISION.into(),
+ self.alias_registry.clone(),
+ plans,
+ self.grants.clone(),
+ )?;
+ if publication.grants != self.grants {
+ return Err(PublicationError::InvalidGrant);
+ }
+ publication.plan_heads = self.plan_heads.clone();
+ publication.aliases =
+ materialize_aliases(&publication.plans, &publication.enabled_grants()?)?;
+ publication.validate()?;
+ if Self::freeze(&publication)? != *self {
+ return Err(PublicationError::InvalidExecutableProjection);
+ }
+ Ok(publication)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn current_fixture_is_a_deterministic_projection_of_stable_business_facts() {
+ let stored: StoredPublicationV1 = serde_json::from_str(include_str!(
+ "../../../../e2e/product/fixtures/routing/stored-publication.v1.json"
+ ))
+ .unwrap();
+ let publication: GatewayPublicationV1 = serde_json::from_str(include_str!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
+ publication.validate_current_contract().unwrap();
+ assert_eq!(StoredPublicationV1::freeze(&publication).unwrap(), stored);
+ let rebuilt = stored.build().unwrap();
+ assert_eq!(StoredPublicationV1::freeze(&rebuilt).unwrap(), stored);
+ assert_eq!(
+ rebuilt.canonical_bytes().unwrap(),
+ publication.canonical_bytes().unwrap()
+ );
+ assert_eq!(stored.build().unwrap(), rebuilt);
+ let mut corrupt = publication.plans[0].clone();
+ std::sync::Arc::make_mut(&mut corrupt.body).agent_plan_revision += 1;
+ assert!(corrupt.validate().is_err());
+ }
+}
diff --git a/crates/domain/src/publication/validation_tests.rs b/crates/domain/src/publication/validation_tests.rs
index 348df758..2d2f2cfe 100644
--- a/crates/domain/src/publication/validation_tests.rs
+++ b/crates/domain/src/publication/validation_tests.rs
@@ -3,8 +3,8 @@ use super::*;
use crate::routing::CANDIDATE_VALIDATIONS;
fn current_catalog_only(count: usize) -> GatewayPublicationV1 {
- let mut publication = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let mut publication = serde_json::from_slice::<crate::GatewayPublicationV1>(include_bytes!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap()
.into_current()
@@ -91,8 +91,8 @@ fn publication_raw_boundaries_still_reject_nested_tampering_and_noncanonical_byt
#[test]
fn current_publication_still_checks_exact_grant_plan_binding_before_projection() {
- let mut publication = GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let mut publication = serde_json::from_slice::<crate::GatewayPublicationV1>(include_bytes!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap()
.into_current()
diff --git a/crates/domain/src/routing/capability_compiler.rs b/crates/domain/src/routing/capability_compiler.rs
new file mode 100644
index 00000000..89e2aa5c
--- /dev/null
+++ b/crates/domain/src/routing/capability_compiler.rs
@@ -0,0 +1,116 @@
+//! Current executable protocol features. Both new plans and storage admission use this builder.
+use super::*;
+use crate::UpstreamProtocol;
+
+impl StoredModelCapabilitiesV1 {
+ pub fn compile(
+ &self,
+ upstream_protocol: UpstreamProtocol,
+ ) -> GatewayCandidateCapabilityProfileV1 {
+ let exact = GatewayFidelityV1::Exact;
+ let unsupported = GatewayFidelityV1::Unsupported;
+ let fidelity = |fact: &GatewayCriticalFactV1<bool>| match fact {
+ GatewayCriticalFactV1::Exact(true) => exact,
+ GatewayCriticalFactV1::Exact(false) => unsupported,
+ GatewayCriticalFactV1::Unknown => GatewayFidelityV1::Unknown,
+ };
+ let tool = fidelity(&self.model_support.tools);
+ let vision = fidelity(&self.model_support.vision);
+ let provider_state = matches!(
+ upstream_protocol,
+ UpstreamProtocol::Responses | UpstreamProtocol::Messages
+ );
+ GatewayCandidateCapabilityProfileV1 {
+ schema_version: "hiroute.candidate-capability/v1".into(),
+ capability_id: self.capability_id.clone(),
+ capability_revision: self.capability_revision.clone(),
+ upstream_protocol,
+ model_configuration_id: self.model_configuration_id.clone(),
+ native_model: self.native_model.clone(),
+ model_support: self.model_support.clone(),
+ request: GatewayRequestFeatureProfileV1 {
+ text: exact,
+ initial_instructions: exact,
+ mid_conversation_instructions: if upstream_protocol == UpstreamProtocol::Messages {
+ unsupported
+ } else {
+ exact
+ },
+ image_url: vision,
+ image_base64: vision,
+ image_base64_media_types: match &self.model_support.vision {
+ GatewayCriticalFactV1::Exact(true) => GatewayCriticalFactV1::Exact(vec![
+ "image/gif".into(),
+ "image/jpeg".into(),
+ "image/png".into(),
+ "image/webp".into(),
+ ]),
+ GatewayCriticalFactV1::Exact(false) => GatewayCriticalFactV1::Exact(Vec::new()),
+ GatewayCriticalFactV1::Unknown => GatewayCriticalFactV1::Unknown,
+ },
+ function_tools: tool,
+ strict_tools: if upstream_protocol == UpstreamProtocol::Messages {
+ unsupported
+ } else {
+ tool
+ },
+ tool_choice_none: if upstream_protocol == UpstreamProtocol::Messages {
+ unsupported
+ } else {
+ tool
+ },
+ tool_choice_auto: tool,
+ tool_choice_required_any: tool,
+ tool_choice_required_named: tool,
+ parallel_tools: tool,
+ tool_roundtrip: tool,
+ tool_result_text: tool,
+ tool_result_json: tool,
+ logical_tool_id_mapping: tool,
+ provider_state: if provider_state { exact } else { unsupported },
+ },
+ response: GatewayResponseFeatureProfileV1 {
+ text: exact,
+ reasoning: exact,
+ refusal: exact,
+ tool_calls: tool,
+ logical_tool_id_mapping: tool,
+ usage: exact,
+ finish_reason: exact,
+ typed_error: exact,
+ provider_state: if provider_state { exact } else { unsupported },
+ stream_refusal: if upstream_protocol == UpstreamProtocol::Messages {
+ GatewayStreamingRefusalSemanticsV1::TerminalClassified
+ } else {
+ GatewayStreamingRefusalSemanticsV1::ExactDelta
+ },
+ stream_text_delta: exact,
+ stream_tool_argument_delta: tool,
+ stream_reasoning_delta: exact,
+ stream_usage: exact,
+ },
+ reasoning_profiles: self
+ .reasoning_profiles
+ .iter()
+ .map(StoredNativeReasoningV1::compile)
+ .collect(),
+ selected_reasoning_profile_id: self.selected_reasoning_profile_id.clone(),
+ context: GatewayContextLimitsV1 {
+ max_input_tokens: self.max_input_tokens.clone(),
+ max_output_tokens: self.max_output_tokens.clone(),
+ max_total_tokens: self.max_total_tokens.clone(),
+ estimator: GatewayCriticalFactV1::Exact(GatewayTokenEstimatorProfileV1 {
+ revision: "byte-upper-bound/v1".into(),
+ bytes_per_token: 1,
+ fixed_overhead_tokens: 0,
+ }),
+ },
+ native_streaming: self.native_streaming.clone(),
+ native_provider_state: if provider_state {
+ GatewayNativeProviderStateEmissionV1::Native
+ } else {
+ GatewayNativeProviderStateEmissionV1::Never
+ },
+ }
+ }
+}
diff --git a/crates/domain/src/routing/gateway_execution.rs b/crates/domain/src/routing/gateway_execution.rs
index 598703ab..01ba00b1 100644
--- a/crates/domain/src/routing/gateway_execution.rs
+++ b/crates/domain/src/routing/gateway_execution.rs
@@ -444,6 +444,8 @@ pub struct GatewayCandidateCapabilityProfileV1 {
/// candidate also carries it as `native_transport_model`; it is not the
/// catalog-bound logical `upstream_model_id` for a managed CPA target.
pub native_model: String,
+ /// Model evidence, independent of the current adapter's feature fidelity.
+ pub model_support: super::StoredModelSupportV1,
pub request: GatewayRequestFeatureProfileV1,
pub response: GatewayResponseFeatureProfileV1,
pub reasoning_profiles: Vec<GatewayReasoningProfileCapabilityV1>,
diff --git a/crates/domain/src/routing/materialized.rs b/crates/domain/src/routing/materialized.rs
index 9358a271..e66930ab 100644
--- a/crates/domain/src/routing/materialized.rs
+++ b/crates/domain/src/routing/materialized.rs
@@ -12,12 +12,11 @@ use crate::{
use super::gateway_execution::{GatewayCandidateProtocolProfileV1, GatewayOperationalTargetV1};
use super::{
- AGENT_PLAN_COMPILED_SCHEMA_V1, AGENT_PLAN_COMPILED_SCHEMA_V2, AGENT_PLAN_COMPILER_REVISION_V1,
- AGENT_PLAN_COMPILER_REVISION_V2, ComplexityClassifierV1, RoutingLimitsV1,
+ AGENT_PLAN_COMPILED_SCHEMA_V1, AGENT_PLAN_COMPILED_SCHEMA_V3, AGENT_PLAN_COMPILER_REVISION_V1,
+ AGENT_PLAN_COMPILER_REVISION_V3, ComplexityClassifierV1, RoutingLimitsV1,
};
const LEGACY_MATERIALIZED_ROUTE_DIGEST_SCHEMA_V1: &str = "hiroute.materialized-route-digest/v1";
-pub const MATERIALIZED_ROUTE_DIGEST_SCHEMA_V2: &str = "hiroute.materialized-route-digest/v2";
#[cfg(test)]
thread_local! {
@@ -408,16 +407,40 @@ impl MaterializedAgentPlanV1 {
/// provenance, so a rating/price/new-offer refresh cannot silently change a saved route.
pub fn route_digest(&self) -> Result<CanonicalDigest, CompiledPlanError> {
self.validate()?;
+ self.route_digest_for_sealing()
+ }
+
+ /// Calculates the frozen-fact hash without claiming validation. A newly assembled
+ /// stored Plan passes full validation in seal_current before receiving its proof.
+ pub(super) fn route_digest_for_sealing(&self) -> Result<CanonicalDigest, CompiledPlanError> {
if self.attempt_owned.groups.iter().any(|group| {
group.ordering_evidence != MaterializedOrderingV1::ExplicitOrder
|| !group.pinned_ratings.is_empty()
}) {
return Err(CompiledPlanError::InvalidOrderingFacts);
}
+ let groups = self
+ .attempt_owned
+ .groups
+ .iter()
+ .map(|g| {
+ Ok(super::StoredGroupV1 {
+ group_id: g.group_id,
+ ordering_evidence: g.ordering_evidence.clone(),
+ pinned_ratings: g.pinned_ratings.clone(),
+ candidates: g
+ .candidates
+ .iter()
+ .map(super::StoredCandidateV1::freeze_validated)
+ .collect::<Result<_, _>>()?,
+ })
+ })
+ .collect::<Result<Vec<_>, CompiledPlanError>>()?;
CanonicalDigest::of(&(
- MATERIALIZED_ROUTE_DIGEST_SCHEMA_V2,
+ super::STABLE_ROUTE_SCHEMA,
&self.request_owned,
- &self.attempt_owned,
+ &self.attempt_owned.limits,
+ groups,
))
.map_err(|_| CompiledPlanError::Encoding)
}
@@ -577,7 +600,7 @@ impl CompiledAgentPlanV1 {
/// Seals the sole live compiled-plan contract. Historical bodies must enter through the
/// authenticated persisted-record reader and are converted before any new publication write.
pub fn seal_current(body: CompiledAgentPlanBodyV1) -> Result<Self, CompiledPlanError> {
- if body.schema != AGENT_PLAN_COMPILED_SCHEMA_V2 {
+ if body.schema != AGENT_PLAN_COMPILED_SCHEMA_V3 {
return Err(CompiledPlanError::UnsupportedSchema);
}
Self::seal_compatible(body)
@@ -629,7 +652,7 @@ impl CompiledAgentPlanV1 {
/// explicit order and computes the one current route digest.
pub fn into_current(mut self) -> Result<Self, CompiledPlanError> {
self.validate()?;
- if self.body.schema == AGENT_PLAN_COMPILED_SCHEMA_V2 {
+ if self.body.schema == AGENT_PLAN_COMPILED_SCHEMA_V3 {
return Ok(self);
}
let body = Arc::make_mut(&mut self.body);
@@ -637,8 +660,8 @@ impl CompiledAgentPlanV1 {
group.ordering_evidence = MaterializedOrderingV1::ExplicitOrder;
group.pinned_ratings.clear();
}
- body.schema = AGENT_PLAN_COMPILED_SCHEMA_V2.to_owned();
- body.compiler_revision = AGENT_PLAN_COMPILER_REVISION_V2.to_owned();
+ body.schema = AGENT_PLAN_COMPILED_SCHEMA_V3.to_owned();
+ body.compiler_revision = AGENT_PLAN_COMPILER_REVISION_V3.to_owned();
body.materialized_route_digest = body.materialized.route_digest()?;
Self::seal_current((*self.body).clone())
}
@@ -655,7 +678,7 @@ impl CompiledAgentPlanV1 {
fn validate_body(body: &CompiledAgentPlanBodyV1) -> Result<(), CompiledPlanError> {
let expected_revision = match body.schema.as_str() {
AGENT_PLAN_COMPILED_SCHEMA_V1 => AGENT_PLAN_COMPILER_REVISION_V1,
- AGENT_PLAN_COMPILED_SCHEMA_V2 => AGENT_PLAN_COMPILER_REVISION_V2,
+ AGENT_PLAN_COMPILED_SCHEMA_V3 => AGENT_PLAN_COMPILER_REVISION_V3,
_ => return Err(CompiledPlanError::UnsupportedSchema),
};
if body.compiler_revision != expected_revision {
@@ -668,7 +691,7 @@ fn validate_body(body: &CompiledAgentPlanBodyV1) -> Result<(), CompiledPlanError
return Err(CompiledPlanError::InvalidIdentity);
}
// Both digest methods fully validate the borrowed materialized route.
- let route_digest = if body.schema == AGENT_PLAN_COMPILED_SCHEMA_V2 {
+ let route_digest = if body.schema == AGENT_PLAN_COMPILED_SCHEMA_V3 {
body.materialized.route_digest()?
} else {
body.materialized.legacy_route_digest()?
diff --git a/crates/domain/src/routing/mod.rs b/crates/domain/src/routing/mod.rs
index 8cb4d414..621dfb2b 100644
--- a/crates/domain/src/routing/mod.rs
+++ b/crates/domain/src/routing/mod.rs
@@ -5,10 +5,15 @@
//! these desired-state templates or consults rating and price inputs.
mod authoring;
+mod capability_compiler;
mod classifier;
mod context_window;
mod gateway_execution;
mod materialized;
+mod stored;
+mod stored_capability;
+pub use stored::*;
+pub use stored_capability::*;
mod ordering;
mod reasoning;
mod strategy;
@@ -25,5 +30,5 @@ pub const AGENT_PLAN_FACTS_SCHEMA_V1: &str = "hiroute.agent-plan-facts/v1";
pub const AGENT_PLAN_COMPILED_SCHEMA_V1: &str = "hiroute.compiled-agent-plan/v1";
pub const AGENT_PLAN_COMPILER_REVISION_V1: &str = "agent-plan-compiler/v1";
-pub const AGENT_PLAN_COMPILED_SCHEMA_V2: &str = "hiroute.compiled-agent-plan/v2";
-pub const AGENT_PLAN_COMPILER_REVISION_V2: &str = "agent-plan-compiler/v2";
+pub const AGENT_PLAN_COMPILED_SCHEMA_V3: &str = "hiroute.compiled-agent-plan/v3";
+pub const AGENT_PLAN_COMPILER_REVISION_V3: &str = "agent-plan-compiler/v3";
diff --git a/crates/domain/src/routing/stored.rs b/crates/domain/src/routing/stored.rs
new file mode 100644
index 00000000..4c69052e
--- /dev/null
+++ b/crates/domain/src/routing/stored.rs
@@ -0,0 +1,557 @@
+//! Frozen business choices. Execution profiles and their checksums are rebuilt on admission.
+use super::*;
+use crate::*;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+pub const STORED_PLAN_SCHEMA: &str = "hiroute.stored-plan/v1";
+pub const STABLE_ROUTE_SCHEMA: &str = "hiroute.stable-route/v1";
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredProtocolChoiceV1 {
+ pub ingress_protocol: UpstreamProtocol,
+ /// Frozen model/transport guarantees required by the confirmed plan.
+ pub capability: StoredModelCapabilitiesV1,
+ pub connector: StoredConnectorFactsV1,
+ pub native_target: Option<GatewayNativeProfileTargetV2>,
+ /// Credential destinations bind this source profile identity. It is not a decoder revision.
+ pub credential_profile_identity: Option<String>,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredConnectorFactsV1 {
+ pub provider_id: String,
+ pub endpoint_id: String,
+ pub entitlement_id: String,
+ pub connector_id: String,
+ pub connector_revision: String,
+ pub upstream_protocol: UpstreamProtocol,
+ pub request_path: String,
+ pub authentication: GatewayCriticalFactV1<GatewayAuthenticationSemanticsV1>,
+ pub content_type: String,
+ pub required_headers: Vec<(String, String)>,
+}
+
+impl StoredProtocolChoiceV1 {
+ fn freeze(profile: &GatewayCandidateProtocolProfileV1) -> Result<Self, CompiledPlanError> {
+ let headers = profile
+ .connector
+ .headers
+ .exact()
+ .ok_or(CompiledPlanError::InvalidCandidate)?;
+ Ok(Self {
+ ingress_protocol: profile.ingress_protocol,
+ capability: StoredModelCapabilitiesV1::freeze(&profile.capability),
+ connector: StoredConnectorFactsV1 {
+ provider_id: profile.connector.provider_id.clone(),
+ endpoint_id: profile.connector.endpoint_id.clone(),
+ entitlement_id: profile.connector.entitlement_id.clone(),
+ connector_id: profile.connector.connector_id.clone(),
+ connector_revision: profile.connector.connector_revision.clone(),
+ upstream_protocol: profile.connector.upstream_protocol,
+ request_path: profile.connector.request_path.clone(),
+ authentication: profile.connector.authentication.clone(),
+ content_type: headers.content_type.clone(),
+ required_headers: headers.required_headers.clone(),
+ },
+ native_target: profile.native_target.clone(),
+ credential_profile_identity: profile
+ .native_target
+ .as_ref()
+ .map(|_| profile.adapter_revision.clone()),
+ })
+ }
+
+ fn build(&self) -> Result<GatewayCandidateProtocolProfileV1, CompiledPlanError> {
+ if self.native_target.is_some() != self.credential_profile_identity.is_some() {
+ return Err(CompiledPlanError::InvalidCandidate);
+ }
+ let c = &self.connector;
+ let mut forbidden = vec!["authorization".to_owned(), "x-api-key".to_owned()];
+ if let GatewayCriticalFactV1::Exact(GatewayAuthenticationSemanticsV1::ApiKeyHeader {
+ header,
+ }) = &c.authentication
+ && !forbidden.contains(header)
+ {
+ forbidden.push(header.clone());
+ }
+ Ok(GatewayCandidateProtocolProfileV1 {
+ schema_version: "hiroute.candidate-protocol-profile/v1".into(),
+ path_id: format!(
+ "{}-to-{}",
+ protocol_name(self.ingress_protocol),
+ protocol_name(c.upstream_protocol)
+ ),
+ ingress_protocol: self.ingress_protocol,
+ adapter_revision: self.credential_profile_identity.clone().unwrap_or_else(|| {
+ format!("adapter/native/{}@1", protocol_name(c.upstream_protocol))
+ }),
+ serializer_revision: "hiroute-target-json/v1".into(),
+ decoder_revision: "hiroute-native-response/v1".into(),
+ capability: self.capability.compile(c.upstream_protocol),
+ connector: GatewayConnectorProfileV1 {
+ schema_version: "hiroute.connector-profile/v1".into(),
+ provider_id: c.provider_id.clone(),
+ endpoint_id: c.endpoint_id.clone(),
+ entitlement_id: c.entitlement_id.clone(),
+ connector_id: c.connector_id.clone(),
+ connector_revision: c.connector_revision.clone(),
+ upstream_protocol: c.upstream_protocol,
+ request_path: c.request_path.clone(),
+ authentication: c.authentication.clone(),
+ headers: GatewayCriticalFactV1::Exact(GatewayHeaderSemanticsV1 {
+ content_type: c.content_type.clone(),
+ required_headers: c.required_headers.clone(),
+ forbidden_forward_headers: forbidden,
+ }),
+ errors: GatewayCriticalFactV1::Exact(GatewayErrorSemanticsV1 {
+ http_status_typed: true,
+ sse_error_typed: true,
+ retry_after_header: Some("retry-after".into()),
+ }),
+ },
+ native_target: self.native_target.clone(),
+ })
+ }
+}
+
+fn protocol_name(p: UpstreamProtocol) -> &'static str {
+ match p {
+ UpstreamProtocol::Responses => "responses",
+ UpstreamProtocol::Messages => "messages",
+ UpstreamProtocol::ChatCompletions => "chat-completions",
+ }
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredCandidateV1 {
+ pub binding_id: String,
+ pub binding_revision: u64,
+ pub binding_digest: CanonicalDigest,
+ pub source_id: String,
+ pub source_revision: u64,
+ pub source_identity_digest: CanonicalDigest,
+ pub connection_option_id: String,
+ pub offer_ref: String,
+ pub offer_revision: u64,
+ pub offer_evidence_digest: CanonicalDigest,
+ pub billing_class: BillingClass,
+ pub model_configuration_id: String,
+ pub model_configuration_revision: u64,
+ pub upstream_model_id: String,
+ pub native_transport_model: String,
+ pub capability_id: String,
+ pub capability_revision: u64,
+ pub capability_evidence_digest: CanonicalDigest,
+ pub connector_id: String,
+ pub connector_revision: u64,
+ pub endpoint_profile_id: String,
+ pub endpoint_profile_revision: u64,
+ pub protocol_endpoint_id: String,
+ pub endpoint: String,
+ pub connector_runtime: ConnectorRuntimeKind,
+ pub operational_target: GatewayOperationalTargetV1,
+ pub upstream_protocol: UpstreamProtocol,
+ pub credential_refs: Vec<String>,
+ pub credential_destination_ref: Option<String>,
+ pub credential_pool_id: Option<String>,
+ pub free_offer: Option<MaterializedFreeOfferRefV1>,
+ pub exact_reasoning: ExactNativeReasoningV1,
+ pub protocols: Vec<StoredProtocolChoiceV1>,
+}
+
+impl StoredCandidateV1 {
+ pub fn freeze(candidate: &AttemptOwnedCandidateV1) -> Result<Self, CompiledPlanError> {
+ candidate.validate()?;
+ Self::freeze_validated(candidate)
+ }
+
+ /// Projection for an already-validated immutable Plan, or for calculating a
+ /// provisional digest which the enclosing Plan must still authenticate.
+ pub(super) fn freeze_validated(
+ candidate: &AttemptOwnedCandidateV1,
+ ) -> Result<Self, CompiledPlanError> {
+ // Exhaustive destructuring makes a new runtime field an explicit storage decision.
+ let AttemptOwnedCandidateV1 {
+ binding_id,
+ binding_revision,
+ binding_digest,
+ source_id,
+ source_revision,
+ source_identity_digest,
+ connection_option_id,
+ offer_ref,
+ offer_revision,
+ offer_evidence_digest,
+ billing_class,
+ model_configuration_id,
+ model_configuration_revision,
+ upstream_model_id,
+ native_transport_model,
+ capability_id,
+ capability_revision,
+ capability_evidence_digest,
+ connector_id,
+ connector_revision,
+ endpoint_profile_id,
+ endpoint_profile_revision,
+ protocol_endpoint_id,
+ endpoint,
+ connector_runtime,
+ operational_target,
+ operational_target_digest,
+ protocol_profiles,
+ protocol_profile_digest,
+ upstream_protocol,
+ adapter_ref,
+ adapter_revision,
+ credential_refs,
+ credential_destination_ref,
+ credential_pool_id,
+ free_offer,
+ exact_reasoning,
+ } = candidate;
+ let _ = (
+ operational_target_digest,
+ protocol_profile_digest,
+ adapter_ref,
+ adapter_revision,
+ );
+ Ok(Self {
+ binding_id: binding_id.clone(),
+ binding_revision: *binding_revision,
+ binding_digest: binding_digest.clone(),
+ source_id: source_id.clone(),
+ source_revision: *source_revision,
+ source_identity_digest: source_identity_digest.clone(),
+ connection_option_id: connection_option_id.clone(),
+ offer_ref: offer_ref.clone(),
+ offer_revision: *offer_revision,
+ offer_evidence_digest: offer_evidence_digest.clone(),
+ billing_class: *billing_class,
+ model_configuration_id: model_configuration_id.clone(),
+ model_configuration_revision: *model_configuration_revision,
+ upstream_model_id: upstream_model_id.clone(),
+ native_transport_model: native_transport_model.clone(),
+ capability_id: capability_id.clone(),
+ capability_revision: *capability_revision,
+ capability_evidence_digest: capability_evidence_digest.clone(),
+ connector_id: connector_id.clone(),
+ connector_revision: *connector_revision,
+ endpoint_profile_id: endpoint_profile_id.clone(),
+ endpoint_profile_revision: *endpoint_profile_revision,
+ protocol_endpoint_id: protocol_endpoint_id.clone(),
+ endpoint: endpoint.clone(),
+ connector_runtime: *connector_runtime,
+ operational_target: operational_target.clone(),
+ upstream_protocol: *upstream_protocol,
+ credential_refs: credential_refs.clone(),
+ credential_destination_ref: credential_destination_ref.clone(),
+ credential_pool_id: credential_pool_id.clone(),
+ free_offer: free_offer.clone(),
+ exact_reasoning: exact_reasoning.clone(),
+ protocols: protocol_profiles
+ .iter()
+ .map(StoredProtocolChoiceV1::freeze)
+ .collect::<Result<_, _>>()?,
+ })
+ }
+
+ pub fn build(&self) -> Result<AttemptOwnedCandidateV1, CompiledPlanError> {
+ let candidate = self.build_for_plan()?;
+ candidate.validate()?;
+ Ok(candidate)
+ }
+
+ // Only StoredPlan calls this assembly path; seal_current validates the whole
+ // materialized Plan before an executable value can escape.
+ fn build_for_plan(&self) -> Result<AttemptOwnedCandidateV1, CompiledPlanError> {
+ let protocol_profiles = self
+ .protocols
+ .iter()
+ .map(StoredProtocolChoiceV1::build)
+ .collect::<Result<Vec<_>, _>>()?;
+ let candidate = AttemptOwnedCandidateV1 {
+ binding_id: self.binding_id.clone(),
+ binding_revision: self.binding_revision,
+ binding_digest: self.binding_digest.clone(),
+ source_id: self.source_id.clone(),
+ source_revision: self.source_revision,
+ source_identity_digest: self.source_identity_digest.clone(),
+ connection_option_id: self.connection_option_id.clone(),
+ offer_ref: self.offer_ref.clone(),
+ offer_revision: self.offer_revision,
+ offer_evidence_digest: self.offer_evidence_digest.clone(),
+ billing_class: self.billing_class,
+ model_configuration_id: self.model_configuration_id.clone(),
+ model_configuration_revision: self.model_configuration_revision,
+ upstream_model_id: self.upstream_model_id.clone(),
+ native_transport_model: self.native_transport_model.clone(),
+ capability_id: self.capability_id.clone(),
+ capability_revision: self.capability_revision,
+ capability_evidence_digest: self.capability_evidence_digest.clone(),
+ connector_id: self.connector_id.clone(),
+ connector_revision: self.connector_revision,
+ endpoint_profile_id: self.endpoint_profile_id.clone(),
+ endpoint_profile_revision: self.endpoint_profile_revision,
+ protocol_endpoint_id: self.protocol_endpoint_id.clone(),
+ endpoint: self.endpoint.clone(),
+ connector_runtime: self.connector_runtime,
+ operational_target: self.operational_target.clone(),
+ upstream_protocol: self.upstream_protocol,
+ credential_refs: self.credential_refs.clone(),
+ credential_destination_ref: self.credential_destination_ref.clone(),
+ credential_pool_id: self.credential_pool_id.clone(),
+ free_offer: self.free_offer.clone(),
+ exact_reasoning: self.exact_reasoning.clone(),
+ operational_target_digest: CanonicalDigest::of(&self.operational_target)
+ .map_err(|_| CompiledPlanError::Encoding)?,
+ protocol_profile_digest: CanonicalDigest::of(&protocol_profiles)
+ .map_err(|_| CompiledPlanError::Encoding)?,
+ protocol_profiles,
+ adapter_ref: format!("adapter/native/{}", protocol_name(self.upstream_protocol)),
+ adapter_revision: 1,
+ };
+ Ok(candidate)
+ }
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredGroupV1 {
+ pub group_id: MaterializedGroupId,
+ pub ordering_evidence: MaterializedOrderingV1,
+ pub pinned_ratings: BTreeMap<String, MaterializedRatingFactV1>,
+ pub candidates: Vec<StoredCandidateV1>,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredPlanV1 {
+ pub schema: String,
+ pub identity: AgentPlanIdentityV1,
+ pub revision: u64,
+ pub fact_refs: AgentPlanFactRefsV1,
+ pub request: RequestOwnedRouteV1,
+ pub limits: RoutingLimitsV1,
+ pub groups: Vec<StoredGroupV1>,
+}
+
+impl StoredPlanV1 {
+ pub fn freeze(plan: &CompiledAgentPlanV1) -> Result<Self, CompiledPlanError> {
+ plan.validate()?;
+ let m = &plan.body.materialized;
+ Ok(Self {
+ schema: STORED_PLAN_SCHEMA.into(),
+ identity: plan.body.identity.clone(),
+ revision: plan.body.agent_plan_revision,
+ fact_refs: m.fact_refs.clone(),
+ request: m.request_owned.clone(),
+ limits: m.attempt_owned.limits.clone(),
+ groups: m
+ .attempt_owned
+ .groups
+ .iter()
+ .map(|g| {
+ Ok(StoredGroupV1 {
+ group_id: g.group_id,
+ ordering_evidence: g.ordering_evidence.clone(),
+ pinned_ratings: g.pinned_ratings.clone(),
+ candidates: g
+ .candidates
+ .iter()
+ .map(StoredCandidateV1::freeze_validated)
+ .collect::<Result<_, _>>()?,
+ })
+ })
+ .collect::<Result<_, CompiledPlanError>>()?,
+ })
+ }
+
+ pub fn build(&self) -> Result<CompiledAgentPlanV1, CompiledPlanError> {
+ if self.schema != STORED_PLAN_SCHEMA {
+ return Err(CompiledPlanError::UnsupportedSchema);
+ }
+ let m = MaterializedAgentPlanV1 {
+ fact_refs: self.fact_refs.clone(),
+ request_owned: self.request.clone(),
+ attempt_owned: AttemptOwnedRouteV1 {
+ limits: self.limits.clone(),
+ groups: self
+ .groups
+ .iter()
+ .map(|g| {
+ Ok(MaterializedModelGroupV1 {
+ group_id: g.group_id,
+ ordering_evidence: g.ordering_evidence.clone(),
+ pinned_ratings: g.pinned_ratings.clone(),
+ candidates: g
+ .candidates
+ .iter()
+ .map(StoredCandidateV1::build_for_plan)
+ .collect::<Result<_, _>>()?,
+ })
+ })
+ .collect::<Result<_, CompiledPlanError>>()?,
+ },
+ };
+ CompiledAgentPlanV1::seal_current(CompiledAgentPlanBodyV1 {
+ schema: AGENT_PLAN_COMPILED_SCHEMA_V3.into(),
+ compiler_revision: AGENT_PLAN_COMPILER_REVISION_V3.into(),
+ identity: self.identity.clone(),
+ agent_plan_revision: self.revision,
+ materialized_route_digest: m.route_digest_for_sealing()?,
+ materialized: m,
+ })
+ }
+}
+
+pub mod plan_codec {
+ use super::*;
+ pub fn serialize<S: serde::Serializer>(
+ plan: &CompiledAgentPlanV1,
+ s: S,
+ ) -> Result<S::Ok, S::Error> {
+ StoredPlanV1::freeze(plan)
+ .map_err(serde::ser::Error::custom)?
+ .serialize(s)
+ }
+ pub fn deserialize<'de, D: serde::Deserializer<'de>>(
+ d: D,
+ ) -> Result<CompiledAgentPlanV1, D::Error> {
+ StoredPlanV1::deserialize(d)?
+ .build()
+ .map_err(serde::de::Error::custom)
+ }
+}
+
+/// Fixed-model grant binding codec; runtime candidate layout is never written to a grant.
+pub mod binding_codec {
+ use super::*;
+ pub fn serialize<S: serde::Serializer>(
+ binding: &AttemptOwnedCandidateV1,
+ s: S,
+ ) -> Result<S::Ok, S::Error> {
+ StoredCandidateV1::freeze(binding)
+ .map_err(serde::ser::Error::custom)?
+ .serialize(s)
+ }
+ pub fn deserialize<'de, D: serde::Deserializer<'de>>(
+ d: D,
+ ) -> Result<Box<AttemptOwnedCandidateV1>, D::Error> {
+ Ok(Box::new(
+ StoredCandidateV1::deserialize(d)?
+ .build()
+ .map_err(serde::de::Error::custom)?,
+ ))
+ }
+}
+
+#[cfg(test)]
+mod storage_tests {
+ use super::*;
+ fn fixture() -> CompiledAgentPlanV1 {
+ let input: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
+ serde_json::from_value::<crate::CompiledAgentPlanV1>(input["plans"][0].clone()).unwrap()
+ }
+ #[test]
+ fn runtime_revision_changes_do_not_change_stable_plan_or_route() {
+ let plan = fixture();
+ let facts = StoredPlanV1::freeze(&plan).unwrap();
+ let mut body = (*plan.body).clone();
+ for g in &mut body.materialized.attempt_owned.groups {
+ for c in &mut g.candidates {
+ c.adapter_ref = "another-internal-adapter".into();
+ c.adapter_revision += 1;
+ for p in &mut c.protocol_profiles {
+ p.path_id = "internal-path-revision".into();
+ p.serializer_revision = "serializer/revision2".into();
+ p.decoder_revision = "decoder/revision2".into();
+ p.capability.request.text = GatewayFidelityV1::Normalized;
+ p.capability.request.function_tools = GatewayFidelityV1::Unsupported;
+ p.capability.request.image_url = GatewayFidelityV1::Unsupported;
+ p.capability.response.text = GatewayFidelityV1::Normalized;
+ p.capability.response.stream_refusal =
+ GatewayStreamingRefusalSemanticsV1::Unsupported;
+ p.capability.native_provider_state =
+ GatewayNativeProviderStateEmissionV1::Never;
+ p.capability.context.estimator =
+ GatewayCriticalFactV1::Exact(GatewayTokenEstimatorProfileV1 {
+ revision: "estimator/revision2".into(),
+ bytes_per_token: 4,
+ fixed_overhead_tokens: 31,
+ });
+ for reasoning in &mut p.capability.reasoning_profiles {
+ reasoning.accounting = GatewayReasoningAccountingV1::Additive;
+ reasoning.additional_reservation_tokens = 13;
+ }
+ }
+ c.protocol_profile_digest = CanonicalDigest::of(&c.protocol_profiles).unwrap();
+ }
+ }
+ body.materialized_route_digest = body.materialized.route_digest().unwrap();
+ let changed = CompiledAgentPlanV1::seal_current(body).unwrap();
+ assert_ne!(plan.digest, changed.digest);
+ assert_eq!(facts, StoredPlanV1::freeze(&changed).unwrap());
+ assert_eq!(
+ plan.body.materialized_route_digest,
+ changed.body.materialized_route_digest
+ );
+ let restored: StoredPlanV1 =
+ serde_json::from_slice(&serde_json::to_vec(&facts).unwrap()).unwrap();
+ let rebuilt = restored.build().unwrap();
+ for g in &rebuilt.body.materialized.attempt_owned.groups {
+ for c in &g.candidates {
+ for p in &c.protocol_profiles {
+ assert_eq!(p.capability.request.text, GatewayFidelityV1::Exact);
+ assert_eq!(
+ p.capability.context.estimator.exact().unwrap().revision,
+ "byte-upper-bound/v1"
+ );
+ assert_eq!(
+ p.capability,
+ StoredModelCapabilitiesV1::freeze(&p.capability)
+ .compile(p.connector.upstream_protocol)
+ );
+ assert_ne!(
+ p.capability.response.stream_refusal,
+ GatewayStreamingRefusalSemanticsV1::Unsupported
+ );
+ assert!(p.capability.reasoning_profiles.iter().all(|r| r.accounting
+ == GatewayReasoningAccountingV1::WithinOutputCap
+ && r.additional_reservation_tokens == 0));
+ }
+ }
+ }
+ let encoded = serde_json::to_value(&facts).unwrap();
+ let capability = &encoded["groups"][0]["candidates"][0]["protocols"][0]["capability"];
+ for key in ["request", "response", "estimator", "native_provider_state"] {
+ assert!(
+ capability.get(key).is_none(),
+ "derived field {key} was stored"
+ );
+ }
+ assert_eq!(StoredPlanV1::freeze(&rebuilt).unwrap(), facts);
+ }
+ #[test]
+ fn stable_plan_detects_changed_choices_and_rejects_unknown_fields() {
+ let facts = StoredPlanV1::freeze(&fixture()).unwrap();
+ let mut changed = facts.clone();
+ changed.groups[0].candidates[0].credential_refs.reverse();
+ changed.groups[0].candidates[0].native_transport_model = "different-model".into();
+ assert_ne!(
+ CanonicalDigest::of(&facts).unwrap(),
+ CanonicalDigest::of(&changed).unwrap()
+ );
+ assert!(changed.build().is_err());
+ let mut raw = serde_json::to_value(&facts).unwrap();
+ raw["compiler_revision"] = serde_json::json!("injected");
+ assert!(serde_json::from_value::<StoredPlanV1>(raw).is_err());
+ }
+}
diff --git a/crates/domain/src/routing/stored_capability.rs b/crates/domain/src/routing/stored_capability.rs
new file mode 100644
index 00000000..5bc5f147
--- /dev/null
+++ b/crates/domain/src/routing/stored_capability.rs
@@ -0,0 +1,211 @@
+//! Model evidence and exact native reasoning parameters, independent of execution features.
+use super::*;
+use crate::UpstreamProtocol;
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredModelSupportV1 {
+ pub tools: GatewayCriticalFactV1<bool>,
+ pub vision: GatewayCriticalFactV1<bool>,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredModelCapabilitiesV1 {
+ pub capability_id: String,
+ pub capability_revision: String,
+ pub model_configuration_id: String,
+ pub native_model: String,
+ pub model_support: StoredModelSupportV1,
+ pub max_input_tokens: GatewayCriticalFactV1<u64>,
+ pub max_output_tokens: GatewayCriticalFactV1<u64>,
+ pub max_total_tokens: GatewayCriticalFactV1<Option<u64>>,
+ pub native_streaming: GatewayCriticalFactV1<bool>,
+ pub reasoning_profiles: Vec<StoredNativeReasoningV1>,
+ pub selected_reasoning_profile_id: String,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredNativeReasoningV1 {
+ pub profile_id: String,
+ pub control_kind: GatewayReasoningControlKindV1,
+ pub parameters: StoredReasoningParametersV1,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct StoredNativeParameterV1 {
+ pub path: Vec<String>,
+ pub value: GatewayNativeReasoningValueV1,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
+pub enum StoredReasoningParametersV1 {
+ NoControlParameter,
+ Fields {
+ protocol: UpstreamProtocol,
+ fields: Vec<StoredNativeParameterV1>,
+ },
+ Budget {
+ protocol: UpstreamProtocol,
+ fields: Vec<StoredNativeParameterV1>,
+ budget_path: Vec<String>,
+ selected_tokens: u64,
+ min_tokens: u64,
+ max_tokens: u64,
+ step_tokens: u64,
+ },
+}
+
+impl StoredModelCapabilitiesV1 {
+ pub fn freeze(capability: &GatewayCandidateCapabilityProfileV1) -> Self {
+ // Every new execution field must be classified; implementation fields stay out.
+ let GatewayCandidateCapabilityProfileV1 {
+ schema_version: _,
+ capability_id,
+ capability_revision,
+ upstream_protocol: _,
+ model_configuration_id,
+ native_model,
+ model_support,
+ request: _,
+ response: _,
+ reasoning_profiles,
+ selected_reasoning_profile_id,
+ context,
+ native_streaming,
+ native_provider_state: _,
+ } = capability;
+ let GatewayContextLimitsV1 {
+ max_input_tokens,
+ max_output_tokens,
+ max_total_tokens,
+ estimator: _,
+ } = context;
+ Self {
+ capability_id: capability_id.clone(),
+ capability_revision: capability_revision.clone(),
+ model_configuration_id: model_configuration_id.clone(),
+ native_model: native_model.clone(),
+ model_support: model_support.clone(),
+ max_input_tokens: max_input_tokens.clone(),
+ max_output_tokens: max_output_tokens.clone(),
+ max_total_tokens: max_total_tokens.clone(),
+ native_streaming: native_streaming.clone(),
+ reasoning_profiles: reasoning_profiles
+ .iter()
+ .map(StoredNativeReasoningV1::freeze)
+ .collect(),
+ selected_reasoning_profile_id: selected_reasoning_profile_id.clone(),
+ }
+ }
+}
+
+impl StoredNativeReasoningV1 {
+ pub fn freeze(profile: &GatewayReasoningProfileCapabilityV1) -> Self {
+ let GatewayReasoningProfileCapabilityV1 {
+ profile_id,
+ control_kind,
+ render,
+ accounting: _,
+ additional_reservation_tokens: _,
+ } = profile;
+ let fields = |fields: &[GatewayNativeReasoningFieldAssignmentV1]| {
+ fields
+ .iter()
+ .map(|field| {
+ let GatewayNativeReasoningFieldAssignmentV1 { path, value } = field;
+ StoredNativeParameterV1 {
+ path: path.clone(),
+ value: value.clone(),
+ }
+ })
+ .collect()
+ };
+ let parameters = match render {
+ GatewayNativeReasoningRenderV1::NoControlParameter => {
+ StoredReasoningParametersV1::NoControlParameter
+ }
+ GatewayNativeReasoningRenderV1::ExactFields {
+ protocol,
+ fields: assignments,
+ } => StoredReasoningParametersV1::Fields {
+ protocol: *protocol,
+ fields: fields(assignments),
+ },
+ GatewayNativeReasoningRenderV1::ExactBudget {
+ protocol,
+ fields: assignments,
+ budget_path,
+ selected_tokens,
+ min_tokens,
+ max_tokens,
+ step_tokens,
+ } => StoredReasoningParametersV1::Budget {
+ protocol: *protocol,
+ fields: fields(assignments),
+ budget_path: budget_path.clone(),
+ selected_tokens: *selected_tokens,
+ min_tokens: *min_tokens,
+ max_tokens: *max_tokens,
+ step_tokens: *step_tokens,
+ },
+ };
+ Self {
+ profile_id: profile_id.clone(),
+ control_kind: *control_kind,
+ parameters,
+ }
+ }
+
+ pub(super) fn compile(&self) -> GatewayReasoningProfileCapabilityV1 {
+ let fields = |fields: &[StoredNativeParameterV1]| {
+ fields
+ .iter()
+ .map(|field| GatewayNativeReasoningFieldAssignmentV1 {
+ path: field.path.clone(),
+ value: field.value.clone(),
+ })
+ .collect()
+ };
+ let render = match &self.parameters {
+ StoredReasoningParametersV1::NoControlParameter => {
+ GatewayNativeReasoningRenderV1::NoControlParameter
+ }
+ StoredReasoningParametersV1::Fields {
+ protocol,
+ fields: assignments,
+ } => GatewayNativeReasoningRenderV1::ExactFields {
+ protocol: *protocol,
+ fields: fields(assignments),
+ },
+ StoredReasoningParametersV1::Budget {
+ protocol,
+ fields: assignments,
+ budget_path,
+ selected_tokens,
+ min_tokens,
+ max_tokens,
+ step_tokens,
+ } => GatewayNativeReasoningRenderV1::ExactBudget {
+ protocol: *protocol,
+ fields: fields(assignments),
+ budget_path: budget_path.clone(),
+ selected_tokens: *selected_tokens,
+ min_tokens: *min_tokens,
+ max_tokens: *max_tokens,
+ step_tokens: *step_tokens,
+ },
+ };
+ GatewayReasoningProfileCapabilityV1 {
+ profile_id: self.profile_id.clone(),
+ control_kind: self.control_kind,
+ render,
+ accounting: GatewayReasoningAccountingV1::WithinOutputCap,
+ additional_reservation_tokens: 0,
+ }
+ }
+}
diff --git a/crates/gateway/src/core_runtime.rs b/crates/gateway/src/core_runtime.rs
index 1462667b..011439ec 100644
--- a/crates/gateway/src/core_runtime.rs
+++ b/crates/gateway/src/core_runtime.rs
@@ -69,6 +69,7 @@ use self::observation::{
#[derive(Clone)]
pub struct ProductionGatewayRuntime {
+ upgrade: Arc<hiroute_host_runtime::UpgradeDrain>,
publications: Arc<dyn RuntimePublicationFeed>,
authority: GatewayRequestAuthority,
catalog: GatewayCatalog,
@@ -136,6 +137,7 @@ impl ProductionGatewayRuntime {
.expect("static production lifecycle limits are valid"),
);
Self {
+ upgrade: Arc::new(hiroute_host_runtime::UpgradeDrain::default()),
authority: GatewayRequestAuthority::from_feed(Arc::clone(&publications)),
catalog: GatewayCatalog::from_feed(Arc::clone(&publications)),
publications,
@@ -157,6 +159,11 @@ impl ProductionGatewayRuntime {
self
}
+ pub fn with_upgrade_drain(mut self, upgrade: Arc<hiroute_host_runtime::UpgradeDrain>) -> Self {
+ self.upgrade = upgrade;
+ self
+ }
+
/// Adds the narrow delegated-run branch without changing ordinary publication authority.
pub fn with_run_request_authority(
mut self,
@@ -230,6 +237,15 @@ impl GatewayLifecycle for ProductionGatewayRuntime {
}
let authorization = inbound_authorization(path, &request.headers);
let authorization = authorization.as_deref();
+ // Existing delegated runs still need model calls to finish. The ordinary run bearer
+ // verifier below remains the authority; this prefix never authorizes an aggregate call.
+ let Some(_upgrade_call) = self
+ .upgrade
+ .enter(authorization.is_some_and(|a| a.starts_with("Bearer hr_run_model_")))
+ else {
+ return write_typed_error(session, StatusCode::SERVICE_UNAVAILABLE, "UPGRADE_WAITING")
+ .await;
+ };
let declared_content_length = request
.headers
.get(CONTENT_LENGTH)
diff --git a/crates/gateway/src/profiles/capability.rs b/crates/gateway/src/profiles/capability.rs
index 7bffc45b..09e14ffa 100644
--- a/crates/gateway/src/profiles/capability.rs
+++ b/crates/gateway/src/profiles/capability.rs
@@ -76,6 +76,7 @@ pub struct CandidateCapabilityProfile {
pub upstream_protocol: IngressProtocol,
pub model_configuration_id: String,
pub native_model: String,
+ pub model_support: hiroute_domain::StoredModelSupportV1,
pub request: RequestFeatureProfile,
pub response: ResponseFeatureProfile,
pub reasoning_profiles: Vec<ReasoningProfileCapability>,
@@ -154,6 +155,10 @@ impl CandidateProtocolProfile {
upstream_protocol,
model_configuration_id: format!("fixture-model-config-{protocol_name}"),
native_model,
+ model_support: hiroute_domain::StoredModelSupportV1 {
+ tools: hiroute_domain::GatewayCriticalFactV1::Exact(true),
+ vision: hiroute_domain::GatewayCriticalFactV1::Exact(true),
+ },
request: RequestFeatureProfile {
text: exact,
initial_instructions: exact,
diff --git a/crates/gateway/src/publication/installer.rs b/crates/gateway/src/publication/installer.rs
index d0ba88c2..9834dc93 100644
--- a/crates/gateway/src/publication/installer.rs
+++ b/crates/gateway/src/publication/installer.rs
@@ -19,6 +19,17 @@ use super::{
const CORE_INSTALL_DEADLINE: Duration = Duration::from_secs(5);
const DURABLE_PUBLICATION_SCHEMA: &str = "hiroute.gateway.durable-publication/v1";
+const CACHE_SCHEMA: &str = "hiroute.gateway.publication-cache/v1";
+const CACHE_COMPILER: &str = "hiroute.gateway-cache-compiler/v1";
+#[derive(serde::Serialize, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+struct PublicationCache {
+ schema_version: String,
+ compiler_revision: String,
+ source_publication_digest: String,
+ snapshot_sha256: String,
+ snapshot: GatewayPublicationSnapshotV3,
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct DurablePublicationState {
@@ -186,6 +197,28 @@ pub struct GatewayPublicationInstaller {
}
impl GatewayPublicationInstaller {
+ /// Product startup resolves its authoritative publication and installation decision from
+ /// control.db. A cache, including a stale or corrupt cache, never grants initial admission.
+ pub fn open_for_product_authority(
+ path: impl AsRef<Path>,
+ ) -> Result<Self, PublicationInstallError> {
+ let path = path.as_ref();
+ if path.file_name().is_none() {
+ return Err(PublicationInstallError::InvalidLkgPath);
+ }
+ Ok(Self::empty(path.to_path_buf()))
+ }
+
+ fn empty(path: PathBuf) -> Self {
+ Self {
+ lkg_path: path,
+ core: Arc::new(PublicationInstaller::new()),
+ active: AtomicPublicationSlot::empty(),
+ pending: Arc::new(AtomicBool::new(false)),
+ durability_uncertain: AtomicBool::new(false),
+ publish_gate: Mutex::new(()),
+ }
+ }
/// Opens a durable aggregate feed. A missing LKG is a valid unavailable
/// starting state; an existing but invalid LKG fails closed.
pub fn open(path: impl AsRef<Path>) -> Result<Self, PublicationInstallError> {
@@ -196,14 +229,7 @@ impl GatewayPublicationInstaller {
} else {
None
};
- let installer = Self {
- lkg_path: path.clone(),
- core: Arc::new(PublicationInstaller::new()),
- active: AtomicPublicationSlot::empty(),
- pending: Arc::new(AtomicBool::new(false)),
- durability_uncertain: AtomicBool::new(false),
- publish_gate: Mutex::new(()),
- };
+ let installer = Self::empty(path);
if let Some(snapshot) = restored {
let prepared = match installer.prepare(snapshot)? {
GatewayPrepareOutcome::Prepared(prepared) => prepared,
@@ -387,13 +413,17 @@ impl GatewayPublicationInstaller {
// after restart; the Gateway LKG stores only execution semantics.
let mut durable_snapshot = snapshot.clone();
durable_snapshot.clear_pricing_identities();
- let durable = encode_durable_state(&durable_snapshot);
+ let durable = encode_durable_state(&durable_snapshot)?;
let mut bytes = serde_json::to_vec(&durable).map_err(PublicationInstallError::Json)?;
bytes.push(b'\n');
- let mut file = OpenOptions::new()
- .create(true)
- .truncate(true)
- .write(true)
+ let mut options = OpenOptions::new();
+ options.create(true).truncate(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options
.open(&temporary)
.map_err(PublicationInstallError::Io)?;
file.write_all(&bytes)
@@ -414,17 +444,35 @@ impl GatewayPublicationInstaller {
}
}
-fn encode_durable_state(snapshot: &GatewayPublicationSnapshotV3) -> DurablePublicationState {
- DurablePublicationState {
- schema_version: DURABLE_PUBLICATION_SCHEMA.into(),
+fn encode_durable_state(
+ snapshot: &GatewayPublicationSnapshotV3,
+) -> Result<PublicationCache, PublicationInstallError> {
+ let bytes = serde_json::to_string(snapshot).map_err(PublicationInstallError::Json)?;
+ Ok(PublicationCache {
+ schema_version: CACHE_SCHEMA.into(),
+ compiler_revision: CACHE_COMPILER.into(),
+ source_publication_digest: snapshot.payload_digest.clone(),
+ snapshot_sha256: token_sha256(&bytes),
snapshot: snapshot.clone(),
- agent_plan_revisions: Vec::new(),
- }
+ })
}
fn decode_durable_state(
bytes: &[u8],
) -> Result<GatewayPublicationSnapshotV3, PublicationInstallError> {
+ if let Ok(cache) = serde_json::from_slice::<PublicationCache>(bytes) {
+ let snapshot =
+ serde_json::to_string(&cache.snapshot).map_err(PublicationInstallError::Json)?;
+ if cache.schema_version != CACHE_SCHEMA
+ || cache.compiler_revision != CACHE_COMPILER
+ || cache.source_publication_digest != cache.snapshot.payload_digest
+ || cache.snapshot_sha256 != token_sha256(&snapshot)
+ {
+ return Err(PublicationInstallError::InvalidDurableState);
+ }
+ cache.snapshot.validate()?;
+ return Ok(cache.snapshot);
+ }
let durable: DurablePublicationState =
serde_json::from_slice(bytes).map_err(PublicationInstallError::Json)?;
if durable.schema_version != DURABLE_PUBLICATION_SCHEMA {
diff --git a/crates/gateway/src/publication/tests.rs b/crates/gateway/src/publication/tests.rs
index deba869c..45272d16 100644
--- a/crates/gateway/src/publication/tests.rs
+++ b/crates/gateway/src/publication/tests.rs
@@ -12,6 +12,27 @@ use crate::server::request_plan::IngressProtocol;
static DIRECTORY_SEQUENCE: AtomicUsize = AtomicUsize::new(0);
+#[test]
+fn domain_gateway_profile_roundtrip_preserves_model_evidence() {
+ use crate::server::core_runtime::profiles::CandidateProtocolProfile;
+ use hiroute_domain::{
+ GatewayCandidateProtocolProfileV1, GatewayCriticalFactV1, GatewayFidelityV1,
+ };
+ let mut profile = candidate(1).protocol_profiles.remove(0);
+ profile.capability.model_support.tools = GatewayCriticalFactV1::Exact(true);
+ profile.capability.model_support.vision = GatewayCriticalFactV1::Exact(false);
+ // Current implementation fidelity is independent of the model's frozen support.
+ profile.capability.request.function_tools = GatewayFidelityV1::Unsupported;
+ let gateway: CandidateProtocolProfile =
+ serde_json::from_value(serde_json::to_value(&profile).unwrap()).unwrap();
+ let restored: GatewayCandidateProtocolProfileV1 =
+ serde_json::from_value(serde_json::to_value(&gateway).unwrap()).unwrap();
+ assert_eq!(profile, restored);
+ let mut raw = serde_json::to_value(&profile).unwrap();
+ raw["capability"]["unknown_execution_field"] = serde_json::json!(true);
+ assert!(serde_json::from_value::<CandidateProtocolProfile>(raw).is_err());
+}
+
#[test]
fn published_attempt_phases_default_to_ten_minutes() {
let aggregate = super::compiler::compile(&snapshot(1, "renderer")).unwrap();
diff --git a/crates/gateway/src/publication/tests/grant_projection.rs b/crates/gateway/src/publication/tests/grant_projection.rs
index 15eda303..5263f468 100644
--- a/crates/gateway/src/publication/tests/grant_projection.rs
+++ b/crates/gateway/src/publication/tests/grant_projection.rs
@@ -32,8 +32,8 @@ fn active_plan_revision_accepts_grant_reachable_protocol_expansion() {
let directory = TestDirectory::new();
let lkg = directory.path().join("publication.json");
let installer = GatewayPublicationInstaller::open(&lkg).unwrap();
- let product = hiroute_domain::GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let product = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
let mut initial: GatewayPublicationSnapshotV3 =
@@ -94,8 +94,8 @@ fn restored_plan_can_serve_codex_and_claude_without_a_new_plan_revision() {
let directory = TestDirectory::new();
let lkg = directory.path().join("publication.json");
let installer = GatewayPublicationInstaller::open(&lkg).unwrap();
- let product = hiroute_domain::GatewayPublicationV1::decode_persisted(include_bytes!(
- "../../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let product = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(include_bytes!(
+ "../../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
let initial: GatewayPublicationSnapshotV3 =
diff --git a/crates/host-runtime/Cargo.toml b/crates/host-runtime/Cargo.toml
index 44231fd2..bdc20909 100644
--- a/crates/host-runtime/Cargo.toml
+++ b/crates/host-runtime/Cargo.toml
@@ -10,6 +10,8 @@ getrandom.workspace = true
nix.workspace = true
serde.workspace = true
serde_json.workspace = true
+semver.workspace = true
+sha2.workspace = true
thiserror.workspace = true
[dev-dependencies]
diff --git a/crates/host-runtime/src/desktop_package.rs b/crates/host-runtime/src/desktop_package.rs
new file mode 100644
index 00000000..54ee8638
--- /dev/null
+++ b/crates/host-runtime/src/desktop_package.rs
@@ -0,0 +1,414 @@
+//! The existing full-App inventory is shared by update installation and manual recovery.
+use crate::DesktopRelease;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::{
+ collections::BTreeMap,
+ fs,
+ io::Read,
+ path::{Component, Path, PathBuf},
+};
+
+const COMPONENTS: [&str; 4] = ["hiroute-desktop", "hirouted", "hiroute", "cliproxyapi"];
+const INVENTORY: &str = "Contents/Resources/installation.json";
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct DesktopPackageIdentity {
+ pub app_path: PathBuf,
+ pub version: String,
+ pub revision: String,
+ pub architecture: String,
+ pub distribution: String,
+ pub inventory_sha256: String,
+ pub binaries: BTreeMap<String, String>,
+}
+
+pub fn file_sha256(path: &Path) -> Result<String, &'static str> {
+ let mut file = regular_file(path)?;
+ let mut hasher = Sha256::new();
+ let mut buffer = [0u8; 64 * 1024];
+ loop {
+ let count = file.read(&mut buffer).map_err(|_| "PACKAGE_READ_FAILED")?;
+ if count == 0 {
+ break;
+ }
+ hasher.update(&buffer[..count]);
+ }
+ Ok(format!("{:x}", hasher.finalize()))
+}
+fn regular_file(path: &Path) -> Result<fs::File, &'static str> {
+ let mut options = fs::OpenOptions::new();
+ options.read(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.custom_flags(nix::libc::O_NOFOLLOW | nix::libc::O_NONBLOCK);
+ }
+ let file = options.open(path).map_err(|_| "PACKAGE_READ_FAILED")?;
+ if !file
+ .metadata()
+ .map_err(|_| "PACKAGE_READ_FAILED")?
+ .is_file()
+ {
+ return Err("PACKAGE_FILE_INVALID");
+ }
+ Ok(file)
+}
+fn bounded_json(path: &Path) -> Result<serde_json::Value, &'static str> {
+ let mut bytes = Vec::new();
+ regular_file(path)?
+ .take(1024 * 1024 + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|_| "PACKAGE_READ_FAILED")?;
+ if bytes.len() > 1024 * 1024 {
+ return Err("PACKAGE_INVENTORY_INVALID");
+ }
+ serde_json::from_slice(&bytes).map_err(|_| "PACKAGE_INVENTORY_INVALID")
+}
+fn text<'a>(value: &'a serde_json::Value, field: &str) -> Result<&'a str, &'static str> {
+ value[field]
+ .as_str()
+ .filter(|s| !s.is_empty())
+ .ok_or("PACKAGE_INVENTORY_INVALID")
+}
+fn sha(value: &str) -> bool {
+ value.len() == 64
+ && value
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+}
+fn inventory(
+ root: &Path,
+ path: &Path,
+ files: &mut BTreeMap<String, String>,
+) -> Result<(), &'static str> {
+ let metadata = fs::symlink_metadata(path).map_err(|_| "PACKAGE_READ_FAILED")?;
+ if metadata.file_type().is_symlink() {
+ return Err("PACKAGE_SYMLINK_DENIED");
+ }
+ if metadata.is_dir() {
+ for entry in fs::read_dir(path).map_err(|_| "PACKAGE_READ_FAILED")? {
+ let entry = entry.map_err(|_| "PACKAGE_READ_FAILED")?;
+ inventory(root, &entry.path(), files)?;
+ }
+ } else if metadata.is_file() {
+ let relative = path
+ .strip_prefix(root)
+ .map_err(|_| "PACKAGE_INVENTORY_INVALID")?;
+ if relative
+ .components()
+ .any(|c| c == Component::Normal("_CodeSignature".as_ref()))
+ || relative == Path::new("Contents/MacOS/hiroute-desktop")
+ || relative == Path::new(INVENTORY)
+ {
+ return Ok(());
+ }
+ let name = relative
+ .to_str()
+ .ok_or("PACKAGE_INVENTORY_INVALID")?
+ .to_owned();
+ files.insert(name, file_sha256(path)?);
+ } else {
+ return Err("PACKAGE_FILE_INVALID");
+ }
+ Ok(())
+}
+
+/// Validates the producer's closed inventory and every component byte. No App executable is run.
+/// macOS hosts additionally validate the code signature below before installing a new App.
+pub fn read_desktop_package_identity(app: &Path) -> Result<DesktopPackageIdentity, &'static str> {
+ if !app.is_absolute()
+ || fs::symlink_metadata(app)
+ .map_err(|_| "PACKAGE_READ_FAILED")?
+ .file_type()
+ .is_symlink()
+ {
+ return Err("PACKAGE_PATH_INVALID");
+ }
+ let app = fs::canonicalize(app).map_err(|_| "PACKAGE_PATH_INVALID")?;
+ let value = bounded_json(&app.join(INVENTORY))?;
+ let version = text(&value, "version")?;
+ semver::Version::parse(version).map_err(|_| "PACKAGE_VERSION_INVALID")?;
+ let revision = text(&value, "revision")?;
+ if revision.len() != 40
+ || !revision
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+ {
+ return Err("PACKAGE_REVISION_INVALID");
+ }
+ let architecture = text(&value, "architecture")?;
+ let target = match architecture {
+ "arm64" => "aarch64-apple-darwin",
+ "x86_64" => "x86_64-apple-darwin",
+ _ => return Err("PACKAGE_PLATFORM_INVALID"),
+ };
+ let distribution = text(&value, "distribution")?;
+ if text(&value, "target")? != target
+ || !matches!(distribution, "controlled-trial" | "developer-id")
+ {
+ return Err("PACKAGE_PLATFORM_INVALID");
+ }
+ let expected: BTreeMap<String, String> =
+ serde_json::from_value(value["files"].clone()).map_err(|_| "PACKAGE_INVENTORY_INVALID")?;
+ if expected.is_empty()
+ || expected.len() > 10000
+ || expected.iter().any(|(p, d)| {
+ let path = Path::new(p);
+ !sha(d)
+ || path.is_absolute()
+ || !p.starts_with("Contents/")
+ || path
+ .components()
+ .any(|c| !matches!(c, Component::Normal(_)))
+ })
+ {
+ return Err("PACKAGE_INVENTORY_INVALID");
+ }
+ let mut actual = BTreeMap::new();
+ inventory(&app, &app, &mut actual)?;
+ if actual != expected {
+ return Err("PACKAGE_INVENTORY_MISMATCH");
+ }
+ let binary_manifest = value["binaries"]
+ .as_object()
+ .ok_or("PACKAGE_COMPONENT_INVALID")?;
+ if binary_manifest.len() != COMPONENTS.len() {
+ return Err("PACKAGE_COMPONENT_INVALID");
+ }
+ let mut binaries = BTreeMap::new();
+ for name in COMPONENTS {
+ let path = app.join("Contents/MacOS").join(name);
+ let record = binary_manifest
+ .get(name)
+ .ok_or("PACKAGE_COMPONENT_INVALID")?;
+ let hash = file_sha256(&path)?;
+ if record["architecture"] != architecture
+ || (name != "hiroute-desktop"
+ && (record["sha256"] != hash
+ || record["size"].as_u64()
+ != Some(
+ regular_file(&path)?
+ .metadata()
+ .map_err(|_| "PACKAGE_READ_FAILED")?
+ .len(),
+ )))
+ {
+ return Err("PACKAGE_COMPONENT_MISMATCH");
+ }
+ binaries.insert(name.into(), hash);
+ }
+ let cpa = &value["cpa"]["artifacts"];
+ if cpa.as_array().is_none_or(|a| a.len() != 1) || cpa[0]["sha256"] != binaries["cliproxyapi"] {
+ return Err("PACKAGE_COMPONENT_MISMATCH");
+ }
+ Ok(DesktopPackageIdentity {
+ app_path: app.clone(),
+ version: version.into(),
+ revision: revision.into(),
+ architecture: architecture.into(),
+ distribution: distribution.into(),
+ inventory_sha256: file_sha256(&app.join(INVENTORY))?,
+ binaries,
+ })
+}
+
+#[cfg(target_os = "macos")]
+fn tool(program: &str, args: &[&std::ffi::OsStr]) -> Result<String, &'static str> {
+ let output = std::process::Command::new(program)
+ .args(args)
+ .output()
+ .map_err(|_| "PACKAGE_VERIFY_FAILED")?;
+ if !output.status.success() {
+ return Err("PACKAGE_VERIFY_FAILED");
+ }
+ let mut bytes = output.stdout;
+ bytes.extend(output.stderr);
+ String::from_utf8(bytes).map_err(|_| "PACKAGE_VERIFY_FAILED")
+}
+
+#[cfg(target_os = "macos")]
+pub fn verify_desktop_app(
+ app: &Path,
+ bundle_id: &str,
+ release: Option<&DesktopRelease>,
+ expected_team: Option<&str>,
+) -> Result<DesktopPackageIdentity, &'static str> {
+ let identity = read_desktop_package_identity(app)?;
+ if let Some(release) = release {
+ let distribution = if release.distribution == "self-signed" {
+ "controlled-trial"
+ } else {
+ "developer-id"
+ };
+ if identity.version != release.version
+ || !identity.revision.starts_with(release.revision_prefix()?)
+ || identity.architecture != release.architecture
+ || identity.distribution != distribution
+ {
+ return Err("UPGRADE_PACKAGE_IDENTITY_MISMATCH");
+ }
+ }
+ use std::ffi::OsStr as O;
+ let info = identity.app_path.join("Contents/Info.plist");
+ let read_info = |key: &str| {
+ tool(
+ "/usr/bin/plutil",
+ &[
+ O::new("-extract"),
+ O::new(key),
+ O::new("raw"),
+ O::new("-o"),
+ O::new("-"),
+ info.as_os_str(),
+ ],
+ )
+ };
+ if read_info("CFBundleIdentifier")?.trim() != bundle_id
+ || read_info("CFBundleShortVersionString")?.trim() != identity.version
+ || read_info("LSMinimumSystemVersion")?.trim() != "15.0"
+ {
+ return Err("PACKAGE_BUNDLE_IDENTITY_MISMATCH");
+ }
+ for name in COMPONENTS {
+ let binary = identity.app_path.join("Contents/MacOS").join(name);
+ tool(
+ "/usr/bin/codesign",
+ &[O::new("--verify"), O::new("--strict"), binary.as_os_str()],
+ )?;
+ if tool("/usr/bin/lipo", &[O::new("-archs"), binary.as_os_str()])?.trim()
+ != identity.architecture
+ {
+ return Err("PACKAGE_PLATFORM_INVALID");
+ }
+ }
+ tool(
+ "/usr/bin/codesign",
+ &[
+ O::new("--verify"),
+ O::new("--strict"),
+ identity.app_path.as_os_str(),
+ ],
+ )?;
+ let signature = tool(
+ "/usr/bin/codesign",
+ &[
+ O::new("--display"),
+ O::new("--verbose=4"),
+ identity.app_path.as_os_str(),
+ ],
+ )?;
+ if identity.distribution == "controlled-trial" {
+ if !signature.lines().any(|l| l == "Signature=adhoc") {
+ return Err("PACKAGE_SIGNATURE_IDENTITY_MISMATCH");
+ }
+ } else {
+ let team = expected_team.ok_or("UPGRADE_SIGNATURE_IDENTITY_UNCONFIGURED")?;
+ if !signature
+ .lines()
+ .any(|l| l == format!("TeamIdentifier={team}"))
+ || !signature.contains("Authority=Developer ID Application:")
+ {
+ return Err("PACKAGE_SIGNATURE_IDENTITY_MISMATCH");
+ }
+ tool(
+ "/usr/sbin/spctl",
+ &[
+ O::new("--assess"),
+ O::new("--type"),
+ O::new("execute"),
+ identity.app_path.as_os_str(),
+ ],
+ )?;
+ }
+ Ok(identity)
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn verify_desktop_app(
+ _: &Path,
+ _: &str,
+ _: Option<&DesktopRelease>,
+ _: Option<&str>,
+) -> Result<DesktopPackageIdentity, &'static str> {
+ Err("UPGRADE_PLATFORM_UNSUPPORTED")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn package() -> tempfile::TempDir {
+ let directory = tempfile::tempdir().unwrap();
+ let app = directory.path();
+ fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
+ fs::create_dir_all(app.join("Contents/Resources")).unwrap();
+ let mut binaries = serde_json::Map::new();
+ for name in COMPONENTS {
+ let path = app.join("Contents/MacOS").join(name);
+ fs::write(&path, name.as_bytes()).unwrap();
+ let mut value = serde_json::json!({"architecture":"arm64"});
+ if name != "hiroute-desktop" {
+ value["sha256"] = file_sha256(&path).unwrap().into();
+ value["size"] = (name.len() as u64).into();
+ }
+ binaries.insert(name.into(), value);
+ }
+ fs::write(app.join("Contents/Info.plist"), b"fixture bundle identity").unwrap();
+ let mut files = BTreeMap::new();
+ inventory(app, app, &mut files).unwrap();
+ let cpa_sha = binaries["cliproxyapi"]["sha256"].clone();
+ let value = serde_json::json!({"version":"0.1.0","revision":"a".repeat(40),
+ "architecture":"arm64","target":"aarch64-apple-darwin","distribution":"controlled-trial",
+ "binaries":binaries,"files":files,"cpa":{"artifacts":[{"sha256":cpa_sha}]}});
+ fs::write(app.join(INVENTORY), serde_json::to_vec(&value).unwrap()).unwrap();
+ directory
+ }
+ #[test]
+ fn upgrade_package_inventory_rejects_changed_and_extra_components() {
+ let good = package();
+ let identity = read_desktop_package_identity(good.path()).unwrap();
+ assert_eq!(identity.binaries.len(), 4);
+ fs::write(
+ good.path().join("Contents/MacOS/hirouted"),
+ b"modified daemon",
+ )
+ .unwrap();
+ assert_eq!(
+ read_desktop_package_identity(good.path()).unwrap_err(),
+ "PACKAGE_INVENTORY_MISMATCH"
+ );
+ let extra = package();
+ fs::write(
+ extra.path().join("Contents/MacOS/other-service"),
+ b"extra executable",
+ )
+ .unwrap();
+ assert_eq!(
+ read_desktop_package_identity(extra.path()).unwrap_err(),
+ "PACKAGE_INVENTORY_MISMATCH"
+ );
+ }
+ #[test]
+ #[cfg(unix)]
+ fn upgrade_package_inventory_rejects_links_and_escaping_manifest_paths() {
+ let linked = package();
+ let daemon = linked.path().join("Contents/MacOS/hirouted");
+ fs::remove_file(&daemon).unwrap();
+ std::os::unix::fs::symlink("hiroute", &daemon).unwrap();
+ assert_eq!(
+ read_desktop_package_identity(linked.path()).unwrap_err(),
+ "PACKAGE_SYMLINK_DENIED"
+ );
+ let invalid = package();
+ let path = invalid.path().join(INVENTORY);
+ let mut manifest: serde_json::Value =
+ serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
+ manifest["files"]["Contents/../../outside"] = "a".repeat(64).into();
+ fs::write(path, serde_json::to_vec(&manifest).unwrap()).unwrap();
+ assert_eq!(
+ read_desktop_package_identity(invalid.path()).unwrap_err(),
+ "PACKAGE_INVENTORY_INVALID"
+ );
+ }
+}
diff --git a/crates/host-runtime/src/lib.rs b/crates/host-runtime/src/lib.rs
index dff9e9e7..225497e5 100644
--- a/crates/host-runtime/src/lib.rs
+++ b/crates/host-runtime/src/lib.rs
@@ -6,8 +6,17 @@
//! owns only the one listener record and one standalone installation/layout contract that are
//! consumed by all current native entrypoints.
+mod desktop_package;
mod gateway_listener;
+mod releases;
mod standalone;
+mod upgrade;
+pub use desktop_package::*;
pub use gateway_listener::*;
+pub use releases::*;
pub use standalone::*;
+pub use upgrade::*;
+
+mod storage_progress;
+pub use storage_progress::StorageUpgradePhase;
diff --git a/crates/host-runtime/src/releases.rs b/crates/host-runtime/src/releases.rs
new file mode 100644
index 00000000..119070b0
--- /dev/null
+++ b/crates/host-runtime/src/releases.rs
@@ -0,0 +1,318 @@
+//! Read the website's one current release catalog; URLs are native-derived, never IPC input.
+use semver::Version;
+use serde::{Deserialize, Serialize};
+
+pub const RELEASE_FEED: &str = "https://hiroute.ai/releases.json";
+pub const MAX_RELEASE_FEED_BYTES: usize = 1024 * 1024;
+
+#[derive(Clone, Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct WebsiteReleasesV2 {
+ schema: String,
+ releases: Vec<WebsiteReleaseV2>,
+}
+#[derive(Clone, Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct WebsiteReleaseV2 {
+ version: String,
+ channel: String,
+ published_at: String,
+ notes: ReleaseNotes,
+ artifacts: Vec<ReleaseArtifactV2>,
+}
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ReleaseNotes {
+ pub zh: String,
+ pub en: String,
+}
+#[derive(Clone, Debug, Deserialize)]
+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
+enum ReleaseArtifactV2 {
+ Desktop {
+ platform: String,
+ architecture: String,
+ format: String,
+ minimum_os: String,
+ distribution: String,
+ filename: String,
+ sha256: String,
+ size: u64,
+ },
+ Standalone {
+ platform: String,
+ architecture: String,
+ target: String,
+ format: String,
+ distribution: String,
+ filename: String,
+ sha256: String,
+ size: u64,
+ manifest_filename: String,
+ manifest_sha256: String,
+ manifest_size: u64,
+ },
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct DesktopRelease {
+ pub version: String,
+ pub notes: ReleaseNotes,
+ pub architecture: String,
+ pub distribution: String,
+ pub filename: String,
+ pub sha256: String,
+ pub size: u64,
+}
+impl DesktopRelease {
+ pub fn download_url(&self) -> String {
+ format!(
+ "https://hiroute.ai/releases/{}/{}",
+ self.version, self.filename
+ )
+ }
+ pub fn revision_prefix(&self) -> Result<&str, &'static str> {
+ let prefix = format!("HiRoute-{}-", self.version);
+ let suffix = match self.distribution.as_str() {
+ "self-signed" => "trial",
+ "developer-id" => "developer-id",
+ _ => return Err("UPGRADE_ARTIFACT_INVALID"),
+ };
+ let tail = format!("-macos-{}-{suffix}.dmg", self.architecture);
+ let revision = self
+ .filename
+ .strip_prefix(&prefix)
+ .and_then(|s| s.strip_suffix(&tail))
+ .ok_or("UPGRADE_ARTIFACT_INVALID")?;
+ if semver::Version::parse(&self.version).is_err()
+ || !matches!(self.architecture.as_str(), "arm64" | "x86_64")
+ || !sized_digest(&self.filename, &self.sha256, self.size)
+ || revision.len() != 12
+ || !revision
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+ {
+ return Err("UPGRADE_ARTIFACT_INVALID");
+ }
+ Ok(revision)
+ }
+}
+fn digest(value: &str) -> bool {
+ value.len() == 64
+ && value
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+}
+fn filename(value: &str) -> bool {
+ !value.is_empty()
+ && value.len() <= 240
+ && value
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
+}
+fn sized_digest(name: &str, sha: &str, size: u64) -> bool {
+ filename(name) && digest(sha) && size > 0 && size <= 2 * 1024 * 1024 * 1024
+}
+impl WebsiteReleasesV2 {
+ pub fn parse(bytes: &[u8]) -> Result<Self, &'static str> {
+ if bytes.is_empty() || bytes.len() > MAX_RELEASE_FEED_BYTES {
+ return Err("UPGRADE_CATALOG_INVALID");
+ }
+ let result: Self = serde_json::from_slice(bytes).map_err(|_| "UPGRADE_CATALOG_INVALID")?;
+ result.validate()?;
+ Ok(result)
+ }
+ fn validate(&self) -> Result<(), &'static str> {
+ let invalid = || "UPGRADE_CATALOG_INVALID";
+ if self.schema != "hiroute.website.releases/v2" || self.releases.len() > 64 {
+ return Err(invalid());
+ }
+ let mut versions = std::collections::BTreeSet::new();
+ for release in &self.releases {
+ let version = Version::parse(&release.version).map_err(|_| invalid())?;
+ if !versions.insert(&release.version)
+ || release.version.len() > 64
+ || !matches!(release.channel.as_str(), "stable" | "preview")
+ || (release.channel == "stable" && !version.pre.is_empty())
+ || release.published_at.is_empty()
+ || release.published_at.len() > 64
+ || [&release.notes.zh, &release.notes.en]
+ .iter()
+ .any(|n| n.trim().is_empty() || n.len() > 64 * 1024)
+ || release.artifacts.is_empty()
+ || release.artifacts.len() > 16
+ {
+ return Err(invalid());
+ }
+ let mut names = std::collections::BTreeSet::new();
+ for artifact in &release.artifacts {
+ match artifact {
+ ReleaseArtifactV2::Desktop {
+ platform,
+ architecture,
+ format,
+ minimum_os,
+ distribution,
+ filename,
+ sha256,
+ size,
+ } => {
+ let suffix = match distribution.as_str() {
+ "self-signed" => "trial",
+ "developer-id" => "developer-id",
+ _ => return Err(invalid()),
+ };
+ let prefix = format!("HiRoute-{}-", release.version);
+ let tail = format!("-macos-{architecture}-{suffix}.dmg");
+ let revision = filename
+ .strip_prefix(&prefix)
+ .and_then(|s| s.strip_suffix(&tail))
+ .ok_or_else(invalid)?;
+ if platform != "macOS"
+ || !matches!(architecture.as_str(), "arm64" | "x86_64")
+ || format != "dmg"
+ || minimum_os != "15.0"
+ || !sized_digest(filename, sha256, *size)
+ || revision.len() != 12
+ || !revision
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+ || !names.insert(filename.as_str())
+ {
+ return Err(invalid());
+ }
+ }
+ ReleaseArtifactV2::Standalone {
+ platform,
+ architecture,
+ target,
+ format,
+ distribution,
+ filename,
+ sha256,
+ size,
+ manifest_filename,
+ manifest_sha256,
+ manifest_size,
+ } => {
+ let expected_target = match architecture.as_str() {
+ "x86_64" => "x86_64-unknown-linux-gnu",
+ "aarch64" => "aarch64-unknown-linux-gnu",
+ _ => return Err(invalid()),
+ };
+ let prefix = format!("hiroute-{}-", release.version);
+ let tail = format!("-{target}.tar.gz");
+ let revision = filename
+ .strip_prefix(&prefix)
+ .and_then(|s| s.strip_suffix(&tail))
+ .ok_or_else(invalid)?;
+ if platform != "Linux"
+ || target != expected_target
+ || format != "tar.gz"
+ || distribution != "unsigned"
+ || !sized_digest(filename, sha256, *size)
+ || !sized_digest(manifest_filename, manifest_sha256, *manifest_size)
+ || manifest_filename != &format!("{filename}.json")
+ || revision.len() != 12
+ || !revision
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+ || !names.insert(filename.as_str())
+ || !names.insert(manifest_filename.as_str())
+ {
+ return Err(invalid());
+ }
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+ pub fn desktop_update(
+ &self,
+ current: &str,
+ architecture: &str,
+ ) -> Result<Option<DesktopRelease>, &'static str> {
+ let current = Version::parse(current).map_err(|_| "UPGRADE_VERSION_INVALID")?;
+ let mut selected: Option<(Version, DesktopRelease)> = None;
+ for release in self.releases.iter().filter(|r| r.channel == "stable") {
+ let version =
+ Version::parse(&release.version).map_err(|_| "UPGRADE_CATALOG_INVALID")?;
+ if version <= current || selected.as_ref().is_some_and(|(v, _)| v >= &version) {
+ continue;
+ }
+ let matches = release
+ .artifacts
+ .iter()
+ .filter_map(|a| match a {
+ ReleaseArtifactV2::Desktop {
+ architecture: arch,
+ distribution,
+ filename,
+ sha256,
+ size,
+ ..
+ } if arch == architecture => Some(DesktopRelease {
+ version: release.version.clone(),
+ notes: release.notes.clone(),
+ architecture: arch.clone(),
+ distribution: distribution.clone(),
+ filename: filename.clone(),
+ sha256: sha256.clone(),
+ size: *size,
+ }),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ if matches.len() > 1 {
+ return Err("UPGRADE_ARTIFACT_AMBIGUOUS");
+ }
+ if let Some(artifact) = matches.into_iter().next() {
+ selected = Some((version, artifact));
+ }
+ }
+ Ok(selected.map(|(_, release)| release))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn current_website_catalog_is_the_upgrade_reader_contract() {
+ let bytes = include_bytes!("../../../apps/website/data/releases.json");
+ let catalog = WebsiteReleasesV2::parse(bytes).unwrap();
+ let update = catalog.desktop_update("0.0.1", "arm64").unwrap().unwrap();
+ assert!(
+ update
+ .download_url()
+ .starts_with("https://hiroute.ai/releases/0.1.0/HiRoute-")
+ );
+ assert!(catalog.desktop_update("0.1.0", "arm64").unwrap().is_none());
+ assert!(catalog.desktop_update("99.0.0", "arm64").unwrap().is_none());
+ assert!(
+ catalog
+ .desktop_update("0.0.1", "riscv64")
+ .unwrap()
+ .is_none()
+ );
+ let original: serde_json::Value = serde_json::from_slice(bytes).unwrap();
+ for (field, bad) in [
+ ("filename", "../other.dmg"),
+ ("sha256", "unverified"),
+ ("platform", "Windows"),
+ ("distribution", "unsigned"),
+ ] {
+ let mut broken = original.clone();
+ broken["releases"][0]["artifacts"][0][field] = bad.into();
+ assert!(
+ WebsiteReleasesV2::parse(&serde_json::to_vec(&broken).unwrap()).is_err(),
+ "{field}"
+ );
+ }
+ let mut broken = original;
+ broken["download_url"] = "https://other.invalid".into();
+ assert!(WebsiteReleasesV2::parse(&serde_json::to_vec(&broken).unwrap()).is_err());
+ }
+}
diff --git a/crates/host-runtime/src/storage_progress.rs b/crates/host-runtime/src/storage_progress.rs
new file mode 100644
index 00000000..d78f571f
--- /dev/null
+++ b/crates/host-runtime/src/storage_progress.rs
@@ -0,0 +1,12 @@
+//! Storage readiness phases shared by daemon startup and the Desktop status projection.
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum StorageUpgradePhase {
+ SourceCheck,
+ Backup,
+ Conversion,
+ Validation,
+ ServiceRecovery,
+}
diff --git a/crates/host-runtime/src/upgrade.rs b/crates/host-runtime/src/upgrade.rs
new file mode 100644
index 00000000..bebade10
--- /dev/null
+++ b/crates/host-runtime/src/upgrade.rs
@@ -0,0 +1,96 @@
+//! Host maintenance admission; no persistent authority, cancellation or task resubmission.
+use serde::{Deserialize, Serialize};
+use std::sync::{
+ Arc,
+ atomic::{AtomicU64, Ordering},
+};
+
+#[derive(Default)]
+pub struct UpgradeDrain {
+ state: AtomicU64,
+}
+pub struct UpgradeCall {
+ owner: Arc<UpgradeDrain>,
+}
+impl UpgradeDrain {
+ pub fn pause(&self) {
+ self.state.fetch_or(1, Ordering::AcqRel);
+ }
+ pub fn resume(&self) {
+ self.state.fetch_and(!1, Ordering::AcqRel);
+ }
+ pub fn paused(&self) -> bool {
+ self.state.load(Ordering::Acquire) & 1 != 0
+ }
+ pub fn active(&self) -> u64 {
+ self.state.load(Ordering::Acquire) >> 1
+ }
+ pub fn enter(self: &Arc<Self>, existing_task: bool) -> Option<UpgradeCall> {
+ self.state
+ .fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| {
+ if state & 1 != 0 && !existing_task {
+ None
+ } else {
+ state.checked_add(2)
+ }
+ })
+ .ok()
+ .map(|_| UpgradeCall {
+ owner: self.clone(),
+ })
+ }
+}
+impl Drop for UpgradeCall {
+ fn drop(&mut self) {
+ self.owner.state.fetch_sub(2, Ordering::AcqRel);
+ }
+}
+
+#[derive(Clone, Copy, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum UpgradeAction {
+ Prepare,
+ Status,
+ Cancel,
+}
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct LauncherUpgradeRequest {
+ pub schema: String,
+ pub registration_id: String,
+ pub action: UpgradeAction,
+}
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct LauncherUpgradeStatus {
+ pub schema: String,
+ pub registration_id: String,
+ pub paused: bool,
+ pub active_calls: u64,
+ pub active_tasks: u64,
+}
+impl LauncherUpgradeStatus {
+ pub fn drained(&self) -> bool {
+ self.paused && self.active_calls == 0 && self.active_tasks == 0
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn upgrade_wait_retains_existing_calls_and_allows_task_completion_then_cancel_resumes() {
+ let gate = Arc::new(UpgradeDrain::default());
+ let call = gate.enter(false).unwrap();
+ gate.pause();
+ assert!(gate.enter(false).is_none());
+ let task = gate.enter(true).unwrap();
+ assert_eq!(gate.active(), 2);
+ drop(call);
+ drop(task);
+ assert_eq!(gate.active(), 0);
+ assert!(gate.paused());
+ gate.resume();
+ assert!(gate.enter(false).is_some());
+ }
+}
diff --git a/crates/integrations/src/agents/codex_catalog_plan_tests.rs b/crates/integrations/src/agents/codex_catalog_plan_tests.rs
index 7c9b2753..a8d2d729 100644
--- a/crates/integrations/src/agents/codex_catalog_plan_tests.rs
+++ b/crates/integrations/src/agents/codex_catalog_plan_tests.rs
@@ -3,11 +3,11 @@ use super::*;
use hiroute_domain::{CanonicalDigest, GatewayCriticalFactV1, GatewayFidelityV1, UpstreamProtocol};
fn plan() -> CompiledAgentPlanV1 {
- let fixture: Value = serde_json::from_slice(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let fixture: Value = serde_json::from_slice::<serde_json::Value>(include_bytes!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
- serde_json::from_value::<CompiledAgentPlanV1>(fixture["plans"][0].clone())
+ serde_json::from_value::<hiroute_domain::CompiledAgentPlanV1>(fixture["plans"][0].clone())
.unwrap()
.into_current()
.unwrap()
@@ -15,7 +15,8 @@ fn plan() -> CompiledAgentPlanV1 {
fn original() -> CodexCatalogSelection {
let value: Value =
- serde_json::from_slice(include_bytes!("codex_bundled_catalog.json")).unwrap();
+ serde_json::from_slice::<serde_json::Value>(include_bytes!("codex_bundled_catalog.json"))
+ .unwrap();
CodexCatalogSelection::parse(value).unwrap()
}
diff --git a/crates/integrations/src/gateway/tests.rs b/crates/integrations/src/gateway/tests.rs
index 4d91736f..5d05ff63 100644
--- a/crates/integrations/src/gateway/tests.rs
+++ b/crates/integrations/src/gateway/tests.rs
@@ -41,12 +41,13 @@ fn correlation() -> Value {
#[test]
fn fixed_publication_digest_matches_the_actual_gateway_binding() {
use hiroute_domain as domain;
- let fixture: Value = serde_json::from_slice(include_bytes!(
- "../../../../e2e/product/golden/routing/compiled-publication.v2.json"
+ let fixture: Value = serde_json::from_slice::<serde_json::Value>(include_bytes!(
+ "../../../../e2e/product/fixtures/routing/current-publication.v3.json"
))
.unwrap();
- let plan: domain::CompiledAgentPlanV1 =
- serde_json::from_value(fixture["plans"][0].clone()).unwrap();
+ let plan =
+ serde_json::from_value::<hiroute_domain::CompiledAgentPlanV1>(fixture["plans"][0].clone())
+ .unwrap();
let plan = plan.into_current().unwrap();
let binding = plan.body.materialized.attempt_owned.groups[0].candidates[0].clone();
let grant = domain::AgentModelGrantV2::seal(
diff --git a/crates/local-storage/Cargo.toml b/crates/local-storage/Cargo.toml
index 33428256..925a096c 100644
--- a/crates/local-storage/Cargo.toml
+++ b/crates/local-storage/Cargo.toml
@@ -7,12 +7,14 @@ rust-version.workspace = true
[dependencies]
hiroute-diagnostics = { path = "../diagnostics" }
+hiroute-host-runtime = { path = "../host-runtime" }
aes-gcm.workspace = true
getrandom.workspace = true
+fs2.workspace = true
hmac.workspace = true
hiroute-domain = { path = "../domain" }
rusqlite.workspace = true
-rustix.workspace = true
+rustix = { workspace = true, features = ["fs"] }
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
@@ -20,6 +22,7 @@ thiserror.workspace = true
zeroize.workspace = true
[dev-dependencies]
+base64.workspace = true
hiroute-application = { path = "../application" }
hiroute-application-api = { path = "../application-api" }
hiroute-integrations = { path = "../integrations" }
diff --git a/crates/local-storage/src/agents/native_artifacts.rs b/crates/local-storage/src/agents/native_artifacts.rs
index 76bfbe63..22ce91af 100644
--- a/crates/local-storage/src/agents/native_artifacts.rs
+++ b/crates/local-storage/src/agents/native_artifacts.rs
@@ -205,7 +205,7 @@ impl NativeAgentArtifactPort for ManagedArtifactStore {
}
/// Bound allocation before reading and check the opened inode, not a following path lookup.
-fn read_native_file(
+pub(super) fn read_native_file(
path: &Path,
limit: usize,
) -> Result<Option<Zeroizing<Vec<u8>>>, LocalStorageError> {
diff --git a/crates/local-storage/src/agents/plan_references.rs b/crates/local-storage/src/agents/plan_references.rs
index 0ce2e739..668dd437 100644
--- a/crates/local-storage/src/agents/plan_references.rs
+++ b/crates/local-storage/src/agents/plan_references.rs
@@ -1,9 +1,9 @@
//! Coherent read projection of original Operation model settings and independent grants.
-use super::{ControlStore, decode_operation, port};
+use super::{ControlStore, agent_read::decode_succeeded_agent, port};
use hiroute_domain::{
AgentCollaborationGrant, AgentPlanId, AgentPlanReference, AgentPlanReferenceKind,
AgentPlanReferenceReadPort, AgentPlanReferenceSubject, AgentPlanReferences, CanonicalDigest,
- OperationState, PortErrorCode, PortResult, WorkspaceId,
+ PortErrorCode, PortResult, WorkspaceId,
};
use rusqlite::params;
use std::collections::BTreeSet;
@@ -26,24 +26,19 @@ impl AgentPlanReferenceReadPort for ControlStore {
let mut seen = BTreeSet::new();
{
let mut statement = transaction.prepare(
- "SELECT operation_json FROM operations WHERE workspace_id=?1 AND operation_kind IN ('ApplyAgentConnectionChange','ApplyAgentConnectionRestore') ORDER BY rowid DESC"
+ "SELECT state,operation_json FROM operations WHERE workspace_id=?1 AND operation_kind IN ('ApplyAgentConnectionChange','ApplyAgentConnectionRestore') ORDER BY rowid DESC"
).map_err(|_| port(PortErrorCode::Unavailable, "agents.references.operations"))?;
let rows = statement
- .query_map(params![workspace.as_str()], |row| row.get::<_, String>(0))
+ .query_map(params![workspace.as_str()], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
+ })
.map_err(|_| port(PortErrorCode::Unavailable, "agents.references.rows"))?;
for row in rows {
- let operation = decode_operation(
- &self.diagnostics.borrow(),
- &row.map_err(|_| port(PortErrorCode::Corrupt, "agents.references.row"))?,
- )?;
- if &operation.workspace_id != workspace {
- return Err(port(PortErrorCode::Corrupt, "agents.references.workspace"));
- }
- match operation.state {
- OperationState::Succeeded => {}
- OperationState::RolledBack => continue,
- // An incomplete operation may have changed authority before terminal commit.
- // Do not mistake its previous completed projection for current absence.
+ let (state, encoded) =
+ row.map_err(|_| port(PortErrorCode::Corrupt, "agents.references.row"))?;
+ match state.as_str() {
+ "rolled_back" => continue,
+ "succeeded" => {}
_ => {
return Err(port(
PortErrorCode::Unavailable,
@@ -51,6 +46,10 @@ impl AgentPlanReferenceReadPort for ControlStore {
));
}
}
+ let operation = decode_succeeded_agent(&transaction, &encoded)?;
+ if &operation.workspace_id != workspace {
+ return Err(port(PortErrorCode::Corrupt, "agents.references.workspace"));
+ }
let connection_id = operation
.plan
.spec()
diff --git a/crates/local-storage/src/agents/plan_references_tests.rs b/crates/local-storage/src/agents/plan_references_tests.rs
index 0cf0fcbd..9efef4d1 100644
--- a/crates/local-storage/src/agents/plan_references_tests.rs
+++ b/crates/local-storage/src/agents/plan_references_tests.rs
@@ -162,6 +162,9 @@ fn agent_plan_references_join_independent_grants_restore_and_workspace() {
.store_collaboration_grant(&operation.operation_id, 0, &grant)
.unwrap();
assert!(control.agent_plan_references(&workspace, &plan).is_err());
+ for step in &mut operation.steps {
+ step.status = OperationStepStatus::Applied;
+ }
operation.state = OperationState::Succeeded;
control.finish_operation(&mut operation).unwrap();
let initial = control.agent_plan_references(&workspace, &plan).unwrap();
@@ -184,6 +187,9 @@ fn agent_plan_references_join_independent_grants_restore_and_workspace() {
.is_empty()
);
let mut restore = begin_plan(&control, true, "references-restore");
+ for step in &mut restore.steps {
+ step.status = OperationStepStatus::Applied;
+ }
restore.state = OperationState::Succeeded;
control.finish_operation(&mut restore).unwrap();
let after = control.agent_plan_references(&workspace, &plan).unwrap();
@@ -204,6 +210,9 @@ fn agent_plan_references_corrupt_projection_is_not_no_references() {
)
.unwrap();
let mut operation = begin_plan(&control, false, "references-corrupt");
+ for step in &mut operation.steps {
+ step.status = OperationStepStatus::Applied;
+ }
operation.state = OperationState::Succeeded;
control.finish_operation(&mut operation).unwrap();
control.with_connection(|db| {
diff --git a/crates/local-storage/src/backup/mod.rs b/crates/local-storage/src/backup/mod.rs
index 4f0af321..232ace95 100644
--- a/crates/local-storage/src/backup/mod.rs
+++ b/crates/local-storage/src/backup/mod.rs
@@ -1,3 +1,4 @@
+pub(crate) mod source_snapshot;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
@@ -283,6 +284,45 @@ pub(crate) fn test_writer_barrier() -> SingleWriterBackupBarrier {
}
impl BackupSet {
+ /// Saves the complete stopped storage authority beside this verified three-store backup.
+ /// The caller must retain the startup barrier and directory ownership until publication ends.
+ pub fn publish_stopped_source(
+ &self,
+ _barrier: &SingleWriterBackupBarrier,
+ storage_root: &Path,
+ options: &crate::StorageStartupOptions,
+ ) -> Result<(), LocalStorageError> {
+ if self
+ .root
+ .canonicalize()?
+ .starts_with(storage_root.canonicalize()?)
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ for (name, backup) in [
+ ("control.db", &self.control),
+ ("runtime.db", &self.runtime),
+ ("secrets.db", &self.secrets),
+ ] {
+ let connection = Connection::open_with_flags(
+ storage_root.join("live").join(name),
+ OpenFlags::SQLITE_OPEN_READ_ONLY,
+ )?;
+ validate_restored_source_identity(&connection, backup.manifest())?;
+ if database_state_digest(&connection)? != backup.manifest().source_state_digest {
+ return Err(LocalStorageError::InvalidData);
+ }
+ }
+ let metadata = serde_json::json!({
+ "batch_id": self.set_id(), "target_schema_version": self.target_schema_version(),
+ "source_stores": {"control":self.control.manifest(),"runtime":self.runtime.manifest(),"secrets":self.secrets.manifest()}
+ });
+ source_snapshot::publish(storage_root, &self.root, &metadata, options)
+ }
+
+ pub(crate) fn directory(&self) -> &Path {
+ &self.root
+ }
/// Creates a local three-store snapshot under the hirouted single-writer barrier. A durable
/// writer claim proves that the barrier is not held and causes a fail-closed refusal.
pub fn create(
@@ -300,6 +340,7 @@ impl BackupSet {
secrets,
None,
crate::migrations::LATEST_SCHEMA_VERSION,
+ false,
)
}
@@ -320,6 +361,7 @@ impl BackupSet {
secrets,
Some(secret_key_id),
target_schema_version,
+ true,
)
}
@@ -332,6 +374,7 @@ impl BackupSet {
secrets: &Connection,
secret_key_id: Option<&CanonicalDigest>,
target_schema_version: u32,
+ startup_migration: bool,
) -> Result<Self, LocalStorageError> {
prepare_owner_directory(backup_root)?;
if reconcile_set_manifest_publication(backup_root)? {
@@ -354,7 +397,7 @@ impl BackupSet {
&& control.query_row("SELECT EXISTS(SELECT 1 FROM writer_claim)", [], |row| {
row.get::<_, bool>(0)
})?;
- if writer_claim {
+ if writer_claim && !startup_migration {
return Err(LocalStorageError::InvalidData);
}
control.execute_batch("PRAGMA wal_checkpoint(FULL)")?;
@@ -868,6 +911,27 @@ fn database_identity(connection: &Connection) -> Result<DatabaseIdentity, LocalS
}
}
+/// A manually restored, completed source may have new business rows. Match its identity,
+/// rather than the old state digest; interrupted migration still uses its exact source digest.
+pub(crate) fn validate_restored_source_identity(
+ connection: &Connection,
+ source: &BackupManifest,
+) -> Result<(), LocalStorageError> {
+ let integrity: String = connection.query_row("PRAGMA integrity_check", [], |row| row.get(0))?;
+ let identity = database_identity(connection)?;
+ if integrity != "ok"
+ || source.store_uuid.is_empty()
+ || source.store_uuid == "legacy-unbound"
+ || identity.kind != source.database_kind
+ || identity.store_uuid != source.store_uuid
+ || identity.schema_version != source.schema_version
+ || identity.key_id != source.key_id
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ Ok(())
+}
+
fn generic_store_binding(
connection: &Connection,
) -> Result<(String, Option<String>), LocalStorageError> {
diff --git a/crates/local-storage/src/backup/source_snapshot.rs b/crates/local-storage/src/backup/source_snapshot.rs
new file mode 100644
index 00000000..ab78fdee
--- /dev/null
+++ b/crates/local-storage/src/backup/source_snapshot.rs
@@ -0,0 +1,319 @@
+//! Atomic publication of the complete stopped authority snapshot and recovery instructions.
+use super::*;
+use crate::migrations::{prepare_storage_root as prepare_owner_directory, validate_owner_file};
+use serde_json::{Value, json};
+use std::collections::BTreeMap;
+use std::io::Write;
+
+const MANIFEST: &str = "source-backup.json";
+
+pub(crate) fn archive_guide(
+ backup: &Path,
+ archived: &Path,
+ batch_id: &str,
+) -> Result<(), LocalStorageError> {
+ if !backup.join("source").exists() {
+ return Ok(());
+ }
+ verify(backup)?;
+ let text = format!(
+ "# HiRoute 已完成升级批次定位说明\n\n批次 ID:{batch_id}\n\n恢复源以本说明所在目录/source/ 为准。归档后的完整源路径:{}\n\n请阅读 source/恢复说明.md。旧说明中的固定 migration-set/source 绝对源路径可能已失效,必须改为本说明所在目录/source/,不得使用下一批备份。storage/ 和其它源文件均在该 source/ 下,恢复目标及对应旧完整 App 仍以原说明和 source/source-backup.json 为准。\n\n原备份文件、恢复说明和已哈希清单保持不变。\n",
+ archived.join("source").display()
+ );
+ let directory = hiroute_diagnostics::files::PrivateDir::open_existing(backup)
+ .map_err(|_| LocalStorageError::Permission)?;
+ let mut stage = directory
+ .open_append_or_create("归档说明.tmp")
+ .map_err(|_| LocalStorageError::Permission)?;
+ stage
+ .replace_contents(text.as_bytes())
+ .map_err(|_| LocalStorageError::Permission)?;
+ stage.sync().map_err(|_| LocalStorageError::Permission)?;
+ directory
+ .rename_verified("归档说明.tmp", "归档说明.md", stage.identity())
+ .map_err(|_| LocalStorageError::Permission)?;
+ directory.sync().map_err(|_| LocalStorageError::Permission)
+}
+fn copy_tree(source: &Path, target: &Path) -> Result<(), LocalStorageError> {
+ let metadata = fs::symlink_metadata(source)?;
+ if metadata.file_type().is_symlink() {
+ return Err(LocalStorageError::Permission);
+ }
+ if metadata.is_dir() {
+ prepare_owner_directory(target)?;
+ for entry in fs::read_dir(source)? {
+ let entry = entry?;
+ copy_tree(&entry.path(), &target.join(entry.file_name()))?;
+ }
+ std::fs::File::open(target)?.sync_all()?;
+ } else if metadata.is_file() {
+ fs::copy(source, target)?;
+ fs::set_permissions(target, metadata.permissions())?;
+ std::fs::File::open(target)?.sync_all()?;
+ } else {
+ return Err(LocalStorageError::InvalidData);
+ }
+ Ok(())
+}
+fn excluded(name: &str) -> bool {
+ name == "live"
+ || name.starts_with("migration-set")
+ || name == "startup.lock"
+ || name.ends_with(".pid")
+ || name.ends_with(".sock")
+}
+fn write_private(path: &Path, bytes: &[u8]) -> Result<(), LocalStorageError> {
+ let mut options = fs::OpenOptions::new();
+ options.create_new(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options.open(path)?;
+ file.write_all(bytes)?;
+ file.sync_all()?;
+ Ok(())
+}
+pub(super) fn publish(
+ root: &Path,
+ backup: &Path,
+ metadata: &Value,
+ options: &crate::StorageStartupOptions,
+) -> Result<(), LocalStorageError> {
+ let source = backup.join("source");
+ if source.exists() {
+ return verify(backup);
+ }
+ let stage = backup.join("source-staging");
+ if stage.exists() {
+ // Preserve an interrupted attempt; it is never promoted or reused as complete.
+ let mut id = [0u8; 8];
+ getrandom::fill(&mut id).map_err(|_| LocalStorageError::Crypto)?;
+ let id = CanonicalDigest::of_bytes(&id);
+ fs::rename(
+ &stage,
+ backup.join(format!("source-incomplete.{}", &id.as_str()[7..23])),
+ )?;
+ }
+ prepare_owner_directory(&stage)?;
+ let storage = stage.join("storage");
+ prepare_owner_directory(&storage)?;
+ for entry in fs::read_dir(root)? {
+ let entry = entry?;
+ let name = entry.file_name();
+ if excluded(&name.to_string_lossy()) {
+ continue;
+ }
+ copy_tree(&entry.path(), &storage.join(name))?;
+ }
+ prepare_owner_directory(&storage.join("live"))?;
+ for name in ["control.db", "runtime.db", "secrets.db"] {
+ copy_tree(&backup.join(name), &storage.join("live").join(name))?;
+ }
+ let mut extra = BTreeMap::new();
+ if let Some(parent) = root.parent() {
+ for (name, path) in [
+ (
+ "gateway.lkg",
+ options
+ .gateway_lkg
+ .clone()
+ .unwrap_or_else(|| parent.join("gateway.lkg")),
+ ),
+ (
+ "gateway-listener.json",
+ parent.join("gateway-listener.json"),
+ ),
+ ] {
+ if path.exists() {
+ if name == "gateway.lkg" {
+ // Historical cache producers used ordinary 0644 files. This derived,
+ // non-secret cache is kept byte-for-byte for manual restoration only.
+ let metadata = fs::symlink_metadata(&path)?;
+ if !metadata.is_file() {
+ return Err(LocalStorageError::Permission);
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ if metadata.uid() != rustix::process::getuid().as_raw()
+ || metadata.mode() & 0o022 != 0
+ {
+ return Err(LocalStorageError::Permission);
+ }
+ }
+ } else {
+ validate_owner_file(&path)?;
+ }
+ copy_tree(&path, &stage.join(name))?;
+ extra.insert(name.to_owned(), path.to_string_lossy().into_owned());
+ }
+ }
+ }
+ let extra_paths = extra
+ .iter()
+ .map(|(name, target)| format!("- {name} → {target}\n"))
+ .collect::<String>();
+ let text = format!(
+ "# HiRoute 手工恢复\n\n备份批次 ID:{}\n\n备份源以本说明所在目录为准,目录改名或归档后仍从这里读取;不要使用其它批次。以下源文件路径均相对于本说明所在目录,目标路径为绝对位置。\n\n1. 完全退出 HiRoute,确认服务、CPA、任务与后台自动重启均已停止。\n2. 将 storage 目录 {} 改名保留;不要改名它的上级目录,备份仍保留在上述位置。恢复将舍弃备份之后的新数据。\n3. 将 storage/ 整个复制回 {},保留权限。不要逐库覆盖,不要遗留不配套的 WAL/SHM。再按以下源 → 目标路径复制额外文件:\n\n{}\n4. 按下面的完整 App 路径和身份覆盖安装旧包,启动后检查配置、Agent 接入及一次真实请求。\n\n{}\n\n本次只修改三个数据库;该目录同时保存密钥、原生恢复材料及其余自有持久状态。不要将此备份加入诊断导出。\n",
+ metadata["batch_id"]
+ .as_str()
+ .ok_or(LocalStorageError::InvalidData)?,
+ root.display(),
+ root.display(),
+ extra_paths,
+ "使用创建备份时的配套完整安装包;本说明不承诺支持其它存储格式。"
+ );
+ write_private(&stage.join("恢复说明.md"), text.as_bytes())?;
+ let mut files = BTreeMap::new();
+ collect(&stage, &stage, &mut files)?;
+ let created = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_err(|_| LocalStorageError::InvalidData)?
+ .as_secs();
+ let mut info = metadata.clone();
+ info["created_unix_seconds"] = json!(created);
+ let manifest = json!({"schema":"hiroute.upgrade-source-backup/v1","complete":true,
+ "source_storage":root.to_string_lossy(),"extra_locations":extra,"files":files,"source_info":info});
+ write_private(
+ &stage.join(MANIFEST),
+ &serde_json::to_vec_pretty(&manifest).map_err(|_| LocalStorageError::InvalidData)?,
+ )?;
+ std::fs::File::open(&stage)?.sync_all()?;
+ fs::rename(stage, &source)?;
+ std::fs::File::open(backup)?.sync_all()?;
+ verify(backup)
+}
+fn collect(
+ root: &Path,
+ path: &Path,
+ files: &mut BTreeMap<String, String>,
+) -> Result<(), LocalStorageError> {
+ let metadata = fs::symlink_metadata(path)?;
+ if metadata.file_type().is_symlink() {
+ return Err(LocalStorageError::Permission);
+ }
+ if metadata.is_dir() {
+ for entry in fs::read_dir(path)? {
+ let entry = entry?;
+ if entry.path() == root.join(MANIFEST) {
+ continue;
+ }
+ collect(root, &entry.path(), files)?;
+ }
+ } else if metadata.is_file() {
+ files.insert(
+ path.strip_prefix(root)
+ .map_err(|_| LocalStorageError::InvalidData)?
+ .to_string_lossy()
+ .into_owned(),
+ CanonicalDigest::of_bytes(&fs::read(path)?).to_string(),
+ );
+ } else {
+ return Err(LocalStorageError::InvalidData);
+ }
+ Ok(())
+}
+fn manifest(backup: &Path) -> Result<Value, LocalStorageError> {
+ validate_owner_file(&backup.join("source").join(MANIFEST))?;
+ let value: Value = serde_json::from_slice(&fs::read(backup.join("source").join(MANIFEST))?)
+ .map_err(|_| LocalStorageError::InvalidData)?;
+ if value["schema"] != "hiroute.upgrade-source-backup/v1"
+ || value["complete"] != true
+ || value.as_object().is_none_or(|o| o.len() != 6)
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ Ok(value)
+}
+pub(super) fn verify(backup: &Path) -> Result<(), LocalStorageError> {
+ let value = manifest(backup)?;
+ let mut actual = BTreeMap::new();
+ collect(&backup.join("source"), &backup.join("source"), &mut actual)?;
+ if json!(actual) != value["files"] {
+ return Err(LocalStorageError::InvalidData);
+ }
+ Ok(())
+}
+pub(crate) fn verify_unchanged(root: &Path, backup: &Path) -> Result<(), LocalStorageError> {
+ verify(backup)?;
+ let value = manifest(backup)?;
+ if value["source_storage"] != root.to_string_lossy().as_ref() {
+ return Err(LocalStorageError::InvalidData);
+ }
+ let mut actual = BTreeMap::new();
+ for entry in fs::read_dir(root)? {
+ let entry = entry?;
+ if excluded(&entry.file_name().to_string_lossy()) {
+ continue;
+ }
+ collect(root, &entry.path(), &mut actual)?;
+ }
+ let expected = value["files"]
+ .as_object()
+ .ok_or(LocalStorageError::InvalidData)?
+ .iter()
+ .filter_map(|(path, digest)| {
+ path.strip_prefix("storage/")
+ .filter(|p| !p.starts_with("live/"))
+ .map(|p| (p.to_owned(), digest.as_str().unwrap_or("").to_owned()))
+ })
+ .collect::<BTreeMap<_, _>>();
+ if actual != expected {
+ return Err(LocalStorageError::InvalidData);
+ }
+ for (name, path) in value["extra_locations"]
+ .as_object()
+ .ok_or(LocalStorageError::InvalidData)?
+ {
+ let path = path.as_str().ok_or(LocalStorageError::InvalidData)?;
+ if json!(CanonicalDigest::of_bytes(&fs::read(path)?).to_string()) != value["files"][name] {
+ return Err(LocalStorageError::InvalidData);
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn stopped_current_snapshot_preserves_keys_auxiliary_files_and_complete_manifest() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().join("storage");
+ let stores = crate::LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ prepare_owner_directory(&root.join("observation")).unwrap();
+ fs::write(root.join("observation/body"), b"preserved observation").unwrap();
+ set_owner_file_permissions(&root.join("observation/body")).unwrap();
+ let backup = temporary.path().join("backup");
+ let barrier = test_writer_barrier();
+ let set = BackupSet::create(
+ &barrier,
+ &backup,
+ &stores.control().connection.borrow(),
+ &stores.runtime().connection.borrow(),
+ &stores.secrets().connection.borrow(),
+ )
+ .unwrap();
+ set.publish_stopped_source(&barrier, &root, &crate::StorageStartupOptions::default())
+ .unwrap();
+ verify(&backup).unwrap();
+ for name in ["master-key", "observation/body"] {
+ assert_eq!(
+ fs::read(root.join(name)).unwrap(),
+ fs::read(backup.join("source/storage").join(name)).unwrap()
+ );
+ }
+ let manifest = fs::read(backup.join("source/source-backup.json")).unwrap();
+ set.publish_stopped_source(&barrier, &root, &crate::StorageStartupOptions::default())
+ .unwrap();
+ assert_eq!(
+ fs::read(backup.join("source/source-backup.json")).unwrap(),
+ manifest
+ );
+ fs::write(root.join("observation/body"), b"changed").unwrap();
+ assert!(verify_unchanged(&root, &backup).is_err());
+ }
+}
diff --git a/crates/local-storage/src/control/agent_read.rs b/crates/local-storage/src/control/agent_read.rs
new file mode 100644
index 00000000..4979021d
--- /dev/null
+++ b/crates/local-storage/src/control/agent_read.rs
@@ -0,0 +1,240 @@
+//! Strict successful Agent journal projection. It has no execution or journal-write capability.
+use super::*;
+use hiroute_domain::{
+ AgentOperationInputView, AgentOperationRead, AgentPlanReadV1, OperationStepKind,
+};
+
+#[derive(Clone, Debug)]
+pub struct SucceededAgentOperationV1 {
+ pub operation_id: OperationId,
+ pub workspace_id: WorkspaceId,
+ pub idempotency: IdempotencyScopeV1,
+ pub accepted_digest: CanonicalDigest,
+ pub state: OperationState,
+ pub plan: AgentPlanReadV1,
+ steps: Vec<OperationStepV1>,
+}
+
+impl SucceededAgentOperationV1 {
+ pub fn step(&self, kind: OperationStepKind) -> &OperationStepV1 {
+ &self.steps[OperationStepKind::ALL
+ .iter()
+ .position(|k| *k == kind)
+ .expect("fixed journal")]
+ }
+}
+
+impl AgentOperationRead for SucceededAgentOperationV1 {
+ fn agent_input(&self) -> AgentOperationInputView<'_> {
+ AgentOperationInputView {
+ spec: self.plan.spec(),
+ control: self.plan.control(),
+ external: self.plan.external(),
+ grants: self.plan.agent_access_grants(),
+ }
+ }
+ fn operation_id(&self) -> &OperationId {
+ &self.operation_id
+ }
+ fn accepted_digest(&self) -> &CanonicalDigest {
+ &self.accepted_digest
+ }
+ fn state(&self) -> OperationState {
+ self.state
+ }
+}
+
+pub(super) fn decode_succeeded_agent(
+ connection: &Connection,
+ encoded: &str,
+) -> PortResult<SucceededAgentOperationV1> {
+ let invalid = || port(PortErrorCode::Corrupt, "control.agent-read.journal");
+ let durable: DurableOperation = serde_json::from_str(encoded).map_err(|_| invalid())?;
+ if durable.schema_version != hiroute_domain::OPERATION_SCHEMA_VERSION
+ || durable.state != OperationState::Succeeded
+ || OperationId::derive(
+ &durable.workspace_id,
+ &durable.idempotency,
+ &durable.request_digest,
+ ) != durable.operation_id
+ {
+ return Err(invalid());
+ }
+ WorkspaceId::parse(durable.workspace_id.as_str()).map_err(|_| invalid())?;
+ IdempotencyScopeV1::new(
+ durable.idempotency.principal.as_str(),
+ durable.idempotency.operation_kind.as_str(),
+ durable.idempotency.key.as_str(),
+ )
+ .map_err(|_| invalid())?;
+ for digest in [&durable.request_digest, &durable.accepted_digest] {
+ CanonicalDigest::parse(digest.as_str()).map_err(|_| invalid())?;
+ }
+ let plan = AgentPlanReadV1::from_stored(&durable.plan).map_err(|_| invalid())?;
+ let expected_kind = plan.operation_kind().map_err(|_| invalid())?;
+ if durable.idempotency.operation_kind != expected_kind
+ || durable
+ .steps
+ .iter()
+ .any(|s| s.status != hiroute_domain::OperationStepStatus::Applied)
+ {
+ return Err(invalid());
+ }
+ durable
+ .plan
+ .validate_step_proofs(
+ &durable.accepted_digest,
+ &durable.expected_revisions,
+ plan.agent_access_grants(),
+ &durable.steps,
+ )
+ .map_err(|_| invalid())?;
+ if plan
+ .external()
+ .iter()
+ .any(hiroute_domain::is_settings_managed_configuration)
+ {
+ let receipt = durable.steps[5]
+ .terminal_result
+ .as_deref()
+ .and_then(hiroute_domain::SettingsServiceCompletionV1::parse)
+ .ok_or_else(invalid)?;
+ let proof = CanonicalDigest::of(&(
+ "hiroute.settings-service-proof/v2",
+ durable.operation_id.as_str(),
+ &durable.accepted_digest,
+ receipt.publication_revision,
+ &receipt.publication_digest,
+ durable.plan.digest().map_err(|_| invalid())?,
+ ))
+ .map_err(|_| invalid())?;
+ if proof != receipt.completed_effects_digest
+ || !durable.steps[3].effects.iter().any(|e| {
+ e.kind == OwnedEffectKind::Publication
+ && e.after_fingerprint.as_ref() == Some(&receipt.publication_digest)
+ && e.compensation["publication_revision"].as_u64()
+ == Some(receipt.publication_revision)
+ })
+ {
+ return Err(invalid());
+ }
+ }
+ let raw: Value = serde_json::from_str(encoded).map_err(|_| invalid())?;
+ if serde_json::to_value(&durable.steps).map_err(|_| invalid())? != raw["steps"]
+ || durable.steps.iter().flat_map(|s| &s.effects).any(|effect| {
+ effect
+ .compensation
+ .get("operation_id")
+ .is_some_and(|id| id != durable.operation_id.as_str())
+ })
+ {
+ return Err(invalid());
+ }
+ let identity: bool = connection
+ .query_row(
+ "SELECT EXISTS(SELECT 1 FROM operations WHERE operation_id=?1 AND workspace_id=?2
+ AND principal=?3 AND operation_kind=?4 AND idempotency_key=?5 AND request_digest=?6
+ AND accepted_change_digest=?7 AND state='succeeded' AND generation=?8)",
+ params![
+ durable.operation_id.as_str(),
+ durable.workspace_id.as_str(),
+ durable.idempotency.principal,
+ durable.idempotency.operation_kind,
+ durable.idempotency.key,
+ durable.request_digest.as_str(),
+ durable.accepted_digest.as_str(),
+ durable.generation
+ ],
+ |r| r.get(0),
+ )
+ .map_err(|_| port(PortErrorCode::Unavailable, "control.agent-read.identity"))?;
+ if !identity {
+ return Err(invalid());
+ }
+ let mut statement = connection.prepare("SELECT step_no,step_kind,state,step_json FROM operation_steps WHERE operation_id=?1 ORDER BY step_no")
+ .map_err(|_| port(PortErrorCode::Unavailable,"control.agent-read.steps"))?;
+ let rows = statement
+ .query_map([durable.operation_id.as_str()], |r| {
+ Ok((
+ r.get::<_, usize>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, String>(2)?,
+ r.get::<_, String>(3)?,
+ ))
+ })
+ .map_err(|_| port(PortErrorCode::Unavailable, "control.agent-read.steps"))?;
+ let mut count = 0;
+ for row in rows {
+ let (number, kind, state, encoded) = row.map_err(|_| invalid())?;
+ let step: Value = serde_json::from_str(&encoded).map_err(|_| invalid())?;
+ if number != count
+ || number >= 6
+ || step.as_object().is_none_or(|o| o.len() != 2)
+ || step["schema"] != "hiroute.operation-step/v1"
+ || step["step"] != raw["steps"][number]
+ || step["step"]["kind"] != kind
+ || step["step"]["status"] != state
+ {
+ return Err(invalid());
+ }
+ count += 1;
+ }
+ if count != 6 {
+ return Err(invalid());
+ }
+ Ok(SucceededAgentOperationV1 {
+ operation_id: durable.operation_id,
+ workspace_id: durable.workspace_id,
+ idempotency: durable.idempotency,
+ accepted_digest: durable.accepted_digest,
+ state: durable.state,
+ plan,
+ steps: durable.steps,
+ })
+}
+
+impl ControlStore {
+ pub fn succeeded_agent_operations_for_kind(
+ &self,
+ workspace: &WorkspaceId,
+ kind: &str,
+ ) -> PortResult<Vec<SucceededAgentOperationV1>> {
+ self.succeeded_agent_operations_for_kinds(workspace, &[kind])
+ }
+ pub fn succeeded_agent_operations_for_kinds(
+ &self,
+ workspace: &WorkspaceId,
+ kinds: &[&str],
+ ) -> PortResult<Vec<SucceededAgentOperationV1>> {
+ if kinds.is_empty()
+ || kinds.len() > 2
+ || kinds.iter().any(|kind| {
+ !matches!(
+ *kind,
+ "ApplyAgentConnectionChange" | "ApplyAgentConnectionRestore"
+ )
+ })
+ {
+ return Err(port(PortErrorCode::InvalidData, "control.agent-read.kinds"));
+ }
+ let placeholders = vec!["?"; kinds.len()].join(",");
+ let connection = self.connection.borrow();
+ let mut statement = connection.prepare(&format!("SELECT operation_json FROM operations WHERE workspace_id=? AND operation_kind IN ({placeholders}) AND state='succeeded' ORDER BY rowid DESC"))
+ .map_err(|_| port(PortErrorCode::Unavailable,"control.agent-read.query"))?;
+ let rows = statement
+ .query_map(
+ rusqlite::params_from_iter(
+ std::iter::once(workspace.as_str()).chain(kinds.iter().copied()),
+ ),
+ |r| r.get::<_, String>(0),
+ )
+ .map_err(|_| port(PortErrorCode::Unavailable, "control.agent-read.query"))?;
+ rows.map(|row| {
+ decode_succeeded_agent(
+ &connection,
+ &row.map_err(|_| port(PortErrorCode::Corrupt, "control.agent-read.row"))?,
+ )
+ })
+ .collect()
+ }
+}
diff --git a/crates/local-storage/src/control/agent_transaction_tests.rs b/crates/local-storage/src/control/agent_transaction_tests.rs
index d5e05128..bf2cc583 100644
--- a/crates/local-storage/src/control/agent_transaction_tests.rs
+++ b/crates/local-storage/src/control/agent_transaction_tests.rs
@@ -230,6 +230,82 @@ fn agent_operation(plan: TransactionPlanV1, key: &str) -> OperationV1 {
.unwrap()
}
+#[test]
+fn succeeded_agent_read_projection_checks_sql_identity_and_both_step_copies() {
+ let directory = tempdir().unwrap();
+ let control = ControlStore::open(
+ &crate::test_storage_authority(),
+ directory.path().join("control.db"),
+ directory.path().join("backups"),
+ )
+ .unwrap();
+ let mut operation = agent_operation(
+ agent_transaction_plan(AgentConnectionTransactionKindV1::Apply, None),
+ "read-facts",
+ );
+ control
+ .grant_apply_capability("read-facts-capability", &operation, i64::MAX)
+ .unwrap();
+ let authorization = control
+ .verify_apply_authorization(
+ &ProtectedApplyCapability::new("read-facts-capability".into()).unwrap(),
+ &operation.workspace_id,
+ &operation.idempotency.principal,
+ &operation.idempotency.operation_kind,
+ &operation.accepted_digest,
+ &operation.expected_revisions,
+ )
+ .unwrap();
+ control.begin_operation(&operation, &authorization).unwrap();
+ operation.state = hiroute_domain::OperationState::Succeeded;
+ for step in &mut operation.steps {
+ step.status = hiroute_domain::OperationStepStatus::Applied;
+ }
+ control.save_operation(&mut operation).unwrap();
+ let facts = control
+ .succeeded_agent_operations_for_kind(&operation.workspace_id, "ApplyAgentConnectionChange")
+ .unwrap();
+ assert_eq!(facts.len(), 1);
+ assert_eq!(facts[0].operation_id, operation.operation_id);
+ assert_eq!(facts[0].plan.spec(), operation.plan.spec());
+ assert_eq!(facts[0].plan.external(), operation.plan.external());
+ control.connection.borrow().execute("UPDATE operation_steps SET step_json=json_set(step_json,'$.step.attempts',99) WHERE step_no=2", []).unwrap();
+ assert_eq!(
+ control
+ .succeeded_agent_operations_for_kind(
+ &operation.workspace_id,
+ "ApplyAgentConnectionChange"
+ )
+ .unwrap_err()
+ .code,
+ hiroute_domain::PortErrorCode::Corrupt
+ );
+ control.connection.borrow().execute("UPDATE operation_steps SET step_json=json_set(step_json,'$.step.attempts',0) WHERE step_no=2", []).unwrap();
+ assert!(
+ control
+ .succeeded_agent_operations_for_kind(
+ &operation.workspace_id,
+ "ApplyAgentConnectionChange"
+ )
+ .is_ok()
+ );
+ control
+ .connection
+ .borrow()
+ .execute("UPDATE operations SET generation=generation+1", [])
+ .unwrap();
+ assert_eq!(
+ control
+ .succeeded_agent_operations_for_kind(
+ &operation.workspace_id,
+ "ApplyAgentConnectionChange"
+ )
+ .unwrap_err()
+ .code,
+ hiroute_domain::PortErrorCode::Corrupt
+ );
+}
+
#[test]
fn agent_connection_transaction_journal_reopens_with_exact_typed_plan() {
let directory = tempdir().unwrap();
diff --git a/crates/local-storage/src/control/compute/projection/tests.rs b/crates/local-storage/src/control/compute/projection/tests.rs
index c0261782..a35b22bc 100644
--- a/crates/local-storage/src/control/compute/projection/tests.rs
+++ b/crates/local-storage/src/control/compute/projection/tests.rs
@@ -942,12 +942,30 @@ pub(super) fn v7_operation_json() -> (
"accepted_digest": accepted,
"expected_revisions": expected_revisions,
});
- let step_two = serde_json::json!([plan["control"].clone(), serde_json::Value::Null]);
+ // This fixture isolates the schema-7 projection/CAS migration inside the current journal.
+ // Historical journal proofs are covered by the independently frozen schema-22 sources.
+ let step_two = serde_json::json!([
+ plan["control"].clone(),
+ serde_json::Value::Null,
+ serde_json::Value::Null
+ ]);
let _ = plan;
- durable["steps"][0]["deterministic_input_digest"] =
- serde_json::json!(CanonicalDigest::of(&step_zero).unwrap());
- durable["steps"][2]["deterministic_input_digest"] =
- serde_json::json!(CanonicalDigest::of(&step_two).unwrap());
+ durable["steps"][0]["deterministic_input_digest"] = serde_json::json!(
+ CanonicalDigest::of(&(
+ "hiroute.operation-step-input/v1",
+ hiroute_domain::OperationStepKind::Prepare,
+ step_zero
+ ))
+ .unwrap()
+ );
+ durable["steps"][2]["deterministic_input_digest"] = serde_json::json!(
+ CanonicalDigest::of(&(
+ "hiroute.operation-step-input/v1",
+ hiroute_domain::OperationStepKind::MaterializeSources,
+ step_two
+ ))
+ .unwrap()
+ );
(
serde_json::to_string(&durable).unwrap(),
operation_id,
diff --git a/crates/local-storage/src/control/mod.rs b/crates/local-storage/src/control/mod.rs
index e773326b..12459a76 100644
--- a/crates/local-storage/src/control/mod.rs
+++ b/crates/local-storage/src/control/mod.rs
@@ -1,6 +1,6 @@
use hiroute_diagnostics::publication::{PublicationStage, measure};
use std::cell::RefCell;
-use std::collections::{BTreeMap, BTreeSet};
+use std::collections::BTreeMap;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
@@ -8,14 +8,14 @@ use std::path::{Component, Path, PathBuf};
use aes_gcm::aead::{Aead, Payload};
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use hiroute_domain::{
- BeginOperationOutcome, CanonicalDigest, ChangeSpecV1, CompensationOutcome,
- ControlRepositoryPort, CredentialPoolMutationV1, CredentialRefV1, EffectReconciliation,
- ExternalEffectIntentV1, ExternalEffectPort, IdempotencyScopeV1, OperationId, OperationState,
- OperationStepV1, OperationV1, OwnedEffectKind, OwnedEffectV1, PortError, PortErrorCode,
- PortResult, ProtectedApplyCapability, RevisionMismatch, RevisionSetV1, RuntimeMutationV1,
- SecretFingerprintAlgorithm, SecretMutationKind, SecretMutationV1, TransactionPlanV1,
- VerifiedApplyAuthorizationV1, WorkerDependencySelectionChangeV1, WorkspaceId,
+ BeginOperationOutcome, CanonicalDigest, CompensationOutcome, ControlRepositoryPort,
+ EffectReconciliation, ExternalEffectIntentV1, ExternalEffectPort, IdempotencyScopeV1,
+ OperationId, OperationState, OperationStepV1, OperationV1, OwnedEffectKind, OwnedEffectV1,
+ PortError, PortErrorCode, PortResult, ProtectedApplyCapability, RevisionMismatch,
+ RevisionSetV1, VerifiedApplyAuthorizationV1, WorkerDependencySelectionChangeV1, WorkspaceId,
};
+#[cfg(test)]
+use hiroute_domain::{ChangeSpecV1, TransactionPlanV1};
use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior, params};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -32,6 +32,8 @@ mod surface_check_tests;
mod transaction_v2_tests;
mod agent_check;
+mod agent_read;
+pub use agent_read::SucceededAgentOperationV1;
#[path = "../agents/collaboration_store.rs"]
mod collaboration_store;
mod compute;
@@ -61,7 +63,8 @@ pub use compute::{
pub struct ControlStore {
diagnostics: RefCell<hiroute_diagnostics::DiagnosticsPort>,
- connection: RefCell<Connection>,
+ pub(crate) connection: RefCell<Connection>,
+ pub(crate) startup_lock: Option<std::sync::Arc<std::fs::File>>,
}
/// One exact grant received over the daemon launcher's protected inherited channel. The raw
@@ -210,6 +213,7 @@ impl ControlStore {
) -> Result<Self, LocalStorageError> {
Ok(Self {
diagnostics: RefCell::new(Default::default()),
+ startup_lock: None,
connection: RefCell::new(open_database(
_authority,
path,
@@ -227,6 +231,7 @@ impl ControlStore {
) -> Result<Self, LocalStorageError> {
Ok(Self {
diagnostics: RefCell::new(Default::default()),
+ startup_lock: None,
connection: RefCell::new(open_database_from_set(
authority,
path,
@@ -1742,62 +1747,6 @@ fn load_operation_where<P: rusqlite::Params>(
.transpose()
}
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct DurableSecretMutation {
- kind: SecretMutationKind,
- credential: CredentialRefV1,
- expected_generation: u64,
- #[serde(default)]
- fingerprint_algorithm: SecretFingerprintAlgorithm,
- input_slot: Option<String>,
- fingerprint: Option<CanonicalDigest>,
- new_allowed_destinations: Option<BTreeSet<String>>,
-}
-
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct DurableRuntimeMutation {
- key: String,
- value: Value,
- expected_generation: u64,
-}
-
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct DurableExternalIntent {
- effect_id: String,
- kind: OwnedEffectKind,
- target: String,
- before_fingerprint: Option<CanonicalDigest>,
- desired: Value,
- #[serde(default = "default_artifact_mode")]
- desired_mode: u32,
- #[serde(default)]
- sensitive: bool,
-}
-
-const fn default_artifact_mode() -> u32 {
- 0o644
-}
-
-#[derive(Deserialize)]
-#[serde(deny_unknown_fields)]
-struct DurablePlan {
- spec: ChangeSpecV1,
- control: Value,
- #[serde(default)]
- credential_pool: Option<CredentialPoolMutationV1>,
- #[serde(default)]
- worker_dependency_selection: Option<WorkerDependencySelectionChangeV1>,
- #[serde(default)]
- secrets: Vec<DurableSecretMutation>,
- #[serde(default)]
- runtime: Vec<DurableRuntimeMutation>,
- #[serde(default)]
- external: Vec<DurableExternalIntent>,
-}
-
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DurableOperation {
@@ -1808,7 +1757,7 @@ struct DurableOperation {
request_digest: CanonicalDigest,
accepted_digest: CanonicalDigest,
expected_revisions: RevisionSetV1,
- plan: DurablePlan,
+ plan: hiroute_domain::StoredOperationInputV1,
state: OperationState,
generation: u64,
steps: Vec<OperationStepV1>,
@@ -1845,150 +1794,16 @@ fn decode_operation(
Some(&operation_id),
Some(encoded.len()),
|| {
- let secrets = durable
- .plan
- .secrets
- .into_iter()
- .map(|mutation| {
- if mutation.fingerprint_algorithm
- != SecretFingerprintAlgorithm::HmacSha256V1
- {
- return Err(port(
- PortErrorCode::Corrupt,
- "control.operation.secret_algorithm",
- ));
- }
- match mutation.kind {
- SecretMutationKind::Upsert => SecretMutationV1::upsert(
- mutation.credential,
- mutation.expected_generation,
- mutation.input_slot.ok_or_else(|| {
- port(
- PortErrorCode::Corrupt,
- "control.operation.secret_slot",
- )
- })?,
- mutation.fingerprint,
- ),
- SecretMutationKind::Delete => {
- if mutation.input_slot.is_some()
- || mutation.fingerprint.is_some()
- {
- return Err(port(
- PortErrorCode::Corrupt,
- "control.operation.secret_delete",
- ));
- }
- SecretMutationV1::delete(
- mutation.credential,
- mutation.expected_generation,
- )
- }
- SecretMutationKind::Rebind => {
- if mutation.input_slot.is_some() {
- return Err(port(
- PortErrorCode::Corrupt,
- "control.operation.secret_rebind_slot",
- ));
- }
- SecretMutationV1::rebind(
- mutation.credential,
- mutation.new_allowed_destinations.ok_or_else(|| {
- port(
- PortErrorCode::Corrupt,
- "control.operation.secret_rebind_destinations",
- )
- })?,
- mutation.fingerprint.ok_or_else(|| {
- port(
- PortErrorCode::Corrupt,
- "control.operation.secret_rebind_fingerprint",
- )
- })?,
- )
- }
- }
- .map_err(|_| port(PortErrorCode::Corrupt, "control.operation.secret"))
- })
- .collect::<PortResult<Vec<_>>>()?;
- let runtime = durable
- .plan
- .runtime
- .into_iter()
- .map(|mutation| {
- RuntimeMutationV1::from_registered_planner(
- mutation.key,
- mutation.value,
- mutation.expected_generation,
- )
- .map_err(|_| port(PortErrorCode::Corrupt, "control.operation.runtime"))
- })
- .collect::<PortResult<Vec<_>>>()?;
- let external = durable
- .plan
- .external
- .into_iter()
- .map(|intent| {
- ExternalEffectIntentV1::from_registered_adapter(
- intent.effect_id,
- intent.kind,
- intent.target,
- intent.before_fingerprint,
- intent.desired,
- intent.desired_mode,
- intent.sensitive,
- )
- .map_err(|_| port(PortErrorCode::Corrupt, "control.operation.external"))
- })
- .collect::<PortResult<Vec<_>>>()?;
let plan = measure(
diagnostics,
PublicationStage::OperationPlanValidate,
Some(&operation_id),
Some(encoded.len()),
|| {
- if let Some(change) = durable.plan.worker_dependency_selection {
- if durable.plan.control != json!({})
- || durable.plan.credential_pool.is_some()
- || !secrets.is_empty()
- || !runtime.is_empty()
- || !external.is_empty()
- {
- return Err(port(
- PortErrorCode::Corrupt,
- "control.operation.plan",
- ));
- }
- let selection = WorkerDependencySelectionChangeV1::new(
- change.before_revision,
- hiroute_domain::WorkerDependencySelectionRecordV1::new(
- change.after_selection.harness,
- change.after_selection.adapter_path,
- change.after_selection.cli_path,
- change.after_selection.node_path,
- )
- .map_err(|_| {
- port(PortErrorCode::Corrupt, "control.operation.plan")
- })?,
- )
- .map_err(|_| {
- port(PortErrorCode::Corrupt, "control.operation.plan")
- })?;
- TransactionPlanV1::from_worker_dependency_selection_planner(
- durable.plan.spec,
- selection,
- )
- } else {
- TransactionPlanV1::from_registered_typed_planner(
- durable.plan.spec,
- durable.plan.control,
- durable.plan.credential_pool,
- secrets,
- runtime,
- external,
- )
- }
- .map_err(|_| port(PortErrorCode::Corrupt, "control.operation.plan"))
+ durable
+ .plan
+ .build()
+ .map_err(|_| port(PortErrorCode::Corrupt, "control.operation.plan"))
},
)?;
let expected_id = OperationId::derive(
diff --git a/crates/local-storage/src/control/plans/tests.rs b/crates/local-storage/src/control/plans/tests.rs
index a95cfdc2..f01c1cfd 100644
--- a/crates/local-storage/src/control/plans/tests.rs
+++ b/crates/local-storage/src/control/plans/tests.rs
@@ -62,8 +62,8 @@ fn saved_draft_cas_survives_reopen_and_cannot_overwrite_or_delete_newer_input()
}
fn version() -> PlanVersionV1 {
- let publication = GatewayPublicationV1::decode_persisted(
- include_str!("../../../../../e2e/product/golden/routing/compiled-publication.v2.json")
+ let publication = serde_json::from_slice::<hiroute_domain::GatewayPublicationV1>(
+ include_str!("../../../../../e2e/product/fixtures/routing/current-publication.v3.json")
.as_bytes(),
)
.unwrap();
diff --git a/crates/local-storage/src/lib.rs b/crates/local-storage/src/lib.rs
index b0814d45..eba7f62f 100644
--- a/crates/local-storage/src/lib.rs
+++ b/crates/local-storage/src/lib.rs
@@ -21,6 +21,7 @@ pub use backup::{BackupSet, SingleWriterBackupBarrier, SqliteBackup};
pub use control::{
ApplyCapabilityRegistrar, ApplyCapabilityRegistrationV1, ComputeSubscriptionValidationRecordV1,
ComputeSubscriptionValidationStateV1, ControlStore, ManagedArtifactStore,
+ SucceededAgentOperationV1,
};
pub use runtime::RuntimeStore;
pub use secrets::{LocalNativeCredentialAuthority, LocalSecretStore};
@@ -36,6 +37,13 @@ pub struct LocalStorageSet {
secrets: LocalSecretStore,
}
+#[derive(Clone, Debug, Default)]
+pub struct StorageStartupOptions {
+ pub gateway_lkg: Option<std::path::PathBuf>,
+ pub upgrade_progress:
+ Option<std::sync::mpsc::Sender<hiroute_host_runtime::StorageUpgradePhase>>,
+}
+
impl LocalStorageSet {
/// Opens and migrates the coordinated three-store set before daemon listeners or
/// transaction admission become available. The authority and writer barrier are minted only
@@ -43,21 +51,67 @@ impl LocalStorageSet {
/// ambient backup barrier.
pub fn open_for_daemon_startup(
storage_root: impl AsRef<Path>,
+ ) -> Result<Self, LocalStorageError> {
+ Self::open_for_daemon_startup_with_options(storage_root, &StorageStartupOptions::default())
+ }
+
+ pub fn open_for_daemon_startup_with_options(
+ storage_root: impl AsRef<Path>,
+ options: &StorageStartupOptions,
) -> Result<Self, LocalStorageError> {
let authority = daemon_storage_authority();
let barrier = backup::daemon_startup_barrier();
- Self::open(&authority, &barrier, storage_root)
+ Self::open_with_options(&authority, &barrier, storage_root, options)
}
- pub(crate) fn open(
+ fn open_with_options(
authority: &DaemonStorageAuthority,
barrier: &SingleWriterBackupBarrier,
storage_root: impl AsRef<Path>,
+ _options: &StorageStartupOptions,
) -> Result<Self, LocalStorageError> {
let storage_root = storage_root.as_ref();
migrations::prepare_storage_root(storage_root)?;
+ migrations::validate_startup_format(storage_root)?;
+ let startup_lock = std::sync::Arc::new(migrations::acquire_startup_lock(storage_root)?);
+ migrations::validate_startup_format(storage_root)?;
+ Self::open_locked_stores(authority, barrier, storage_root, startup_lock)
+ }
+
+ // SQL coordinator component harness only: unsupported formats never pass through the
+ // production startup entry. Retains the coordinator's crash/backup assertions independently.
+ #[cfg(test)]
+ pub(crate) fn open_migration_component_fixture(
+ authority: &DaemonStorageAuthority,
+ barrier: &SingleWriterBackupBarrier,
+ storage_root: &Path,
+ ) -> Result<Self, LocalStorageError> {
+ migrations::prepare_storage_root(storage_root)?;
+ let lock = std::sync::Arc::new(migrations::acquire_startup_lock(storage_root)?);
+ Self::open_locked_stores(authority, barrier, storage_root, lock)
+ }
+
+ fn open_locked_stores(
+ authority: &DaemonStorageAuthority,
+ barrier: &SingleWriterBackupBarrier,
+ storage_root: &Path,
+ startup_lock: std::sync::Arc<std::fs::File>,
+ ) -> Result<Self, LocalStorageError> {
let live_root = storage_root.join("live");
- let backup_root = storage_root.join("migration-set");
+ let backup_root = upgrade_backup_root(storage_root)?;
+ migrations::prepare_storage_root(
+ backup_root.parent().ok_or(LocalStorageError::InvalidData)?,
+ )?;
+ let previous = storage_root.join("migration-set");
+ if previous.exists() {
+ if backup_root.exists() {
+ return Err(LocalStorageError::InvalidData);
+ }
+ std::fs::rename(previous, &backup_root)?;
+ std::fs::File::open(storage_root)?.sync_all()?;
+ std::fs::File::open(backup_root.parent().ok_or(LocalStorageError::InvalidData)?)?
+ .sync_all()?;
+ }
let master_key_path = storage_root.join("master-key");
let control_path = live_root.join("control.db");
let runtime_path = live_root.join("runtime.db");
@@ -70,7 +124,6 @@ impl LocalStorageSet {
&backup_root,
secret_binding.as_ref(),
)?;
-
let control_result = if migration.durable_set_prepared() {
ControlStore::open_from_migration_set(
authority,
@@ -83,7 +136,7 @@ impl LocalStorageSet {
} else {
ControlStore::open(authority, &control_path, &backup_root)
};
- let control = match control_result {
+ let mut control = match control_result {
Ok(control) => control,
Err(error) => {
migration.restore_after_failure(barrier, &live_root)?;
@@ -108,7 +161,7 @@ impl LocalStorageSet {
} else {
RuntimeStore::open(authority, &runtime_path, &backup_root)
};
- let runtime = match runtime_result {
+ let mut runtime = match runtime_result {
Ok(runtime) => runtime,
Err(error) => {
drop(control);
@@ -134,7 +187,7 @@ impl LocalStorageSet {
} else {
LocalSecretStore::open(authority, &secrets_path, &master_key_path, &backup_root)
};
- let secrets = match secrets_result {
+ let mut secrets = match secrets_result {
Ok(secrets) => secrets,
Err(error) => {
drop(runtime);
@@ -150,6 +203,15 @@ impl LocalStorageSet {
migration.restore_after_failure(barrier, &live_root)?;
return Err(error);
}
+ if let Err(error) = migrations::validate_current_storage(&control, &runtime, &secrets)
+ .map_err(|error| error.at_upgrade_stage("current storage validation"))
+ {
+ drop(secrets);
+ drop(runtime);
+ drop(control);
+ migration.restore_after_failure(barrier, &live_root)?;
+ return Err(error);
+ }
if let Err(error) = migration.mark_completed(barrier) {
drop(secrets);
drop(runtime);
@@ -157,6 +219,9 @@ impl LocalStorageSet {
migration.restore_after_failure(barrier, &live_root)?;
return Err(error);
}
+ control.startup_lock = Some(startup_lock.clone());
+ runtime.startup_lock = Some(startup_lock.clone());
+ secrets.startup_lock = Some(startup_lock);
Ok(Self {
control,
runtime,
@@ -164,6 +229,12 @@ impl LocalStorageSet {
})
}
+ /// Validate cross-store grant/publication equality after Operation recovery and before
+ /// serving admission opens. Store opening deliberately admits recoverable saga checkpoints.
+ pub fn validate_recovered_grant_publications(&self) -> Result<(), LocalStorageError> {
+ migrations::validate_recovered_grant_publications(&self.control, &self.secrets)
+ }
+
pub fn control(&self) -> &ControlStore {
&self.control
}
@@ -231,6 +302,19 @@ impl LocalStorageSet {
)
}
}
+/// Upgrade backups live beside the directory restored as a whole, never inside it.
+pub fn upgrade_backup_root(storage_root: &Path) -> Result<std::path::PathBuf, LocalStorageError> {
+ let mut name = storage_root
+ .file_name()
+ .ok_or(LocalStorageError::InvalidData)?
+ .to_os_string();
+ name.push(".upgrade-backups");
+ Ok(storage_root
+ .parent()
+ .ok_or(LocalStorageError::InvalidData)?
+ .join(name)
+ .join("migration-set"))
+}
#[cfg(test)]
mod startup_tests {
@@ -399,6 +483,15 @@ pub const IMPLEMENTATION_STATUS: &str = "transaction-v1";
#[derive(Debug, Error)]
pub enum LocalStorageError {
+ #[error(
+ "UPGRADE_SOURCE_UNSUPPORTED: this source format has no validated upgrade and recovery path"
+ )]
+ UpgradeSourceUnsupported,
+ #[error("stable storage upgrade failed at {stage}: {source}")]
+ UpgradeStage {
+ stage: &'static str,
+ source: Box<LocalStorageError>,
+ },
#[error("local storage I/O failed")]
Io(#[from] std::io::Error),
#[error("local SQLite operation failed")]
@@ -412,3 +505,12 @@ pub enum LocalStorageError {
#[error("encrypted local state is locked because its exact key binding is unavailable")]
Locked,
}
+
+impl LocalStorageError {
+ pub(crate) fn at_upgrade_stage(self, stage: &'static str) -> Self {
+ Self::UpgradeStage {
+ stage,
+ source: Box::new(self),
+ }
+ }
+}
diff --git a/crates/local-storage/src/migrations/completed_batches.rs b/crates/local-storage/src/migrations/completed_batches.rs
new file mode 100644
index 00000000..83c30637
--- /dev/null
+++ b/crates/local-storage/src/migrations/completed_batches.rs
@@ -0,0 +1,40 @@
+//! Completed backups belong to one migration batch, including after manual old-data recovery.
+use super::*;
+
+pub(super) fn archive_if_needed(
+ previous: &BackupSet,
+ paths: &[PathBuf; 3],
+ backup_root: &Path,
+ _secret_binding: Option<&MigrationSecretBinding>,
+) -> Result<(), LocalStorageError> {
+ if previous.phase() != BackupSetPhase::Completed
+ || previous.target_schema_version() > LATEST_SCHEMA_VERSION
+ {
+ return Ok(());
+ }
+ let versions = [
+ database_version(&paths[0])?,
+ database_version(&paths[1])?,
+ database_version(&paths[2])?,
+ ];
+ if previous.target_schema_version() == LATEST_SCHEMA_VERSION {
+ return Ok(());
+ }
+ if versions
+ .iter()
+ .any(|v| *v != Some(previous.target_schema_version()))
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ let parent = backup_root.parent().ok_or(LocalStorageError::InvalidData)?;
+ let archived = parent.join(format!("migration-set.{}", previous.set_id()));
+ match fs::symlink_metadata(&archived) {
+ Ok(_) => return Err(LocalStorageError::InvalidData),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error.into()),
+ }
+ crate::backup::source_snapshot::archive_guide(backup_root, &archived, previous.set_id())?;
+ fs::rename(backup_root, &archived)?;
+ std::fs::File::open(parent)?.sync_all()?;
+ Ok(())
+}
diff --git a/crates/local-storage/src/migrations/current_storage.rs b/crates/local-storage/src/migrations/current_storage.rs
new file mode 100644
index 00000000..b0c32106
--- /dev/null
+++ b/crates/local-storage/src/migrations/current_storage.rs
@@ -0,0 +1,154 @@
+//! Current stable-format initialization, ownership and integrity validation.
+use super::*;
+use hiroute_domain::*;
+
+pub(super) const MARKER_SQL: &str = "CREATE TABLE stable_storage_format(singleton INTEGER PRIMARY KEY CHECK(singleton=1), format_version INTEGER NOT NULL CHECK(format_version=1), converted INTEGER NOT NULL CHECK(converted IN (0,1))); INSERT INTO stable_storage_format VALUES(1,1,1);";
+
+pub(crate) fn acquire_startup_lock(root: &Path) -> Result<std::fs::File, LocalStorageError> {
+ use fs2::FileExt;
+ let path = root.join("startup.lock");
+ if path.exists() {
+ validate_owner_file(&path)?;
+ }
+ let mut options = std::fs::OpenOptions::new();
+ options.create(true).read(true).write(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ options.custom_flags(
+ (rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32,
+ );
+ }
+ let file = options.open(&path)?;
+ validate_owner_file(&path)?;
+ file.try_lock_exclusive()
+ .map_err(|_| LocalStorageError::InvalidData)?;
+ Ok(file)
+}
+
+pub(crate) fn validate_current_storage(
+ control: &crate::ControlStore,
+ runtime: &crate::RuntimeStore,
+ secrets: &crate::LocalSecretStore,
+) -> Result<(), LocalStorageError> {
+ crate::secrets::validate_stable_grants(secrets)?;
+ let connection = control.connection.borrow();
+ let mut statement=connection.prepare("SELECT workspace_id,plan_id,content_revision,content_digest,version_json FROM plan_versions")?;
+ for row in statement.query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, u64>(2)?,
+ r.get::<_, String>(3)?,
+ r.get::<_, String>(4)?,
+ ))
+ })? {
+ let (workspace, plan, revision, digest, json) = row?;
+ let value: PlanVersionV1 =
+ serde_json::from_str(&json).map_err(|_| LocalStorageError::InvalidData)?;
+ value
+ .validate()
+ .map_err(|_| LocalStorageError::InvalidData)?;
+ if value.reference.workspace_id.as_str() != workspace
+ || value.reference.plan_id.as_str() != plan
+ || value.reference.content_revision != revision
+ || value.reference.content_digest.as_str() != digest
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ }
+ let invalid:bool=connection.query_row("SELECT EXISTS(SELECT 1 FROM plan_version_holds h LEFT JOIN plan_versions v USING(workspace_id,plan_id,content_revision) WHERE v.content_digest IS NULL OR h.content_digest!=v.content_digest)",[],|r|r.get(0))?;
+ if invalid {
+ return Err(LocalStorageError::InvalidData);
+ }
+ let invalid: bool = connection.query_row("SELECT EXISTS(SELECT 1 FROM plan_heads h LEFT JOIN plan_versions v ON v.workspace_id=h.workspace_id AND v.plan_id=h.plan_id AND v.content_revision=json_extract(h.head_json,'$.reference.content_revision') WHERE v.content_digest IS NULL OR v.content_digest IS NOT json_extract(h.head_json,'$.reference.content_digest'))", [], |r| r.get(0))?;
+ if invalid {
+ return Err(LocalStorageError::InvalidData);
+ }
+ visit_publications(&connection, |_| {})?;
+ // Cross-store grant/publication equality is checked only after Operation recovery.
+ // Each store's format and integrity must already be valid before recovery writes.
+ let secret_connection = secrets.connection.borrow();
+ for store in [
+ &*connection,
+ &*runtime.connection.borrow(),
+ &*secret_connection,
+ ] {
+ let result: String = store.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
+ if result != "ok" {
+ return Err(LocalStorageError::InvalidData);
+ }
+ }
+ Ok(())
+}
+
+/// Validate every retained publication, retaining only one decoded runtime object at a time.
+fn visit_publications(
+ connection: &rusqlite::Connection,
+ mut inspect: impl FnMut(&GatewayPublicationV1),
+) -> Result<(), LocalStorageError> {
+ let mut statement=connection.prepare("SELECT workspace_id,publication_revision,digest,publication_bytes FROM gateway_publications")?;
+ for row in statement.query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, u64>(1)?,
+ r.get::<_, String>(2)?,
+ r.get::<_, Vec<u8>>(3)?,
+ ))
+ })? {
+ let (workspace, revision, digest, bytes) = row?;
+ let publication =
+ GatewayPublicationV1::decode(&bytes).map_err(|_| LocalStorageError::InvalidData)?;
+ if publication.workspace_id.as_str() != workspace
+ || publication.publication_revision.get() != revision
+ || CanonicalDigest::of_bytes(&bytes).as_str() != digest
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ inspect(&publication);
+ }
+ Ok(())
+}
+
+/// Active Secret heads may legitimately precede publication compensation on a crash.
+/// Run only after journal recovery, before resuming serving admission. Historical revoked
+/// grants remain history and never regain admission authority through this check.
+pub(crate) fn validate_recovered_grant_publications(
+ control: &crate::ControlStore,
+ secrets: &crate::LocalSecretStore,
+) -> Result<(), LocalStorageError> {
+ let secret_connection = secrets.connection.borrow();
+ let mut statement=secret_connection.prepare("SELECT v.grant_id,v.generation,v.scope_json,v.material_sha256 FROM agent_access_grant_heads h JOIN agent_access_grant_versions v ON v.connection_id=h.connection_id AND v.generation=h.active_version_generation")?;
+ let mut unmatched = Vec::new();
+ for row in statement.query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, u64>(1)?,
+ r.get::<_, String>(2)?,
+ r.get::<_, String>(3)?,
+ ))
+ })? {
+ let (id, generation, json, material) = row?;
+ let scope: AgentAccessGrantScopeV1 =
+ serde_json::from_str(&json).map_err(|_| LocalStorageError::InvalidData)?;
+ unmatched.push((id, generation, scope, material));
+ }
+ visit_publications(&control.connection.borrow(), |publication| {
+ unmatched.retain(|(id, generation, scope, material)| {
+ !publication.grants.iter().any(|grant| {
+ grant.grant_id == *id
+ && grant.generation == *generation
+ && grant.bearer_token_sha256.as_str() == material
+ && grant.model_grant == *scope.model_grant()
+ })
+ });
+ })?;
+ if !unmatched.is_empty() {
+ return Err(LocalStorageError::InvalidData);
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/local-storage/src/migrations/current_storage/tests.rs b/crates/local-storage/src/migrations/current_storage/tests.rs
new file mode 100644
index 00000000..b445f53d
--- /dev/null
+++ b/crates/local-storage/src/migrations/current_storage/tests.rs
@@ -0,0 +1,143 @@
+use super::*;
+use crate::LocalStorageSet;
+
+fn history(stores: &LocalStorageSet, count: u64) {
+ let mut publication: GatewayPublicationV1 = serde_json::from_slice(include_bytes!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../../e2e/product/fixtures/routing/current-publication.v3.json"
+ )))
+ .unwrap();
+ publication.grants.clear();
+ publication.aliases.clear();
+ for revision in 1..=count {
+ publication.publication_revision = GatewayPublicationRevision::new(revision).unwrap();
+ let record =
+ PublicationRecordV1::from_publication(WorkspaceId::default(), &publication).unwrap();
+ stores
+ .control()
+ .prepare_publication(
+ &record,
+ (revision > 1).then(|| GatewayPublicationRevision::new(revision - 1).unwrap()),
+ )
+ .unwrap();
+ stores
+ .control()
+ .mark_publication_active(
+ &WorkspaceId::default(),
+ record.publication_revision,
+ &record.digest,
+ )
+ .unwrap();
+ }
+}
+
+#[test]
+fn retained_publications_are_visited_one_at_a_time_including_history() {
+ let root = crate::test_tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ history(&stores, 256);
+ let mut visited = std::collections::BTreeSet::new();
+ visit_publications(&stores.control.connection.borrow(), |publication| {
+ // Only scalar identities survive the visitor; decoded publications are borrowed.
+ assert!(visited.insert(publication.publication_revision.get()));
+ })
+ .unwrap();
+ assert_eq!(visited, (1..=256).collect());
+ validate_current_storage(stores.control(), stores.runtime(), stores.secrets()).unwrap();
+ stores.validate_recovered_grant_publications().unwrap();
+}
+
+#[test]
+fn corrupt_historical_publication_is_rejected_even_without_active_grants() {
+ let root = crate::test_tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ history(&stores, 3);
+ // Keep active and LKG records intact; damage only retained history.
+ stores.control.connection.borrow().execute(
+ "UPDATE gateway_publications SET digest='corrupted-history' WHERE publication_revision=1",
+ [],
+ ).unwrap();
+ assert!(
+ validate_current_storage(stores.control(), stores.runtime(), stores.secrets()).is_err()
+ );
+ assert!(stores.validate_recovered_grant_publications().is_err());
+ drop(stores);
+ assert!(LocalStorageSet::open_for_daemon_startup(root.path()).is_err());
+}
+
+#[test]
+fn recovered_grants_match_exact_material_and_generation_in_retained_history() {
+ let root = crate::test_tempdir().unwrap();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ history(&stores, 3);
+ let mut publication: GatewayPublicationV1 = serde_json::from_slice(include_bytes!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../../e2e/product/fixtures/routing/current-publication.v3.json"
+ )))
+ .unwrap();
+ // Project the frozen facts with this test build's current compiler before issuing a grant.
+ publication = publication.into_current().unwrap();
+ let scope = AgentAccessGrantScopeV1::new(
+ "agent-connection/history-match",
+ publication.grants[0].model_grant.clone(),
+ )
+ .unwrap();
+ let mutation = AgentAccessGrantMutationV1::ensure("principal/local-owner", scope, 0).unwrap();
+ let operation = OperationId::parse("op_0123456789abcdef0123456789abcdef").unwrap();
+ let effect = stores
+ .secrets()
+ .apply_agent_access_grant(&operation, &mutation, None)
+ .unwrap();
+ let reference = AgentAccessGrantRefV1::from_ensure_effect(&effect, &mutation).unwrap();
+ stores
+ .secrets()
+ .activate_agent_access_grant(&effect)
+ .unwrap();
+ // Retain the other fixture grants so its executable alias projection stays closed.
+ publication.grants[0].grant_id = reference.grant_id().into();
+ publication.grants[0].generation = reference.generation();
+ publication.grants[0].bearer_token_sha256 = reference.material_sha256().clone();
+ publication
+ .grants
+ .sort_by(|a, b| a.grant_id.cmp(&b.grant_id));
+ let grant_index = publication
+ .grants
+ .iter()
+ .position(|grant| grant.grant_id == reference.grant_id())
+ .unwrap();
+ for revision in 1..=3 {
+ publication.publication_revision = GatewayPublicationRevision::new(revision).unwrap();
+ if revision == 2 {
+ publication.grants[grant_index].bearer_token_sha256 =
+ CanonicalDigest::of_bytes(b"different bearer");
+ } else if revision == 3 {
+ publication.grants[grant_index].bearer_token_sha256 =
+ reference.material_sha256().clone();
+ publication.grants[grant_index].generation += 1;
+ }
+ let record =
+ PublicationRecordV1::from_publication(WorkspaceId::default(), &publication).unwrap();
+ // Inject individually valid records with deliberately inconsistent cross-store grants.
+ // Normal publication transitions correctly reject changing a generation's bearer.
+ stores.control.connection.borrow().execute(
+ "UPDATE gateway_publications SET digest=?1, publication_bytes=?2 WHERE publication_revision=?3",
+ rusqlite::params![record.digest.as_str(), record.bytes.as_slice(), revision],
+ ).unwrap();
+ }
+ stores.validate_recovered_grant_publications().unwrap();
+ stores
+ .control
+ .connection
+ .borrow()
+ .execute(
+ "DELETE FROM gateway_publications WHERE publication_revision=1",
+ [],
+ )
+ .unwrap();
+ // Different material or generation never satisfies the active Secret's exact reference.
+ assert!(stores.validate_recovered_grant_publications().is_err());
+ // This state can be a saga checkpoint: opening admits recovery, not serving traffic.
+ drop(stores);
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ assert!(stores.validate_recovered_grant_publications().is_err());
+}
diff --git a/crates/local-storage/src/migrations/integration_v17_tests.rs b/crates/local-storage/src/migrations/integration_v17_tests.rs
index 8394e429..b3bcb767 100644
--- a/crates/local-storage/src/migrations/integration_v17_tests.rs
+++ b/crates/local-storage/src/migrations/integration_v17_tests.rs
@@ -8,7 +8,7 @@ fn fresh_current_contains_worker_subscription_and_concurrency_formats_and_reopen
let root = tempdir().unwrap();
let storage = root.path().join("storage");
drop(
- LocalStorageSet::open(
+ LocalStorageSet::open_migration_component_fixture(
&crate::test_storage_authority(),
&test_writer_barrier(),
&storage,
@@ -51,7 +51,7 @@ fn fresh_current_contains_worker_subscription_and_concurrency_formats_and_reopen
assert_eq!(worker_settings, if index == 1 { 1 } else { 0 });
}
drop(
- LocalStorageSet::open(
+ LocalStorageSet::open_migration_component_fixture(
&crate::test_storage_authority(),
&test_writer_barrier(),
&storage,
@@ -78,7 +78,7 @@ fn v15_and_both_experimental_v16_layouts_converge_without_losing_data_or_keys()
let storage = root.path().join("storage");
let live = storage.join("live");
drop(
- LocalStorageSet::open(
+ LocalStorageSet::open_migration_component_fixture(
&crate::test_storage_authority(),
&test_writer_barrier(),
&storage,
@@ -100,6 +100,7 @@ fn v15_and_both_experimental_v16_layouts_converge_without_losing_data_or_keys()
"CREATE TABLE IF NOT EXISTS convergence_sentinel(value TEXT NOT NULL);
DELETE FROM convergence_sentinel;
INSERT INTO convergence_sentinel(value) VALUES ('preserve-me');
+ DROP TABLE IF EXISTS stable_storage_format;
DROP TABLE IF EXISTS worker_authorization_format;
DROP TABLE IF EXISTS worker_settings;",
)
@@ -141,7 +142,7 @@ fn v15_and_both_experimental_v16_layouts_converge_without_losing_data_or_keys()
}
drop(
- LocalStorageSet::open(
+ LocalStorageSet::open_migration_component_fixture(
&crate::test_storage_authority(),
&test_writer_barrier(),
&storage,
@@ -154,7 +155,7 @@ fn v15_and_both_experimental_v16_layouts_converge_without_losing_data_or_keys()
);
let backup = BackupSet::open(
&crate::test_storage_authority(),
- storage.join("migration-set"),
+ crate::upgrade_backup_root(&storage).unwrap(),
)
.unwrap();
assert_eq!(backup.phase(), BackupSetPhase::Completed);
@@ -210,7 +211,7 @@ fn v15_and_both_experimental_v16_layouts_converge_without_losing_data_or_keys()
// Completed migration metadata and converged schemas are restart-idempotent.
drop(
- LocalStorageSet::open(
+ LocalStorageSet::open_migration_component_fixture(
&crate::test_storage_authority(),
&test_writer_barrier(),
&storage,
diff --git a/crates/local-storage/src/migrations/mod.rs b/crates/local-storage/src/migrations/mod.rs
index b4297fd3..db6e1ea0 100644
--- a/crates/local-storage/src/migrations/mod.rs
+++ b/crates/local-storage/src/migrations/mod.rs
@@ -11,7 +11,16 @@ use hiroute_domain::CanonicalDigest;
mod agent_access_grant_v9;
mod agent_surface_checks_v22;
+mod current_storage;
+mod startup_format;
+pub(crate) use startup_format::validate_startup_format;
+#[cfg(test)]
+mod stopped_read_tests;
+pub(crate) use current_storage::{
+ acquire_startup_lock, validate_current_storage, validate_recovered_grant_publications,
+};
mod collaboration_dependency;
+mod completed_batches;
mod compute_v8;
mod convergence_v15;
mod convergence_v17;
@@ -31,7 +40,7 @@ mod convergence_tests;
/// Converged integration format: Worker marker in all stores, Control subscription validations,
/// and the single runtime-owned Worker concurrency setting. Older layouts migrate through a
/// durable three-store backup set.
-pub const LATEST_SCHEMA_VERSION: u32 = 22;
+pub const LATEST_SCHEMA_VERSION: u32 = 23;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DatabaseKind {
@@ -210,7 +219,7 @@ pub(crate) fn prepare_storage_root(path: &Path) -> Result<(), LocalStorageError>
prepare_owner_directory(path)
}
-fn validate_owner_file(path: &Path) -> Result<(), LocalStorageError> {
+pub(crate) fn validate_owner_file(path: &Path) -> Result<(), LocalStorageError> {
let metadata = fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
return Err(LocalStorageError::Permission);
@@ -331,12 +340,32 @@ impl MigrationSetCoordinator {
backup_root: &Path,
secret_binding: Option<&MigrationSecretBinding>,
) -> Result<Self, LocalStorageError> {
+ if BackupSet::durable_manifest_present(backup_root)? {
+ let previous = BackupSet::open(authority, backup_root)?;
+ completed_batches::archive_if_needed(
+ &previous,
+ &live_database_paths(live_root),
+ backup_root,
+ secret_binding,
+ )?;
+ }
let durable_present = BackupSet::durable_manifest_present(backup_root)?;
let mut durable_set = if durable_present {
Some(BackupSet::open(authority, backup_root)?)
} else {
None
};
+ if let Some(set) = durable_set.as_mut()
+ && set.phase() != BackupSetPhase::Completed
+ && backup_root.join("conversion-in-progress").exists()
+ {
+ crate::backup::source_snapshot::verify_unchanged(
+ live_root.parent().ok_or(LocalStorageError::InvalidData)?,
+ backup_root,
+ )?;
+ set.restore_over_live_root(barrier, live_root)?;
+ return Err(LocalStorageError::InvalidData);
+ }
// Reconcile the directory swap before creating or inspecting `live`. In the
// after-live-rename crash state that path is intentionally absent; recreating an empty
// directory here would hide the durable restore-ready generation and make recovery fail.
@@ -487,6 +516,12 @@ impl MigrationSetCoordinator {
if set.phase() == BackupSetPhase::Completed {
return Err(LocalStorageError::InvalidData);
}
+ if set.directory().join("source/source-backup.json").exists() {
+ crate::backup::source_snapshot::verify_unchanged(
+ live_root.parent().ok_or(LocalStorageError::InvalidData)?,
+ set.directory(),
+ )?;
+ }
set.restore_over_live_root(barrier, live_root)
}
@@ -731,6 +766,9 @@ fn migration_sql(kind: DatabaseKind, version: u32) -> Result<&'static str, Local
(DatabaseKind::Control | DatabaseKind::Secrets, 21) => Ok(NOOP_V9),
(DatabaseKind::Control, 22) => Ok(agent_surface_checks_v22::CONTROL),
(DatabaseKind::Runtime | DatabaseKind::Secrets, 22) => Ok(NOOP_V9),
+ (DatabaseKind::Control | DatabaseKind::Runtime | DatabaseKind::Secrets, 23) => {
+ Ok(current_storage::MARKER_SQL)
+ }
_ => Err(LocalStorageError::InvalidData),
}
}
@@ -1199,7 +1237,7 @@ mod tests {
fn replace_with_legacy_v1_set(storage_root: &Path) {
drop(
- LocalStorageSet::open(
+ LocalStorageSet::open_migration_component_fixture(
&crate::test_storage_authority(),
&test_writer_barrier(),
storage_root,
@@ -1242,8 +1280,8 @@ mod tests {
"INSERT INTO workspace_state(
workspace_id, desired_json, target_revision, desired_digest,
owner_operation_id, updated_at
- ) VALUES ('personal/default', '{}', 17, ?1, NULL, 1)",
- [CanonicalDigest::of_bytes(b"legacy-control").as_str()],
+ ) VALUES ('personal/default', '{\"schema\":\"hiroute.control-desired/v1\",\"value\":{}}', 17, ?1, NULL, 1)",
+ [CanonicalDigest::of(&serde_json::json!({})).unwrap().as_str()],
)
.unwrap();
}
@@ -1472,7 +1510,7 @@ mod tests {
let storage_root = directory.path().join("storage");
replace_with_legacy_v1_set(&storage_root);
let live = storage_root.join("live");
- let backup_root = storage_root.join("migration-set");
+ let backup_root = crate::upgrade_backup_root(&storage_root).unwrap();
let binding = LocalSecretStore::migration_binding(
&live.join("secrets.db"),
&storage_root.join("master-key"),
@@ -1525,9 +1563,12 @@ mod tests {
// Restart observes either the source phase or the persisted control phase, proves the
// already-upgraded control UUID, and deterministically completes the remaining pair.
- let storage =
- LocalStorageSet::open(&crate::test_storage_authority(), &barrier, &storage_root)
- .unwrap();
+ let storage = LocalStorageSet::open_migration_component_fixture(
+ &crate::test_storage_authority(),
+ &barrier,
+ &storage_root,
+ )
+ .unwrap();
let assert_latest = |connection: &Connection| {
let version: u32 = connection
.query_row("PRAGMA user_version", [], |row| row.get(0))
@@ -1579,8 +1620,12 @@ mod tests {
assert_eq!(revision, 17);
drop(restored_control);
drop(
- LocalStorageSet::open(&crate::test_storage_authority(), &barrier, &storage_root)
- .unwrap(),
+ LocalStorageSet::open_migration_component_fixture(
+ &crate::test_storage_authority(),
+ &barrier,
+ &storage_root,
+ )
+ .unwrap(),
);
}
}
@@ -1599,7 +1644,7 @@ mod tests {
let storage_root = directory.path().join("storage");
replace_with_legacy_v1_set(&storage_root);
let live = storage_root.join("live");
- let backup_root = storage_root.join("migration-set");
+ let backup_root = crate::upgrade_backup_root(&storage_root).unwrap();
let binding = LocalSecretStore::migration_binding(
&live.join("secrets.db"),
&storage_root.join("master-key"),
@@ -1643,13 +1688,21 @@ mod tests {
// the exact three source backups, republishes the set manifest, and finishes all
// migrations. A second restart proves the stage cannot become a permanent blocker.
drop(
- LocalStorageSet::open(&crate::test_storage_authority(), &barrier, &storage_root)
- .unwrap(),
+ LocalStorageSet::open_migration_component_fixture(
+ &crate::test_storage_authority(),
+ &barrier,
+ &storage_root,
+ )
+ .unwrap(),
);
assert!(!stage.exists());
drop(
- LocalStorageSet::open(&crate::test_storage_authority(), &barrier, &storage_root)
- .unwrap(),
+ LocalStorageSet::open_migration_component_fixture(
+ &crate::test_storage_authority(),
+ &barrier,
+ &storage_root,
+ )
+ .unwrap(),
);
let completed =
BackupSet::open(&crate::test_storage_authority(), &backup_root).unwrap();
@@ -1678,7 +1731,7 @@ mod tests {
let storage_root = directory.path().join("storage");
replace_with_legacy_v1_set(&storage_root);
let live = storage_root.join("live");
- let backup_root = storage_root.join("migration-set");
+ let backup_root = crate::upgrade_backup_root(&storage_root).unwrap();
let binding = LocalSecretStore::migration_binding(
&live.join("secrets.db"),
&storage_root.join("master-key"),
@@ -1724,11 +1777,16 @@ mod tests {
}
drop(set);
- // Exercise the production-shaped storage owner, not the coordinator test seam. The
+ // Exercise the SQL coordinator component harness. Unsupported sources cannot enter
+ // production startup. The
// first reopen completes the exact group restore and stays fail-closed for that call.
assert!(
- LocalStorageSet::open(&crate::test_storage_authority(), &barrier, &storage_root,)
- .is_err()
+ LocalStorageSet::open_migration_component_fixture(
+ &crate::test_storage_authority(),
+ &barrier,
+ &storage_root,
+ )
+ .is_err()
);
let restored = BackupSet::open(&crate::test_storage_authority(), &backup_root).unwrap();
assert_eq!(restored.phase(), BackupSetPhase::Restored);
diff --git a/crates/local-storage/src/migrations/startup_format.rs b/crates/local-storage/src/migrations/startup_format.rs
new file mode 100644
index 00000000..8e180846
--- /dev/null
+++ b/crates/local-storage/src/migrations/startup_format.rs
@@ -0,0 +1,198 @@
+//! Reject unsupported source formats before any database, key or backup mutation.
+use super::*;
+
+pub(crate) fn validate_startup_format(root: &Path) -> Result<(), LocalStorageError> {
+ let live = root.join("live");
+ let paths = live_database_paths(&live);
+ let present = paths.map(|path| path.exists());
+ if present == [false; 3] {
+ // Only a fresh directory may initialize. A missing live set with durable facts is
+ // damage or an interrupted restore, never an invitation to create empty databases.
+ if fs::read_dir(root)?.any(|entry| {
+ entry.map_or(true, |entry| {
+ let name = entry.file_name();
+ name != "startup.lock"
+ && !(name == "diagnostics" && bootstrap_diagnostics_directory(&entry.path()))
+ && !(name == "live"
+ && fs::read_dir(entry.path())
+ .is_ok_and(|mut entries| entries.next().is_none()))
+ })
+ }) || crate::upgrade_backup_root(root)?.exists()
+ {
+ return Err(LocalStorageError::InvalidData);
+ }
+ return Ok(());
+ }
+ if present != [true; 3] {
+ return Err(LocalStorageError::InvalidData);
+ }
+ for path in live_database_paths(&live) {
+ validate_owner_file(&path)?;
+ let connection = Connection::open_with_flags(
+ &path,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )?;
+ let version: u32 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
+ if version != LATEST_SCHEMA_VERSION {
+ return Err(LocalStorageError::UpgradeSourceUnsupported);
+ }
+ let marker = connection.query_row(
+ "SELECT format_version, converted FROM stable_storage_format WHERE singleton=1",
+ [],
+ |row| Ok((row.get::<_, u32>(0)?, row.get::<_, u32>(1)?)),
+ );
+ if !matches!(marker, Ok((1, 1))) {
+ return Err(LocalStorageError::UpgradeSourceUnsupported);
+ }
+ }
+ Ok(())
+}
+
+// The production diagnostics runtime starts before storage and retains startup failures.
+// Recognize only its real private directory; never follow a link or modify its contents.
+fn bootstrap_diagnostics_directory(path: &Path) -> bool {
+ let Ok(metadata) = fs::symlink_metadata(path) else {
+ return false;
+ };
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
+ return false;
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ if metadata.mode() & 0o777 != 0o700 || metadata.uid() != rustix::process::getuid().as_raw()
+ {
+ return false;
+ }
+ }
+ true
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn production_diagnostics_can_precede_first_store_without_being_discarded() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().join("storage");
+ prepare_storage_root(&root).unwrap();
+ prepare_storage_root(&root.join("diagnostics")).unwrap();
+ prepare_storage_root(&root.join("diagnostics/daemon")).unwrap();
+ let log = root.join("diagnostics/daemon/current.jsonl");
+ fs::write(&log, b"retained startup diagnostic\n").unwrap();
+ set_owner_file_permissions(&log).unwrap();
+ drop(crate::LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+ assert_eq!(fs::read(log).unwrap(), b"retained startup diagnostic\n");
+ assert!(root.join("live/control.db").is_file());
+ }
+
+ #[test]
+ fn unknown_bootstrap_data_is_preserved_and_refused() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().join("storage");
+ prepare_storage_root(&root).unwrap();
+ fs::write(root.join("old-control.db"), b"old durable facts").unwrap();
+ assert!(crate::LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ assert_eq!(
+ fs::read(root.join("old-control.db")).unwrap(),
+ b"old durable facts"
+ );
+ assert!(!root.join("master-key").exists());
+ assert!(!root.join("live/control.db").exists());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn diagnostics_symlink_does_not_authorize_first_store() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().join("storage");
+ prepare_storage_root(&root).unwrap();
+ let outside = temporary.path().join("outside");
+ prepare_storage_root(&outside).unwrap();
+ std::os::unix::fs::symlink(&outside, root.join("diagnostics")).unwrap();
+ assert!(crate::LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ assert!(!root.join("master-key").exists());
+ assert_eq!(fs::read_dir(outside).unwrap().count(), 0);
+ }
+
+ #[test]
+ fn incomplete_or_unmarked_current_directories_are_preserved() {
+ for missing_database in [false, true] {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().join("storage");
+ drop(crate::LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+ if missing_database {
+ fs::rename(root.join("live/runtime.db"), root.join("runtime-kept.db")).unwrap();
+ } else {
+ Connection::open(root.join("live/control.db"))
+ .unwrap()
+ .execute("DROP TABLE stable_storage_format", [])
+ .unwrap();
+ }
+ let key = fs::read(root.join("master-key")).unwrap();
+ assert!(crate::LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ if missing_database {
+ assert!(!root.join("live/runtime.db").exists());
+ assert!(root.join("runtime-kept.db").is_file());
+ }
+ }
+ }
+
+ #[test]
+ fn startup_exclusion_lives_until_the_last_store_is_dropped() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = temporary.path().join("storage");
+ let stores = crate::LocalStorageSet::open_for_daemon_startup(&root).unwrap();
+ assert!(crate::LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ let (control, runtime, secrets) = stores.into_parts();
+ drop(control);
+ drop(runtime);
+ assert!(crate::LocalStorageSet::open_for_daemon_startup(&root).is_err());
+ drop(secrets);
+ assert!(crate::LocalStorageSet::open_for_daemon_startup(&root).is_ok());
+ }
+
+ #[test]
+ fn unsupported_source_is_rejected_without_changing_database_or_key_bytes() {
+ for version in [0, 1, 22, LATEST_SCHEMA_VERSION + 1] {
+ let directory = tempfile::tempdir().unwrap();
+ let root = directory.path().join("storage");
+ drop(crate::LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+ let paths = live_database_paths(&root.join("live"));
+ for path in &paths {
+ let db = Connection::open(path).unwrap();
+ db.pragma_update(None, "user_version", version).unwrap();
+ }
+ let before = paths.clone().map(|path| fs::read(path).unwrap());
+ let key = fs::read(root.join("master-key")).unwrap();
+ assert!(matches!(
+ crate::LocalStorageSet::open_for_daemon_startup(&root),
+ Err(LocalStorageError::UpgradeSourceUnsupported)
+ ));
+ assert_eq!(paths.map(|path| fs::read(path).unwrap()), before);
+ assert_eq!(fs::read(root.join("master-key")).unwrap(), key);
+ }
+ }
+
+ #[test]
+ fn current_format_reopens_and_unfinished_format_is_preserved_and_refused() {
+ let directory = tempfile::tempdir().unwrap();
+ let root = directory.path().join("storage");
+ drop(crate::LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+ drop(crate::LocalStorageSet::open_for_daemon_startup(&root).unwrap());
+ let path = root.join("live/control.db");
+ let connection = Connection::open(&path).unwrap();
+ connection
+ .execute("UPDATE stable_storage_format SET converted=0", [])
+ .unwrap();
+ drop(connection);
+ let before = fs::read(&path).unwrap();
+ assert!(matches!(
+ crate::LocalStorageSet::open_for_daemon_startup(&root),
+ Err(LocalStorageError::UpgradeSourceUnsupported)
+ ));
+ assert_eq!(fs::read(path).unwrap(), before);
+ }
+}
diff --git a/crates/local-storage/src/migrations/stopped_read_tests.rs b/crates/local-storage/src/migrations/stopped_read_tests.rs
new file mode 100644
index 00000000..175f4dbc
--- /dev/null
+++ b/crates/local-storage/src/migrations/stopped_read_tests.rs
@@ -0,0 +1,60 @@
+//! Native SQLite preflight must preserve the database and consume existing WAL.
+use super::*;
+
+#[test]
+fn checkpointed_wal_preflight_keeps_the_database_read_only() {
+ let root = tempfile::tempdir().unwrap();
+ let source = root.path().join("source.db");
+ let connection = Connection::open(&source).unwrap();
+ connection
+ .execute_batch("PRAGMA journal_mode=WAL; PRAGMA user_version=23; CREATE TABLE facts(value); INSERT INTO facts VALUES('retained');")
+ .unwrap();
+ drop(connection);
+ let path = root.path().join("checkpointed ? % 数据.db");
+ fs::copy(source, &path).unwrap();
+ let before = fs::read(&path).unwrap();
+ let connection = Connection::open_with_flags(
+ &path,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )
+ .unwrap();
+ assert_eq!(
+ connection
+ .query_row("PRAGMA user_version", [], |r| r.get::<_, u32>(0))
+ .unwrap(),
+ 23
+ );
+ assert_eq!(
+ connection
+ .query_row("SELECT value FROM facts", [], |r| r.get::<_, String>(0))
+ .unwrap(),
+ "retained"
+ );
+ assert!(
+ connection
+ .execute("INSERT INTO facts VALUES('forbidden')", [])
+ .is_err()
+ );
+ drop(connection);
+ assert_eq!(fs::read(&path).unwrap(), before);
+}
+
+#[test]
+fn remaining_wal_is_consumed_instead_of_reading_only_the_main_file() {
+ let root = tempfile::tempdir().unwrap();
+ let path = root.path().join("source.db");
+ let writer = Connection::open(&path).unwrap();
+ writer.execute_batch("PRAGMA journal_mode=WAL; CREATE TABLE facts(value); PRAGMA wal_checkpoint(TRUNCATE); INSERT INTO facts VALUES('in WAL');").unwrap();
+ assert!(root.path().join("source.db-wal").metadata().unwrap().len() > 0);
+ let reader = Connection::open_with_flags(
+ &path,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )
+ .unwrap();
+ assert_eq!(
+ reader
+ .query_row("SELECT value FROM facts", [], |r| r.get::<_, String>(0))
+ .unwrap(),
+ "in WAL"
+ );
+}
diff --git a/crates/local-storage/src/runtime/delegation/mod.rs b/crates/local-storage/src/runtime/delegation/mod.rs
index d448644f..b24ed77a 100644
--- a/crates/local-storage/src/runtime/delegation/mod.rs
+++ b/crates/local-storage/src/runtime/delegation/mod.rs
@@ -13,6 +13,16 @@ mod tests;
type Result<T> = std::result::Result<T, DelegationErrorV1>;
+impl RuntimeStore {
+ pub fn upgrade_occupied_tasks(&self) -> std::result::Result<u64, crate::LocalStorageError> {
+ Ok(self.connection.borrow().query_row(
+ "SELECT count(*) FROM delegation_runs WHERE occupied=1",
+ [],
+ |row| row.get(0),
+ )?)
+ }
+}
+
impl DelegationRuntimePort for RuntimeStore {
fn worker_concurrency_settings(&self) -> Result<WorkerConcurrencySettingsV1> {
read_worker_concurrency_settings(&self.connection.borrow())
diff --git a/crates/local-storage/src/runtime/mod.rs b/crates/local-storage/src/runtime/mod.rs
index 851f0554..76e76e10 100644
--- a/crates/local-storage/src/runtime/mod.rs
+++ b/crates/local-storage/src/runtime/mod.rs
@@ -18,7 +18,8 @@ mod delegation;
mod compute_state_tests;
pub struct RuntimeStore {
- connection: RefCell<Connection>,
+ pub(crate) connection: RefCell<Connection>,
+ pub(crate) startup_lock: Option<std::sync::Arc<std::fs::File>>,
}
impl RuntimeStore {
@@ -28,6 +29,7 @@ impl RuntimeStore {
migration_backup_root: impl AsRef<Path>,
) -> Result<Self, LocalStorageError> {
Ok(Self {
+ startup_lock: None,
connection: RefCell::new(open_database(
_authority,
path,
@@ -44,6 +46,7 @@ impl RuntimeStore {
expected_store_uuid: &str,
) -> Result<Self, LocalStorageError> {
Ok(Self {
+ startup_lock: None,
connection: RefCell::new(open_database_from_set(
authority,
path,
diff --git a/crates/local-storage/src/secrets/grant.rs b/crates/local-storage/src/secrets/grant.rs
index 932bad66..c5e90602 100644
--- a/crates/local-storage/src/secrets/grant.rs
+++ b/crates/local-storage/src/secrets/grant.rs
@@ -11,6 +11,7 @@ use serde_json::Value;
use super::{KEY_VERSION, LocalSecretStore, NONCE_BYTES, port};
+pub(crate) mod integrity;
mod prepared;
mod records;
diff --git a/crates/local-storage/src/secrets/grant/integrity.rs b/crates/local-storage/src/secrets/grant/integrity.rs
new file mode 100644
index 00000000..3b462581
--- /dev/null
+++ b/crates/local-storage/src/secrets/grant/integrity.rs
@@ -0,0 +1,31 @@
+//! Authenticate current grants and their exact persisted effect references.
+use super::*;
+use crate::LocalStorageError;
+
+pub(crate) fn validate(store: &LocalSecretStore) -> Result<(), LocalStorageError> {
+ let connection = store.connection.borrow();
+ let mut statement =
+ connection.prepare("SELECT connection_id,generation FROM agent_access_grant_versions")?;
+ for row in statement.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, u64>(1)?)))? {
+ let (id, generation) = row?;
+ let version = read_version(&connection, &id, generation)
+ .map_err(|_| LocalStorageError::InvalidData)?
+ .ok_or(LocalStorageError::InvalidData)?;
+ authenticate_version(store, &version).map_err(|_| LocalStorageError::InvalidData)?;
+ }
+ validate_version_links(&connection)
+}
+
+fn validate_version_links(connection: &Connection) -> Result<(), LocalStorageError> {
+ let invalid:bool=connection.query_row("SELECT EXISTS(SELECT 1 FROM agent_access_grant_heads h LEFT JOIN agent_access_grant_versions v ON v.connection_id=h.connection_id AND v.generation=h.active_version_generation WHERE h.active_version_generation IS NOT NULL AND (v.connection_id IS NULL OR h.generation!=v.generation OR h.owner_scope!=v.owner_scope))",[],|r|r.get(0))?;
+ if invalid {
+ return Err(LocalStorageError::InvalidData);
+ }
+ // Every persisted effect's metadata must still name its exact version, including revoked
+ // and compensated versions; neither a newer head nor a revoked head changes its evidence.
+ let invalid:bool=connection.query_row("SELECT EXISTS(SELECT 1 FROM agent_access_grant_effects e LEFT JOIN agent_access_grant_versions v ON v.connection_id=e.connection_id AND v.generation=e.after_active_version_generation WHERE e.after_active_version_generation IS NOT NULL AND (v.connection_id IS NULL OR e.after_grant_id IS NOT v.grant_id OR e.after_scope_hash IS NOT v.scope_hash OR e.after_material_sha256 IS NOT v.material_sha256))",[],|r|r.get(0))?;
+ if invalid {
+ return Err(LocalStorageError::InvalidData);
+ }
+ Ok(())
+}
diff --git a/crates/local-storage/src/secrets/mod.rs b/crates/local-storage/src/secrets/mod.rs
index 57e8dd97..a3ec8864 100644
--- a/crates/local-storage/src/secrets/mod.rs
+++ b/crates/local-storage/src/secrets/mod.rs
@@ -30,6 +30,7 @@ mod collaboration_bootstrap;
#[path = "../agents/collaboration_credentials.rs"]
mod collaboration_credentials;
mod grant;
+pub(crate) use grant::integrity::validate as validate_stable_grants;
#[cfg(test)]
mod grant_tests;
mod runtime;
@@ -66,7 +67,8 @@ impl KeyMaterial {
}
pub struct LocalSecretStore {
- connection: RefCell<Connection>,
+ pub(crate) connection: RefCell<Connection>,
+ pub(crate) startup_lock: Option<std::sync::Arc<std::fs::File>>,
keys: KeyMaterial,
#[cfg(test)]
database_path: PathBuf,
@@ -181,6 +183,7 @@ impl LocalSecretStore {
bind_store_metadata(&connection, &keys)?;
migrate_legacy_secret_aad(&mut connection, &keys)?;
Ok(Self {
+ startup_lock: None,
connection: RefCell::new(connection),
keys,
#[cfg(test)]
@@ -2268,6 +2271,7 @@ mod tests {
],
)
.unwrap();
+ connection.execute_batch("DROP TABLE stable_storage_format; DELETE FROM schema_migrations WHERE version>16;").unwrap();
connection.pragma_update(None, "user_version", 16).unwrap();
connection
.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
diff --git a/crates/local-storage/tests/canonical_compat.rs b/crates/local-storage/tests/canonical_compat.rs
index 5a4f1334..935f042a 100644
--- a/crates/local-storage/tests/canonical_compat.rs
+++ b/crates/local-storage/tests/canonical_compat.rs
@@ -104,25 +104,86 @@ fn capture_pre_fix_canonical_records() {
}
#[test]
-fn canonical_legacy_default_operation_and_grant_survive_storage_reopen() {
+fn frozen_default_canonical_digests_and_step_proofs_remain_compatible() {
let value: Value = serde_json::from_slice(&std::fs::read(fixture_path()).unwrap()).unwrap();
- let grant: AgentCollaborationGrant =
- serde_json::from_value(value["collaboration_grant"].clone()).unwrap();
let scope: LegacyAgentAccessGrantScopeV1 =
serde_json::from_value(value["model_grant_scope"].clone()).unwrap();
assert_eq!(
scope.digest().as_str(),
value["model_grant_scope_digest"].as_str().unwrap()
);
+ let operation = &value["operation"];
+ let plan = &operation["plan"];
+ assert_eq!(
+ serde_json::from_str::<Value>(value["operation_json"].as_str().unwrap()).unwrap(),
+ *operation
+ );
+ for (input, expected) in [
+ (
+ &operation["expected_revisions"],
+ &value["expected_revisions_digest"],
+ ),
+ (plan, &value["transaction_plan_digest"]),
+ ] {
+ assert_eq!(
+ CanonicalDigest::of(input).unwrap().as_str(),
+ expected.as_str().unwrap()
+ );
+ }
+ let effects = |kind: &str| {
+ plan["external"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|effect| effect["kind"] == kind)
+ .cloned()
+ .collect::<Vec<_>>()
+ };
+ // The old producer's six proofs use its exact runtime-shaped inputs. These
+ // bytes remain frozen; a current Operation seals a different durable input.
+ let inputs = [
+ json!({"spec": plan["spec"], "accepted_digest": operation["accepted_digest"], "expected_revisions": operation["expected_revisions"]}),
+ json!([plan["secrets"], []]),
+ json!([plan["control"], null]),
+ json!(effects("publication")),
+ json!(effects("agent_artifact")),
+ plan["runtime"].clone(),
+ ];
+ assert_eq!(operation["steps"].as_array().unwrap().len(), inputs.len());
+ for (step, input) in operation["steps"].as_array().unwrap().iter().zip(inputs) {
+ assert_eq!(
+ CanonicalDigest::of(&input).unwrap().as_str(),
+ step["deterministic_input_digest"].as_str().unwrap()
+ );
+ }
+}
+
+#[test]
+fn current_operation_and_legacy_grant_survive_storage_reopen() {
+ let value: Value = serde_json::from_slice(&std::fs::read(fixture_path()).unwrap()).unwrap();
+ let grant: AgentCollaborationGrant =
+ serde_json::from_value(value["collaboration_grant"].clone()).unwrap();
let root = private_tempdir();
let operation_id;
+ let current_operation;
{
let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
let operation = support::begin(&stores, "canonical-legacy");
operation_id = operation.operation_id.clone();
+ current_operation = serde_json::to_value(&operation).unwrap();
+ for field in [
+ "operation_id",
+ "workspace_id",
+ "idempotency",
+ "request_digest",
+ "accepted_digest",
+ "expected_revisions",
+ ] {
+ assert_eq!(current_operation[field], value["operation"][field]);
+ }
assert_eq!(
- serde_json::to_value(&operation).unwrap(),
- value["operation"]
+ current_operation["plan"]["spec"],
+ value["operation"]["plan"]["spec"]
);
assert_eq!(
CanonicalDigest::of(&operation.expected_revisions)
@@ -130,25 +191,6 @@ fn canonical_legacy_default_operation_and_grant_survive_storage_reopen() {
.as_str(),
value["expected_revisions_digest"].as_str().unwrap()
);
- assert_eq!(
- CanonicalDigest::of(&operation.plan).unwrap().as_str(),
- value["transaction_plan_digest"].as_str().unwrap()
- );
- // Replay the byte-for-byte old persisted journal into the identical row. This is a
- // fixture import only; production recovery must use its existing strict decoder.
- let connection = rusqlite::Connection::open(root.path().join("live/control.db")).unwrap();
- assert_eq!(
- connection
- .execute(
- "UPDATE operations SET operation_json = ?1 WHERE operation_id = ?2",
- rusqlite::params![
- value["operation_json"].as_str().unwrap(),
- operation_id.as_str()
- ]
- )
- .unwrap(),
- 1
- );
stores
.control()
.store_collaboration_grant(&operation_id, 0, &grant)
@@ -160,10 +202,7 @@ fn canonical_legacy_default_operation_and_grant_survive_storage_reopen() {
.load_operation(&operation_id)
.unwrap()
.unwrap();
- assert_eq!(
- serde_json::to_value(&recovered).unwrap(),
- value["operation"]
- );
+ assert_eq!(serde_json::to_value(&recovered).unwrap(), current_operation);
assert!(
stores
.control()
@@ -198,3 +237,30 @@ fn canonical_legacy_default_operation_and_grant_survive_storage_reopen() {
value["collaboration_grant"]
);
}
+
+#[test]
+fn current_store_rejects_frozen_pre_mvp_journal_without_migration() {
+ let value: Value = serde_json::from_slice(&std::fs::read(fixture_path()).unwrap()).unwrap();
+ let root = private_tempdir();
+ let stores = LocalStorageSet::open_for_daemon_startup(root.path()).unwrap();
+ let operation = support::begin(&stores, "canonical-legacy");
+ let connection = rusqlite::Connection::open(root.path().join("live/control.db")).unwrap();
+ assert_eq!(
+ connection
+ .execute(
+ "UPDATE operations SET operation_json = ?1 WHERE operation_id = ?2",
+ rusqlite::params![
+ value["operation_json"].as_str().unwrap(),
+ operation.operation_id.as_str()
+ ],
+ )
+ .unwrap(),
+ 1
+ );
+ assert!(
+ stores
+ .control()
+ .load_operation(&operation.operation_id)
+ .is_err()
+ );
+}
diff --git a/crates/local-storage/tests/canonical_compat/README.md b/crates/local-storage/tests/canonical_compat/README.md
index f101d02a..d54b9f60 100644
--- a/crates/local-storage/tests/canonical_compat/README.md
+++ b/crates/local-storage/tests/canonical_compat/README.md
@@ -8,9 +8,17 @@ revision and transaction digests, model-grant scope and its digest, and a stored
collaboration grant. All data is synthetic; no user credentials or stores.
Do not regenerate after the digest fix. The ignored capture test is a historical
-recipe only. Recovery imports the exact old journal bytes into the identical
-Operation row and uses the production storage decoder after reopen. The same
-fixed JSON is tested with default and serde_json/preserve_order dependencies.
+recipe only. Its original JSON, plan/revision/scope digests and all six step proofs
+are checked with default and serde_json/preserve_order dependencies. A separate
+current-producer test preserves Operation identities and business inputs across
+cold reopen, and verifies the original collaboration grant's positive and negative
+authorization cases.
+
+This pre-MVP agents.connect.apply sample predates the supported schema22 upgrade
+sources and lacks their complete Plan/grant facts. It is registered as a frozen
+canonical fixture, not a production migration reader. Injecting its journal into
+a schema23 store without migration must be rejected; source22 migration is covered
+by the separately frozen upgrade-schema22 fixtures.
This fixture proves compatibility with the previous normal default graph; it is
not an inventory of user stores written by experimental order-sensitive binaries.
diff --git a/crates/observation/src/maintenance.rs b/crates/observation/src/maintenance.rs
index 9d574f2e..7aa8e93c 100644
--- a/crates/observation/src/maintenance.rs
+++ b/crates/observation/src/maintenance.rs
@@ -10,6 +10,7 @@ const BLOB_GC_BATCH: usize = 32;
pub struct ObservationMaintenance {
stop: mpsc::Sender<()>,
+ worker: Option<std::thread::JoinHandle<()>>,
}
/// Optional product-owned work attached to the one maintenance lifecycle. The hook receives no
@@ -44,19 +45,26 @@ impl ObservationMaintenance {
let _lease = lease;
run(weak, receiver, hook)
});
- if let Err(error) = result {
+ let worker = result.inspect_err(|_| {
store
.maintenance_errors
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
- return Err(error);
- }
- Ok(Self { stop })
+ })?;
+ Ok(Self {
+ stop,
+ worker: Some(worker),
+ })
}
}
impl Drop for ObservationMaintenance {
fn drop(&mut self) {
let _ = self.stop.send(());
+ // Finish the current bounded cycle before releasing the owner. A hook may
+ // hold the product stores, and an immediate reopen must not race that lease.
+ if let Some(worker) = self.worker.take() {
+ let _ = worker.join();
+ }
}
}
@@ -252,4 +260,55 @@ mod tests {
clock.set(clock.get() + Duration::from_millis(1));
gc.run_if_due(|| clock.get(), || Ok(0)).unwrap();
}
+
+ struct BlockedCycle {
+ entered: mpsc::Sender<()>,
+ release: std::sync::Mutex<mpsc::Receiver<()>>,
+ }
+
+ impl ObservationMaintenanceHook for BlockedCycle {
+ fn cycle(&self, _: i64) -> Result<(), ObservationMaintenanceHookError> {
+ self.entered.send(()).unwrap();
+ self.release
+ .lock()
+ .unwrap()
+ .recv_timeout(Duration::from_secs(5))
+ .unwrap();
+ Ok(())
+ }
+ }
+
+ #[test]
+ fn dropping_maintenance_finishes_its_current_cycle_and_releases_the_lease() {
+ let root = tempfile::tempdir().unwrap();
+ let store = Arc::new(
+ LocalObservationStore::open(root.path(), crate::DigestAuthority::new([1; 32])).unwrap(),
+ );
+ let (entered, did_enter) = mpsc::channel();
+ let (release, wait_for_release) = mpsc::channel();
+ let worker = ObservationMaintenance::start_with_hook(
+ &store,
+ Some(Arc::new(BlockedCycle {
+ entered,
+ release: std::sync::Mutex::new(wait_for_release),
+ })),
+ )
+ .unwrap();
+ did_enter.recv_timeout(Duration::from_secs(5)).unwrap();
+ let (dropped, did_drop) = mpsc::channel();
+ let owner = std::thread::spawn(move || {
+ drop(worker);
+ dropped.send(()).unwrap();
+ });
+ assert!(matches!(
+ did_drop.recv_timeout(Duration::from_millis(50)),
+ Err(mpsc::RecvTimeoutError::Timeout)
+ ));
+ release.send(()).unwrap();
+ did_drop.recv_timeout(Duration::from_secs(5)).unwrap();
+ owner.join().unwrap();
+ assert!(!store.maintenance_status().0);
+ drop(ObservationMaintenance::start(&store).unwrap());
+ assert!(!store.maintenance_status().0);
+ }
}
diff --git a/crates/observation/src/query_v2/mod.rs b/crates/observation/src/query_v2/mod.rs
index 34734de2..798c8e59 100644
--- a/crates/observation/src/query_v2/mod.rs
+++ b/crates/observation/src/query_v2/mod.rs
@@ -46,7 +46,9 @@ pub enum ObservationV2Error {
}
impl From<rusqlite::Error> for ObservationV2Error {
- fn from(_: rusqlite::Error) -> Self {
+ fn from(_error: rusqlite::Error) -> Self {
+ #[cfg(test)]
+ eprintln!("observation query SQLite failure: {_error:?}");
Self::Unavailable
}
}
@@ -144,7 +146,11 @@ impl QueryDeadline {
}
}
})
- .map_err(|_| ObservationV2Error::Unavailable)?;
+ .map_err(|_error| {
+ #[cfg(test)]
+ eprintln!("observation query deadline thread failure: {_error:?}");
+ ObservationV2Error::Unavailable
+ })?;
Ok(Self(send))
}
}
diff --git a/docs/macos-installation.md b/docs/macos-installation.md
index 5030b1dd..c642573c 100644
--- a/docs/macos-installation.md
+++ b/docs/macos-installation.md
@@ -63,12 +63,28 @@ manually.
1. Explicitly quit HiRoute and confirm that this service instance and its tasks have stopped.
Closing the window only hides the application. Full lifecycle acceptance is tracked
separately; a vanished window alone is not stop evidence.
-2. Replace `/Applications/HiRoute.app` while preserving application data, then launch it. A
- fixed location keeps the per-user symlink target stable.
+2. Preserve the complete previous App before replacing `/Applications/HiRoute.app`; keep
+ application data, then launch the new App. A fixed location keeps the per-user symlink
+ target stable. If startup asks for a recovery package, select the preserved matching App;
+ HiRoute validates the full package before converting data.
3. If the app moved or integration checks report an invalid path, use the integration Preview
and confirmation in Settings. Resolve user-configuration drift instead of overwriting it.
Check and, if needed, disable/re-enable the login item.
+Settings → Updates checks the official release catalog and validates the full DMG and App.
+Installation pauses new work, waits for existing calls and tasks, and can be cancelled while
+waiting. Both the owned daemon and Desktop exit before replacement. The previous complete
+App remains alongside the installation; storage migration uses the same startup path as a
+manual upgrade.
+
+When a storage conversion is required, startup preserves a complete private source backup
+at `storage.upgrade-backups/migration-set/source` under the application data root. If startup
+fails, use the backup button and follow `恢复说明.md`: fully stop HiRoute, retain the current
+data directory, restore the whole recorded set to its original locations, and install the
+exact previous complete App named in the guide. Do not combine databases, keys or individual
+binaries from different versions. Manual restoration discards changes made after the backup.
+HiRoute does not automatically roll back data after the migration has completed.
+
Before removal, Preview and restore managed model/Agent integration from Settings, disable
background launch at login, explicitly quit, and delete the app. App deletion preserves data
by default. For a complete data removal, first confirm that no task is running, integration
diff --git a/docs/macos-installation.zh-CN.md b/docs/macos-installation.zh-CN.md
index ca0fcc89..8da3ca48 100644
--- a/docs/macos-installation.zh-CN.md
+++ b/docs/macos-installation.zh-CN.md
@@ -49,10 +49,22 @@ CPA 随包提供,只在获准订阅路径使用。缺失、替换或不能执
1. 在 HiRoute 中明确退出,确认本次服务和任务完成停止;关闭窗口只隐藏应用。
生命周期完整收尾的组合验收跟踪 #93,不能仅凭窗口消失判断已停止。
-2. 替换 `/Applications/HiRoute.app`,保留应用数据,再启动。固定位置让用户级符号链接目标不变。
+2. 先保留完整的旧 App,再替换 `/Applications/HiRoute.app`,保留应用数据后启动新版本。
+ 固定位置让用户级符号链接目标不变。若启动提示选择恢复包,选择已保留的配套旧 App;
+ 程序会校验完整包后才转换数据。
3. 若移动了 App 或接入检查报告路径失效,使用设置中的接入预览和确认重新配置;
若出现用户配置漂移,先解决冲突,不能直接覆盖。登录项在设置中检查,必要时关闭再启用。
+“设置 → 版本升级”从官网检查发布版本并校验完整 DMG 和 App。安装先暂停新工作,
+等待现有调用和任务结束;等待期间可以取消升级。所属 daemon 和 Desktop 均退出后才替换 App,
+完整旧 App 保留在安装目录旁;数据迁移与手动升级使用同一启动入口。
+
+需要转换持久数据时,启动会在应用数据根目录的
+`storage.upgrade-backups/migration-set/source` 保存完整私有备份。启动失败时点击备份入口,
+按《恢复说明.md》完全停止 HiRoute、保留当前数据目录、将整组数据恢复到清单原位置,
+并覆盖安装说明指定的完整旧 App。不要混配不同批次的数据库、密钥或单个二进制。
+手工恢复会舍弃备份之后的新数据;迁移完成后程序不会自动回灌旧备份。
+
卸载前先通过设置预览/恢复受管模型及 Agent 接入,再关闭“登录后后台启动”,明确退出,
然后删除 App。删除 App 默认保留数据。若选择彻底清理,确认无任务运行、已恢复接入且
不再需要会话/日志/回执后,只删除当前用户 `~/Library/Application Support/ai.hiroute.desktop`
diff --git a/docs/release-contracts.md b/docs/release-contracts.md
new file mode 100644
index 00000000..6e6f4774
--- /dev/null
+++ b/docs/release-contracts.md
@@ -0,0 +1,99 @@
+# Release contract records and upgrade navigation
+
+These are release facts, not an automatic promise to migrate every recorded release.
+The first supported upgrade baseline is 0.2.0 once it is published and its snapshot is
+merged. Historical 0.1.0 remains recorded but is outside the supported migration scope.
+
+## Read the recorded release
+
+The version is data, not a skill constant. From the repository root run:
+
+```sh
+python3 scripts/release-contracts.py check
+python3 scripts/release-contracts.py current
+```
+
+PR CI also compares every historical snapshot byte-for-byte with the actual PR base; editing
+or deleting one fails even if the index is recomputed. Locally use `check --base BASE_REF` for
+the same check. The index itself is regenerated as new snapshots are appended.
+
+The [index](../contracts/releases/index.v1.json) selects the highest recorded stable
+semantic version. Each adjacent `<tag>.json` snapshot freezes the exact published commit,
+repository/tag/channel, publication time, installer names/sizes/SHA-256, released SQL schema,
+compatibility register and CLI contract-set descriptor. The register and descriptor retain
+both their original source-byte digest and parsed content. Read other affected types, schemas
+and producer behavior with `git show REVISION:path`; the current file is not the old contract.
+The snapshot is evidence, not another current contract producer or a promise of migration support.
+
+Fetch missing source objects/tags from the configured public remote without replacing an existing
+tag. A missing/moved tag or index/hash mismatch must be resolved, not regenerated into agreement.
+Never use a branch tip or a same-version development package as the released source.
+
+Before compatibility work and release handoff, compare the index with the observed public stable
+Release channel (use the repository in the snapshot). A newly published Release may have its
+snapshot PR pending. Resolve that gap through the release workflow/PR before treating the recorded
+baseline as current. Retain all older sources still declared supported; `latest_stable` is not an
+end-of-support rule. The retired schema22 trial recovery catalog is no longer an upgrade entry;
+published 0.1.0 records remain immutable historical facts, while 0.2.0 is the first supported baseline.
+
+## Publication and retry
+
+[Release workflow](../.github/workflows/release.yml) verifies the published assets and
+package identities, then publishes the installers/site. Only after those jobs succeed does
+`record-contracts` call [the PR publisher](../.github/scripts/release-contract-pr.sh).
+It reads the verified manifest revision and exact released source, cross-checks published asset
+sizes/digests, and proposes only `contracts/releases/` changes on `chore/release-contracts-<tag>`.
+
+Normal review/checks and merge into `main` advance the repository's baseline. The workflow never
+approves or merges its own PR. Existing snapshots are immutable; older reruns and previews retain
+the highest stable baseline. A repeat reuses the same open PR; after merge it is a no-op. Failed
+PR creation leaves a retryable branch. A closed PR, conflicting histories or unrelated edits on
+that branch require review rather than force-pushing over them. With two pending release PRs,
+merging one may cause an index conflict in the other; retain both snapshots, take the merged
+main's index, and rerun `record` for the latter release with its verified inputs, then run `check`.
+
+The job needs `contents: write` and `pull-requests: write`, plus the repository Actions setting
+that allows GitHub Actions to create pull requests. GitHub exposes that setting together with
+permission to approve; this workflow contains no approval action. PR checks must run through
+the ordinary pull-request event and repository review policy. If GitHub marks the bot-created
+workflow run as awaiting approval, an authorized reviewer must approve that run; a manual
+`workflow_dispatch` run is not a substitute for required PR checks. See the
+[GitHub event-trigger rules](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow).
+
+If publication succeeds but recording fails, fix the reported cause and rerun the failed job.
+This does not undo the published release. Initial backfill uses `gh release view TAG --repo REPO
+--json tagName,isDraft,isPrerelease,publishedAt,assets` saved to a local file, followed by:
+
+```sh
+python3 scripts/release-contracts.py record --release-json /path/to/release.json \
+ --manifest /path/to/verified-releases.json --revision FULL_SOURCE_SHA --repository OWNER/REPO
+python3 scripts/release-contracts.py check
+```
+
+The manifest must be the one verified against the published package bytes and source identity.
+Generate twice and confirm the second run has no diff. Commit the snapshot/index through a normal
+PR. Do not edit historical snapshots or overwrite a collision to get a green check. Publication
+records and contract-source checks do not establish real old-package upgrade/manual restoration;
+supported-source acceptance remains a separate release obligation after the first 0.2.0 baseline.
+
+## Find the current storage and upgrade boundaries
+
+Inspect the current support register, dispatch and affected tests; this navigation does not fix
+any particular product or SQL version as the target.
+
+| Responsibility | Existing entry |
+| --- | --- |
+| Current contracts, retained readers and fixtures | [compatibility support register](../contracts/compatibility-support.v1.json) |
+| First supported baseline | 0.2.0; the schema22 trial recovery catalog and package-selection entry have been retired |
+| Startup, backup batches and SQL/payload dispatch | `crates/local-storage/src/lib.rs`, `crates/local-storage/src/migrations/mod.rs` and its dispatched modules, daemon startup |
+| Startup format admission and current integrity | `crates/local-storage/src/migrations/startup_format.rs`, `current_storage.rs`; unsupported old stores are preserved and refused |
+| Stable facts and execution projection | `crates/domain/src/routing/stored.rs`, `stored_capability.rs`, `capability_compiler.rs`; publication/Operation stored codecs |
+| Operation, secret and native recovery | `crates/domain/src/operation/`, `crates/local-storage/src/secrets/`, `crates/local-storage/src/agents/` |
+| Public CLI | Frozen CLI descriptor in the release snapshot; schemas and consumer/application-api code at its revision |
+| Gateway semantics | Affected ingress/serializer/response code at the released revision and production listener tests |
+| Current source fixtures and restart regressions | Registered fixtures, stable-codec tests and production publication/recovery scenarios |
+
+Trace concrete format markers, complete-source backup rules and the three-store coordinator as
+well as SQL dispatch. A future migration is not implemented merely because its number appears
+in documentation. Users need not install intermediate binaries when the current startup actually
+implements and validates the complete supported source-to-current chain.
diff --git a/e2e/golden/p0-gateway-planner.json b/e2e/golden/p0-gateway-planner.json
index df1d9fee..32e00466 100644
--- a/e2e/golden/p0-gateway-planner.json
+++ b/e2e/golden/p0-gateway-planner.json
@@ -1,8 +1,8 @@
{
"schema_version": "hiroute.planner-complexity-golden/v1",
"strategy_digest": "sha256:52538aba36f48b47ae2de6cdb7060e84138c7d3093ae9908e05021f26d0bf5da",
- "planner_input_digest": "sha256:c58bcbc7602ef38cef24ff809e965254bedf1e71d451892a914ff732a98d0790",
- "planner_output_digest": "sha256:e9fc6ff59d21b6ac931f249a0c238a4554478362222864bda55ef0c4b5edb194",
+ "planner_input_digest": "sha256:2ad377019306e8c8cad4b42ba779e795f1b6fd7a7673fa8922270431d6e51e88",
+ "planner_output_digest": "sha256:ee5579a026597e3ea99fcdf7ba4a50ecf3162e0f0b6b72607042c603db90fd4d",
"cases": [
{
"id": "readme-responses",
diff --git a/e2e/product/fixtures/routing/current-publication.v3.json b/e2e/product/fixtures/routing/current-publication.v3.json
new file mode 100644
index 00000000..29b1eab4
--- /dev/null
+++ b/e2e/product/fixtures/routing/current-publication.v3.json
@@ -0,0 +1,12842 @@
+{
+ "schema": "hiroute.gateway-publication/v3",
+ "compiler_revision": "agent-plan-compiler/v3",
+ "workspace_id": "personal/default",
+ "authority_id": "workspace/personal/default/gateway",
+ "authority_epoch": 1,
+ "publication_revision": 11,
+ "catalog_renderer_revision": "hiroute.gateway-catalog-renderer/v1",
+ "alias_registry": {
+ "schema": "hiroute.agent-plan-alias-registry/v1",
+ "next_sequence": 5,
+ "active": {
+ "plan/custom": "hiroute/2590c10eeae4f930",
+ "plan/free": "hiroute/2b52668dd5854ef1",
+ "plan/free-fallback": "hiroute/6a87b28966202d08",
+ "plan/smart": "hiroute/89e03a7d2c57bbc9"
+ },
+ "tombstones": [],
+ "retired_plan_ids": []
+ },
+ "plans": [
+ {
+ "body": {
+ "schema": "hiroute.compiled-agent-plan/v3",
+ "compiler_revision": "agent-plan-compiler/v3",
+ "identity": {
+ "agent_plan_id": "plan/custom",
+ "model_alias": "hiroute/2590c10eeae4f930",
+ "display_name": "Explicit chain",
+ "purpose": "Use the exact user-selected candidate order"
+ },
+ "agent_plan_revision": 1,
+ "materialized_route_digest": "sha256:e208befbe54c8d44ceed59a79a920d4985c48a54c8edcf4d27143d8f84c3106a",
+ "materialized": {
+ "fact_refs": {
+ "connector_registry_version": "registry.v1",
+ "connector_registry_digest": "sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822",
+ "model_data_bundle_version": "model-data.v1",
+ "model_data_digest": "sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333",
+ "capability_slice_version": "capabilities.v1",
+ "capability_slice_digest": "sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08",
+ "ratings_slice_version": "ratings.v1",
+ "ratings_slice_digest": "sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693",
+ "free_offers_slice_version": "free-offers.v1",
+ "free_offers_slice_digest": "sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b",
+ "inventory_revision": 9,
+ "inventory_digest": "sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189",
+ "price_tracking": "follow_latest"
+ },
+ "request_owned": {
+ "strategy": "ordered",
+ "cost_policy": "api_equivalent",
+ "ordered_groups": [
+ "custom"
+ ]
+ },
+ "attempt_owned": {
+ "limits": {
+ "maximum_attempts": 6,
+ "request_timeout_ms": 120000,
+ "attempt_timeout_ms": 60000
+ },
+ "groups": [
+ {
+ "group_id": "custom",
+ "ordering_evidence": {
+ "kind": "explicit_order"
+ },
+ "pinned_ratings": {},
+ "candidates": [
+ {
+ "binding_id": "binding/primary-b",
+ "binding_revision": 1,
+ "binding_digest": "sha256:9205afa8d854b1c8c7d668ea1db0cf79b9e2c26581eed81956292a22b7beb877",
+ "source_id": "source/primary-b",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:c763add7a5ec53ea3b3376a3ff3c2b8322102ef5446ef331a2296e2ece4188f6",
+ "connection_option_id": "option/primary-b",
+ "offer_ref": "offer/primary-b",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:2bd867c82a64bbe32d505234ea0cfe529f1d35729f6332c72471cc469a424cd7",
+ "billing_class": "paid",
+ "model_configuration_id": "model.primary-b",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-primary-b",
+ "native_transport_model": "upstream-primary-b",
+ "capability_id": "capability/primary-b",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:0d092592692914efad1c3776df31f5488a62dee4c8d1c4f1b14380dad846bf49",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/primary-b",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/primary-b",
+ "endpoint": "https://primary-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:6177ffb3f981ccaddd778a0459b0e1958c97e8bc22aa950920c791baba3b57aa",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:a172443f307bde83f0a954a5a8778c9b92fb1f30db79319b737c85c083265d12",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/primary-b"
+ ],
+ "credential_pool_id": "pool/primary-b",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "low",
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/primary-a",
+ "binding_revision": 1,
+ "binding_digest": "sha256:bc72b46479bf87bd914998841f9dd1fc20039c553d51f38b98de9861ed239a10",
+ "source_id": "source/primary-a",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:ec2b08f84b9c6d83286b4425e155752cb5f5f23fc041a735ddee3fe7acb9c258",
+ "connection_option_id": "option/primary-a",
+ "offer_ref": "offer/primary-a",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:88924ff21883853ef2c486c512ed13224b96c75984104b6a18fa6f72f2ec863c",
+ "billing_class": "paid",
+ "model_configuration_id": "model.primary-a",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-primary-a",
+ "native_transport_model": "upstream-primary-a",
+ "capability_id": "capability/primary-a",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:5c740f261397a0d499ff3bd1215ce1192b4fa9225ca45fa072b1ab2e08eb02e9",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/primary-a",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/primary-a",
+ "endpoint": "https://primary-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:30d61f7e5af1fd7cf13507541bbbdae5825b22816abc227d92ab301cc4a16954",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f81b8d62cbfb64b9a1bfb578d223443ca5e6f18599ec525f9b877d642074bf5a",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/primary-a"
+ ],
+ "credential_pool_id": "pool/primary-a",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "high",
+ "render_mode": "explicit_native"
+ }
+ }
+ ]
+ }
+ ]
+ }
+ }
+ },
+ "digest": "sha256:9866b90a7505a7c9e009cdb6c97fd678b3e29e563582564a0a620d9303bd19b0"
+ },
+ {
+ "body": {
+ "schema": "hiroute.compiled-agent-plan/v3",
+ "compiler_revision": "agent-plan-compiler/v3",
+ "identity": {
+ "agent_plan_id": "plan/free",
+ "model_alias": "hiroute/2b52668dd5854ef1",
+ "display_name": "Free research",
+ "purpose": "Research tasks that prefer the pinned free pool"
+ },
+ "agent_plan_revision": 2,
+ "materialized_route_digest": "sha256:b8733e042f27345751bf552066087f518e2f880b8af5bfffd38210460568586e",
+ "materialized": {
+ "fact_refs": {
+ "connector_registry_version": "registry.v1",
+ "connector_registry_digest": "sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822",
+ "model_data_bundle_version": "model-data.v1",
+ "model_data_digest": "sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333",
+ "capability_slice_version": "capabilities.v1",
+ "capability_slice_digest": "sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08",
+ "ratings_slice_version": "ratings.v1",
+ "ratings_slice_digest": "sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693",
+ "free_offers_slice_version": "free-offers.v1",
+ "free_offers_slice_digest": "sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b",
+ "inventory_revision": 9,
+ "inventory_digest": "sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189",
+ "price_tracking": "follow_latest"
+ },
+ "request_owned": {
+ "strategy": "ordered",
+ "cost_policy": "strict_free",
+ "ordered_groups": [
+ "free"
+ ]
+ },
+ "attempt_owned": {
+ "limits": {
+ "maximum_attempts": 6,
+ "request_timeout_ms": 120000,
+ "attempt_timeout_ms": 60000
+ },
+ "groups": [
+ {
+ "group_id": "free",
+ "ordering_evidence": {
+ "kind": "explicit_order"
+ },
+ "pinned_ratings": {},
+ "candidates": [
+ {
+ "binding_id": "binding/free-a",
+ "binding_revision": 1,
+ "binding_digest": "sha256:f2f62274234d5d6478417fe0a516e69127d7a30e1cecf605552f6ae305601cce",
+ "source_id": "source/free-a",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:d5eb6a62fabe0f3a8979572ea72980328d93d994bf9a13bc2604bd21dfeca9d0",
+ "connection_option_id": "option/free-a",
+ "offer_ref": "offer/free-a",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:c6e1aac1c995b1927c57ffa1b3df73893eaf4e6fd5edc17f0311a9211b1348e0",
+ "billing_class": "free",
+ "model_configuration_id": "model.free-a",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-free-a",
+ "native_transport_model": "upstream-free-a",
+ "capability_id": "capability/free-a",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:3f5ac32e719a6f10e7deeac8de577069ad389967a7fbb53cb6836b04d866738a",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/free-a",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/free-a",
+ "endpoint": "https://free-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:0b4c464b0e788da93df655a3524018c6662efc4d4eacb226b7896ef8d6ee1f98",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f2fffed1b1abe15352867881944be3d38fc821fef42c8543edb45c5eb11f5a67",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/free-a"
+ ],
+ "free_offer": {
+ "free_offer_id": "free-offer/free-a",
+ "free_offer_revision": 1,
+ "offer_ref": "offer/free-a",
+ "access": "direct",
+ "evidence_digest": "sha256:5aee1ca1a796cb1042ddb6a26017b31f5fe4174c543d3941a724623de51f330b"
+ },
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "low",
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/free-b",
+ "binding_revision": 1,
+ "binding_digest": "sha256:8986c7cd25ffd9a9034795fee918aa2b0b0f46baa7e0eca33a0f0fa04300dc5a",
+ "source_id": "source/free-b",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:e3654a532251abe2cf8180da0d9060f33455dc3ce60c57e8f720ffc48bf0148a",
+ "connection_option_id": "option/free-b",
+ "offer_ref": "offer/free-b",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:88a8353cbca7424344bda727346c965998e15fc3c8ccdf9b2ce4f2fe90b2d9c7",
+ "billing_class": "free",
+ "model_configuration_id": "model.free-b",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-free-b",
+ "native_transport_model": "upstream-free-b",
+ "capability_id": "capability/free-b",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:7608766fd4b211643bdb65d35adb2fa422f808ce08f8c02cd69d930173a99a2b",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/free-b",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/free-b",
+ "endpoint": "https://free-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:3ec2919760d37618dc911d2c887ec96cdab27642ca517bb7ab9994e5948d4e01",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:d8287003935f6cc715992af6e1699356b9af2f6f7017eb35aa02b351b3a3064f",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/free-b"
+ ],
+ "free_offer": {
+ "free_offer_id": "free-offer/free-b",
+ "free_offer_revision": 1,
+ "offer_ref": "offer/free-b",
+ "access": "direct",
+ "evidence_digest": "sha256:94ad11fb1d7e77a92c4bd3a1b618ab99a489af9258398f553ae0d3cac9768a7d"
+ },
+ "exact_reasoning": {
+ "kind": "fixed",
+ "profile": "fixed",
+ "render_mode": "no_control_parameter"
+ }
+ }
+ ]
+ }
+ ]
+ }
+ }
+ },
+ "digest": "sha256:0fce8f6a2a920eb6c863794e2e4cad6c6a85f26331c8590ca2fbd8c0386b1bbe"
+ },
+ {
+ "body": {
+ "schema": "hiroute.compiled-agent-plan/v3",
+ "compiler_revision": "agent-plan-compiler/v3",
+ "identity": {
+ "agent_plan_id": "plan/free-fallback",
+ "model_alias": "hiroute/6a87b28966202d08",
+ "display_name": "Free research",
+ "purpose": "Research tasks that prefer the pinned free pool"
+ },
+ "agent_plan_revision": 1,
+ "materialized_route_digest": "sha256:d522e644eb987012f8c047283a37f878f24d0748dbc613b528edd60476ec135f",
+ "materialized": {
+ "fact_refs": {
+ "connector_registry_version": "registry.v1",
+ "connector_registry_digest": "sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822",
+ "model_data_bundle_version": "model-data.v1",
+ "model_data_digest": "sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333",
+ "capability_slice_version": "capabilities.v1",
+ "capability_slice_digest": "sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08",
+ "ratings_slice_version": "ratings.v1",
+ "ratings_slice_digest": "sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693",
+ "free_offers_slice_version": "free-offers.v1",
+ "free_offers_slice_digest": "sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b",
+ "inventory_revision": 9,
+ "inventory_digest": "sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189",
+ "price_tracking": "follow_latest"
+ },
+ "request_owned": {
+ "strategy": "ordered",
+ "cost_policy": "api_equivalent",
+ "ordered_groups": [
+ "free",
+ "primary"
+ ]
+ },
+ "attempt_owned": {
+ "limits": {
+ "maximum_attempts": 6,
+ "request_timeout_ms": 120000,
+ "attempt_timeout_ms": 60000
+ },
+ "groups": [
+ {
+ "group_id": "free",
+ "ordering_evidence": {
+ "kind": "explicit_order"
+ },
+ "pinned_ratings": {},
+ "candidates": [
+ {
+ "binding_id": "binding/free-a",
+ "binding_revision": 1,
+ "binding_digest": "sha256:f2f62274234d5d6478417fe0a516e69127d7a30e1cecf605552f6ae305601cce",
+ "source_id": "source/free-a",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:d5eb6a62fabe0f3a8979572ea72980328d93d994bf9a13bc2604bd21dfeca9d0",
+ "connection_option_id": "option/free-a",
+ "offer_ref": "offer/free-a",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:c6e1aac1c995b1927c57ffa1b3df73893eaf4e6fd5edc17f0311a9211b1348e0",
+ "billing_class": "free",
+ "model_configuration_id": "model.free-a",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-free-a",
+ "native_transport_model": "upstream-free-a",
+ "capability_id": "capability/free-a",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:3f5ac32e719a6f10e7deeac8de577069ad389967a7fbb53cb6836b04d866738a",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/free-a",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/free-a",
+ "endpoint": "https://free-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:0b4c464b0e788da93df655a3524018c6662efc4d4eacb226b7896ef8d6ee1f98",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f2fffed1b1abe15352867881944be3d38fc821fef42c8543edb45c5eb11f5a67",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/free-a"
+ ],
+ "free_offer": {
+ "free_offer_id": "free-offer/free-a",
+ "free_offer_revision": 1,
+ "offer_ref": "offer/free-a",
+ "access": "direct",
+ "evidence_digest": "sha256:5aee1ca1a796cb1042ddb6a26017b31f5fe4174c543d3941a724623de51f330b"
+ },
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "low",
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/free-toggle",
+ "binding_revision": 1,
+ "binding_digest": "sha256:23caa04a713c0dc7604408955963a8302513f9f47f5fc6504d4854fdda7bdcc8",
+ "source_id": "source/free-toggle",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:056ade35e960ca377e939453e70136eda549574fb65f791d5a4ebf2f99ac7963",
+ "connection_option_id": "option/free-toggle",
+ "offer_ref": "offer/free-toggle",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:09d40cbd60b3565090afaa54ff3bf23b8f7a106f36f2c9dea0b1f07f6136b8cd",
+ "billing_class": "free",
+ "model_configuration_id": "model.free-toggle",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-free-toggle",
+ "native_transport_model": "upstream-free-toggle",
+ "capability_id": "capability/free-toggle",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:5a34328b6d2fbb50867aa5541ef430070fc35d3f76c86cbfb48798ae74820608",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/free-toggle",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/free-toggle",
+ "endpoint": "https://free-toggle.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-toggle.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:0c2dec52f78aba7a51da95ba201a46cfe4f7a5a63774e37065098c1cb280a50d",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-toggle",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-toggle",
+ "native_model": "upstream-free-toggle",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "disabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": false
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "enabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": true
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "enabled",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-toggle",
+ "entitlement_id": "entitlement/upstream-free-toggle",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-toggle",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-toggle",
+ "native_model": "upstream-free-toggle",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "disabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": false
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "enabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": true
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "enabled",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-toggle",
+ "entitlement_id": "entitlement/upstream-free-toggle",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:13d4e3cabe4b7a3847575a074ff3aeb185a448b774f5b25a17917dddb3c92250",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/free-toggle"
+ ],
+ "free_offer": {
+ "free_offer_id": "free-offer/free-toggle",
+ "free_offer_revision": 1,
+ "offer_ref": "offer/free-toggle",
+ "access": "direct",
+ "evidence_digest": "sha256:1b13d90e87f9d8c37797417abd3a50dea0f7bb9cfea8c09b1c49118569869ab5"
+ },
+ "exact_reasoning": {
+ "kind": "toggle",
+ "parameter": "reasoning",
+ "enabled": true,
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/free-budget",
+ "binding_revision": 1,
+ "binding_digest": "sha256:ebc833790cca5ef7a1ac6c205ef0959bdc10f8a829713c12e21a233741f45bc8",
+ "source_id": "source/free-budget",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:75def2742abc7ed74de10238e290e7d88b6ecf50619e2e9930099918c55b6477",
+ "connection_option_id": "option/free-budget",
+ "offer_ref": "offer/free-budget",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:d664a276197ec6b4d30f413b6318bf8debb7fb77b8cb384b3c2cf29052ab4ee9",
+ "billing_class": "free",
+ "model_configuration_id": "model.free-budget",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-free-budget",
+ "native_transport_model": "upstream-free-budget",
+ "capability_id": "capability/free-budget",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:4600179108eb0f7390d3f3c0a566e2ee0c9b37d8b90b1834e749a2adfca104a5",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/free-budget",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/free-budget",
+ "endpoint": "https://free-budget.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-budget.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:97fc8c80a78370115e0271c0eb2ff882107cb846d0c8af8c2eafd68e03b79dd2",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-budget",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-budget",
+ "native_model": "upstream-free-budget",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "budget-512",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 512
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 512,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1024",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1024
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1024,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1536",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1536
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1536,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2048",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2048
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2048,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2560",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2560
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2560,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3072",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3072
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3072,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3584",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3584
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3584,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-4096",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 4096
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 4096,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "budget-1024",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-budget",
+ "entitlement_id": "entitlement/upstream-free-budget",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-budget",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-budget",
+ "native_model": "upstream-free-budget",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "budget-512",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 512
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 512,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1024",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1024
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1024,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1536",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1536
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1536,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2048",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2048
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2048,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2560",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2560
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2560,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3072",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3072
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3072,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3584",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3584
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3584,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-4096",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 4096
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 4096,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "budget-1024",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-budget",
+ "entitlement_id": "entitlement/upstream-free-budget",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:6365f4dfb8851b9bf3dc4c375eb753b3dbfd2f42df452309d9bbd8b678c7e81a",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/free-budget"
+ ],
+ "credential_pool_id": "pool/free-budget",
+ "free_offer": {
+ "free_offer_id": "free-offer/free-budget",
+ "free_offer_revision": 1,
+ "offer_ref": "offer/free-budget",
+ "access": "api_key_required",
+ "evidence_digest": "sha256:2200dded9b065236fe5abbb4971b029ee772a395510437e377517726018e93e0"
+ },
+ "exact_reasoning": {
+ "kind": "budget",
+ "parameter": "thinking_budget",
+ "tokens": 1024,
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/free-b",
+ "binding_revision": 1,
+ "binding_digest": "sha256:8986c7cd25ffd9a9034795fee918aa2b0b0f46baa7e0eca33a0f0fa04300dc5a",
+ "source_id": "source/free-b",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:e3654a532251abe2cf8180da0d9060f33455dc3ce60c57e8f720ffc48bf0148a",
+ "connection_option_id": "option/free-b",
+ "offer_ref": "offer/free-b",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:88a8353cbca7424344bda727346c965998e15fc3c8ccdf9b2ce4f2fe90b2d9c7",
+ "billing_class": "free",
+ "model_configuration_id": "model.free-b",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-free-b",
+ "native_transport_model": "upstream-free-b",
+ "capability_id": "capability/free-b",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:7608766fd4b211643bdb65d35adb2fa422f808ce08f8c02cd69d930173a99a2b",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/free-b",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/free-b",
+ "endpoint": "https://free-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:3ec2919760d37618dc911d2c887ec96cdab27642ca517bb7ab9994e5948d4e01",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:d8287003935f6cc715992af6e1699356b9af2f6f7017eb35aa02b351b3a3064f",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/free-b"
+ ],
+ "free_offer": {
+ "free_offer_id": "free-offer/free-b",
+ "free_offer_revision": 1,
+ "offer_ref": "offer/free-b",
+ "access": "direct",
+ "evidence_digest": "sha256:94ad11fb1d7e77a92c4bd3a1b618ab99a489af9258398f553ae0d3cac9768a7d"
+ },
+ "exact_reasoning": {
+ "kind": "fixed",
+ "profile": "fixed",
+ "render_mode": "no_control_parameter"
+ }
+ }
+ ]
+ },
+ {
+ "group_id": "primary",
+ "ordering_evidence": {
+ "kind": "explicit_order"
+ },
+ "pinned_ratings": {},
+ "candidates": [
+ {
+ "binding_id": "binding/primary-a",
+ "binding_revision": 1,
+ "binding_digest": "sha256:bc72b46479bf87bd914998841f9dd1fc20039c553d51f38b98de9861ed239a10",
+ "source_id": "source/primary-a",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:ec2b08f84b9c6d83286b4425e155752cb5f5f23fc041a735ddee3fe7acb9c258",
+ "connection_option_id": "option/primary-a",
+ "offer_ref": "offer/primary-a",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:88924ff21883853ef2c486c512ed13224b96c75984104b6a18fa6f72f2ec863c",
+ "billing_class": "paid",
+ "model_configuration_id": "model.primary-a",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-primary-a",
+ "native_transport_model": "upstream-primary-a",
+ "capability_id": "capability/primary-a",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:5c740f261397a0d499ff3bd1215ce1192b4fa9225ca45fa072b1ab2e08eb02e9",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/primary-a",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/primary-a",
+ "endpoint": "https://primary-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:30d61f7e5af1fd7cf13507541bbbdae5825b22816abc227d92ab301cc4a16954",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f81b8d62cbfb64b9a1bfb578d223443ca5e6f18599ec525f9b877d642074bf5a",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/primary-a"
+ ],
+ "credential_pool_id": "pool/primary-a",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "high",
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/primary-b",
+ "binding_revision": 1,
+ "binding_digest": "sha256:9205afa8d854b1c8c7d668ea1db0cf79b9e2c26581eed81956292a22b7beb877",
+ "source_id": "source/primary-b",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:c763add7a5ec53ea3b3376a3ff3c2b8322102ef5446ef331a2296e2ece4188f6",
+ "connection_option_id": "option/primary-b",
+ "offer_ref": "offer/primary-b",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:2bd867c82a64bbe32d505234ea0cfe529f1d35729f6332c72471cc469a424cd7",
+ "billing_class": "paid",
+ "model_configuration_id": "model.primary-b",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-primary-b",
+ "native_transport_model": "upstream-primary-b",
+ "capability_id": "capability/primary-b",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:0d092592692914efad1c3776df31f5488a62dee4c8d1c4f1b14380dad846bf49",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/primary-b",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/primary-b",
+ "endpoint": "https://primary-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:6177ffb3f981ccaddd778a0459b0e1958c97e8bc22aa950920c791baba3b57aa",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:7cf9d7be2442c7a7ecbf417d1fff850321e1e0ba7b0a946046979b93aeb6b085",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/primary-b"
+ ],
+ "credential_pool_id": "pool/primary-b",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "high",
+ "render_mode": "explicit_native"
+ }
+ }
+ ]
+ }
+ ]
+ }
+ }
+ },
+ "digest": "sha256:65f7e52543536d02292202e818cb395d1afe3c92553c77f0d45603ec287c8cac"
+ },
+ {
+ "body": {
+ "schema": "hiroute.compiled-agent-plan/v3",
+ "compiler_revision": "agent-plan-compiler/v3",
+ "identity": {
+ "agent_plan_id": "plan/smart",
+ "model_alias": "hiroute/89e03a7d2c57bbc9",
+ "display_name": "Daily saving",
+ "purpose": "Routine coding with a quality-protected economy path"
+ },
+ "agent_plan_revision": 3,
+ "materialized_route_digest": "sha256:b1be20aa2f815899b4be10330a68738244a4e472c269afeba03b54a4e65223a9",
+ "materialized": {
+ "fact_refs": {
+ "connector_registry_version": "registry.v1",
+ "connector_registry_digest": "sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822",
+ "model_data_bundle_version": "model-data.v1",
+ "model_data_digest": "sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333",
+ "capability_slice_version": "capabilities.v1",
+ "capability_slice_digest": "sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08",
+ "ratings_slice_version": "ratings.v1",
+ "ratings_slice_digest": "sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693",
+ "free_offers_slice_version": "free-offers.v1",
+ "free_offers_slice_digest": "sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b",
+ "inventory_revision": 9,
+ "inventory_digest": "sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189",
+ "price_tracking": "follow_latest"
+ },
+ "request_owned": {
+ "strategy": "classified",
+ "classifier": {
+ "revision": "hiroute-complexity-v1",
+ "mode": {
+ "kind": "local_rules"
+ },
+ "user_keywords": [
+ "performance regression",
+ "性能回归"
+ ]
+ },
+ "reselect_on_user_message": false,
+ "simple_groups": [
+ "economy",
+ "primary"
+ ],
+ "complex_groups": [
+ "primary"
+ ]
+ },
+ "attempt_owned": {
+ "limits": {
+ "maximum_attempts": 6,
+ "request_timeout_ms": 120000,
+ "attempt_timeout_ms": 60000
+ },
+ "groups": [
+ {
+ "group_id": "economy",
+ "ordering_evidence": {
+ "kind": "explicit_order"
+ },
+ "pinned_ratings": {},
+ "candidates": [
+ {
+ "binding_id": "binding/economy-a",
+ "binding_revision": 1,
+ "binding_digest": "sha256:5e3d435b3c1b1de2d83f13f5ead4445eb39163ff81bd411bf7b73bfe7327e6ab",
+ "source_id": "source/economy-a",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:cc675da2cbf7366fdddc8211c733223e3f2def6c3c85ce826db5b0d8c8e42606",
+ "connection_option_id": "option/economy-a",
+ "offer_ref": "offer/economy-a",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:900ac293a7e52dcba4e3d5fc11c8d90105c0551a890d56155581ec355f46b561",
+ "billing_class": "paid",
+ "model_configuration_id": "model.economy-a",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-economy-a",
+ "native_transport_model": "upstream-economy-a",
+ "capability_id": "capability/economy-a",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:67eaab5d0015a83f97fa956dcc457f635c4fc466667511f06cd16da0238e16ee",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/economy-a",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/economy-a",
+ "endpoint": "https://economy-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://economy-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:823b9fc1359364686849a1b50f9bc6747e603cf987414653a3ee6afcad9f32cf",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-a",
+ "native_model": "upstream-economy-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-a",
+ "entitlement_id": "entitlement/upstream-economy-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-a",
+ "native_model": "upstream-economy-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-a",
+ "entitlement_id": "entitlement/upstream-economy-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:4eebd0958987be4686b0e4e3ae2c1ece60cea503a0e6d2a8e1858fbeb067b01f",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/economy-a"
+ ],
+ "credential_pool_id": "pool/economy-a",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "low",
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/economy-c",
+ "binding_revision": 1,
+ "binding_digest": "sha256:9d899d74d9aec41c15172d9ded7761e48bf099307ec8804792aaf7c729723a45",
+ "source_id": "source/economy-c",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:cef0c877da662def854ff9e5f149debe74491a4729dda2c985dd6b4d606b02f2",
+ "connection_option_id": "option/economy-c",
+ "offer_ref": "offer/economy-c",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:210ed1feffec897b81423f1dba248b99956dcc2eec390ff99493c50f86b7a24d",
+ "billing_class": "paid",
+ "model_configuration_id": "model.economy-c",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-economy-c",
+ "native_transport_model": "upstream-economy-c",
+ "capability_id": "capability/economy-c",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:88bf26b16d6f60943204f8758fab6a31b0cdb128b84732bfedd5c796d1476242",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/economy-c",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/economy-c",
+ "endpoint": "https://economy-c.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://economy-c.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:45dde7e4b3cf6aa212a7c2869df0cc679be5dd51053609fd00e5aa5a5fe9a852",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-c",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-c",
+ "native_model": "upstream-economy-c",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-c",
+ "entitlement_id": "entitlement/upstream-economy-c",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-c",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-c",
+ "native_model": "upstream-economy-c",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-c",
+ "entitlement_id": "entitlement/upstream-economy-c",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:e323f4615ec0930d31b2ec4725b863af8649dd0f8cebd2de978f721eb9cfe63e",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/economy-c"
+ ],
+ "credential_pool_id": "pool/economy-c",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "low",
+ "render_mode": "explicit_native"
+ }
+ }
+ ]
+ },
+ {
+ "group_id": "primary",
+ "ordering_evidence": {
+ "kind": "explicit_order"
+ },
+ "pinned_ratings": {},
+ "candidates": [
+ {
+ "binding_id": "binding/primary-a",
+ "binding_revision": 1,
+ "binding_digest": "sha256:bc72b46479bf87bd914998841f9dd1fc20039c553d51f38b98de9861ed239a10",
+ "source_id": "source/primary-a",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:ec2b08f84b9c6d83286b4425e155752cb5f5f23fc041a735ddee3fe7acb9c258",
+ "connection_option_id": "option/primary-a",
+ "offer_ref": "offer/primary-a",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:88924ff21883853ef2c486c512ed13224b96c75984104b6a18fa6f72f2ec863c",
+ "billing_class": "paid",
+ "model_configuration_id": "model.primary-a",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-primary-a",
+ "native_transport_model": "upstream-primary-a",
+ "capability_id": "capability/primary-a",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:5c740f261397a0d499ff3bd1215ce1192b4fa9225ca45fa072b1ab2e08eb02e9",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/primary-a",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/primary-a",
+ "endpoint": "https://primary-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:30d61f7e5af1fd7cf13507541bbbdae5825b22816abc227d92ab301cc4a16954",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f81b8d62cbfb64b9a1bfb578d223443ca5e6f18599ec525f9b877d642074bf5a",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/primary-a"
+ ],
+ "credential_pool_id": "pool/primary-a",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "high",
+ "render_mode": "explicit_native"
+ }
+ },
+ {
+ "binding_id": "binding/primary-b",
+ "binding_revision": 1,
+ "binding_digest": "sha256:9205afa8d854b1c8c7d668ea1db0cf79b9e2c26581eed81956292a22b7beb877",
+ "source_id": "source/primary-b",
+ "source_revision": 1,
+ "source_identity_digest": "sha256:c763add7a5ec53ea3b3376a3ff3c2b8322102ef5446ef331a2296e2ece4188f6",
+ "connection_option_id": "option/primary-b",
+ "offer_ref": "offer/primary-b",
+ "offer_revision": 1,
+ "offer_evidence_digest": "sha256:2bd867c82a64bbe32d505234ea0cfe529f1d35729f6332c72471cc469a424cd7",
+ "billing_class": "paid",
+ "model_configuration_id": "model.primary-b",
+ "model_configuration_revision": 1,
+ "upstream_model_id": "upstream-primary-b",
+ "native_transport_model": "upstream-primary-b",
+ "capability_id": "capability/primary-b",
+ "capability_revision": 1,
+ "capability_evidence_digest": "sha256:0d092592692914efad1c3776df31f5488a62dee4c8d1c4f1b14380dad846bf49",
+ "connector_id": "connector.builtin",
+ "connector_revision": 1,
+ "endpoint_profile_id": "endpoint/primary-b",
+ "endpoint_profile_revision": 1,
+ "protocol_endpoint_id": "protocol/primary-b",
+ "endpoint": "https://primary-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:6177ffb3f981ccaddd778a0459b0e1958c97e8bc22aa950920c791baba3b57aa",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:7cf9d7be2442c7a7ecbf417d1fff850321e1e0ba7b0a946046979b93aeb6b085",
+ "upstream_protocol": "responses",
+ "adapter_ref": "adapter/native/responses",
+ "adapter_revision": 1,
+ "credential_refs": [
+ "credential/primary-b"
+ ],
+ "credential_pool_id": "pool/primary-b",
+ "exact_reasoning": {
+ "kind": "profile",
+ "parameter": "reasoning_effort",
+ "profile": "high",
+ "render_mode": "explicit_native"
+ }
+ }
+ ]
+ }
+ ]
+ }
+ }
+ },
+ "digest": "sha256:59d79b0c6cd5748d55f7b3e7828a2a416a8491e0791b48b8a7b8a018d360cbfe"
+ }
+ ],
+ "aliases": [
+ {
+ "served_model_id": "hiroute/2590c10eeae4f930",
+ "purpose": "Use the exact user-selected candidate order",
+ "agent_plan_revision": 1,
+ "protocols": [
+ "responses",
+ "messages"
+ ],
+ "overall_timeout_ms": 120000,
+ "max_attempts": 6,
+ "routing": {
+ "agent_plan_id": "plan/custom",
+ "plan_display_name": "Explicit chain",
+ "request_owned": {
+ "strategy": "ordered",
+ "cost_policy": "api_equivalent",
+ "ordered_groups": [
+ "custom"
+ ]
+ },
+ "groups": [
+ {
+ "group_id": "custom",
+ "candidate_local_ids": [
+ 2710267646,
+ 232715680
+ ]
+ }
+ ]
+ },
+ "candidates": [
+ {
+ "local_id": 2710267646,
+ "stable_target_key": "binding/primary-b",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/primary-b"
+ ],
+ "credential_destination_ref": "connection-option/option/primary-b",
+ "upstream_model_id": "upstream-primary-b",
+ "native_transport_model": "upstream-primary-b",
+ "endpoint": "https://primary-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:6177ffb3f981ccaddd778a0459b0e1958c97e8bc22aa950920c791baba3b57aa",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:a172443f307bde83f0a954a5a8778c9b92fb1f30db79319b737c85c083265d12"
+ },
+ {
+ "local_id": 232715680,
+ "stable_target_key": "binding/primary-a",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/primary-a"
+ ],
+ "credential_destination_ref": "connection-option/option/primary-a",
+ "upstream_model_id": "upstream-primary-a",
+ "native_transport_model": "upstream-primary-a",
+ "endpoint": "https://primary-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:30d61f7e5af1fd7cf13507541bbbdae5825b22816abc227d92ab301cc4a16954",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f81b8d62cbfb64b9a1bfb578d223443ca5e6f18599ec525f9b877d642074bf5a"
+ }
+ ]
+ },
+ {
+ "served_model_id": "hiroute/2b52668dd5854ef1",
+ "purpose": "Research tasks that prefer the pinned free pool",
+ "agent_plan_revision": 2,
+ "protocols": [
+ "responses"
+ ],
+ "overall_timeout_ms": 120000,
+ "max_attempts": 6,
+ "routing": {
+ "agent_plan_id": "plan/free",
+ "plan_display_name": "Free research",
+ "request_owned": {
+ "strategy": "ordered",
+ "cost_policy": "strict_free",
+ "ordered_groups": [
+ "free"
+ ]
+ },
+ "groups": [
+ {
+ "group_id": "free",
+ "candidate_local_ids": [
+ 1568451870,
+ 2216548935
+ ]
+ }
+ ]
+ },
+ "candidates": [
+ {
+ "local_id": 1568451870,
+ "stable_target_key": "binding/free-a",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/free-a"
+ ],
+ "credential_destination_ref": "connection-option/option/free-a",
+ "upstream_model_id": "upstream-free-a",
+ "native_transport_model": "upstream-free-a",
+ "endpoint": "https://free-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:0b4c464b0e788da93df655a3524018c6662efc4d4eacb226b7896ef8d6ee1f98",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f2fffed1b1abe15352867881944be3d38fc821fef42c8543edb45c5eb11f5a67"
+ },
+ {
+ "local_id": 2216548935,
+ "stable_target_key": "binding/free-b",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/free-b"
+ ],
+ "credential_destination_ref": "connection-option/option/free-b",
+ "upstream_model_id": "upstream-free-b",
+ "native_transport_model": "upstream-free-b",
+ "endpoint": "https://free-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:3ec2919760d37618dc911d2c887ec96cdab27642ca517bb7ab9994e5948d4e01",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:d8287003935f6cc715992af6e1699356b9af2f6f7017eb35aa02b351b3a3064f"
+ }
+ ]
+ },
+ {
+ "served_model_id": "hiroute/6a87b28966202d08",
+ "purpose": "Research tasks that prefer the pinned free pool",
+ "agent_plan_revision": 1,
+ "protocols": [
+ "responses"
+ ],
+ "overall_timeout_ms": 120000,
+ "max_attempts": 6,
+ "routing": {
+ "agent_plan_id": "plan/free-fallback",
+ "plan_display_name": "Free research",
+ "request_owned": {
+ "strategy": "ordered",
+ "cost_policy": "api_equivalent",
+ "ordered_groups": [
+ "free",
+ "primary"
+ ]
+ },
+ "groups": [
+ {
+ "group_id": "free",
+ "candidate_local_ids": [
+ 2565149417,
+ 1441018858,
+ 1422684107,
+ 4178931494
+ ]
+ },
+ {
+ "group_id": "primary",
+ "candidate_local_ids": [
+ 3012200749,
+ 479350674
+ ]
+ }
+ ]
+ },
+ "candidates": [
+ {
+ "local_id": 2565149417,
+ "stable_target_key": "binding/free-a",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/free-a"
+ ],
+ "credential_destination_ref": "connection-option/option/free-a",
+ "upstream_model_id": "upstream-free-a",
+ "native_transport_model": "upstream-free-a",
+ "endpoint": "https://free-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:0b4c464b0e788da93df655a3524018c6662efc4d4eacb226b7896ef8d6ee1f98",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-a",
+ "native_model": "upstream-free-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-a",
+ "entitlement_id": "entitlement/upstream-free-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f2fffed1b1abe15352867881944be3d38fc821fef42c8543edb45c5eb11f5a67"
+ },
+ {
+ "local_id": 1441018858,
+ "stable_target_key": "binding/free-toggle",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/free-toggle"
+ ],
+ "credential_destination_ref": "connection-option/option/free-toggle",
+ "upstream_model_id": "upstream-free-toggle",
+ "native_transport_model": "upstream-free-toggle",
+ "endpoint": "https://free-toggle.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-toggle.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:0c2dec52f78aba7a51da95ba201a46cfe4f7a5a63774e37065098c1cb280a50d",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-toggle",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-toggle",
+ "native_model": "upstream-free-toggle",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "disabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": false
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "enabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": true
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "enabled",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-toggle",
+ "entitlement_id": "entitlement/upstream-free-toggle",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-toggle",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-toggle",
+ "native_model": "upstream-free-toggle",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "disabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": false
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "enabled",
+ "control_kind": "toggle",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning"
+ ],
+ "value": {
+ "kind": "bool",
+ "value": true
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "enabled",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-toggle",
+ "entitlement_id": "entitlement/upstream-free-toggle",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:13d4e3cabe4b7a3847575a074ff3aeb185a448b774f5b25a17917dddb3c92250"
+ },
+ {
+ "local_id": 1422684107,
+ "stable_target_key": "binding/free-budget",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/free-budget"
+ ],
+ "credential_destination_ref": "connection-option/option/free-budget",
+ "upstream_model_id": "upstream-free-budget",
+ "native_transport_model": "upstream-free-budget",
+ "endpoint": "https://free-budget.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-budget.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:97fc8c80a78370115e0271c0eb2ff882107cb846d0c8af8c2eafd68e03b79dd2",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-budget",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-budget",
+ "native_model": "upstream-free-budget",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "budget-512",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 512
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 512,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1024",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1024
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1024,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1536",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1536
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1536,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2048",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2048
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2048,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2560",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2560
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2560,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3072",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3072
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3072,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3584",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3584
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3584,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-4096",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 4096
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 4096,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "budget-1024",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-budget",
+ "entitlement_id": "entitlement/upstream-free-budget",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-budget",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-budget",
+ "native_model": "upstream-free-budget",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "budget-512",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 512
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 512,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1024",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1024
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1024,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-1536",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 1536
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 1536,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2048",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2048
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2048,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-2560",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 2560
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 2560,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3072",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3072
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3072,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-3584",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 3584
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 3584,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "budget-4096",
+ "control_kind": "budget",
+ "render": {
+ "kind": "exact_budget",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "thinking_budget"
+ ],
+ "value": {
+ "kind": "u64",
+ "value": 4096
+ }
+ }
+ ],
+ "budget_path": [
+ "thinking_budget"
+ ],
+ "selected_tokens": 4096,
+ "min_tokens": 512,
+ "max_tokens": 4096,
+ "step_tokens": 512
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "budget-1024",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-budget",
+ "entitlement_id": "entitlement/upstream-free-budget",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:6365f4dfb8851b9bf3dc4c375eb753b3dbfd2f42df452309d9bbd8b678c7e81a"
+ },
+ {
+ "local_id": 4178931494,
+ "stable_target_key": "binding/free-b",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/free-b"
+ ],
+ "credential_destination_ref": "connection-option/option/free-b",
+ "upstream_model_id": "upstream-free-b",
+ "native_transport_model": "upstream-free-b",
+ "endpoint": "https://free-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://free-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:3ec2919760d37618dc911d2c887ec96cdab27642ca517bb7ab9994e5948d4e01",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/free-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.free-b",
+ "native_model": "upstream-free-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "fixed",
+ "control_kind": "fixed",
+ "render": {
+ "kind": "no_control_parameter"
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "fixed",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-free-b",
+ "entitlement_id": "entitlement/upstream-free-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:d8287003935f6cc715992af6e1699356b9af2f6f7017eb35aa02b351b3a3064f"
+ },
+ {
+ "local_id": 3012200749,
+ "stable_target_key": "binding/primary-a",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/primary-a"
+ ],
+ "credential_destination_ref": "connection-option/option/primary-a",
+ "upstream_model_id": "upstream-primary-a",
+ "native_transport_model": "upstream-primary-a",
+ "endpoint": "https://primary-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:30d61f7e5af1fd7cf13507541bbbdae5825b22816abc227d92ab301cc4a16954",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f81b8d62cbfb64b9a1bfb578d223443ca5e6f18599ec525f9b877d642074bf5a"
+ },
+ {
+ "local_id": 479350674,
+ "stable_target_key": "binding/primary-b",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/primary-b"
+ ],
+ "credential_destination_ref": "connection-option/option/primary-b",
+ "upstream_model_id": "upstream-primary-b",
+ "native_transport_model": "upstream-primary-b",
+ "endpoint": "https://primary-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:6177ffb3f981ccaddd778a0459b0e1958c97e8bc22aa950920c791baba3b57aa",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:7cf9d7be2442c7a7ecbf417d1fff850321e1e0ba7b0a946046979b93aeb6b085"
+ }
+ ]
+ },
+ {
+ "served_model_id": "hiroute/89e03a7d2c57bbc9",
+ "purpose": "Routine coding with a quality-protected economy path",
+ "agent_plan_revision": 3,
+ "protocols": [
+ "responses",
+ "messages"
+ ],
+ "overall_timeout_ms": 120000,
+ "max_attempts": 6,
+ "routing": {
+ "agent_plan_id": "plan/smart",
+ "plan_display_name": "Daily saving",
+ "request_owned": {
+ "strategy": "classified",
+ "classifier": {
+ "revision": "hiroute-complexity-v1",
+ "mode": {
+ "kind": "local_rules"
+ },
+ "user_keywords": [
+ "performance regression",
+ "性能回归"
+ ]
+ },
+ "reselect_on_user_message": false,
+ "simple_groups": [
+ "economy",
+ "primary"
+ ],
+ "complex_groups": [
+ "primary"
+ ]
+ },
+ "groups": [
+ {
+ "group_id": "economy",
+ "candidate_local_ids": [
+ 1625224380,
+ 2756832356
+ ]
+ },
+ {
+ "group_id": "primary",
+ "candidate_local_ids": [
+ 3758193879,
+ 1732819286
+ ]
+ }
+ ]
+ },
+ "candidates": [
+ {
+ "local_id": 1625224380,
+ "stable_target_key": "binding/economy-a",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/economy-a"
+ ],
+ "credential_destination_ref": "connection-option/option/economy-a",
+ "upstream_model_id": "upstream-economy-a",
+ "native_transport_model": "upstream-economy-a",
+ "endpoint": "https://economy-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://economy-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:823b9fc1359364686849a1b50f9bc6747e603cf987414653a3ee6afcad9f32cf",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-a",
+ "native_model": "upstream-economy-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-a",
+ "entitlement_id": "entitlement/upstream-economy-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-a",
+ "native_model": "upstream-economy-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-a",
+ "entitlement_id": "entitlement/upstream-economy-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:4eebd0958987be4686b0e4e3ae2c1ece60cea503a0e6d2a8e1858fbeb067b01f"
+ },
+ {
+ "local_id": 2756832356,
+ "stable_target_key": "binding/economy-c",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/economy-c"
+ ],
+ "credential_destination_ref": "connection-option/option/economy-c",
+ "upstream_model_id": "upstream-economy-c",
+ "native_transport_model": "upstream-economy-c",
+ "endpoint": "https://economy-c.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://economy-c.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:45dde7e4b3cf6aa212a7c2869df0cc679be5dd51053609fd00e5aa5a5fe9a852",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-c",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-c",
+ "native_model": "upstream-economy-c",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-c",
+ "entitlement_id": "entitlement/upstream-economy-c",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/economy-c",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.economy-c",
+ "native_model": "upstream-economy-c",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "low",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-economy-c",
+ "entitlement_id": "entitlement/upstream-economy-c",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:e323f4615ec0930d31b2ec4725b863af8649dd0f8cebd2de978f721eb9cfe63e"
+ },
+ {
+ "local_id": 3758193879,
+ "stable_target_key": "binding/primary-a",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/primary-a"
+ ],
+ "credential_destination_ref": "connection-option/option/primary-a",
+ "upstream_model_id": "upstream-primary-a",
+ "native_transport_model": "upstream-primary-a",
+ "endpoint": "https://primary-a.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-a.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:30d61f7e5af1fd7cf13507541bbbdae5825b22816abc227d92ab301cc4a16954",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-a",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-a",
+ "native_model": "upstream-primary-a",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-a",
+ "entitlement_id": "entitlement/upstream-primary-a",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:f81b8d62cbfb64b9a1bfb578d223443ca5e6f18599ec525f9b877d642074bf5a"
+ },
+ {
+ "local_id": 1732819286,
+ "stable_target_key": "binding/primary-b",
+ "adapter_id": "adapter/native/responses@1",
+ "credential_refs": [
+ "credential/primary-b"
+ ],
+ "credential_destination_ref": "connection-option/option/primary-b",
+ "upstream_model_id": "upstream-primary-b",
+ "native_transport_model": "upstream-primary-b",
+ "endpoint": "https://primary-b.provider.invalid/v1/responses",
+ "connector_runtime": "builtin_native",
+ "operational_target": {
+ "kind": "registered_https",
+ "uri": "https://primary-b.provider.invalid/v1/responses"
+ },
+ "operational_target_digest": "sha256:6177ffb3f981ccaddd778a0459b0e1958c97e8bc22aa950920c791baba3b57aa",
+ "protocol_profiles": [
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "responses-to-responses",
+ "ingress_protocol": "responses",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ },
+ {
+ "schema_version": "hiroute.candidate-protocol-profile/v1",
+ "path_id": "messages-to-responses",
+ "ingress_protocol": "messages",
+ "adapter_revision": "adapter/native/responses@1",
+ "serializer_revision": "hiroute-target-json/v1",
+ "decoder_revision": "hiroute-native-response/v1",
+ "capability": {
+ "schema_version": "hiroute.candidate-capability/v1",
+ "capability_id": "capability/primary-b",
+ "capability_revision": "1",
+ "upstream_protocol": "responses",
+ "model_configuration_id": "model.primary-b",
+ "native_model": "upstream-primary-b",
+ "model_support": {
+ "tools": {
+ "state": "exact",
+ "value": true
+ },
+ "vision": {
+ "state": "exact",
+ "value": true
+ }
+ },
+ "request": {
+ "text": "exact",
+ "initial_instructions": "exact",
+ "mid_conversation_instructions": "exact",
+ "image_url": "exact",
+ "image_base64": "exact",
+ "image_base64_media_types": {
+ "state": "exact",
+ "value": [
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp"
+ ]
+ },
+ "function_tools": "exact",
+ "strict_tools": "exact",
+ "tool_choice_none": "exact",
+ "tool_choice_auto": "exact",
+ "tool_choice_required_any": "exact",
+ "tool_choice_required_named": "exact",
+ "parallel_tools": "exact",
+ "tool_roundtrip": "exact",
+ "tool_result_text": "exact",
+ "tool_result_json": "exact",
+ "logical_tool_id_mapping": "exact",
+ "provider_state": "exact"
+ },
+ "response": {
+ "text": "exact",
+ "reasoning": "exact",
+ "refusal": "exact",
+ "tool_calls": "exact",
+ "logical_tool_id_mapping": "exact",
+ "usage": "exact",
+ "finish_reason": "exact",
+ "typed_error": "exact",
+ "provider_state": "exact",
+ "stream_refusal": {
+ "kind": "exact_delta"
+ },
+ "stream_text_delta": "exact",
+ "stream_tool_argument_delta": "exact",
+ "stream_reasoning_delta": "exact",
+ "stream_usage": "exact"
+ },
+ "reasoning_profiles": [
+ {
+ "profile_id": "low",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "low"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "medium",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "medium"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ },
+ {
+ "profile_id": "high",
+ "control_kind": "discrete",
+ "render": {
+ "kind": "exact_fields",
+ "protocol": "responses",
+ "fields": [
+ {
+ "path": [
+ "reasoning_effort"
+ ],
+ "value": {
+ "kind": "string",
+ "value": "high"
+ }
+ }
+ ]
+ },
+ "accounting": "within_output_cap",
+ "additional_reservation_tokens": 0
+ }
+ ],
+ "selected_reasoning_profile_id": "high",
+ "context": {
+ "max_input_tokens": {
+ "state": "exact",
+ "value": 128000
+ },
+ "max_output_tokens": {
+ "state": "exact",
+ "value": 16384
+ },
+ "max_total_tokens": {
+ "state": "exact",
+ "value": 144384
+ },
+ "estimator": {
+ "state": "exact",
+ "value": {
+ "revision": "byte-upper-bound/v1",
+ "bytes_per_token": 1,
+ "fixed_overhead_tokens": 0
+ }
+ }
+ },
+ "native_streaming": {
+ "state": "exact",
+ "value": true
+ },
+ "native_provider_state": "native"
+ },
+ "connector": {
+ "schema_version": "hiroute.connector-profile/v1",
+ "provider_id": "publisher.builtin",
+ "endpoint_id": "endpoint/upstream-primary-b",
+ "entitlement_id": "entitlement/upstream-primary-b",
+ "connector_id": "connector.builtin",
+ "connector_revision": "1",
+ "upstream_protocol": "responses",
+ "request_path": "/v1/responses",
+ "authentication": {
+ "state": "exact",
+ "value": {
+ "kind": "bearer"
+ }
+ },
+ "headers": {
+ "state": "exact",
+ "value": {
+ "content_type": "application/json",
+ "required_headers": [],
+ "forbidden_forward_headers": [
+ "authorization",
+ "x-api-key"
+ ]
+ }
+ },
+ "errors": {
+ "state": "exact",
+ "value": {
+ "http_status_typed": true,
+ "sse_error_typed": true,
+ "retry_after_header": "retry-after"
+ }
+ }
+ }
+ }
+ ],
+ "protocol_profile_digest": "sha256:7cf9d7be2442c7a7ecbf417d1fff850321e1e0ba7b0a946046979b93aeb6b085"
+ }
+ ]
+ }
+ ],
+ "grants": [
+ {
+ "grant_id": "grant/claude",
+ "generation": 3,
+ "bearer_token_sha256": "sha256:a72fb69b049ed4858e1fbed82d235f27c354df06f6afb996e14f71a36e452618",
+ "model_grant": {
+ "protocol": "messages",
+ "routes": {
+ "hiroute/2590c10eeae4f930": {
+ "kind": "plan",
+ "plan_id": "plan/custom",
+ "alias": "hiroute/2590c10eeae4f930",
+ "revision": 1,
+ "semantic_digest": "sha256:e208befbe54c8d44ceed59a79a920d4985c48a54c8edcf4d27143d8f84c3106a"
+ },
+ "hiroute/89e03a7d2c57bbc9": {
+ "kind": "plan",
+ "plan_id": "plan/smart",
+ "alias": "hiroute/89e03a7d2c57bbc9",
+ "revision": 3,
+ "semantic_digest": "sha256:b1be20aa2f815899b4be10330a68738244a4e472c269afeba03b54a4e65223a9"
+ }
+ },
+ "digest": "sha256:c5c4d58249fae8f882b290b8c612802a4e05c3410631708795cb08083fa0960a"
+ }
+ },
+ {
+ "grant_id": "grant/codex",
+ "generation": 7,
+ "bearer_token_sha256": "sha256:88ecd719b793798ff9b90e7290f551c792abfa133b8eff0b9e9edc808a00193f",
+ "model_grant": {
+ "protocol": "responses",
+ "routes": {
+ "hiroute/2590c10eeae4f930": {
+ "kind": "plan",
+ "plan_id": "plan/custom",
+ "alias": "hiroute/2590c10eeae4f930",
+ "revision": 1,
+ "semantic_digest": "sha256:e208befbe54c8d44ceed59a79a920d4985c48a54c8edcf4d27143d8f84c3106a"
+ },
+ "hiroute/2b52668dd5854ef1": {
+ "kind": "plan",
+ "plan_id": "plan/free",
+ "alias": "hiroute/2b52668dd5854ef1",
+ "revision": 2,
+ "semantic_digest": "sha256:b8733e042f27345751bf552066087f518e2f880b8af5bfffd38210460568586e"
+ },
+ "hiroute/6a87b28966202d08": {
+ "kind": "plan",
+ "plan_id": "plan/free-fallback",
+ "alias": "hiroute/6a87b28966202d08",
+ "revision": 1,
+ "semantic_digest": "sha256:d522e644eb987012f8c047283a37f878f24d0748dbc613b528edd60476ec135f"
+ },
+ "hiroute/89e03a7d2c57bbc9": {
+ "kind": "plan",
+ "plan_id": "plan/smart",
+ "alias": "hiroute/89e03a7d2c57bbc9",
+ "revision": 3,
+ "semantic_digest": "sha256:b1be20aa2f815899b4be10330a68738244a4e472c269afeba03b54a4e65223a9"
+ }
+ },
+ "digest": "sha256:94f6863a50d904f3628ff300c188e25e20664af3b6ad20a7c31e57a8c42ec689"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/e2e/product/fixtures/routing/stored-publication.v1.json b/e2e/product/fixtures/routing/stored-publication.v1.json
new file mode 100644
index 00000000..7aac7da8
--- /dev/null
+++ b/e2e/product/fixtures/routing/stored-publication.v1.json
@@ -0,0 +1 @@
+{"schema":"hiroute.stored-publication/v1","workspace_id":"personal/default","authority_id":"workspace/personal/default/gateway","authority_epoch":1,"publication_revision":11,"alias_registry":{"schema":"hiroute.agent-plan-alias-registry/v1","next_sequence":5,"active":{"plan/custom":"hiroute/2590c10eeae4f930","plan/free":"hiroute/2b52668dd5854ef1","plan/free-fallback":"hiroute/6a87b28966202d08","plan/smart":"hiroute/89e03a7d2c57bbc9"},"tombstones":[],"retired_plan_ids":[]},"plans":[{"schema":"hiroute.stored-plan/v1","identity":{"agent_plan_id":"plan/custom","model_alias":"hiroute/2590c10eeae4f930","display_name":"Explicit chain","purpose":"Use the exact user-selected candidate order"},"revision":1,"fact_refs":{"connector_registry_version":"registry.v1","connector_registry_digest":"sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822","model_data_bundle_version":"model-data.v1","model_data_digest":"sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333","capability_slice_version":"capabilities.v1","capability_slice_digest":"sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08","ratings_slice_version":"ratings.v1","ratings_slice_digest":"sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693","free_offers_slice_version":"free-offers.v1","free_offers_slice_digest":"sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b","inventory_revision":9,"inventory_digest":"sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189","price_tracking":"follow_latest"},"request":{"strategy":"ordered","cost_policy":"api_equivalent","ordered_groups":["custom"]},"limits":{"maximum_attempts":6,"request_timeout_ms":120000,"attempt_timeout_ms":60000},"groups":[{"group_id":"custom","ordering_evidence":{"kind":"explicit_order"},"pinned_ratings":{},"candidates":[{"binding_id":"binding/primary-b","binding_revision":1,"binding_digest":"sha256:9205afa8d854b1c8c7d668ea1db0cf79b9e2c26581eed81956292a22b7beb877","source_id":"source/primary-b","source_revision":1,"source_identity_digest":"sha256:c763add7a5ec53ea3b3376a3ff3c2b8322102ef5446ef331a2296e2ece4188f6","connection_option_id":"option/primary-b","offer_ref":"offer/primary-b","offer_revision":1,"offer_evidence_digest":"sha256:2bd867c82a64bbe32d505234ea0cfe529f1d35729f6332c72471cc469a424cd7","billing_class":"paid","model_configuration_id":"model.primary-b","model_configuration_revision":1,"upstream_model_id":"upstream-primary-b","native_transport_model":"upstream-primary-b","capability_id":"capability/primary-b","capability_revision":1,"capability_evidence_digest":"sha256:0d092592692914efad1c3776df31f5488a62dee4c8d1c4f1b14380dad846bf49","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/primary-b","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/primary-b","endpoint":"https://primary-b.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://primary-b.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/primary-b"],"credential_destination_ref":null,"credential_pool_id":"pool/primary-b","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"low","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/primary-b","capability_revision":"1","model_configuration_id":"model.primary-b","native_model":"upstream-primary-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-b","entitlement_id":"entitlement/upstream-primary-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/primary-b","capability_revision":"1","model_configuration_id":"model.primary-b","native_model":"upstream-primary-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-b","entitlement_id":"entitlement/upstream-primary-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/primary-a","binding_revision":1,"binding_digest":"sha256:bc72b46479bf87bd914998841f9dd1fc20039c553d51f38b98de9861ed239a10","source_id":"source/primary-a","source_revision":1,"source_identity_digest":"sha256:ec2b08f84b9c6d83286b4425e155752cb5f5f23fc041a735ddee3fe7acb9c258","connection_option_id":"option/primary-a","offer_ref":"offer/primary-a","offer_revision":1,"offer_evidence_digest":"sha256:88924ff21883853ef2c486c512ed13224b96c75984104b6a18fa6f72f2ec863c","billing_class":"paid","model_configuration_id":"model.primary-a","model_configuration_revision":1,"upstream_model_id":"upstream-primary-a","native_transport_model":"upstream-primary-a","capability_id":"capability/primary-a","capability_revision":1,"capability_evidence_digest":"sha256:5c740f261397a0d499ff3bd1215ce1192b4fa9225ca45fa072b1ab2e08eb02e9","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/primary-a","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/primary-a","endpoint":"https://primary-a.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://primary-a.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/primary-a"],"credential_destination_ref":null,"credential_pool_id":"pool/primary-a","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"high","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/primary-a","capability_revision":"1","model_configuration_id":"model.primary-a","native_model":"upstream-primary-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-a","entitlement_id":"entitlement/upstream-primary-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/primary-a","capability_revision":"1","model_configuration_id":"model.primary-a","native_model":"upstream-primary-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-a","entitlement_id":"entitlement/upstream-primary-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]}]}]},{"schema":"hiroute.stored-plan/v1","identity":{"agent_plan_id":"plan/free","model_alias":"hiroute/2b52668dd5854ef1","display_name":"Free research","purpose":"Research tasks that prefer the pinned free pool"},"revision":2,"fact_refs":{"connector_registry_version":"registry.v1","connector_registry_digest":"sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822","model_data_bundle_version":"model-data.v1","model_data_digest":"sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333","capability_slice_version":"capabilities.v1","capability_slice_digest":"sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08","ratings_slice_version":"ratings.v1","ratings_slice_digest":"sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693","free_offers_slice_version":"free-offers.v1","free_offers_slice_digest":"sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b","inventory_revision":9,"inventory_digest":"sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189","price_tracking":"follow_latest"},"request":{"strategy":"ordered","cost_policy":"strict_free","ordered_groups":["free"]},"limits":{"maximum_attempts":6,"request_timeout_ms":120000,"attempt_timeout_ms":60000},"groups":[{"group_id":"free","ordering_evidence":{"kind":"explicit_order"},"pinned_ratings":{},"candidates":[{"binding_id":"binding/free-a","binding_revision":1,"binding_digest":"sha256:f2f62274234d5d6478417fe0a516e69127d7a30e1cecf605552f6ae305601cce","source_id":"source/free-a","source_revision":1,"source_identity_digest":"sha256:d5eb6a62fabe0f3a8979572ea72980328d93d994bf9a13bc2604bd21dfeca9d0","connection_option_id":"option/free-a","offer_ref":"offer/free-a","offer_revision":1,"offer_evidence_digest":"sha256:c6e1aac1c995b1927c57ffa1b3df73893eaf4e6fd5edc17f0311a9211b1348e0","billing_class":"free","model_configuration_id":"model.free-a","model_configuration_revision":1,"upstream_model_id":"upstream-free-a","native_transport_model":"upstream-free-a","capability_id":"capability/free-a","capability_revision":1,"capability_evidence_digest":"sha256:3f5ac32e719a6f10e7deeac8de577069ad389967a7fbb53cb6836b04d866738a","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/free-a","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/free-a","endpoint":"https://free-a.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://free-a.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/free-a"],"credential_destination_ref":null,"credential_pool_id":null,"free_offer":{"free_offer_id":"free-offer/free-a","free_offer_revision":1,"offer_ref":"offer/free-a","access":"direct","evidence_digest":"sha256:5aee1ca1a796cb1042ddb6a26017b31f5fe4174c543d3941a724623de51f330b"},"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"low","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/free-a","capability_revision":"1","model_configuration_id":"model.free-a","native_model":"upstream-free-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-a","entitlement_id":"entitlement/upstream-free-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/free-a","capability_revision":"1","model_configuration_id":"model.free-a","native_model":"upstream-free-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-a","entitlement_id":"entitlement/upstream-free-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/free-b","binding_revision":1,"binding_digest":"sha256:8986c7cd25ffd9a9034795fee918aa2b0b0f46baa7e0eca33a0f0fa04300dc5a","source_id":"source/free-b","source_revision":1,"source_identity_digest":"sha256:e3654a532251abe2cf8180da0d9060f33455dc3ce60c57e8f720ffc48bf0148a","connection_option_id":"option/free-b","offer_ref":"offer/free-b","offer_revision":1,"offer_evidence_digest":"sha256:88a8353cbca7424344bda727346c965998e15fc3c8ccdf9b2ce4f2fe90b2d9c7","billing_class":"free","model_configuration_id":"model.free-b","model_configuration_revision":1,"upstream_model_id":"upstream-free-b","native_transport_model":"upstream-free-b","capability_id":"capability/free-b","capability_revision":1,"capability_evidence_digest":"sha256:7608766fd4b211643bdb65d35adb2fa422f808ce08f8c02cd69d930173a99a2b","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/free-b","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/free-b","endpoint":"https://free-b.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://free-b.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/free-b"],"credential_destination_ref":null,"credential_pool_id":null,"free_offer":{"free_offer_id":"free-offer/free-b","free_offer_revision":1,"offer_ref":"offer/free-b","access":"direct","evidence_digest":"sha256:94ad11fb1d7e77a92c4bd3a1b618ab99a489af9258398f553ae0d3cac9768a7d"},"exact_reasoning":{"kind":"fixed","profile":"fixed","render_mode":"no_control_parameter"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/free-b","capability_revision":"1","model_configuration_id":"model.free-b","native_model":"upstream-free-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"fixed","control_kind":"fixed","parameters":{"kind":"no_control_parameter"}}],"selected_reasoning_profile_id":"fixed"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-b","entitlement_id":"entitlement/upstream-free-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/free-b","capability_revision":"1","model_configuration_id":"model.free-b","native_model":"upstream-free-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"fixed","control_kind":"fixed","parameters":{"kind":"no_control_parameter"}}],"selected_reasoning_profile_id":"fixed"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-b","entitlement_id":"entitlement/upstream-free-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]}]}]},{"schema":"hiroute.stored-plan/v1","identity":{"agent_plan_id":"plan/free-fallback","model_alias":"hiroute/6a87b28966202d08","display_name":"Free research","purpose":"Research tasks that prefer the pinned free pool"},"revision":1,"fact_refs":{"connector_registry_version":"registry.v1","connector_registry_digest":"sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822","model_data_bundle_version":"model-data.v1","model_data_digest":"sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333","capability_slice_version":"capabilities.v1","capability_slice_digest":"sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08","ratings_slice_version":"ratings.v1","ratings_slice_digest":"sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693","free_offers_slice_version":"free-offers.v1","free_offers_slice_digest":"sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b","inventory_revision":9,"inventory_digest":"sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189","price_tracking":"follow_latest"},"request":{"strategy":"ordered","cost_policy":"api_equivalent","ordered_groups":["free","primary"]},"limits":{"maximum_attempts":6,"request_timeout_ms":120000,"attempt_timeout_ms":60000},"groups":[{"group_id":"free","ordering_evidence":{"kind":"explicit_order"},"pinned_ratings":{},"candidates":[{"binding_id":"binding/free-a","binding_revision":1,"binding_digest":"sha256:f2f62274234d5d6478417fe0a516e69127d7a30e1cecf605552f6ae305601cce","source_id":"source/free-a","source_revision":1,"source_identity_digest":"sha256:d5eb6a62fabe0f3a8979572ea72980328d93d994bf9a13bc2604bd21dfeca9d0","connection_option_id":"option/free-a","offer_ref":"offer/free-a","offer_revision":1,"offer_evidence_digest":"sha256:c6e1aac1c995b1927c57ffa1b3df73893eaf4e6fd5edc17f0311a9211b1348e0","billing_class":"free","model_configuration_id":"model.free-a","model_configuration_revision":1,"upstream_model_id":"upstream-free-a","native_transport_model":"upstream-free-a","capability_id":"capability/free-a","capability_revision":1,"capability_evidence_digest":"sha256:3f5ac32e719a6f10e7deeac8de577069ad389967a7fbb53cb6836b04d866738a","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/free-a","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/free-a","endpoint":"https://free-a.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://free-a.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/free-a"],"credential_destination_ref":null,"credential_pool_id":null,"free_offer":{"free_offer_id":"free-offer/free-a","free_offer_revision":1,"offer_ref":"offer/free-a","access":"direct","evidence_digest":"sha256:5aee1ca1a796cb1042ddb6a26017b31f5fe4174c543d3941a724623de51f330b"},"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"low","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/free-a","capability_revision":"1","model_configuration_id":"model.free-a","native_model":"upstream-free-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-a","entitlement_id":"entitlement/upstream-free-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/free-a","capability_revision":"1","model_configuration_id":"model.free-a","native_model":"upstream-free-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-a","entitlement_id":"entitlement/upstream-free-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/free-toggle","binding_revision":1,"binding_digest":"sha256:23caa04a713c0dc7604408955963a8302513f9f47f5fc6504d4854fdda7bdcc8","source_id":"source/free-toggle","source_revision":1,"source_identity_digest":"sha256:056ade35e960ca377e939453e70136eda549574fb65f791d5a4ebf2f99ac7963","connection_option_id":"option/free-toggle","offer_ref":"offer/free-toggle","offer_revision":1,"offer_evidence_digest":"sha256:09d40cbd60b3565090afaa54ff3bf23b8f7a106f36f2c9dea0b1f07f6136b8cd","billing_class":"free","model_configuration_id":"model.free-toggle","model_configuration_revision":1,"upstream_model_id":"upstream-free-toggle","native_transport_model":"upstream-free-toggle","capability_id":"capability/free-toggle","capability_revision":1,"capability_evidence_digest":"sha256:5a34328b6d2fbb50867aa5541ef430070fc35d3f76c86cbfb48798ae74820608","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/free-toggle","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/free-toggle","endpoint":"https://free-toggle.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://free-toggle.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/free-toggle"],"credential_destination_ref":null,"credential_pool_id":null,"free_offer":{"free_offer_id":"free-offer/free-toggle","free_offer_revision":1,"offer_ref":"offer/free-toggle","access":"direct","evidence_digest":"sha256:1b13d90e87f9d8c37797417abd3a50dea0f7bb9cfea8c09b1c49118569869ab5"},"exact_reasoning":{"kind":"toggle","parameter":"reasoning","enabled":true,"render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/free-toggle","capability_revision":"1","model_configuration_id":"model.free-toggle","native_model":"upstream-free-toggle","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"disabled","control_kind":"toggle","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning"],"value":{"kind":"bool","value":false}}]}},{"profile_id":"enabled","control_kind":"toggle","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning"],"value":{"kind":"bool","value":true}}]}}],"selected_reasoning_profile_id":"enabled"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-toggle","entitlement_id":"entitlement/upstream-free-toggle","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/free-toggle","capability_revision":"1","model_configuration_id":"model.free-toggle","native_model":"upstream-free-toggle","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"disabled","control_kind":"toggle","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning"],"value":{"kind":"bool","value":false}}]}},{"profile_id":"enabled","control_kind":"toggle","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning"],"value":{"kind":"bool","value":true}}]}}],"selected_reasoning_profile_id":"enabled"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-toggle","entitlement_id":"entitlement/upstream-free-toggle","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/free-budget","binding_revision":1,"binding_digest":"sha256:ebc833790cca5ef7a1ac6c205ef0959bdc10f8a829713c12e21a233741f45bc8","source_id":"source/free-budget","source_revision":1,"source_identity_digest":"sha256:75def2742abc7ed74de10238e290e7d88b6ecf50619e2e9930099918c55b6477","connection_option_id":"option/free-budget","offer_ref":"offer/free-budget","offer_revision":1,"offer_evidence_digest":"sha256:d664a276197ec6b4d30f413b6318bf8debb7fb77b8cb384b3c2cf29052ab4ee9","billing_class":"free","model_configuration_id":"model.free-budget","model_configuration_revision":1,"upstream_model_id":"upstream-free-budget","native_transport_model":"upstream-free-budget","capability_id":"capability/free-budget","capability_revision":1,"capability_evidence_digest":"sha256:4600179108eb0f7390d3f3c0a566e2ee0c9b37d8b90b1834e749a2adfca104a5","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/free-budget","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/free-budget","endpoint":"https://free-budget.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://free-budget.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/free-budget"],"credential_destination_ref":null,"credential_pool_id":"pool/free-budget","free_offer":{"free_offer_id":"free-offer/free-budget","free_offer_revision":1,"offer_ref":"offer/free-budget","access":"api_key_required","evidence_digest":"sha256:2200dded9b065236fe5abbb4971b029ee772a395510437e377517726018e93e0"},"exact_reasoning":{"kind":"budget","parameter":"thinking_budget","tokens":1024,"render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/free-budget","capability_revision":"1","model_configuration_id":"model.free-budget","native_model":"upstream-free-budget","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"budget-512","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":512}}],"budget_path":["thinking_budget"],"selected_tokens":512,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-1024","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":1024}}],"budget_path":["thinking_budget"],"selected_tokens":1024,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-1536","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":1536}}],"budget_path":["thinking_budget"],"selected_tokens":1536,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-2048","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":2048}}],"budget_path":["thinking_budget"],"selected_tokens":2048,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-2560","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":2560}}],"budget_path":["thinking_budget"],"selected_tokens":2560,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-3072","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":3072}}],"budget_path":["thinking_budget"],"selected_tokens":3072,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-3584","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":3584}}],"budget_path":["thinking_budget"],"selected_tokens":3584,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-4096","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":4096}}],"budget_path":["thinking_budget"],"selected_tokens":4096,"min_tokens":512,"max_tokens":4096,"step_tokens":512}}],"selected_reasoning_profile_id":"budget-1024"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-budget","entitlement_id":"entitlement/upstream-free-budget","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/free-budget","capability_revision":"1","model_configuration_id":"model.free-budget","native_model":"upstream-free-budget","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"budget-512","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":512}}],"budget_path":["thinking_budget"],"selected_tokens":512,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-1024","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":1024}}],"budget_path":["thinking_budget"],"selected_tokens":1024,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-1536","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":1536}}],"budget_path":["thinking_budget"],"selected_tokens":1536,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-2048","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":2048}}],"budget_path":["thinking_budget"],"selected_tokens":2048,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-2560","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":2560}}],"budget_path":["thinking_budget"],"selected_tokens":2560,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-3072","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":3072}}],"budget_path":["thinking_budget"],"selected_tokens":3072,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-3584","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":3584}}],"budget_path":["thinking_budget"],"selected_tokens":3584,"min_tokens":512,"max_tokens":4096,"step_tokens":512}},{"profile_id":"budget-4096","control_kind":"budget","parameters":{"kind":"budget","protocol":"responses","fields":[{"path":["thinking_budget"],"value":{"kind":"u64","value":4096}}],"budget_path":["thinking_budget"],"selected_tokens":4096,"min_tokens":512,"max_tokens":4096,"step_tokens":512}}],"selected_reasoning_profile_id":"budget-1024"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-budget","entitlement_id":"entitlement/upstream-free-budget","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/free-b","binding_revision":1,"binding_digest":"sha256:8986c7cd25ffd9a9034795fee918aa2b0b0f46baa7e0eca33a0f0fa04300dc5a","source_id":"source/free-b","source_revision":1,"source_identity_digest":"sha256:e3654a532251abe2cf8180da0d9060f33455dc3ce60c57e8f720ffc48bf0148a","connection_option_id":"option/free-b","offer_ref":"offer/free-b","offer_revision":1,"offer_evidence_digest":"sha256:88a8353cbca7424344bda727346c965998e15fc3c8ccdf9b2ce4f2fe90b2d9c7","billing_class":"free","model_configuration_id":"model.free-b","model_configuration_revision":1,"upstream_model_id":"upstream-free-b","native_transport_model":"upstream-free-b","capability_id":"capability/free-b","capability_revision":1,"capability_evidence_digest":"sha256:7608766fd4b211643bdb65d35adb2fa422f808ce08f8c02cd69d930173a99a2b","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/free-b","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/free-b","endpoint":"https://free-b.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://free-b.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/free-b"],"credential_destination_ref":null,"credential_pool_id":null,"free_offer":{"free_offer_id":"free-offer/free-b","free_offer_revision":1,"offer_ref":"offer/free-b","access":"direct","evidence_digest":"sha256:94ad11fb1d7e77a92c4bd3a1b618ab99a489af9258398f553ae0d3cac9768a7d"},"exact_reasoning":{"kind":"fixed","profile":"fixed","render_mode":"no_control_parameter"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/free-b","capability_revision":"1","model_configuration_id":"model.free-b","native_model":"upstream-free-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"fixed","control_kind":"fixed","parameters":{"kind":"no_control_parameter"}}],"selected_reasoning_profile_id":"fixed"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-b","entitlement_id":"entitlement/upstream-free-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/free-b","capability_revision":"1","model_configuration_id":"model.free-b","native_model":"upstream-free-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"fixed","control_kind":"fixed","parameters":{"kind":"no_control_parameter"}}],"selected_reasoning_profile_id":"fixed"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-free-b","entitlement_id":"entitlement/upstream-free-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]}]},{"group_id":"primary","ordering_evidence":{"kind":"explicit_order"},"pinned_ratings":{},"candidates":[{"binding_id":"binding/primary-a","binding_revision":1,"binding_digest":"sha256:bc72b46479bf87bd914998841f9dd1fc20039c553d51f38b98de9861ed239a10","source_id":"source/primary-a","source_revision":1,"source_identity_digest":"sha256:ec2b08f84b9c6d83286b4425e155752cb5f5f23fc041a735ddee3fe7acb9c258","connection_option_id":"option/primary-a","offer_ref":"offer/primary-a","offer_revision":1,"offer_evidence_digest":"sha256:88924ff21883853ef2c486c512ed13224b96c75984104b6a18fa6f72f2ec863c","billing_class":"paid","model_configuration_id":"model.primary-a","model_configuration_revision":1,"upstream_model_id":"upstream-primary-a","native_transport_model":"upstream-primary-a","capability_id":"capability/primary-a","capability_revision":1,"capability_evidence_digest":"sha256:5c740f261397a0d499ff3bd1215ce1192b4fa9225ca45fa072b1ab2e08eb02e9","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/primary-a","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/primary-a","endpoint":"https://primary-a.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://primary-a.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/primary-a"],"credential_destination_ref":null,"credential_pool_id":"pool/primary-a","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"high","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/primary-a","capability_revision":"1","model_configuration_id":"model.primary-a","native_model":"upstream-primary-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-a","entitlement_id":"entitlement/upstream-primary-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/primary-a","capability_revision":"1","model_configuration_id":"model.primary-a","native_model":"upstream-primary-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-a","entitlement_id":"entitlement/upstream-primary-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/primary-b","binding_revision":1,"binding_digest":"sha256:9205afa8d854b1c8c7d668ea1db0cf79b9e2c26581eed81956292a22b7beb877","source_id":"source/primary-b","source_revision":1,"source_identity_digest":"sha256:c763add7a5ec53ea3b3376a3ff3c2b8322102ef5446ef331a2296e2ece4188f6","connection_option_id":"option/primary-b","offer_ref":"offer/primary-b","offer_revision":1,"offer_evidence_digest":"sha256:2bd867c82a64bbe32d505234ea0cfe529f1d35729f6332c72471cc469a424cd7","billing_class":"paid","model_configuration_id":"model.primary-b","model_configuration_revision":1,"upstream_model_id":"upstream-primary-b","native_transport_model":"upstream-primary-b","capability_id":"capability/primary-b","capability_revision":1,"capability_evidence_digest":"sha256:0d092592692914efad1c3776df31f5488a62dee4c8d1c4f1b14380dad846bf49","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/primary-b","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/primary-b","endpoint":"https://primary-b.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://primary-b.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/primary-b"],"credential_destination_ref":null,"credential_pool_id":"pool/primary-b","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"high","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/primary-b","capability_revision":"1","model_configuration_id":"model.primary-b","native_model":"upstream-primary-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-b","entitlement_id":"entitlement/upstream-primary-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/primary-b","capability_revision":"1","model_configuration_id":"model.primary-b","native_model":"upstream-primary-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-b","entitlement_id":"entitlement/upstream-primary-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]}]}]},{"schema":"hiroute.stored-plan/v1","identity":{"agent_plan_id":"plan/smart","model_alias":"hiroute/89e03a7d2c57bbc9","display_name":"Daily saving","purpose":"Routine coding with a quality-protected economy path"},"revision":3,"fact_refs":{"connector_registry_version":"registry.v1","connector_registry_digest":"sha256:872491a30d60d598962de6e7b834ab76b2aa65fbab102c6ebaaae6acdc238822","model_data_bundle_version":"model-data.v1","model_data_digest":"sha256:78af4dc485eb32a809e795bfca78a4f5313401b58d9bc81cc4d1b89445b97333","capability_slice_version":"capabilities.v1","capability_slice_digest":"sha256:3fc0e5c4c484797a0035141c53252fba96ec5923ec719b5c73d2b9078b31bf08","ratings_slice_version":"ratings.v1","ratings_slice_digest":"sha256:6e8e9fd7a26ff87b90abe40fae707329603f4089cdb22cbe348bc173febc8693","free_offers_slice_version":"free-offers.v1","free_offers_slice_digest":"sha256:7ce24ab9a95668cb5553d69d4e611c750a642ba9e217a5ca3e378e1373ed933b","inventory_revision":9,"inventory_digest":"sha256:b11a85b296a90afc460430434a504e7acb04b064575b7277724688af0e59d189","price_tracking":"follow_latest"},"request":{"strategy":"classified","classifier":{"revision":"hiroute-complexity-v1","mode":{"kind":"local_rules"},"user_keywords":["performance regression","性能回归"]},"reselect_on_user_message":false,"simple_groups":["economy","primary"],"complex_groups":["primary"]},"limits":{"maximum_attempts":6,"request_timeout_ms":120000,"attempt_timeout_ms":60000},"groups":[{"group_id":"economy","ordering_evidence":{"kind":"explicit_order"},"pinned_ratings":{},"candidates":[{"binding_id":"binding/economy-a","binding_revision":1,"binding_digest":"sha256:5e3d435b3c1b1de2d83f13f5ead4445eb39163ff81bd411bf7b73bfe7327e6ab","source_id":"source/economy-a","source_revision":1,"source_identity_digest":"sha256:cc675da2cbf7366fdddc8211c733223e3f2def6c3c85ce826db5b0d8c8e42606","connection_option_id":"option/economy-a","offer_ref":"offer/economy-a","offer_revision":1,"offer_evidence_digest":"sha256:900ac293a7e52dcba4e3d5fc11c8d90105c0551a890d56155581ec355f46b561","billing_class":"paid","model_configuration_id":"model.economy-a","model_configuration_revision":1,"upstream_model_id":"upstream-economy-a","native_transport_model":"upstream-economy-a","capability_id":"capability/economy-a","capability_revision":1,"capability_evidence_digest":"sha256:67eaab5d0015a83f97fa956dcc457f635c4fc466667511f06cd16da0238e16ee","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/economy-a","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/economy-a","endpoint":"https://economy-a.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://economy-a.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/economy-a"],"credential_destination_ref":null,"credential_pool_id":"pool/economy-a","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"low","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/economy-a","capability_revision":"1","model_configuration_id":"model.economy-a","native_model":"upstream-economy-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-economy-a","entitlement_id":"entitlement/upstream-economy-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/economy-a","capability_revision":"1","model_configuration_id":"model.economy-a","native_model":"upstream-economy-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-economy-a","entitlement_id":"entitlement/upstream-economy-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/economy-c","binding_revision":1,"binding_digest":"sha256:9d899d74d9aec41c15172d9ded7761e48bf099307ec8804792aaf7c729723a45","source_id":"source/economy-c","source_revision":1,"source_identity_digest":"sha256:cef0c877da662def854ff9e5f149debe74491a4729dda2c985dd6b4d606b02f2","connection_option_id":"option/economy-c","offer_ref":"offer/economy-c","offer_revision":1,"offer_evidence_digest":"sha256:210ed1feffec897b81423f1dba248b99956dcc2eec390ff99493c50f86b7a24d","billing_class":"paid","model_configuration_id":"model.economy-c","model_configuration_revision":1,"upstream_model_id":"upstream-economy-c","native_transport_model":"upstream-economy-c","capability_id":"capability/economy-c","capability_revision":1,"capability_evidence_digest":"sha256:88bf26b16d6f60943204f8758fab6a31b0cdb128b84732bfedd5c796d1476242","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/economy-c","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/economy-c","endpoint":"https://economy-c.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://economy-c.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/economy-c"],"credential_destination_ref":null,"credential_pool_id":"pool/economy-c","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"low","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/economy-c","capability_revision":"1","model_configuration_id":"model.economy-c","native_model":"upstream-economy-c","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-economy-c","entitlement_id":"entitlement/upstream-economy-c","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/economy-c","capability_revision":"1","model_configuration_id":"model.economy-c","native_model":"upstream-economy-c","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"low"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-economy-c","entitlement_id":"entitlement/upstream-economy-c","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]}]},{"group_id":"primary","ordering_evidence":{"kind":"explicit_order"},"pinned_ratings":{},"candidates":[{"binding_id":"binding/primary-a","binding_revision":1,"binding_digest":"sha256:bc72b46479bf87bd914998841f9dd1fc20039c553d51f38b98de9861ed239a10","source_id":"source/primary-a","source_revision":1,"source_identity_digest":"sha256:ec2b08f84b9c6d83286b4425e155752cb5f5f23fc041a735ddee3fe7acb9c258","connection_option_id":"option/primary-a","offer_ref":"offer/primary-a","offer_revision":1,"offer_evidence_digest":"sha256:88924ff21883853ef2c486c512ed13224b96c75984104b6a18fa6f72f2ec863c","billing_class":"paid","model_configuration_id":"model.primary-a","model_configuration_revision":1,"upstream_model_id":"upstream-primary-a","native_transport_model":"upstream-primary-a","capability_id":"capability/primary-a","capability_revision":1,"capability_evidence_digest":"sha256:5c740f261397a0d499ff3bd1215ce1192b4fa9225ca45fa072b1ab2e08eb02e9","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/primary-a","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/primary-a","endpoint":"https://primary-a.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://primary-a.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/primary-a"],"credential_destination_ref":null,"credential_pool_id":"pool/primary-a","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"high","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/primary-a","capability_revision":"1","model_configuration_id":"model.primary-a","native_model":"upstream-primary-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-a","entitlement_id":"entitlement/upstream-primary-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/primary-a","capability_revision":"1","model_configuration_id":"model.primary-a","native_model":"upstream-primary-a","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-a","entitlement_id":"entitlement/upstream-primary-a","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]},{"binding_id":"binding/primary-b","binding_revision":1,"binding_digest":"sha256:9205afa8d854b1c8c7d668ea1db0cf79b9e2c26581eed81956292a22b7beb877","source_id":"source/primary-b","source_revision":1,"source_identity_digest":"sha256:c763add7a5ec53ea3b3376a3ff3c2b8322102ef5446ef331a2296e2ece4188f6","connection_option_id":"option/primary-b","offer_ref":"offer/primary-b","offer_revision":1,"offer_evidence_digest":"sha256:2bd867c82a64bbe32d505234ea0cfe529f1d35729f6332c72471cc469a424cd7","billing_class":"paid","model_configuration_id":"model.primary-b","model_configuration_revision":1,"upstream_model_id":"upstream-primary-b","native_transport_model":"upstream-primary-b","capability_id":"capability/primary-b","capability_revision":1,"capability_evidence_digest":"sha256:0d092592692914efad1c3776df31f5488a62dee4c8d1c4f1b14380dad846bf49","connector_id":"connector.builtin","connector_revision":1,"endpoint_profile_id":"endpoint/primary-b","endpoint_profile_revision":1,"protocol_endpoint_id":"protocol/primary-b","endpoint":"https://primary-b.provider.invalid/v1/responses","connector_runtime":"builtin_native","operational_target":{"kind":"registered_https","uri":"https://primary-b.provider.invalid/v1/responses"},"upstream_protocol":"responses","credential_refs":["credential/primary-b"],"credential_destination_ref":null,"credential_pool_id":"pool/primary-b","free_offer":null,"exact_reasoning":{"kind":"profile","parameter":"reasoning_effort","profile":"high","render_mode":"explicit_native"},"protocols":[{"ingress_protocol":"responses","capability":{"capability_id":"capability/primary-b","capability_revision":"1","model_configuration_id":"model.primary-b","native_model":"upstream-primary-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-b","entitlement_id":"entitlement/upstream-primary-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null},{"ingress_protocol":"messages","capability":{"capability_id":"capability/primary-b","capability_revision":"1","model_configuration_id":"model.primary-b","native_model":"upstream-primary-b","model_support":{"tools":{"state":"exact","value":true},"vision":{"state":"exact","value":true}},"max_input_tokens":{"state":"exact","value":128000},"max_output_tokens":{"state":"exact","value":16384},"max_total_tokens":{"state":"exact","value":144384},"native_streaming":{"state":"exact","value":true},"reasoning_profiles":[{"profile_id":"low","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"low"}}]}},{"profile_id":"medium","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"medium"}}]}},{"profile_id":"high","control_kind":"discrete","parameters":{"kind":"fields","protocol":"responses","fields":[{"path":["reasoning_effort"],"value":{"kind":"string","value":"high"}}]}}],"selected_reasoning_profile_id":"high"},"connector":{"provider_id":"publisher.builtin","endpoint_id":"endpoint/upstream-primary-b","entitlement_id":"entitlement/upstream-primary-b","connector_id":"connector.builtin","connector_revision":"1","upstream_protocol":"responses","request_path":"/v1/responses","authentication":{"state":"exact","value":{"kind":"bearer"}},"content_type":"application/json","required_headers":[]},"native_target":null,"credential_profile_identity":null}]}]}]}],"plan_heads":[],"grants":[{"grant_id":"grant/claude","generation":3,"bearer_token_sha256":"sha256:a72fb69b049ed4858e1fbed82d235f27c354df06f6afb996e14f71a36e452618","model_grant":{"protocol":"messages","routes":{"hiroute/2590c10eeae4f930":{"kind":"plan","plan_id":"plan/custom","alias":"hiroute/2590c10eeae4f930","revision":1,"semantic_digest":"sha256:e208befbe54c8d44ceed59a79a920d4985c48a54c8edcf4d27143d8f84c3106a"},"hiroute/89e03a7d2c57bbc9":{"kind":"plan","plan_id":"plan/smart","alias":"hiroute/89e03a7d2c57bbc9","revision":3,"semantic_digest":"sha256:b1be20aa2f815899b4be10330a68738244a4e472c269afeba03b54a4e65223a9"}},"digest":"sha256:c5c4d58249fae8f882b290b8c612802a4e05c3410631708795cb08083fa0960a"}},{"grant_id":"grant/codex","generation":7,"bearer_token_sha256":"sha256:88ecd719b793798ff9b90e7290f551c792abfa133b8eff0b9e9edc808a00193f","model_grant":{"protocol":"responses","routes":{"hiroute/2590c10eeae4f930":{"kind":"plan","plan_id":"plan/custom","alias":"hiroute/2590c10eeae4f930","revision":1,"semantic_digest":"sha256:e208befbe54c8d44ceed59a79a920d4985c48a54c8edcf4d27143d8f84c3106a"},"hiroute/2b52668dd5854ef1":{"kind":"plan","plan_id":"plan/free","alias":"hiroute/2b52668dd5854ef1","revision":2,"semantic_digest":"sha256:b8733e042f27345751bf552066087f518e2f880b8af5bfffd38210460568586e"},"hiroute/6a87b28966202d08":{"kind":"plan","plan_id":"plan/free-fallback","alias":"hiroute/6a87b28966202d08","revision":1,"semantic_digest":"sha256:d522e644eb987012f8c047283a37f878f24d0748dbc613b528edd60476ec135f"},"hiroute/89e03a7d2c57bbc9":{"kind":"plan","plan_id":"plan/smart","alias":"hiroute/89e03a7d2c57bbc9","revision":3,"semantic_digest":"sha256:b1be20aa2f815899b4be10330a68738244a4e472c269afeba03b54a4e65223a9"}},"digest":"sha256:94f6863a50d904f3628ff300c188e25e20664af3b6ad20a7c31e57a8c42ec689"}}]}
\ No newline at end of file
diff --git a/scripts/check-contract-convergence.py b/scripts/check-contract-convergence.py
index dac6bcc4..423563f4 100755
--- a/scripts/check-contract-convergence.py
+++ b/scripts/check-contract-convergence.py
@@ -58,6 +58,19 @@ def load_text(root, path):
return ""
+def historical_release_snapshot(path, source):
+ # These files describe released producers, never current readers/writers or test
+ # fixtures. Their full index, digest and Git-source validation belongs to
+ # release-contracts.py check. Do not exempt code, arbitrary JSON or other paths.
+ if not re.fullmatch(r"contracts/releases/v[0-9][0-9A-Za-z.+-]*\.json", path):
+ return False
+ try:
+ value = json.loads(source)
+ except ValueError:
+ return False
+ return isinstance(value, dict) and value.get("schema") == "hiroute.release-contract-snapshot/v1"
+
+
def production_source_path(path):
"""Select shipped/internal Rust sources, not tests, fixtures, docs, or third-party data."""
value = Path(path)
@@ -208,6 +221,8 @@ def audit(root, registry, paths=None):
if (root / path).is_file():
errors.append(f"obsolete live contract file reintroduced: {path}")
texts = {path: load_text(root, path) for path in paths}
+ texts = {path: source for path, source in texts.items()
+ if not historical_release_snapshot(path, source)}
production = discover_production_contracts(texts)
declared_production = set(registry["production_contracts"])
for contract in sorted(set(production) - declared_production):
diff --git a/scripts/package-desktop.py b/scripts/package-desktop.py
index c9b0d622..db9e7633 100644
--- a/scripts/package-desktop.py
+++ b/scripts/package-desktop.py
@@ -31,6 +31,19 @@ BUILD_TIMINGS = []
BINARIES = ("hiroute-desktop", "hirouted", "hiroute", "cliproxyapi")
+def validate_release_versions(version):
+ # Local Control uses the application-api package version for its exact
+ # same-release handshake. It must track the shipped clients and daemon.
+ for relative in ("crates/application-api/Cargo.toml", "crates/cli/Cargo.toml",
+ "crates/daemon/Cargo.toml", "apps/desktop/src-tauri/Cargo.toml"):
+ section = re.search(r"(?ms)^\[package\]\s*\n(.*?)(?=^\[|\Z)",
+ (REPO / relative).read_text())
+ declared = re.search(r'^version\s*=\s*"([^"]+)"\s*$', section[1], re.M) if section else None
+ actual = declared[1] if declared else None
+ if actual != version:
+ raise ValueError(f"release version mismatch: {relative} is {actual}, expected {version}")
+
+
def run(*args, cwd=REPO, env=None, timeout=None):
print(f"Running {Path(args[0]).name} {' '.join(args[1:3])}", file=sys.stderr, flush=True)
started = time.monotonic()
@@ -244,6 +257,8 @@ def build(args):
raise ValueError("external Cargo targets are forbidden")
if args.identity != "-" and not args.notary_profile:
raise ValueError("Developer ID distribution requires a notary profile")
+ config = json.loads((NATIVE / "tauri.conf.json").read_text())
+ validate_release_versions(config["version"])
revision = run("git", "rev-parse", "HEAD")
output = candidate_output(revision, architecture)
BUILD_LOG = output / "build.log"
@@ -252,7 +267,6 @@ def build(args):
resources = app / "Contents/Resources"
macos.mkdir(parents=True)
resources.mkdir()
- config = json.loads((NATIVE / "tauri.conf.json").read_text())
info = {"CFBundleIdentifier": config["identifier"], "CFBundleName": "HiRoute",
"CFBundleDisplayName": "HiRoute", "CFBundleExecutable": "hiroute-desktop",
"CFBundlePackageType": "APPL", "CFBundleIconFile": "HiRoute.icns",
@@ -283,6 +297,7 @@ def build(args):
environment = os.environ.copy()
environment["RUSTC_WRAPPER"] = "sccache"
environment["CARGO_INCREMENTAL"] = "0"
+ environment["HIROUTE_BUILD_SOURCE_SHA"] = revision
environment["MACOSX_DEPLOYMENT_TARGET"] = MINIMUM_MACOS
environment["HIROUTE_CPA_MANIFEST"] = str(manifest_path)
environment["TAURI_CONFIG"] = json.dumps({"build": {"frontendDist": str(REPO / "apps/desktop/dist")}})
diff --git a/scripts/release-contracts.py b/scripts/release-contracts.py
new file mode 100644
index 00000000..f0597356
--- /dev/null
+++ b/scripts/release-contracts.py
@@ -0,0 +1,280 @@
+#!/usr/bin/env python3
+"""Freeze published contract inventories; never infer migration support from a release label."""
+import argparse
+from datetime import datetime
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+
+
+SNAPSHOT_SCHEMA = "hiroute.release-contract-snapshot/v1"
+INDEX_SCHEMA = "hiroute.release-contract-index/v1"
+INDEX = "index.v1.json"
+TAG = re.compile(r"v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?")
+SHA = re.compile(r"[0-9a-f]{40}")
+HASH = re.compile(r"[0-9a-f]{64}")
+SOURCES = {
+ "compatibility_register": "contracts/compatibility-support.v1.json",
+ "cli_contract_set": "contracts/cli/contract-set.v1.json",
+}
+STORAGE_SOURCE = "crates/local-storage/src/migrations/mod.rs"
+
+
+def require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def encoded(value):
+ return (json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode()
+
+
+def digest(value):
+ return hashlib.sha256(value).hexdigest()
+
+
+def git(repo, *args):
+ return subprocess.check_output(["git", "-C", str(repo), *args], stderr=subprocess.PIPE)
+
+
+def version(tag):
+ match = TAG.fullmatch(tag)
+ require(match is not None, "invalid release tag")
+ return tuple(int(part) for part in match.groups())
+
+
+def create_snapshot(repo, release, manifest, revision, repository):
+ tag = release["tagName"]
+ version(tag)
+ require(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository), "invalid repository")
+ require(SHA.fullmatch(revision), "source revision must be an exact commit SHA")
+ require(release.get("isDraft") is False, "draft is not a published baseline")
+ require(isinstance(release.get("isPrerelease"), bool), "missing release channel")
+ published = release.get("publishedAt")
+ require(isinstance(published, str) and published.endswith("Z"), "missing publication time")
+ datetime.fromisoformat(published.replace("Z", "+00:00"))
+ resolved = git(repo, "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}").decode().strip()
+ require(resolved == revision, "tag differs from the verified package source")
+ channel = "preview" if release["isPrerelease"] else "stable"
+ require(channel != "stable" or "-" not in tag, "prerelease tag cannot advance stable baseline")
+ require(manifest.get("schema") == "hiroute.website.releases/v2", "unknown release manifest")
+ records = [item for item in manifest["releases"] if item["version"] == tag[1:]]
+ require(len(records) == 1, "release manifest must contain exactly one matching version")
+ record = records[0]
+ require(record["channel"] == channel, "publication channel differs from manifest")
+ actual = {asset["name"]: asset for asset in release["assets"]}
+ require(len(actual) == len(release["assets"]), "duplicate published asset")
+ artifacts = []
+ for artifact in record["artifacts"]:
+ names = [(artifact["filename"], artifact["sha256"], artifact["size"])]
+ if artifact["kind"] == "standalone":
+ names.append((artifact["manifest_filename"], artifact["manifest_sha256"], artifact["manifest_size"]))
+ require(f"-{revision[:12]}-" in artifact["filename"], "artifact source differs from tag")
+ for filename, sha256, size in names:
+ require(Path(filename).name == filename and filename not in (".", ".."), "invalid asset name")
+ require(HASH.fullmatch(sha256), "invalid artifact digest")
+ asset = actual.get(filename, {})
+ require(type(size) is int and size > 0 and asset.get("size") == size, "published asset missing or size mismatch")
+ require(asset.get("digest") == "sha256:" + sha256, "published asset digest differs from verified manifest")
+ artifacts.append({"filename": filename, "sha256": sha256, "size": size})
+ require(artifacts and len({a["filename"] for a in artifacts}) == len(artifacts), "empty or duplicate manifest assets")
+ storage = git(repo, "show", f"{revision}:{STORAGE_SOURCE}")
+ versions = re.findall(rb"pub const LATEST_SCHEMA_VERSION:\s*u32\s*=\s*([0-9]+);", storage)
+ require(len(versions) == 1, "cannot identify released SQL schema")
+ contracts = {}
+ for key, path in SOURCES.items():
+ raw = git(repo, "show", f"{revision}:{path}")
+ contracts[key] = {"path": path, "sha256": digest(raw), "content": json.loads(raw)}
+ return {
+ "schema": SNAPSHOT_SCHEMA,
+ "release": {"repository": repository, "tag": tag, "revision": revision,
+ "channel": channel, "published_at": published,
+ "artifacts": sorted(artifacts, key=lambda a: a["filename"])},
+ "storage": {"sql_schema_version": int(versions[0]), "source_path": STORAGE_SOURCE,
+ "source_sha256": digest(storage)},
+ "contracts": contracts,
+ }
+
+
+def validate_snapshot(snapshot, filename):
+ require(snapshot.get("schema") == SNAPSHOT_SCHEMA, "unknown snapshot schema")
+ release = snapshot["release"]
+ version(release["tag"])
+ require(filename == release["tag"] + ".json", "snapshot filename/tag mismatch")
+ require(SHA.fullmatch(release["revision"]), "invalid recorded revision")
+ require(release["channel"] in ("stable", "preview"), "unknown channel")
+ require(release["channel"] != "stable" or "-" not in release["tag"], "preview in stable ledger")
+ require(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", release["repository"]), "invalid recorded repository")
+ published = release["published_at"]
+ require(isinstance(published, str) and published.endswith("Z"), "invalid recorded publication time")
+ datetime.fromisoformat(published.replace("Z", "+00:00"))
+ artifacts = release["artifacts"]
+ require(isinstance(artifacts, list) and artifacts, "missing recorded artifacts")
+ names = []
+ for artifact in artifacts:
+ name = artifact["filename"]
+ require(isinstance(name, str) and Path(name).name == name and name not in (".", ".."), "invalid recorded asset name")
+ require(f"-{release['revision'][:12]}-" in name, "recorded asset source differs from tag")
+ require(HASH.fullmatch(artifact["sha256"]), "invalid recorded asset digest")
+ require(type(artifact["size"]) is int and artifact["size"] > 0, "invalid recorded asset size")
+ names.append(name)
+ require(names == sorted(set(names)), "recorded assets must be sorted and unique")
+ require(type(snapshot["storage"]["sql_schema_version"]) is int and
+ snapshot["storage"]["sql_schema_version"] > 0, "missing storage contract")
+ require(set(snapshot["contracts"]) == set(SOURCES), "incomplete contract inventory")
+ for key, path in SOURCES.items():
+ contract = snapshot["contracts"][key]
+ require(contract["path"] == path and HASH.fullmatch(contract["sha256"]), "invalid source contract")
+ require(isinstance(contract["content"], dict), "invalid contract content")
+
+
+def make_index(snapshots):
+ records = []
+ for name, snapshot in sorted(snapshots.items()):
+ validate_snapshot(snapshot, name)
+ release = snapshot["release"]
+ records.append({"tag": release["tag"], "revision": release["revision"],
+ "channel": release["channel"], "file": name,
+ "sha256": digest(encoded(snapshot))})
+ repositories = {s["release"]["repository"] for s in snapshots.values()}
+ require(len(repositories) <= 1, "mixed repositories in release ledger")
+ stable = [row for row in records if row["channel"] == "stable"]
+ keys = [version(row["tag"]) for row in stable]
+ require(len(set(keys)) == len(keys), "ambiguous stable versions")
+ latest = max(stable, key=lambda row: version(row["tag"]))["tag"] if stable else None
+ return {"schema": INDEX_SCHEMA, "latest_stable": latest, "releases": records}
+
+
+def read_directory(directory, pending=None):
+ require(not directory.is_symlink(), "ledger directory must not be a symlink")
+ snapshots = {}
+ for path in sorted(directory.glob("*.json")):
+ require(not path.is_symlink() and path.is_file(), "invalid ledger entry")
+ if path.name != INDEX:
+ snapshots[path.name] = json.loads(path.read_bytes())
+ index_path = directory / INDEX
+ require(not index_path.is_symlink(), "ledger index must not be a symlink")
+ prior = dict(snapshots)
+ if pending is not None:
+ filename = pending["release"]["tag"] + ".json"
+ if prior.get(filename) == pending:
+ del prior[filename]
+ if index_path.exists():
+ index = json.loads(index_path.read_bytes())
+ require(index == make_index(snapshots) or
+ (pending is not None and index == make_index(prior)), "ledger index/hash mismatch")
+ else:
+ require(not snapshots or (pending is not None and not prior), "existing snapshots lack their index")
+ return snapshots
+
+
+def atomic_write(path, data):
+ with tempfile.NamedTemporaryFile(dir=path.parent, prefix=".release-contract-", delete=False) as handle:
+ temporary = Path(handle.name)
+ try:
+ handle.write(data)
+ handle.flush()
+ temporary.replace(path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def record_snapshot(directory, snapshot):
+ snapshots = read_directory(directory, pending=snapshot)
+ filename = snapshot["release"]["tag"] + ".json"
+ if filename in snapshots:
+ require(snapshots[filename] == snapshot, "published contract snapshot is immutable")
+ snapshots[filename] = snapshot
+ index = make_index(snapshots)
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / filename
+ if not path.exists():
+ atomic_write(path, encoded(snapshot))
+ atomic_write(directory / INDEX, encoded(index))
+ return index
+
+
+def verify_sources(repo, snapshot):
+ release = snapshot["release"]
+ revision = release["revision"]
+ tag_revision = git(repo, "rev-parse", "--verify", f"refs/tags/{release['tag']}^{{commit}}").decode().strip()
+ require(tag_revision == revision, "recorded tag has moved")
+ for key, path in SOURCES.items():
+ raw = git(repo, "show", f"{revision}:{path}")
+ require(snapshot["contracts"][key] == {"path": path, "sha256": digest(raw), "content": json.loads(raw)},
+ "snapshot differs from released contract")
+ raw = git(repo, "show", f"{revision}:{STORAGE_SOURCE}")
+ versions = re.findall(rb"pub const LATEST_SCHEMA_VERSION:\s*u32\s*=\s*([0-9]+);", raw)
+ require(len(versions) == 1 and snapshot["storage"] == {
+ "sql_schema_version": int(versions[0]), "source_path": STORAGE_SOURCE,
+ "source_sha256": digest(raw)}, "snapshot differs from released storage format")
+
+
+def current(repo, directory):
+ snapshots = read_directory(directory)
+ tag = make_index(snapshots)["latest_stable"]
+ require(tag is not None, "no stable published baseline")
+ snapshot = snapshots[tag + ".json"]
+ verify_sources(repo, snapshot)
+ return snapshot
+
+
+def pull_request_base(environment):
+ if environment.get("GITHUB_ACTIONS") != "true" or environment.get("GITHUB_EVENT_NAME") != "pull_request":
+ return None
+ event = json.loads(Path(environment["GITHUB_EVENT_PATH"]).read_bytes())
+ base = event["pull_request"]["base"]["sha"]
+ require(SHA.fullmatch(base), "invalid PR base revision")
+ return base
+
+
+def check_append_only(repo, directory, base):
+ # The index advances, but every snapshot already merged on the PR base is fixed.
+ revision = git(repo, "rev-parse", "--verify", f"{base}^{{commit}}").decode().strip()
+ paths = git(repo, "ls-tree", "-r", "--name-only", revision, "--", "contracts/releases").decode().splitlines()
+ for path in paths:
+ name = Path(path).name
+ if not path.endswith(".json") or name == INDEX:
+ continue
+ target = directory / name
+ require(target.is_file() and not target.is_symlink() and
+ target.read_bytes() == git(repo, "show", f"{revision}:{path}"),
+ f"historical snapshot changed or deleted: {path}")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("command", choices=("record", "check", "current"))
+ parser.add_argument("--repo", type=Path, default=Path.cwd())
+ parser.add_argument("--directory", type=Path, default=Path("contracts/releases"))
+ parser.add_argument("--release-json", type=Path)
+ parser.add_argument("--manifest", type=Path, default=Path("apps/website/data/releases.json"))
+ parser.add_argument("--revision")
+ parser.add_argument("--repository")
+ parser.add_argument("--base", help="check historical snapshots against this Git ref; defaults to the Actions PR base")
+ args = parser.parse_args()
+ if args.command == "record":
+ require(args.release_json and args.revision and args.repository, "record requires release JSON, revision and repository")
+ snapshot = create_snapshot(args.repo, json.loads(args.release_json.read_bytes()),
+ json.loads(args.manifest.read_bytes()), args.revision, args.repository)
+ result = record_snapshot(args.directory, snapshot)
+ elif args.command == "check":
+ base = args.base or pull_request_base(os.environ)
+ if base:
+ check_append_only(args.repo, args.directory, base)
+ snapshots = read_directory(args.directory)
+ result = make_index(snapshots)
+ require(result["releases"], "empty release ledger")
+ for snapshot in snapshots.values():
+ verify_sources(args.repo, snapshot)
+ else:
+ result = current(args.repo, args.directory)
+ print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-contract-convergence.py b/scripts/test-contract-convergence.py
index 0e1dfa63..dae31234 100755
--- a/scripts/test-contract-convergence.py
+++ b/scripts/test-contract-convergence.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
import importlib.util
+import json
import tempfile
import unittest
from pathlib import Path
@@ -56,6 +57,22 @@ class ContractConvergenceTests(unittest.TestCase):
def test_registered_recovery_path_is_green(self):
self.assertEqual(self.run_audit({"legacy.rs": '"hiroute.sample/v1"'}), [])
+ def test_historical_release_inventory_is_not_a_current_reader_or_fixture(self):
+ snapshot = json.dumps({"schema": "hiroute.release-contract-snapshot/v1",
+ "contracts": ["hiroute.sample/v1", "hiroute.forbidden/v1"]})
+ self.assertEqual(self.run_audit({"legacy.rs": '"hiroute.sample/v1"',
+ "contracts/releases/v1.0.0.json": snapshot}), [])
+ for path in ("contracts/releases/live.rs", "contracts/releases/other.json",
+ "contracts/cli/v1.0.0.json"):
+ errors = self.run_audit({"legacy.rs": '"hiroute.sample/v1"', path: snapshot})
+ self.assertTrue(any("forbidden contract" in error for error in errors), errors)
+ errors = self.run_audit({"legacy.rs": '"hiroute.sample/v1"',
+ "contracts/releases/v1.0.0.json": '{"value":"hiroute.forbidden/v1"}'})
+ self.assertTrue(any("forbidden contract" in error for error in errors), errors)
+ # A snapshot cannot make an absent real legacy reader look implemented.
+ errors = self.run_audit({"contracts/releases/v1.0.0.json": snapshot})
+ self.assertTrue(any("stale compatibility registration" in error for error in errors), errors)
+
def test_legacy_escape_is_rejected(self):
errors = self.run_audit(
{
diff --git a/scripts/test-package-desktop.py b/scripts/test-package-desktop.py
index fc9568c1..fcc124ac 100644
--- a/scripts/test-package-desktop.py
+++ b/scripts/test-package-desktop.py
@@ -38,6 +38,19 @@ class BundleIdentityTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "patch checksum mismatch"):
builder.pinned_source()
+ def test_release_handshake_version_matches_every_shipped_component(self):
+ import json
+ version = json.loads((package.NATIVE / "tauri.conf.json").read_text())["version"]
+ package.validate_release_versions(version)
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ api = root / "crates/application-api/Cargo.toml"
+ api.parent.mkdir(parents=True)
+ api.write_text('[package]\nversion = "0.1.0"\n')
+ with patch.object(package, "REPO", root):
+ with self.assertRaisesRegex(ValueError, "release version mismatch: crates/application-api"):
+ package.validate_release_versions(version)
+
def test_build_children_do_not_inherit_validation_lock_descriptors(self):
completed = package.subprocess.CompletedProcess(
["fixture"], 0, stdout="ok\n", stderr=""
diff --git a/scripts/test-plan.py b/scripts/test-plan.py
index 7ac21b2c..bf3080ef 100644
--- a/scripts/test-plan.py
+++ b/scripts/test-plan.py
@@ -38,6 +38,9 @@ SELECTION_TOOLING = {"scripts/test-plan.py", "scripts/test-test-plan.py"}
INTEGRATION_SKILL = ".agents/skills/hiroute-integrate/SKILL.md"
WEBSITE_TOOLING = {".github/workflows/website.yml", ".github/workflows/release.yml"}
WEBSITE_PREFIXES = ("apps/website/", ".github/scripts/")
+RELEASE_CONTRACT_TOOLING = {"scripts/release-contracts.py", "scripts/test-release-contracts.py",
+ "scripts/test-release-contract-pr.py", ".github/scripts/release-contract-pr.sh",
+ ".github/workflows/release.yml"}
HOSTED_BACKEND_EXECUTION = {
".github/workflows/gateway-core.yml",
"scripts/ci-run.py",
@@ -86,8 +89,12 @@ def select(paths, full=False):
reasons = []
selection_tooling = False
validation_tooling = False
+ release_contract_tooling = False
targets = set()
for path in sorted(set(paths)):
+ if path in RELEASE_CONTRACT_TOOLING or path.startswith("contracts/releases/"):
+ release_contract_tooling = True
+ continue
if path in SELECTION_TOOLING or path == INTEGRATION_SKILL:
selection_tooling = True
elif path in WEBSITE_TOOLING or path.startswith(WEBSITE_PREFIXES):
@@ -188,6 +195,10 @@ def select(paths, full=False):
"--", "--exact"])
if selection_tooling:
commands.append(["python3", "scripts/test-test-plan.py"])
+ if full or release_contract_tooling:
+ commands.extend([["python3", "scripts/test-release-contracts.py"],
+ ["python3", "scripts/test-release-contract-pr.py"],
+ ["python3", "scripts/release-contracts.py", "check"]])
if validation_tooling:
commands.extend([["python3", "scripts/" + name] for name in
("test-validation.py", "test-validation-report.py", "test-local-rust.py", "test-remote-rust.py", "test-validation-schedule.py",
@@ -220,6 +231,9 @@ def integration_preflight(plan, collect_failures=False, context_plan=None):
if selected:
targets.update(selected)
reasons.append("early boundary checks: " + path)
+ storage_startup = any(path.startswith("crates/local-storage/src/migrations/")
+ or path == "crates/local-storage/src/lib.rs"
+ for path in plan["paths"])
# These already-selected cheap tooling gates run before Rust preparation.
commands = [c[:] for c in plan["commands"] if c[:1] == ["python3"]]
if targets:
@@ -240,6 +254,17 @@ def integration_preflight(plan, collect_failures=False, context_plan=None):
commands.append([*context, *(["--no-fail-fast"] if collect_failures else []),
*[arg for target in behavior for arg in ("--test", target)],
"--", "--test-threads=1"])
+ if storage_startup:
+ targets.update({"publication_process", "pre_gateway_compute_routing"})
+ reasons.append("storage startup: exercise the production daemon initialization order")
+ broad = next((c for c in context_plan["commands"] if c[:2] == ["cargo", "test"]
+ and "--test" not in c and "--lib" not in c), None)
+ context = broad[:] if broad else ["cargo", "test", "--locked", "-p", "hiroute-daemon", "--all-features"]
+ if "--workspace" not in context and "hiroute-daemon" not in context:
+ context.extend(["-p", "hiroute-daemon"])
+ if "--workspace" not in context and "hiroute-product-e2e" not in context:
+ context.extend(["-p", "hiroute-product-e2e"])
+ commands.append([*context, "--test", "publication_process", "--test", "pre_gateway_compute_routing"])
return {"diagnostic_only": True, "targets": sorted(targets), "reasons": reasons,
"commands": commands, "remote_exclusive": bool(targets) and context_plan["execution"]["remote_exclusive"],
"collect_failures": collect_failures,
diff --git a/scripts/test-release-contract-pr.py b/scripts/test-release-contract-pr.py
new file mode 100644
index 00000000..7055a9f7
--- /dev/null
+++ b/scripts/test-release-contract-pr.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+"""Run the PR publisher with real local Git remotes and a strictly offline gh fixture."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+BRANCH = "chore/release-contracts-v1.2.0"
+
+
+class PublicationTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.base = Path(self.temporary.name)
+ self.repo = self.base / "repo"
+ self.repo.mkdir()
+ self.env = {**os.environ, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull,
+ "FIXTURE_CONTEXT": str(self.base), "GH_REPO": "example/HiRoute",
+ "GITHUB_EVENT_NAME": "release"}
+ self.git("init", "-q", "-b", "main")
+ self.git("config", "user.name", "Fixture")
+ self.git("config", "user.email", "[email protected]")
+ self.write("crates/local-storage/src/migrations/mod.rs", "pub const LATEST_SCHEMA_VERSION: u32 = 7;\n")
+ for path in ("contracts/compatibility-support.v1.json", "contracts/cli/contract-set.v1.json"):
+ self.write(path, '{"contract":"released/v1"}\n')
+ for path in ("scripts/release-contracts.py", ".github/scripts/release-contract-pr.sh"):
+ self.write(path, (ROOT / path).read_text())
+ self.commit("released producer")
+ revision = self.git("rev-parse", "HEAD").strip()
+ self.git("tag", "v1.2.0")
+ name = f"HiRoute-1.2.0-{revision[:12]}-macos-arm64-trial.dmg"
+ self.release = {"tagName": "v1.2.0", "isDraft": False, "isPrerelease": False,
+ "publishedAt": "2026-01-01T01:02:03Z",
+ "assets": [{"name": name, "size": 5, "digest": "sha256:" + "1" * 64}]}
+ (self.base / "release.json").write_text(json.dumps(self.release))
+ self.write("apps/website/data/releases.json", json.dumps({
+ "schema": "hiroute.website.releases/v2", "releases": [{
+ "version": "1.2.0", "channel": "stable", "artifacts": [{
+ "kind": "desktop", "filename": name, "sha256": "1" * 64, "size": 5}]}]}))
+ self.commit("verified website manifest")
+ self.main = self.git("rev-parse", "HEAD").strip()
+ self.env.update(RELEASE_TAG="v1.2.0", RELEASE_REVISION=revision, WEBSITE_REVISION=self.main)
+ self.origin = self.base / "origin.git"
+ self.git("clone", "--bare", str(self.repo), str(self.origin))
+ self.git("remote", "add", "origin", str(self.origin))
+ self.git("fetch", "origin")
+ fakebin = self.base / "bin"
+ fakebin.mkdir()
+ gh = fakebin / "gh"
+ gh.write_text(f"#!{sys.executable}\n" + '''import json, os, pathlib, sys
+p = pathlib.Path(os.environ["FIXTURE_CONTEXT"])
+a = sys.argv[1:]
+with (p / "calls.jsonl").open("a") as out:
+ out.write(json.dumps(a) + "\\n")
+if a[:2] == ["release", "view"]:
+ print((p / "release.json").read_text())
+elif a[:2] == ["pr", "list"]:
+ print((p / "pr.json").read_text() if (p / "pr.json").exists() else "{}")
+elif a[:2] == ["auth", "setup-git"]:
+ pass
+elif a[:2] == ["pr", "create"]:
+ if os.environ.get("FAIL_CREATE"):
+ sys.exit("fixture: PR creation denied")
+ assert not (p / "pr.json").exists(), "duplicate PR"
+ (p / "pr-body.md").write_text(pathlib.Path(a[a.index("--body-file") + 1]).read_text())
+ (p / "pr.json").write_text(json.dumps({"state": "OPEN", "url": "https://example.invalid/pull/1"}))
+ print("https://example.invalid/pull/1")
+else:
+ sys.exit("unexpected gh command")
+''')
+ gh.chmod(0o755)
+ self.env["PATH"] = str(fakebin) + os.pathsep + self.env["PATH"]
+
+ def git(self, *args):
+ return subprocess.check_output(["git", "-C", str(self.repo), *args],
+ stderr=subprocess.PIPE, text=True, env=self.env)
+
+ def write(self, path, content):
+ target = self.repo / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content)
+
+ def commit(self, message):
+ self.git("add", ".")
+ self.git("commit", "-qm", message)
+
+ def remote(self, ref):
+ return self.git("ls-remote", "origin", ref).split()[0]
+
+ def publish(self, success=True, **environment):
+ result = subprocess.run(["bash", ".github/scripts/release-contract-pr.sh"], cwd=self.repo,
+ env={**self.env, **environment}, text=True, capture_output=True)
+ self.assertEqual(result.returncode == 0, success, result.stdout + result.stderr)
+ self.assertEqual(self.git("status", "--porcelain"), "")
+ self.assertEqual(len([line for line in self.git("worktree", "list", "--porcelain").splitlines()
+ if line.startswith("worktree ")]), 1)
+ return result
+
+ def calls(self, prefix):
+ return [row for row in map(json.loads, (self.base / "calls.jsonl").read_text().splitlines())
+ if row[:len(prefix)] == prefix]
+
+ def test_create_repeat_update_and_merged_noop(self):
+ self.publish()
+ self.assertEqual(self.remote("refs/heads/main"), self.main)
+ first = self.remote("refs/heads/" + BRANCH)
+ changed = self.git("diff", "--name-only", self.main, first).splitlines()
+ self.assertEqual(changed, ["contracts/releases/index.v1.json", "contracts/releases/v1.2.0.json"])
+ self.assertIn("does not claim migration acceptance", (self.base / "pr-body.md").read_text())
+ self.publish()
+ self.assertEqual(self.remote("refs/heads/" + BRANCH), first)
+ self.assertEqual(len(self.calls(["pr", "create"])), 1)
+ self.write("future.txt", "unrelated main development")
+ self.commit("new main")
+ self.git("push", "origin", "main")
+ next_main = self.remote("refs/heads/main")
+ self.publish()
+ self.assertEqual(self.remote("refs/heads/main"), next_main)
+ self.git("fetch", "origin", BRANCH)
+ self.git("merge", "--ff-only", "FETCH_HEAD")
+ self.git("push", "origin", "main")
+ (self.base / "pr.json").write_text('{"state":"MERGED"}')
+ self.publish()
+ self.assertEqual(len(self.calls(["pr", "create"])), 1)
+
+ def test_failed_pr_creation_can_retry_existing_branch(self):
+ self.publish(False, FAIL_CREATE="1")
+ first = self.remote("refs/heads/" + BRANCH)
+ self.publish()
+ self.assertEqual(first, self.remote("refs/heads/" + BRANCH))
+ self.assertEqual(self.remote("refs/heads/main"), self.main)
+
+ def test_bad_identity_is_rejected_before_writes(self):
+ self.release["assets"][0]["digest"] = "sha256:" + "2" * 64
+ (self.base / "release.json").write_text(json.dumps(self.release))
+ self.publish(False)
+ self.assertEqual(self.git("ls-remote", "origin", "refs/heads/" + BRANCH), "")
+ self.assertEqual(self.calls(["pr"]), [])
+ self.assertEqual(self.remote("refs/heads/main"), self.main)
+
+ def test_closed_pr_is_not_silently_reopened(self):
+ (self.base / "pr.json").write_text('{"state":"CLOSED"}')
+ self.publish(False)
+ self.assertEqual(self.git("ls-remote", "origin", "refs/heads/" + BRANCH), "")
+ self.assertEqual(self.calls(["pr", "create"]), [])
+
+ def test_existing_branch_with_unrelated_changes_is_rejected(self):
+ self.write("foreign.txt", "another owner's change")
+ self.commit("unrelated")
+ self.git("push", "origin", "HEAD:refs/heads/" + BRANCH)
+ before = self.remote("refs/heads/" + BRANCH)
+ self.publish(False)
+ self.assertEqual(self.remote("refs/heads/" + BRANCH), before)
+ self.assertEqual(self.calls(["pr", "create"]), [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/test-release-contracts.py b/scripts/test-release-contracts.py
new file mode 100644
index 00000000..a9202272
--- /dev/null
+++ b/scripts/test-release-contracts.py
@@ -0,0 +1,199 @@
+#!/usr/bin/env python3
+"""Exercise immutable release inventories against real, isolated Git history."""
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+sys.dont_write_bytecode = True
+spec = importlib.util.spec_from_file_location("release_contracts", Path(__file__).with_name("release-contracts.py"))
+contracts = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(contracts)
+
+
+class ReleaseContractsTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.repo = Path(self.temporary.name) / "repo"
+ self.repo.mkdir()
+ self.run_git("init", "-q")
+ self.run_git("config", "user.name", "Fixture")
+ self.run_git("config", "user.email", "[email protected]")
+ self.write(contracts.STORAGE_SOURCE, "pub const LATEST_SCHEMA_VERSION: u32 = 7;\n")
+ for path in contracts.SOURCES.values():
+ self.write(path, '{"contract":"original/v1"}\n')
+ self.run_git("add", ".")
+ self.run_git("commit", "-qm", "released producer")
+ self.revision = self.run_git("rev-parse", "HEAD").strip()
+ self.run_git("tag", "v1.2.0")
+ self.directory = Path(self.temporary.name) / "ledger"
+ self.release, self.manifest = self.metadata("v1.2.0")
+
+ def run_git(self, *args):
+ return subprocess.check_output(["git", "-C", str(self.repo), *args], stderr=subprocess.PIPE, text=True)
+
+ def write(self, path, value):
+ target = self.repo / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(value)
+
+ def metadata(self, tag, preview=False):
+ name = f"HiRoute-{tag[1:]}-{self.revision[:12]}-macos-arm64-trial.dmg"
+ release = {"tagName": tag, "isDraft": False, "isPrerelease": preview,
+ "publishedAt": "2026-01-01T01:02:03Z",
+ "assets": [{"name": name, "size": 5, "digest": "sha256:" + "1" * 64}]}
+ manifest = {"schema": "hiroute.website.releases/v2", "releases": [{
+ "version": tag[1:], "channel": "preview" if preview else "stable",
+ "artifacts": [{"kind": "desktop", "filename": name, "sha256": "1" * 64, "size": 5}]}]}
+ return release, manifest
+
+ def snapshot(self, release=None, manifest=None, revision=None):
+ return contracts.create_snapshot(self.repo, release or self.release, manifest or self.manifest,
+ revision or self.revision, "example/HiRoute")
+
+ def test_reads_released_contract_instead_of_current_worktree(self):
+ self.write(contracts.STORAGE_SOURCE, "pub const LATEST_SCHEMA_VERSION: u32 = 999;\n")
+ for path in contracts.SOURCES.values():
+ self.write(path, '{"contract":"changed/v2"}\n')
+ self.run_git("add", ".")
+ self.run_git("commit", "-qm", "future work")
+ snapshot = self.snapshot()
+ self.assertEqual(snapshot["storage"]["sql_schema_version"], 7)
+ self.assertEqual(snapshot["contracts"]["cli_contract_set"]["content"]["contract"], "original/v1")
+ contracts.verify_sources(self.repo, snapshot)
+
+ def test_repeat_is_byte_identical_and_cannot_replace_old_snapshot(self):
+ snapshot = self.snapshot()
+ contracts.record_snapshot(self.directory, snapshot)
+ before = {p.name: p.read_bytes() for p in self.directory.iterdir()}
+ contracts.record_snapshot(self.directory, snapshot)
+ self.assertEqual(before, {p.name: p.read_bytes() for p in self.directory.iterdir()})
+ changed = copy.deepcopy(snapshot)
+ changed["storage"]["sql_schema_version"] = 8
+ with self.assertRaisesRegex(ValueError, "immutable"):
+ contracts.record_snapshot(self.directory, changed)
+ self.assertEqual(before, {p.name: p.read_bytes() for p in self.directory.iterdir()})
+
+ def test_older_rerun_and_preview_do_not_replace_latest_stable(self):
+ old = self.snapshot()
+ contracts.record_snapshot(self.directory, old)
+ for tag, preview in [("v1.3.0", False), ("v2.0.0-rc.1", True)]:
+ self.run_git("tag", tag)
+ release, manifest = self.metadata(tag, preview)
+ contracts.record_snapshot(self.directory, self.snapshot(release, manifest))
+ index = contracts.record_snapshot(self.directory, old)
+ self.assertEqual(index["latest_stable"], "v1.3.0")
+ self.assertEqual(len(index["releases"]), 3)
+ self.assertEqual(contracts.current(self.repo, self.directory)["release"]["tag"], "v1.3.0")
+
+ def test_invalid_publication_inputs_fail_before_writes(self):
+ for mutation in [lambda r, m: r.update(isDraft=True),
+ lambda r, m: r.update(publishedAt=None),
+ lambda r, m: r["assets"].clear(),
+ lambda r, m: r["assets"][0].update(size=9),
+ lambda r, m: r["assets"][0].update(digest="sha256:" + "2" * 64),
+ lambda r, m: m["releases"][0].update(channel="preview"),
+ lambda r, m: m["releases"][0]["artifacts"][0].update(sha256="bad")]:
+ release, manifest = copy.deepcopy(self.release), copy.deepcopy(self.manifest)
+ mutation(release, manifest)
+ with self.assertRaises(ValueError):
+ contracts.record_snapshot(self.directory, self.snapshot(release, manifest))
+ self.assertFalse(self.directory.exists())
+ with self.assertRaisesRegex(ValueError, "tag differs"):
+ self.snapshot(revision="0" * 40)
+
+ def test_partial_snapshot_write_can_finish_only_the_exact_pending_record(self):
+ snapshot = self.snapshot()
+ self.directory.mkdir()
+ (self.directory / "v1.2.0.json").write_bytes(contracts.encoded(snapshot))
+ with self.assertRaisesRegex(ValueError, "lack their index"):
+ contracts.read_directory(self.directory)
+ contracts.record_snapshot(self.directory, snapshot)
+ self.assertEqual(contracts.current(self.repo, self.directory), snapshot)
+ self.run_git("tag", "v1.3.0")
+ release, manifest = self.metadata("v1.3.0")
+ next_snapshot = self.snapshot(release, manifest)
+ (self.directory / "v1.3.0.json").write_bytes(contracts.encoded(next_snapshot))
+ with self.assertRaisesRegex(ValueError, "index/hash mismatch"):
+ contracts.read_directory(self.directory)
+ contracts.record_snapshot(self.directory, next_snapshot)
+ self.assertEqual(contracts.current(self.repo, self.directory), next_snapshot)
+
+ def test_corruption_and_relabelled_contract_are_rejected(self):
+ snapshot = self.snapshot()
+ contracts.record_snapshot(self.directory, snapshot)
+ snapshot["contracts"]["cli_contract_set"]["content"]["contract"] = "changed/v2"
+ (self.directory / "v1.2.0.json").write_bytes(contracts.encoded(snapshot))
+ with self.assertRaisesRegex(ValueError, "index/hash mismatch"):
+ contracts.read_directory(self.directory)
+ with self.assertRaisesRegex(ValueError, "released contract"):
+ contracts.verify_sources(self.repo, snapshot)
+
+ def test_moved_tag_is_not_silently_adopted(self):
+ snapshot = self.snapshot()
+ self.write("new-file", "different commit")
+ self.run_git("add", ".")
+ self.run_git("commit", "-qm", "new source")
+ self.run_git("tag", "-f", "v1.2.0")
+ with self.assertRaisesRegex(ValueError, "tag has moved"):
+ contracts.verify_sources(self.repo, snapshot)
+
+ def test_empty_ledger_has_no_inferred_baseline(self):
+ with self.assertRaisesRegex(ValueError, "no stable published baseline"):
+ contracts.current(self.repo, self.directory)
+
+ def test_recorded_metadata_shape_is_checked(self):
+ for mutate in [lambda r: r.update(repository="invalid"),
+ lambda r: r.update(published_at="not-a-dateZ"),
+ lambda r: r.update(artifacts=[]),
+ lambda r: r["artifacts"][0].update(sha256="bad"),
+ lambda r: r["artifacts"][0].update(size=0)]:
+ snapshot = self.snapshot()
+ mutate(snapshot["release"])
+ with self.assertRaises(ValueError):
+ contracts.validate_snapshot(snapshot, "v1.2.0.json")
+
+ def test_pr_base_preserves_prior_snapshots_even_when_index_is_rehashed(self):
+ self.directory = self.repo / "contracts/releases"
+ snapshot = self.snapshot()
+ contracts.record_snapshot(self.directory, snapshot)
+ self.run_git("add", ".")
+ self.run_git("commit", "-qm", "record baseline")
+ base = self.run_git("rev-parse", "HEAD").strip()
+ contracts.check_append_only(self.repo, self.directory, base)
+ self.run_git("tag", "v1.3.0", self.revision)
+ release, manifest = self.metadata("v1.3.0")
+ contracts.record_snapshot(self.directory, self.snapshot(release, manifest))
+ contracts.check_append_only(self.repo, self.directory, base)
+ old = self.directory / "v1.2.0.json"
+ snapshot["release"]["artifacts"][0]["sha256"] = "2" * 64
+ old.write_bytes(contracts.encoded(snapshot))
+ # Deliberately repair the index: source/shape checks alone cannot see this edit.
+ snapshots = {p.name: json.loads(p.read_bytes()) for p in self.directory.glob("v*.json")}
+ (self.directory / contracts.INDEX).write_bytes(contracts.encoded(contracts.make_index(snapshots)))
+ contracts.read_directory(self.directory)
+ contracts.verify_sources(self.repo, snapshot)
+ with self.assertRaisesRegex(ValueError, "changed or deleted"):
+ contracts.check_append_only(self.repo, self.directory, base)
+ old.unlink()
+ with self.assertRaisesRegex(ValueError, "changed or deleted"):
+ contracts.check_append_only(self.repo, self.directory, base)
+
+ def test_actions_check_resolves_the_actual_pr_base(self):
+ event = Path(self.temporary.name) / "event.json"
+ event.write_text(json.dumps({"pull_request": {"base": {"sha": self.revision}}}))
+ env = {"GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "pull_request", "GITHUB_EVENT_PATH": str(event)}
+ self.assertEqual(contracts.pull_request_base(env), self.revision)
+ self.assertIsNone(contracts.pull_request_base({}))
+ event.write_text('{}')
+ with self.assertRaises(KeyError):
+ contracts.pull_request_base(env)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.py
index 832788c9..a37c697a 100644
--- a/scripts/test-test-plan.py
+++ b/scripts/test-test-plan.py
@@ -63,6 +63,23 @@ class SelectionTests(unittest.TestCase):
self.assertFalse(result["native_required"])
self.assertIn(["python3", "scripts/test-contract-convergence.py"], result["commands"])
+ def test_release_contract_updates_select_their_checks_without_product_builds(self):
+ for path in sorted(plan.RELEASE_CONTRACT_TOOLING | {"contracts/releases/v9.0.0.json"}):
+ with self.subTest(path=path):
+ result = plan.select([path])
+ self.assertFalse(result["rust"])
+ self.assertFalse(result["frontend"])
+ self.assertIn(["python3", "scripts/test-release-contracts.py"], result["commands"])
+ self.assertIn(["python3", "scripts/test-release-contract-pr.py"], result["commands"])
+ self.assertIn(["python3", "scripts/release-contracts.py", "check"], result["commands"])
+ mixed = plan.select(["contracts/releases/index.v1.json", "crates/daemon/src/lib.rs"])
+ self.assertTrue(mixed["rust"])
+ for paths, full in [([], True), (["Cargo.lock"], False), (["crates/domain/src/lib.rs"], False)]:
+ selected = plan.select(paths, full=full)
+ self.assertIn(["python3", "scripts/release-contracts.py", "check"], selected["commands"])
+ self.assertIn(["python3", "scripts/test-release-contracts.py"], selected["commands"])
+ self.assertIn(["python3", "scripts/test-release-contract-pr.py"], selected["commands"])
+
def test_native_changes_require_platform_evidence(self):
result = plan.select(["apps/desktop/src-tauri/src/main.rs"])
self.assertTrue(result["native_required"])
@@ -266,6 +283,19 @@ class IntegrationPreflightTests(unittest.TestCase):
self.assertFalse(any('smoke_cli' in c or '--no-fail-fast' in c for c in early['commands']))
self.assertTrue(early['remote_exclusive'])
+ def test_storage_startup_exercises_real_daemon_before_final(self):
+ for path in ['crates/local-storage/src/migrations/startup_format.rs',
+ 'crates/local-storage/src/lib.rs']:
+ final = plan.select([path])
+ original = json.dumps(final, sort_keys=True)
+ early = plan.integration_preflight(final)
+ self.assertIn('publication_process', early['targets'])
+ self.assertIn('pre_gateway_compute_routing', early['targets'])
+ command = next(c for c in early['commands'] if 'publication_process' in c)
+ self.assertIn('--all-features', command)
+ self.assertTrue('--workspace' in command or 'hiroute-daemon' in command)
+ self.assertEqual(original, json.dumps(final, sort_keys=True))
+
def test_production_protocol_changes_have_early_consumers(self):
for path in ['crates/gateway/src/adapters/responses_ingress.rs',
'crates/gateway/src/model_ir/request.rs']:
diff --git a/tools/product-e2e/Cargo.toml b/tools/product-e2e/Cargo.toml
index c83f41e5..cf6f54f5 100644
--- a/tools/product-e2e/Cargo.toml
+++ b/tools/product-e2e/Cargo.toml
@@ -22,6 +22,9 @@ serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
+[dev-dependencies]
+serde_json = { workspace = true, features = ["raw_value"] }
+
[[bin]]
name = "generate-product-contract"
diff --git a/tools/product-e2e/src/smoke/control.rs b/tools/product-e2e/src/smoke/control.rs
index 0d4bf4f4..2866546e 100644
--- a/tools/product-e2e/src/smoke/control.rs
+++ b/tools/product-e2e/src/smoke/control.rs
@@ -135,7 +135,7 @@ fn internal_call(
api_version: LOCAL_CONTROL_SCHEMA_V2,
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
client_name: "hiroute-smoke-internal".into(),
- client_version: env!("CARGO_PKG_VERSION").into(),
+ client_version: hiroute_application_api::LOCAL_CONTROL_RELEASE_VERSION.into(),
},
)?;
stream.write_all(b"\n")?;
@@ -385,7 +385,6 @@ pub(super) fn discover(ctx: &mut Context<'_>) -> Result<()> {
pub(super) fn embedded_catalog(ctx: &mut Context<'_>) -> Result<()> {
let (cli_artifact, daemon) = prepare(ctx)?;
- fixtures::install_storage_catalog_tampering(&ctx.runtime.join("storage"))?;
let endpoint = ctx.runtime.join("control-runtime/hiroute/control.sock");
let mut c = command(&daemon.path, &ctx.runtime);
c.args(["--role", "control", "--storage-root"])
@@ -393,6 +392,14 @@ pub(super) fn embedded_catalog(ctx: &mut Context<'_>) -> Result<()> {
.arg("--runtime-root")
.arg(ctx.runtime.join("control-runtime"))
.args(["--diagnostic-level-override", "debug"]);
+ fixtures::initialize_current_storage(
+ &daemon.path,
+ &ctx.runtime.join("storage"),
+ &ctx.private.join("embedded-catalog-initialize"),
+ ctx.cancel.clone(),
+ ctx.step_deadline(),
+ )?;
+ fixtures::install_storage_catalog_tampering(&ctx.runtime.join("storage"))?;
ctx.enter("embedded_catalog_ready");
ctx.verify_artifact(&daemon)?;
let mut child = Process::spawn(
diff --git a/tools/product-e2e/src/smoke/fixtures.rs b/tools/product-e2e/src/smoke/fixtures.rs
index 1a5a5b6a..d2239cac 100644
--- a/tools/product-e2e/src/smoke/fixtures.rs
+++ b/tools/product-e2e/src/smoke/fixtures.rs
@@ -7,6 +7,53 @@ use std::{
path::{Path, PathBuf},
};
+/// Establish current-format storage through the real daemon before injecting untrusted files.
+/// The subsequent start tests catalog authority, rather than unsupported-source admission.
+pub fn initialize_current_storage(
+ daemon: &Path,
+ storage: &Path,
+ logs: &Path,
+ cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ deadline: std::time::Instant,
+) -> Result<()> {
+ use std::os::unix::fs::FileTypeExt;
+ let isolated = tempfile::tempdir()?;
+ fs::set_permissions(isolated.path(), fs::Permissions::from_mode(0o700))?;
+ let endpoint = isolated.path().join("runtime/hiroute/control.sock");
+ let mut command = std::process::Command::new(daemon);
+ command
+ .env_clear()
+ .env("HOME", isolated.path())
+ .env("PATH", "/usr/bin:/bin")
+ .args(["--role", "control", "--storage-root"])
+ .arg(storage)
+ .arg("--runtime-root")
+ .arg(isolated.path().join("runtime"))
+ .args(["--diagnostic-level-override", "debug"]);
+ let mut child = super::process::Process::spawn(&mut command, logs, cancel)?;
+ loop {
+ if let Err(error) = child.check() {
+ let (_, stderr) = child.output(16 * 1024)?;
+ eprintln!(
+ "initial storage daemon: {}",
+ String::from_utf8_lossy(&stderr)
+ );
+ return Err(error);
+ }
+ if fs::symlink_metadata(&endpoint).is_ok_and(|m| m.file_type().is_socket()) {
+ break;
+ }
+ require(
+ std::time::Instant::now() < deadline,
+ "initial_storage_ready_timeout",
+ )?;
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ child.stop()?;
+ let (_, stderr) = child.output(1024 * 1024)?;
+ require(stderr.is_empty(), "initial_storage_unexpected_stderr")
+}
+
pub fn install_storage_catalog_tampering(storage: &Path) -> Result<()> {
let release_facts = storage.join("release-facts");
let root = release_facts.join("current");
diff --git a/tools/product-e2e/tests/control_shell.rs b/tools/product-e2e/tests/control_shell.rs
index 0358e1c6..4b944882 100644
--- a/tools/product-e2e/tests/control_shell.rs
+++ b/tools/product-e2e/tests/control_shell.rs
@@ -133,7 +133,7 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
api_version: LOCAL_CONTROL_SCHEMA_V2,
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
client_name: "hiroute-desktop".to_owned(),
- client_version: env!("CARGO_PKG_VERSION").to_owned(),
+ client_version: hiroute_application_api::LOCAL_CONTROL_RELEASE_VERSION.to_owned(),
},
Some(LocalControlWireRequestV2 {
schema_version: LOCAL_CONTROL_SCHEMA_V2,
@@ -167,7 +167,7 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
api_version: LOCAL_CONTROL_SCHEMA_V2,
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
client_name: "hiroute-desktop".to_owned(),
- client_version: env!("CARGO_PKG_VERSION").to_owned(),
+ client_version: hiroute_application_api::LOCAL_CONTROL_RELEASE_VERSION.to_owned(),
},
Some(LocalControlWireRequestV2 {
schema_version: LOCAL_CONTROL_SCHEMA_V2,
@@ -280,7 +280,7 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
api_version: SchemaVersion::new(3, 0),
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
client_name: "hiroute-desktop".to_owned(),
- client_version: env!("CARGO_PKG_VERSION").to_owned(),
+ client_version: hiroute_application_api::LOCAL_CONTROL_RELEASE_VERSION.to_owned(),
},
None,
);
@@ -293,7 +293,7 @@ fn control_shell_uses_real_hiroute_and_hirouted_processes() {
api_version: LOCAL_CONTROL_SCHEMA_V2,
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
client_name: "hiroute-skill".to_owned(),
- client_version: env!("CARGO_PKG_VERSION").to_owned(),
+ client_version: hiroute_application_api::LOCAL_CONTROL_RELEASE_VERSION.to_owned(),
},
Some(LocalControlWireRequestV2 {
schema_version: LOCAL_CONTROL_SCHEMA_V2,
diff --git a/tools/product-e2e/tests/pre_gateway_compute_routing.rs b/tools/product-e2e/tests/pre_gateway_compute_routing.rs
index 4fc94446..11ec1bd2 100644
--- a/tools/product-e2e/tests/pre_gateway_compute_routing.rs
+++ b/tools/product-e2e/tests/pre_gateway_compute_routing.rs
@@ -88,31 +88,42 @@ fn production_subprocess_uses_embedded_catalog_and_ignores_storage_tampering() {
let home = temporary.path().join("home");
std::fs::create_dir(&home).unwrap();
std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let mut command = Command::new(&binaries.hirouted);
+ command
+ .args([
+ "--role",
+ "control",
+ "--storage-root",
+ storage_root.to_str().unwrap(),
+ "--runtime-root",
+ runtime_root.to_str().unwrap(),
+ ])
+ .env("HOME", &home)
+ .env_remove("CODEX_HOME")
+ .env_remove("CLAUDE_CONFIG_DIR")
+ .env_remove("ANTHROPIC_AUTH_TOKEN")
+ .env_remove("ANTHROPIC_BASE_URL")
+ .env_remove("ANTHROPIC_MODEL")
+ .env_remove("ANTHROPIC_DEFAULT_OPUS_MODEL")
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped());
+ let endpoint = runtime_root.join("hiroute/control.sock");
+ hiroute_product_e2e::smoke::fixtures::initialize_current_storage(
+ &binaries.hirouted,
+ &storage_root,
+ &temporary.path().join("initialize"),
+ std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ Instant::now() + Duration::from_secs(10),
+ )
+ .unwrap();
install_nonmatching_catalog(&storage_root);
-
let mut daemon = OwnedChild(
- Command::new(&binaries.hirouted)
- .args([
- "--role",
- "control",
- "--storage-root",
- storage_root.to_str().unwrap(),
- "--runtime-root",
- runtime_root.to_str().unwrap(),
- ])
- .env("HOME", &home)
- .env_remove("CODEX_HOME")
- .env_remove("CLAUDE_CONFIG_DIR")
- .env_remove("ANTHROPIC_AUTH_TOKEN")
- .env_remove("ANTHROPIC_BASE_URL")
- .env_remove("ANTHROPIC_MODEL")
- .env_remove("ANTHROPIC_DEFAULT_OPUS_MODEL")
+ command
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.expect("launch production hirouted"),
);
- let endpoint = runtime_root.join("hiroute/control.sock");
let deadline = Instant::now() + Duration::from_secs(10);
while !endpoint.exists() {
assert!(
@@ -182,7 +193,7 @@ fn control_call(endpoint: &Path, operation_id: &str, payload: Value) -> MachineE
api_version: LOCAL_CONTROL_SCHEMA_V2,
machine_schema_version: MACHINE_ENVELOPE_SCHEMA_V2,
client_name: "pre-gateway-product-test".into(),
- client_version: env!("CARGO_PKG_VERSION").into(),
+ client_version: hiroute_application_api::LOCAL_CONTROL_RELEASE_VERSION.into(),
},
)
.unwrap();
diff --git a/tools/product-e2e/tests/routing_plans.rs b/tools/product-e2e/tests/routing_plans.rs
index dc9130cc..4690036e 100644
--- a/tools/product-e2e/tests/routing_plans.rs
+++ b/tools/product-e2e/tests/routing_plans.rs
@@ -3,9 +3,9 @@ use std::collections::{BTreeMap, BTreeSet};
use hiroute_application_api::{CommandLifecycle, command_by_id};
use hiroute_domain::{
AgentIngressProtocolV1, CanonicalDigest, ConnectorRuntimeKind,
- GatewayCandidatePricingIdentityV1, GatewayCandidateProtocolProfileV1, GatewayExecutableAliasV2,
+ GatewayCandidatePricingIdentityV1, GatewayCandidateProtocolProfileV1,
GatewayExecutableCandidateV2, GatewayExecutableRoutingV2, GatewayModelRouteV2,
- GatewayOperationalTargetV1, GatewayPublicationV1,
+ GatewayOperationalTargetV1,
};
use serde::{Deserialize, Serialize};
@@ -113,7 +113,7 @@ struct LegacySnapshotSource {
authority_epoch: u64,
publication_revision: u64,
catalog_renderer_revision: String,
- aliases: Vec<GatewayExecutableAliasV2>,
+ aliases: Vec<LegacyFrozenAlias>,
grants: Vec<LegacyFrozenG0Grant>,
}
@@ -127,7 +127,7 @@ struct LegacyFrozenG0Snapshot {
publication_revision: u64,
payload_digest: String,
catalog_renderer_revision: String,
- aliases: Vec<GatewayExecutableAliasV2>,
+ aliases: Vec<LegacyFrozenAlias>,
grants: Vec<LegacyFrozenG0Grant>,
}
@@ -141,6 +141,51 @@ struct LegacyFrozenG0Grant {
allowed_aliases: Vec<String>,
}
+// The historical snapshot hashed typed serialization, rather than the publication's
+// JSON member order. Freeze only the layers that set that order; opaque candidates
+// retain the original capability contract instead of using today's execution DTO.
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+struct LegacyFrozenAlias {
+ served_model_id: String,
+ purpose: String,
+ agent_plan_revision: u64,
+ protocols: Vec<AgentIngressProtocolV1>,
+ overall_timeout_ms: u64,
+ max_attempts: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ routing: Option<LegacyFrozenRouting>,
+ candidates: Box<serde_json::value::RawValue>,
+}
+
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+struct LegacyFrozenRouting {
+ agent_plan_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ plan_display_name: Option<String>,
+ request_owned: LegacyFrozenRequestOwned,
+ groups: Box<serde_json::value::RawValue>,
+}
+
+#[derive(Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+struct LegacyFrozenRequestOwned {
+ strategy: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ classifier: Option<Box<serde_json::value::RawValue>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ reselect_on_user_message: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ simple_groups: Option<Box<serde_json::value::RawValue>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ complex_groups: Option<Box<serde_json::value::RawValue>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ cost_policy: Option<Box<serde_json::value::RawValue>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ ordered_groups: Option<Box<serde_json::value::RawValue>>,
+}
+
#[test]
fn routing_plans_reports_compiler_and_production_journey_green() {
let scenario: RoutingPlanContractV1 = serde_json::from_str(SCENARIO).unwrap();
@@ -182,10 +227,12 @@ fn routing_plans_reports_compiler_and_production_journey_green() {
#[test]
fn routing_plans_golden_is_a_closed_deterministic_publication() {
- serde_json::from_str::<serde_json::Value>(PUBLICATION_GOLDEN).unwrap();
+ let frozen: serde_json::Value = serde_json::from_str(PUBLICATION_GOLDEN).unwrap();
let bytes = compact_json_preserving_member_order(PUBLICATION_GOLDEN);
- let legacy = GatewayPublicationV1::decode_persisted(PUBLICATION_GOLDEN.as_bytes()).unwrap();
- legacy.validate().unwrap();
+ let publication = serde_json::from_str::<hiroute_domain::GatewayPublicationV1>(include_str!(
+ "../../../e2e/product/fixtures/routing/current-publication.v3.json"
+ ))
+ .unwrap();
let boundary: BoundaryGolden = serde_json::from_str(BOUNDARY_GOLDEN).unwrap();
assert_eq!(boundary.scenario_id, "process-25004-routing-plans");
assert_eq!(boundary.compiler_contract, "green");
@@ -201,8 +248,7 @@ fn routing_plans_golden_is_a_closed_deterministic_publication() {
boundary.publication_digest,
CanonicalDigest::of_bytes(&bytes)
);
- let legacy_snapshot_source: LegacySnapshotSource =
- serde_json::from_str(PUBLICATION_GOLDEN).unwrap();
+ let legacy_snapshot_source: LegacySnapshotSource = serde_json::from_slice(&bytes).unwrap();
let legacy_snapshot = LegacyFrozenG0Snapshot {
schema_version: boundary.gateway_snapshot_schema.clone(),
admission: hiroute_domain::GatewayAdmissionStateV1::NewCallsAllowed,
@@ -215,19 +261,22 @@ fn routing_plans_golden_is_a_closed_deterministic_publication() {
aliases: legacy_snapshot_source.aliases,
grants: legacy_snapshot_source.grants,
};
+ assert_eq!(
+ serde_json::to_value(&legacy_snapshot.aliases).unwrap(),
+ frozen["aliases"]
+ );
assert_eq!(
CanonicalDigest::of_bytes(&serde_json::to_vec(&legacy_snapshot).unwrap()),
boundary.gateway_snapshot_digest
);
- let publication = legacy.into_current().unwrap();
publication.validate_current_contract().unwrap();
assert_eq!(
publication.schema,
hiroute_domain::GATEWAY_PUBLICATION_SCHEMA_V3
);
assert!(publication.plans.iter().all(|plan| {
- plan.body.schema == hiroute_domain::AGENT_PLAN_COMPILED_SCHEMA_V2
- && plan.body.compiler_revision == hiroute_domain::AGENT_PLAN_COMPILER_REVISION_V2
+ plan.body.schema == hiroute_domain::AGENT_PLAN_COMPILED_SCHEMA_V3
+ && plan.body.compiler_revision == hiroute_domain::AGENT_PLAN_COMPILER_REVISION_V3
}));
let gateway_snapshot = publication.gateway_snapshot().unwrap();
assert_eq!(