From c0b43ae3d5a1c9ac5586aa927d9796da215e1fb9 Mon Sep 17 00:00:00 2001 From: "silan.hu" Date: Mon, 11 May 2026 20:14:31 +0800 Subject: [PATCH 1/3] fix: accept device ability resource URAs Teach the Axon SDK and runtime canonicalizers the v4.1.5 resource/device./ability/ route shape, add conformance coverage, and keep device route resources separate from ability subjects. --- .../client-sdk/src/domain/easynet/semantic.rs | 71 ++++++++++ core/runtime-rs/client-sdk/src/tests.rs | 21 +++ core/runtime-rs/src/runtime/security.rs | 131 +++++++++++++++++- .../conformance-vectors/easynet-uri-v1.json | 9 +- 4 files changed, 230 insertions(+), 2 deletions(-) diff --git a/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs b/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs index a11f5276..a698ffe0 100644 --- a/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs +++ b/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs @@ -153,6 +153,17 @@ impl AxonClient { if let Some((_realm, ability_name)) = Self::parse_canonical_hub_ability_path(&path)? { return Ok(ability_name); } + if let Some((_realm, _owner_id, resource_path)) = + Self::parse_canonical_resource_path(&path)? + { + return resource_path + .strip_prefix("ability/") + .filter(|name| !name.is_empty()) + .map(ToString::to_string) + .ok_or_else(|| { + anyhow!("resource_uri route must include resource//ability/") + }); + } let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() < 5 || !parts[3].eq_ignore_ascii_case("abilities") { return Err(anyhow!( @@ -189,6 +200,20 @@ impl AxonClient { } return Ok(format!("easynet:prv:hub:{realm}")); } + if let Some((realm, owner_id, _resource_path)) = Self::parse_canonical_resource_path(&path)? + { + if tenant_id.is_empty() { + return Err(anyhow!( + "canonical resource URI requires non-empty envelope tenant_id" + )); + } + if realm != tenant_id { + return Err(anyhow!( + "canonical resource URI realm must match envelope tenant_id" + )); + } + return Ok(format!("easynet:prv:resource:{owner_id}")); + } let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() < 3 { return Err(anyhow!("r URI path is incomplete")); @@ -427,6 +452,29 @@ impl AxonClient { Ok(Some((realm.to_string(), format!("{namespace}.{member}")))) } + fn parse_canonical_resource_path(path: &str) -> Result> { + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + if parts.len() < 3 || !parts[1].eq_ignore_ascii_case("resource") { + return Ok(None); + } + let realm = parts[0].trim(); + let owner_id = parts[2].trim(); + if realm.is_empty() { + return Err(anyhow!("canonical resource URI is missing realm")); + } + if owner_id.is_empty() { + return Err(anyhow!("canonical resource URI is missing owner id")); + } + if !owner_id.contains('.') { + return Ok(None); + } + Ok(Some(( + realm.to_string(), + owner_id.to_string(), + parts[3..].join("/"), + ))) + } + fn canonicalize_r_path_uri(path: &str, query: &str, tenant_id: &str) -> Result { if let Some((realm, ability_name)) = Self::parse_canonical_hub_ability_path(path)? { if !query.is_empty() { @@ -446,6 +494,29 @@ impl AxonClient { } return Ok(Self::canonical_hub_ability_uri(&realm, &ability_name)); } + if let Some((realm, owner_id, resource_path)) = Self::parse_canonical_resource_path(path)? { + if !query.is_empty() { + return Err(anyhow!( + "canonical resource URI must not include query parameters" + )); + } + if tenant_id.is_empty() { + return Err(anyhow!( + "canonical resource URI requires non-empty envelope tenant_id" + )); + } + if realm != tenant_id { + return Err(anyhow!( + "canonical resource URI realm must match envelope tenant_id" + )); + } + let suffix = if resource_path.is_empty() { + String::new() + } else { + format!("/{resource_path}") + }; + return Ok(format!("easynet:///r/{realm}/resource/{owner_id}{suffix}")); + } let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() < 5 { diff --git a/core/runtime-rs/client-sdk/src/tests.rs b/core/runtime-rs/client-sdk/src/tests.rs index d79cec42..6ce8e582 100644 --- a/core/runtime-rs/client-sdk/src/tests.rs +++ b/core/runtime-rs/client-sdk/src/tests.rs @@ -61,6 +61,27 @@ fn canonicalize_accepts_canonical_hub_ability_uri() { ); } +#[test] +fn canonicalize_accepts_device_ability_resource_route_uri() { + let canonical = AxonClient::canonicalize_easynet_resource_uri( + "easynet:///r/acme/resource/device.dev-1/ability/device.shell.run", + "acme", + ) + .expect("device ability resource route should canonicalize"); + assert_eq!( + canonical, + "easynet:///r/acme/resource/device.dev-1/ability/device.shell.run" + ); + assert_eq!( + AxonClient::ability_name_from_resource_uri(&canonical).unwrap(), + "device.shell.run" + ); + assert_eq!( + AxonClient::default_subject_id_for_resource_uri(&canonical, "acme").unwrap(), + "easynet:prv:resource:device.dev-1" + ); +} + #[test] fn canonicalize_rejects_legacy_hub_ability_uri() { let err = AxonClient::canonicalize_easynet_resource_uri( diff --git a/core/runtime-rs/src/runtime/security.rs b/core/runtime-rs/src/runtime/security.rs index b2ea9ba3..c70478d5 100644 --- a/core/runtime-rs/src/runtime/security.rs +++ b/core/runtime-rs/src/runtime/security.rs @@ -187,6 +187,37 @@ impl AxonRuntime { Ok(Some((realm.to_string(), format!("{namespace}.{member}")))) } + fn parse_canonical_resource_path( + path: &str, + ) -> Result, pb::Error> { + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + if parts.len() < 3 || !parts[1].eq_ignore_ascii_case("resource") { + return Ok(None); + } + let realm = parts[0].trim(); + let owner_id = parts[2].trim(); + if realm.is_empty() { + return Err(Self::easynet_err( + ERR_EASYNET_RESOURCE_URI_INVALID, + "canonical resource URI is missing realm", + )); + } + if owner_id.is_empty() { + return Err(Self::easynet_err( + ERR_EASYNET_RESOURCE_URI_INVALID, + "canonical resource URI is missing owner id", + )); + } + if !owner_id.contains('.') { + return Ok(None); + } + Ok(Some(( + realm.to_string(), + owner_id.to_string(), + parts[3..].join("/"), + ))) + } + fn canonicalize_r_path_uri( path: &str, query: &str, @@ -225,6 +256,53 @@ impl AxonRuntime { tenant_id: realm, }); } + if let Some((realm, owner_id, resource_path)) = Self::parse_canonical_resource_path(path)? { + if !query.is_empty() { + return Err(Self::easynet_err( + ERR_EASYNET_RESOURCE_URI_INVALID, + "canonical resource URI must not include query parameters", + )); + } + if envelope_tenant_id.is_empty() { + return Err(Self::easynet_err( + ERR_EASYNET_TENANT_REQUIRED, + "canonical resource URI requires non-empty envelope tenant_id", + )); + } + if realm != envelope_tenant_id { + return Err(Self::easynet_err( + ERR_EASYNET_TENANT_MISMATCH, + "canonical resource URI realm must match envelope tenant_id", + )); + } + let expected_subject = format!("easynet:prv:resource:{owner_id}"); + if subject_id != expected_subject { + return Err(Self::easynet_err( + ERR_EASYNET_SUBJECT_MISMATCH, + "subject_id does not match canonical resource URI subject", + )); + } + let ability_name = resource_path + .strip_prefix("ability/") + .filter(|name| !name.is_empty()) + .ok_or_else(|| { + Self::easynet_err( + ERR_EASYNET_RESOURCE_URI_INVALID, + "canonical resource route must include resource//ability/", + ) + })? + .to_string(); + let suffix = if resource_path.is_empty() { + String::new() + } else { + format!("/{resource_path}") + }; + return Ok(EasyNetVerifiedResource { + canonical_uri: format!("easynet:///r/{realm}/resource/{owner_id}{suffix}"), + ability_name, + tenant_id: realm, + }); + } let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() < 5 { @@ -476,6 +554,8 @@ impl AxonRuntime { // "this is the realm's own daemon talking to itself". // A future cross-realm hub flow will need a stricter // `descriptor.realm` match here. + // * `easynet::resource:device.` — route/resource + // subject owned by a concrete device. // * Anything else — reject with the legacy mismatch error. match Self::parse_easynet_subject(subject_id) { Some((_namespace, _visibility, "reg", subject_value)) @@ -487,10 +567,17 @@ impl AxonRuntime { Some((_namespace, _visibility, "hub", _realm)) => { self.verify_hub_subject(tenant_id, public_key) } + Some((_namespace, _visibility, "resource", subject_value)) + if subject_value.starts_with("device.") => + { + let device_id = &subject_value["device.".len()..]; + self.verify_device_resource_subject(tenant_id, device_id, public_key) + } _ => Err(Self::easynet_err( ERR_EASYNET_SUBJECT_MISMATCH, "subject_id must map to easynet::reg:agent. \ - or easynet::hub:", + or easynet::hub: \ + or easynet::resource:device.", )), } } @@ -558,6 +645,31 @@ impl AxonRuntime { )) } + fn verify_device_resource_subject( + &self, + tenant_id: &str, + device_id: &str, + public_key: &[u8], + ) -> Result<(), pb::Error> { + for node in self.state.topology.nodes.iter() { + let descriptor = &node.descriptor; + if descriptor.tenant_id != tenant_id || node.key() != device_id { + continue; + } + if self.node_has_active_ed25519_material(node.key(), public_key) { + return Ok(()); + } + return Err(Self::easynet_err( + ERR_EASYNET_PUBLIC_KEY_UNTRUSTED, + "easynet.public_key is not an active trusted key for this device resource subject", + )); + } + Err(Self::easynet_err( + ERR_EASYNET_SUBJECT_KEY_UNREGISTERED, + "device resource subject has no registered trusted key material in tenant scope", + )) + } + fn maybe_gc_easynet_nonce_guard(&self, now: i64) -> Result<(), pb::Error> { let last_gc = self .state @@ -1498,6 +1610,23 @@ mod tests { assert_eq!(verified.tenant_id, "acme"); } + #[test] + fn canonicalize_r_path_accepts_device_ability_resource_route_uri() { + let verified = AxonRuntime::canonicalize_r_path_uri( + "acme/resource/device.dev-1/ability/device.shell.run", + "", + "acme", + "easynet:prv:resource:device.dev-1", + ) + .expect("device ability resource route should verify structurally"); + assert_eq!( + verified.canonical_uri, + "easynet:///r/acme/resource/device.dev-1/ability/device.shell.run" + ); + assert_eq!(verified.ability_name, "device.shell.run"); + assert_eq!(verified.tenant_id, "acme"); + } + #[test] fn canonicalize_r_path_rejects_legacy_hub_ability_uri() { let err = AxonRuntime::canonicalize_r_path_uri( diff --git a/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json b/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json index 6a267a3f..6cbecfec 100644 --- a/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json +++ b/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json @@ -16,6 +16,13 @@ "canonical_uri": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test&a=1&z=9", "expect_error": null }, + { + "id": "device-ability-resource-route", + "tenant_id": "tenant-test", + "input_uri": "easynet:///r/tenant-test/resource/device.dev-1/ability/device.shell.run", + "canonical_uri": "easynet:///r/tenant-test/resource/device.dev-1/ability/device.shell.run", + "expect_error": null + }, { "id": "r-pub-with-tenant-rejected", "tenant_id": "", @@ -31,4 +38,4 @@ "expect_error": "tenant_id mismatch between envelope and resource_uri" } ] -} \ No newline at end of file +} From 4a99542a5f17ee92727361bbfc2a8ef17f7a21d5 Mon Sep 17 00:00:00 2001 From: "Silan.Hu" Date: Mon, 11 May 2026 20:54:09 +0800 Subject: [PATCH 2/3] add Windows runtime local tool transport Route runtime local tool calls through generic async streams and add Windows named-pipe connection support alongside the Unix socket path. --- .../src/interop_native/execution.rs | 110 +++++++++++++----- 1 file changed, 82 insertions(+), 28 deletions(-) diff --git a/core/runtime-rs/src/interop_native/execution.rs b/core/runtime-rs/src/interop_native/execution.rs index 6e2d4984..0787a7d5 100644 --- a/core/runtime-rs/src/interop_native/execution.rs +++ b/core/runtime-rs/src/interop_native/execution.rs @@ -31,7 +31,7 @@ use std::process::Stdio; use crate::*; use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _}; use serde_json::{json, Value}; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; use tokio::process::Command; /// Timeout for real camera capture operations (seconds). @@ -2212,8 +2212,6 @@ async fn call_uds_runtime_local_tool( socket_path: &str, request_line: &str, ) -> Result { - use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; - use tokio::net::UnixStream; use tokio::time::{timeout, Duration}; // 10 minutes covers a worst-case LLM dispatch (codex is currently @@ -2226,31 +2224,46 @@ async fn call_uds_runtime_local_tool( // to bound that instead. const RUNTIME_LOCAL_TOOL_TIMEOUT: Duration = Duration::from_secs(600); - let connect = UnixStream::connect(socket_path); - let stream = timeout(RUNTIME_LOCAL_TOOL_TIMEOUT, connect) - .await - .map_err(|_| format!("connect to {socket_path} timed out"))? - .map_err(|e| format!("connect to {socket_path}: {e}"))?; - let (read_half, mut write_half) = stream.into_split(); + #[cfg(unix)] + let stream = { + use tokio::net::UnixStream; + let connect = UnixStream::connect(socket_path); + timeout(RUNTIME_LOCAL_TOOL_TIMEOUT, connect) + .await + .map_err(|_| format!("connect to {socket_path} timed out"))? + .map_err(|e| format!("connect to {socket_path}: {e}"))? + }; + #[cfg(windows)] + let stream = + connect_windows_runtime_local_tool(socket_path, RUNTIME_LOCAL_TOOL_TIMEOUT).await?; + call_runtime_local_tool_with_stream(stream, request_line, RUNTIME_LOCAL_TOOL_TIMEOUT).await +} + +async fn call_runtime_local_tool_with_stream( + stream: S, + request_line: &str, + timeout_budget: tokio::time::Duration, +) -> Result +where + S: AsyncRead + AsyncWrite + Unpin, +{ + let (read_half, mut write_half) = tokio::io::split(stream); let mut buf = String::with_capacity(request_line.len() + 1); buf.push_str(request_line); buf.push('\n'); - timeout( - RUNTIME_LOCAL_TOOL_TIMEOUT, - write_half.write_all(buf.as_bytes()), - ) - .await - .map_err(|_| "write request timed out".to_string())? - .map_err(|e| format!("write request: {e}"))?; - timeout(RUNTIME_LOCAL_TOOL_TIMEOUT, write_half.flush()) + tokio::time::timeout(timeout_budget, write_half.write_all(buf.as_bytes())) + .await + .map_err(|_| "write request timed out".to_string())? + .map_err(|e| format!("write request: {e}"))?; + tokio::time::timeout(timeout_budget, write_half.flush()) .await .map_err(|_| "flush request timed out".to_string())? .map_err(|e| format!("flush request: {e}"))?; let mut reader = BufReader::new(read_half); let mut response = String::new(); - timeout(RUNTIME_LOCAL_TOOL_TIMEOUT, reader.read_line(&mut response)) + tokio::time::timeout(timeout_budget, reader.read_line(&mut response)) .await .map_err(|_| "read response timed out".to_string())? .map_err(|e| format!("read response: {e}"))?; @@ -2273,8 +2286,6 @@ async fn stream_uds_runtime_local_tool( request_line: &str, chunk_tx: &mpsc::Sender, ) -> Result<(), String> { - use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; - use tokio::net::UnixStream; use tokio::time::{timeout, Duration}; // Connect / write deadlines mirror the unary path. The @@ -2284,21 +2295,39 @@ async fn stream_uds_runtime_local_tool( // is the right place to cap end-to-end duration. const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); - let connect = UnixStream::connect(socket_path); - let stream = timeout(CONNECT_TIMEOUT, connect) - .await - .map_err(|_| format!("connect to {socket_path} timed out"))? - .map_err(|e| format!("connect to {socket_path}: {e}"))?; - let (read_half, mut write_half) = stream.into_split(); + #[cfg(unix)] + let stream = { + use tokio::net::UnixStream; + let connect = UnixStream::connect(socket_path); + timeout(CONNECT_TIMEOUT, connect) + .await + .map_err(|_| format!("connect to {socket_path} timed out"))? + .map_err(|e| format!("connect to {socket_path}: {e}"))? + }; + #[cfg(windows)] + let stream = connect_windows_runtime_local_tool(socket_path, CONNECT_TIMEOUT).await?; + stream_runtime_local_tool_with_stream(stream, request_line, chunk_tx, CONNECT_TIMEOUT).await +} + +async fn stream_runtime_local_tool_with_stream( + stream: S, + request_line: &str, + chunk_tx: &mpsc::Sender, + connect_timeout: tokio::time::Duration, +) -> Result<(), String> +where + S: AsyncRead + AsyncWrite + Unpin, +{ + let (read_half, mut write_half) = tokio::io::split(stream); let mut buf = String::with_capacity(request_line.len() + 1); buf.push_str(request_line); buf.push('\n'); - timeout(CONNECT_TIMEOUT, write_half.write_all(buf.as_bytes())) + tokio::time::timeout(connect_timeout, write_half.write_all(buf.as_bytes())) .await .map_err(|_| "write request timed out".to_string())? .map_err(|e| format!("write request: {e}"))?; - timeout(CONNECT_TIMEOUT, write_half.flush()) + tokio::time::timeout(connect_timeout, write_half.flush()) .await .map_err(|_| "flush request timed out".to_string())? .map_err(|e| format!("flush request: {e}"))?; @@ -2436,6 +2465,31 @@ async fn stream_uds_runtime_local_tool( } } +#[cfg(windows)] +async fn connect_windows_runtime_local_tool( + socket_path: &str, + timeout_budget: tokio::time::Duration, +) -> Result { + use std::io::ErrorKind; + use tokio::net::windows::named_pipe::ClientOptions; + + const ERROR_PIPE_BUSY_OS_CODE: i32 = 231; + let deadline = tokio::time::Instant::now() + timeout_budget; + loop { + match ClientOptions::new().open(socket_path) { + Ok(client) => return Ok(client), + Err(err) + if tokio::time::Instant::now() < deadline + && (err.kind() == ErrorKind::NotFound + || err.raw_os_error() == Some(ERROR_PIPE_BUSY_OS_CODE)) => + { + tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; + } + Err(err) => return Err(format!("connect to {socket_path}: {err}")), + } + } +} + /// Translate the raw UDS round-trip outcome into a `DispatchResult`. /// Pulled out as a free function so it's exercised by unit tests /// without needing a real socket. From 11888746bbc0803a983cabf03f69b3b34234e493 Mon Sep 17 00:00:00 2001 From: "silan.hu" Date: Thu, 14 May 2026 18:46:30 +0800 Subject: [PATCH 3/3] Promote URA as the Axon resource address --- README.md | 22 +- core/proto/axon/v1/capability.proto | 6 +- core/proto/axon/v1/control.proto | 2 +- core/proto/axon/v1/federation.proto | 2 +- core/proto/axon/v1/invoke.proto | 20 +- core/proto/axon/v1/observe.proto | 6 +- core/proto/axon/v1/transfer.proto | 10 +- core/proto/axon/v1/types.proto | 216 ++- core/proto/axon/v1/voice.proto | 2 +- core/runtime-rs/Cargo.lock | 2 + core/runtime-rs/README.md | 2 +- core/runtime-rs/client-sdk/Cargo.lock | 110 ++ core/runtime-rs/client-sdk/Cargo.toml | 2 + core/runtime-rs/client-sdk/README.md | 2 +- .../client-sdk/proto/axon/v1/capability.proto | 6 +- .../client-sdk/proto/axon/v1/control.proto | 2 +- .../client-sdk/proto/axon/v1/federation.proto | 2 +- .../client-sdk/proto/axon/v1/invoke.proto | 20 +- .../client-sdk/proto/axon/v1/observe.proto | 6 +- .../client-sdk/proto/axon/v1/transfer.proto | 10 +- .../client-sdk/proto/axon/v1/types.proto | 216 ++- .../client-sdk/proto/axon/v1/voice.proto | 2 +- core/runtime-rs/client-sdk/src/api/fluent.rs | 15 +- .../client-sdk/src/domain/admission.rs | 153 +- .../src/domain/capability/lifecycle.rs | 24 +- .../client-sdk/src/domain/content.rs | 257 +++ .../client-sdk/src/domain/easynet/semantic.rs | 176 +- core/runtime-rs/client-sdk/src/domain/mod.rs | 9 +- core/runtime-rs/client-sdk/src/domain/ura.rs | 1482 ++++++----------- .../runtime-rs/client-sdk/src/infra/client.rs | 55 +- core/runtime-rs/client-sdk/src/lib.rs | 12 +- core/runtime-rs/client-sdk/src/model/mod.rs | 27 +- core/runtime-rs/client-sdk/src/tests.rs | 102 +- .../tests/invocation_envelope_interop.rs | 36 +- core/runtime-rs/dendrite-bridge/Cargo.lock | 96 ++ .../benches/bench_signed_mcp.rs | 6 +- .../docs/AUTHENTICATED_INVOCATION.md | 20 +- .../docs/BRIDGE_ERROR_CODES.md | 2 +- .../include/axon_dendrite_bridge.h | 2 +- .../runtime-rs/dendrite-bridge/src/ability.rs | 51 +- core/runtime-rs/dendrite-bridge/src/common.rs | 8 +- .../src/control/capability/package.rs | 16 +- .../dendrite-bridge/src/control/requests.rs | 2 +- .../dendrite-bridge/src/control/shared.rs | 14 +- core/runtime-rs/dendrite-bridge/src/errors.rs | 4 +- .../dendrite-bridge/src/ffi_exports.rs | 10 +- .../dendrite-bridge/src/invoke_signed.rs | 108 +- .../dendrite-bridge/src/invoke_signed_bidi.rs | 15 +- .../src/invoke_signed_common.rs | 66 +- .../src/invoke_signed_stream.rs | 24 +- .../runtime-rs/dendrite-bridge/src/signing.rs | 82 +- .../tests/signed_verification_matrix.rs | 8 +- core/runtime-rs/easynet-verify/Cargo.lock | 110 ++ core/runtime-rs/easynet-verify/src/main.rs | 102 +- .../tests/e2e_receipt_verify.rs | 12 +- .../scripts/check-rfc-001-conformance.sh | 4 +- core/runtime-rs/src/errors/security.rs | 2 +- .../runtime-rs/src/interop_native/metadata.rs | 2 +- core/runtime-rs/src/main.rs | 8 +- core/runtime-rs/src/runtime/federation.rs | 4 +- .../src/runtime/federation_client.rs | 96 +- core/runtime-rs/src/runtime/mod.rs | 187 ++- core/runtime-rs/src/runtime/security.rs | 176 +- .../src/services/capability/materialize.rs | 8 +- .../src/services/capability/proof.rs | 4 +- .../src/services/capability/rpc_install.rs | 10 +- .../src/services/capability/rpc_package.rs | 32 +- .../src/services/invocation/admission_gate.rs | 56 +- .../src/services/invocation/bidi_handler.rs | 7 +- .../services/invocation/delegation_gate.rs | 130 +- .../services/invocation/directory_events.rs | 28 +- .../src/services/invocation/hub_forward.rs | 8 +- .../src/services/invocation/hub_profile.rs | 426 ++--- .../src/services/invocation/idempotency.rs | 4 +- .../services/invocation/membership_gate.rs | 70 +- .../src/services/invocation/rpc_handlers.rs | 86 +- .../src/services/invocation/runtime_admin.rs | 4 +- .../services/invocation/session_provider.rs | 18 +- .../services/invocation/session_registry.rs | 50 +- .../src/services/invocation/shard_resolver.rs | 20 +- .../src/services/payload_transfer.rs | 39 +- .../src/services/stream/terminal_proxy.rs | 4 +- core/runtime-rs/src/state/agents.rs | 176 +- core/runtime-rs/src/state/capability.rs | 2 +- core/runtime-rs/src/state/mod.rs | 6 +- core/runtime-rs/src/tests/admission.rs | 101 +- core/runtime-rs/src/tests/capability.rs | 110 +- core/runtime-rs/src/tests/federation.rs | 2 +- core/runtime-rs/src/tests/federation_e2e.rs | 52 +- .../src/tests/forward_invoke_e2e.rs | 95 +- .../src/tests/grpc_multi_shard_e2e.rs | 28 +- core/runtime-rs/src/tests/identity.rs | 72 +- core/runtime-rs/src/tests/invocation.rs | 80 +- core/runtime-rs/src/tests/mod.rs | 48 +- core/runtime-rs/src/tests/multi_shard_e2e.rs | 81 +- core/runtime-rs/src/tests/stream.rs | 56 +- core/runtime-rs/src/tests/target_resolver.rs | 6 +- docs/rfc/AXON-RFC-001-plan-v4.1.1.md | 102 +- docs/rfc/AXON-RFC-001-restatement-mapping.md | 36 +- .../02-six-guarantees-evidence-matrix.md | 16 +- document/concepts/ONTOLOGY_AGENT_ABILITY.md | 4 +- ...ility-delivery-and-usage-interface-plan.md | 2 +- .../03-identity-routing-and-tenant-rules.md | 4 +- ...4-user-node-and-capability-registration.md | 4 +- .../ecosystem/05-rust-native-support-plan.md | 10 +- ...mcp-native-support-deploy-and-reference.md | 8 +- .../08-packaging-and-release-plan.md | 2 +- ...-03-30-review-remediation-upgrade-notes.md | 2 +- document/rfcs/001-envelope-axiom-alignment.md | 10 +- document/rfcs/001-pr2-acceptance-checklist.md | 12 +- .../rfcs/002-1-distributed-realm-routing.md | 12 +- document/rfcs/002-keyring-and-keyresolver.md | 24 +- examples/00-entrance/hello-ability/README.md | 2 +- .../src/app.rs | 20 +- .../src/bin/shared/mcp_list_dir.rs | 2 +- .../src/gateway.rs | 12 +- .../src/models.rs | 4 +- .../include/axon_dendrite_bridge.h | 2 +- .../include/axon_dendrite_bridge.h | 2 +- .../I1-admission-receipt/harness/src/main.rs | 18 +- .../cross-language-sdk/04-gallery/README.md | 12 +- .../clients/go/case/shared/case_kit.go | 10 +- .../04-gallery/clients/go/main.go | 4 +- .../java/io/easynet/gallery/ClientCall.java | 8 +- .../io/easynet/gallery/shared/CaseKit.java | 10 +- .../04-gallery/clients/node/client_call.ts | 8 +- .../clients/node/shared/case_kit.js | 6 +- .../clients/node/shared/case_kit.ts | 8 +- .../04-gallery/clients/python/client_call.py | 4 +- .../clients/python/shared/case_kit.py | 4 +- .../clients/rust/src/bin/client_call.rs | 16 +- .../swift/Sources/ClientCall/main.swift | 2 +- .../swift/Sources/Shared/NativeCaseKit.swift | 4 +- .../04-gallery/run_packaged_local.sh | 52 +- .../clients/go/shared/case_kit.go | 10 +- .../gallery/case05/shared/CaseKit.java | 10 +- .../clients/node/shared/case_kit.js | 6 +- .../clients/node/shared/case_kit.ts | 8 +- .../clients/python/shared/case_kit.py | 4 +- .../clients/rust/src/lib.rs | 4 +- .../swift/Sources/Shared/NativeCaseKit.swift | 4 +- .../clients/python/tool_adapter_demo.py | 2 +- .../clients/rust/src/bin/tool_adapter_demo.rs | 6 +- .../swift/Sources/Case10Swift/main.swift | 2 +- .../11-lifecycle-export/clients/go/main.go | 4 +- .../gallery/case11/LifecycleExportDemo.java | 4 +- .../clients/node_client.mjs | 2 +- .../clients/python_client.py | 2 +- .../clients/rust/src/bin/lifecycle_export.rs | 4 +- .../swift/Sources/Case11Swift/main.swift | 2 +- .../12-remote-device/skill/SKILL.md | 4 +- .../02-multi-user-tui/README.md | 4 +- .../conformance-vectors/easynet-uri-v1.json | 2 +- .../envelope-signing-v1.json | 4 +- sdk/API_MAPPING.md | 2 +- sdk/FEDERATION_INVOKE_SCHEMAS.md | 42 +- sdk/SDK_INTERFACE_SPEC.md | 2 +- sdk/conformance/cases/axiom/README.md | 12 +- .../cases/axiom/axiom-e1-envelope-7tuple.json | 6 +- .../axiom/axiom-e2-caller-sig-required.json | 6 +- .../axiom-e3-nonce-replay-discriminated.json | 12 +- ...axiom-e4-subject-distinct-from-callee.json | 6 +- .../cases/axiom/axiom-e6-causal-scalar.json | 2 +- .../axiom/axiom-e7-causal-list-fanin.json | 8 +- .../axiom-identity-composite-required.json | 12 +- .../cases/axiom/axiom-profile-binding.json | 6 +- .../axiom-subject-survives-callee-swap.json | 14 +- .../axiom-worked-example-authenticated.json | 10 +- sdk/go/easynet/ability_lifecycle.go | 60 +- sdk/go/easynet/audio.go | 12 +- sdk/go/easynet/client.go | 60 +- sdk/go/easynet/client_test.go | 18 +- .../dendrite_bridge_capability_request.go | 8 +- ...dendrite_bridge_capability_request_test.go | 18 +- sdk/go/easynet/dendrite_bridge_cgo.go | 76 +- .../dendrite_bridge_signed_invoke_bidi_cgo.go | 24 +- ...rite_bridge_signed_invoke_bidi_cgo_test.go | 68 +- .../dendrite_bridge_signed_invoke_cgo.go | 22 +- .../dendrite_bridge_signed_invoke_stub.go | 12 +- sdk/go/easynet/federation.go | 36 +- sdk/go/easynet/federation_test.go | 32 +- sdk/go/easynet/invocation/admission.go | 32 +- sdk/go/easynet/invocation/admission_test.go | 8 +- sdk/go/easynet/invocation/audit.go | 42 +- sdk/go/easynet/invocation/axiom.go | 126 +- sdk/go/easynet/invocation/axiom_test.go | 34 +- .../easynet/invocation/axiom_vectors_test.go | 32 +- .../invocation/axiom_worked_example_test.go | 28 +- sdk/go/easynet/invocation/bundle.go | 60 +- .../invocation/cross_language_verify_test.go | 52 +- sdk/go/easynet/invocation/error.go | 12 +- sdk/go/easynet/invocation/handle.go | 22 +- sdk/go/easynet/invocation/invocation_tools.go | 6 +- .../easynet/invocation/invoke_signed_test.go | 6 +- sdk/go/easynet/invocation/local_runtime.go | 36 +- sdk/go/easynet/invocation/messaging.go | 10 +- sdk/go/easynet/invocation/supervisor.go | 8 +- sdk/go/easynet/mcp/server_stream_test.go | 22 +- sdk/go/easynet/orchestrator_lifecycle.go | 4 +- sdk/go/easynet/reconnect.go | 4 +- sdk/go/easynet/semantic.go | 12 +- sdk/go/easynet/signed_invoke_request.go | 48 +- sdk/go/easynet/signed_invoke_request_test.go | 50 +- sdk/go/easynet/streaming.go | 8 +- sdk/go/easynet/tool_adapter.go | 30 +- sdk/go/easynet/tool_adapter_test.go | 14 +- sdk/go/easynet/ura.go | 313 ++++ sdk/go/easynet/ura_test.go | 50 + .../audit_receipt_chain_verify_test.go | 16 +- .../industrial/audit_tamper_detection_test.go | 8 +- .../industrial/error_retriable_hints_test.go | 16 +- .../industrial/error_taxonomy_mapping_test.go | 60 +- .../event_stream_resumption_test.go | 40 +- .../event_stream_sequence_monotonic_test.go | 12 +- ...on_parent_child_cancel_propagation_test.go | 24 +- .../invocation_terminal_monotonicity_test.go | 16 +- .../industrial/message_inbox_bounded_test.go | 16 +- .../industrial/message_inbox_fifo_test.go | 17 +- .../message_inbox_idempotent_test.go | 20 +- .../supervisor_cleanup_before_receipt_test.go | 16 +- .../supervisor_grace_period_test.go | 4 +- .../industrial/supervisor_orphan_reap_test.go | 12 +- .../supervisor_process_group_test.go | 8 +- .../supervisor_resource_limit_test.go | 4 +- .../main/java/run/easynet/axon/Ability.java | 12 +- .../run/easynet/axon/AbilityLifecycle.java | 34 +- .../run/easynet/axon/AbilityToolAdapter.java | 26 +- .../main/java/run/easynet/axon/Client.java | 22 +- .../java/run/easynet/axon/DendriteBridge.java | 18 +- .../java/run/easynet/axon/FederationBody.java | 8 +- .../axon/PublishCapabilityRequest.java | 10 +- .../java/run/easynet/axon/SemanticBridge.java | 22 +- .../run/easynet/axon/SidecarTransport.java | 26 +- .../main/java/run/easynet/axon/Transport.java | 14 +- .../easynet/axon/invocation/Admission.java | 28 +- .../run/easynet/axon/invocation/Axiom.java | 70 +- .../run/easynet/axon/invocation/Bundle.java | 26 +- .../easynet/axon/invocation/LocalRuntime.java | 8 +- .../easynet/axon/AbilityToolAdapterTest.java | 14 +- .../easynet/axon/CapabilityRequestTest.java | 18 +- .../run/easynet/axon/FederationBodyTest.java | 32 +- .../axon/invocation/AdmissionTest.java | 16 +- .../axon/invocation/AxiomVectorsTest.java | 16 +- .../invocation/AxiomWorkedExampleTest.java | 12 +- .../invocation/CrossLanguageVerifyTest.java | 6 +- .../axon/invocation/InvokeSignedTest.java | 28 +- sdk/node/scripts/run-axiom-vectors.mjs | 8 +- sdk/node/src/ability_lifecycle.ts | 30 +- sdk/node/src/capability_request.test.ts | 44 +- sdk/node/src/capability_request.ts | 6 +- sdk/node/src/dendrite_bridge/bridge.ts | 16 +- sdk/node/src/dendrite_bridge/types.ts | 2 +- sdk/node/src/federation_conformance.test.ts | 50 +- sdk/node/src/index.ts | 42 +- sdk/node/src/invocation/admission.ts | 18 +- sdk/node/src/invocation/axiom.ts | 56 +- sdk/node/src/invocation/bundle.ts | 30 +- sdk/node/src/invocation/local-runtime.ts | 8 +- .../presets/ability_dispatch/orchestrator.ts | 2 +- .../src/presets/remote_control/descriptor.ts | 22 +- sdk/node/src/tool_adapter.ts | 16 +- sdk/node/tests/admission.test.mjs | 8 +- sdk/node/tests/axiom-vectors.test.mjs | 20 +- sdk/node/tests/axiom-worked-example.test.mjs | 6 +- sdk/node/tests/cross-language-verify.test.mjs | 8 +- sdk/node/tests/invoke-signed.test.mjs | 18 +- sdk/python/easynet_axon/ability.py | 4 +- sdk/python/easynet_axon/ability_lifecycle.py | 50 +- sdk/python/easynet_axon/capability_request.py | 8 +- sdk/python/easynet_axon/client.py | 50 +- sdk/python/easynet_axon/dendrite_bridge.py | 44 +- .../easynet_axon/invocation/__init__.py | 4 +- .../easynet_axon/invocation/admission.py | 26 +- sdk/python/easynet_axon/invocation/axiom.py | 90 +- sdk/python/easynet_axon/invocation/bundle.py | 22 +- .../easynet_axon/invocation/local_runtime.py | 10 +- sdk/python/easynet_axon/orchestrator.py | 10 +- .../presets/federation/handlers.py | 4 +- sdk/python/easynet_axon/semantic.py | 22 +- sdk/python/easynet_axon/tool_adapter.py | 22 +- sdk/python/tests/test_admission.py | 8 +- sdk/python/tests/test_audit.py | 16 +- sdk/python/tests/test_axiom_vectors.py | 32 +- sdk/python/tests/test_axiom_worked_example.py | 14 +- sdk/python/tests/test_capability_request.py | 50 +- .../tests/test_cross_language_verify.py | 10 +- .../tests/test_federation_conformance.py | 50 +- sdk/python/tests/test_invoke_signed.py | 22 +- sdk/python/tests/test_stream_resume.py | 2 +- sdk/react/src/ability_lifecycle.js | 24 +- sdk/react/src/index.d.ts | 2 +- sdk/react/src/index.js | 6 +- sdk/react/src/index.ts | 6 +- sdk/react/src/tool_adapter.d.ts | 2 +- sdk/react/src/tool_adapter.js | 12 +- sdk/react/src/tool_adapter.ts | 8 +- sdk/rust/Cargo.lock | 140 ++ sdk/rust/Cargo.toml | 4 + sdk/rust/README.md | 2 +- sdk/rust/benches/admission_replay.rs | 18 +- sdk/rust/benches/invocation_core.rs | 8 +- sdk/rust/examples/emit_worked_example.rs | 8 +- sdk/rust/src/ability.rs | 54 +- sdk/rust/src/bin/verify.rs | 12 +- sdk/rust/src/dendrite_bridge.rs | 112 +- sdk/rust/src/invocation/admission.rs | 60 +- sdk/rust/src/invocation/audit.rs | 22 +- sdk/rust/src/invocation/axiom.rs | 194 +-- sdk/rust/src/invocation/bundle.rs | 54 +- sdk/rust/src/invocation/ledger.rs | 1328 +++++++++++++++ sdk/rust/src/invocation/local_runtime.rs | 14 +- sdk/rust/src/invocation/mod.rs | 11 +- sdk/rust/src/lib.rs | 1 + sdk/rust/src/server.rs | 2 +- sdk/rust/src/tool_adapter.rs | 50 +- sdk/rust/src/ura.rs | 729 ++++++++ sdk/rust/tests/admission.rs | 6 +- sdk/rust/tests/axiom_vectors.rs | 44 +- sdk/rust/tests/axiom_worked_example.rs | 22 +- .../admission_replay_concurrent.rs | 4 +- .../concurrency/invocation_core_concurrent.rs | 8 +- sdk/rust/tests/connect_then_signed_mcp.rs | 10 +- sdk/rust/tests/invoke_signed.rs | 20 +- sdk/rust/tests/options_symmetry.rs | 28 +- sdk/rust/tests/verify_binary.rs | 32 +- sdk/rust/tests/verify_end_to_end.rs | 40 +- .../EasyNetAxon/AbilityLifecycle.swift | 40 +- sdk/swift/Sources/EasyNetAxon/Client.swift | 48 +- .../Sources/EasyNetAxon/DendriteBridge.swift | 42 +- .../Sources/EasyNetAxon/FederationBody.swift | 18 +- .../EasyNetAxon/Invocation/Admission.swift | 26 +- .../EasyNetAxon/Invocation/Axiom.swift | 70 +- .../EasyNetAxon/Invocation/Bundle.swift | 32 +- .../EasyNetAxon/Invocation/LocalRuntime.swift | 8 +- .../Sources/EasyNetAxon/ToolAdapter.swift | 18 +- .../EasyNetAxonTests/AdmissionTests.swift | 24 +- .../EasyNetAxonTests/AxiomVectorsTests.swift | 16 +- .../AxiomWorkedExampleTests.swift | 12 +- .../Tests/EasyNetAxonTests/ClientTests.swift | 20 +- .../CrossLanguageVerifyTests.swift | 8 +- .../DendriteBridgeTests.swift | 2 +- .../FederationConformanceTests.swift | 34 +- .../EasyNetAxonTests/InvokeSignedTests.swift | 20 +- .../EasyNetAxonTests/ToolAdapterTests.swift | 2 +- 344 files changed, 8416 insertions(+), 5229 deletions(-) create mode 100644 core/runtime-rs/client-sdk/src/domain/content.rs create mode 100644 sdk/go/easynet/ura.go create mode 100644 sdk/go/easynet/ura_test.go create mode 100644 sdk/rust/src/invocation/ledger.rs create mode 100644 sdk/rust/src/ura.rs diff --git a/README.md b/README.md index 957e6766..13172154 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ In an agent-native system, failure does not come from model quality alone. It co Axon solves this by making execution contract-first: -- Addressability: every network object has a canonical URI. +- Addressability: every network object has a canonical URA. - Decidability: every operation ends in a known state. - Explainability: every routing and scheduling decision can be justified. - Auditability: every state transition leaves a durable trace. @@ -112,7 +112,7 @@ A central design choice in Axon is separating **Skill** from **Ability**. In Axon terms: - A **Skill** is developer logic. -- An **Ability** is that logic elevated into a governed protocol object (`axon://capabilities/`) with explicit schema, trust posture, execution mode, observability, and policy surface. +- An **Ability** is that logic elevated into a governed protocol object (`easynet:///r//ability/`) with explicit schema, trust posture, execution mode, observability, and policy surface. This is the key move from demos to durable AI products: users buy reliable abilities, not private skill implementations. @@ -134,7 +134,7 @@ Axon defines the full contract for resource naming, invocation semantics, conten | Guarantee | Meaning | | --------------- | ------------------------------------------------------------------------- | -| **Addressable** | Every resource has a canonical URI: `axon:///` | +| **Addressable** | Every resource has a canonical URA: `axon:///` | | **Decidable** | Every operation terminates in a known state | | **Explainable** | Scheduler decisions include explicit reasons | | **Auditable** | Every change emits an `AuditEntry` | @@ -143,16 +143,16 @@ Axon defines the full contract for resource naming, invocation semantics, conten ### Resource Namespace (`axon://`) -| URI | Resource | Managed by | +| URA | Resource | Managed by | | ------------------------------------- | ---------------------- | ------------------- | -| `axon://nodes/` | Node | ControlPlane | -| `axon://capabilities/` | Ability | CapabilityLifecycle | -| `axon://invocations/` | Invocation | Invocation | +| `easynet:///r//device/` | Node | ControlPlane | +| `easynet:///r//ability/` | Ability | CapabilityLifecycle | +| `easynet:///r//resource/invocation/` | Invocation | Invocation | | `axon://missions/` | Mission | MissionControl | | `axon://streams/` | Stream session | Stream | -| `axon://payloads/` | Large payload | PayloadTransfer | +| `easynet:///r//resource//payload/` | Large payload | PayloadTransfer | | `axon://policies/` | Policy | Policy | -| `axon://keys/` | Key material reference | Identity | +| `easynet:///r//resource/session-key/` | Key material reference | Identity | ### Execution Modes @@ -180,7 +180,7 @@ Axon defines the full contract for resource naming, invocation semantics, conten Every protocol-crossing payload (input, output, stream chunk) uses `ContentEnvelope` with explicit MIME type, encoding, and optional schema. -Large payloads are referenced by `PayloadRef` (`axon://payloads/`) and carry full content metadata plus integrity digest. +Large payloads are referenced by `PayloadRef` (`easynet:///r//resource//payload/`) and carry full content metadata plus integrity digest. ## Security Contract @@ -234,7 +234,7 @@ See `document/plans/ecosystem/10-capability-control-plane-evidence-and-paper-pla ## Engineering Principles 1. Close AgentNet first, then expand into EasyNet. -2. Reserve extension hooks early (schema fields, state-machine hooks, URI namespaces). +2. Reserve extension hooks early (schema fields, state-machine hooks, URA namespaces). 3. Keep future EasyNet features out of P0 execution-critical paths until activation. ## Repository Structure diff --git a/core/proto/axon/v1/capability.proto b/core/proto/axon/v1/capability.proto index 434ccc44..f7297990 100644 --- a/core/proto/axon/v1/capability.proto +++ b/core/proto/axon/v1/capability.proto @@ -51,7 +51,7 @@ service CapabilityLifecycle { // This proof is generated from protocol-level payload transfer metadata // plus package signature fingerprinting and is re-validated at install time. message CapabilityPackageProof { - string payload_uri = 1; // must be axon://payloads/ + string payload_ura = 1; // must be EasyNet URA /r//resource//payloads/ string payload_digest = 2; // sha256: int64 payload_size_bytes = 3; // immutable payload size string signature_fingerprint = 4; // sha256 of signature bytes @@ -71,7 +71,7 @@ message PublishPackageRequest { map requirements = 8; // "gpu": "optional", "python": ">=3.10" map metadata = 9; // Payload is uploaded separately via object store; this is metadata only. - string payload_uri = 10; // reference to payload in object store + string payload_ura = 10; // reference to payload in object store uint32 publisher_key_version = 11; // key version used to produce the signature CapabilityPackageProof proof = 12; // integrity + security proof (required in vNext) } @@ -93,7 +93,7 @@ message GetPackageRequest { message GetPackageResponse { ResponseHeader header = 1; CapabilityDescriptor descriptor = 2; - string payload_uri = 3; + string payload_ura = 3; CapabilityPackageProof proof = 4; Error error = 100; } diff --git a/core/proto/axon/v1/control.proto b/core/proto/axon/v1/control.proto index 1f25951f..50858dba 100644 --- a/core/proto/axon/v1/control.proto +++ b/core/proto/axon/v1/control.proto @@ -79,7 +79,7 @@ message RegisterNodeRequest { string owner_id = 11; // principal_id of the owning user string device_group = 12; // "home" | "office" | "lab" | custom DeviceMeta device = 13; // device hardware/OS metadata - // Structured runtime role. UNSPECIFIED defaults to FULL. Legacy callers may + // Structured runtime role. UNSPECIFIED defaults to FULL. Existing callers may // instead set `labels["axon.role"]`; that fallback is honored only when this // field is UNSPECIFIED. NodeRole role = 14; diff --git a/core/proto/axon/v1/federation.proto b/core/proto/axon/v1/federation.proto index 8c09730b..5ca65b23 100644 --- a/core/proto/axon/v1/federation.proto +++ b/core/proto/axon/v1/federation.proto @@ -123,7 +123,7 @@ message FederationHeartbeatResponse { // `false` value means "no action required" and a `true` value means // "refresh your join token out-of-band, then re-join". bool token_refresh_hint = 4; - // Legacy scalar mirror for older clients. + // Scalar mirror for clients that do not read structured membership URA fields. // Semantics: the Hub returns the caller member's own spec version here, // not a federation-global counter. This avoids waking unrelated peers when // some other member changes its ability set. diff --git a/core/proto/axon/v1/invoke.proto b/core/proto/axon/v1/invoke.proto index 19eeeb52..286d00c4 100644 --- a/core/proto/axon/v1/invoke.proto +++ b/core/proto/axon/v1/invoke.proto @@ -94,8 +94,8 @@ service Invocation { // Bidirectional invocation (P5-rewrite-15) — realtime multimodal // sessions. PTY uses the session-as-subject pattern: unary - // `fleet.session_create` mints the session URA, then a single - // InvokeBidi against `fleet.session_attach` carries the + // `device.terminal.create` mints the session URA, then a single + // InvokeBidi against `device.terminal.attach` carries the // bidirectional binary stream until close. rpc InvokeBidi(stream InvokeBidiUp) returns (stream InvokeBidiDown); } @@ -139,9 +139,9 @@ message InvokeResponse { // callee's public key (no runtime contact) can re-compute the // canonical bytes and check the signature independently. // - // Absent for legacy unsigned invocations (no admission ⇒ no signed - // receipt). Absent on admission-reject paths (the Error message - // itself is the wire-visible outcome). + // Absent when no signed admission receipt exists. Absent on + // admission-reject paths (the Error message itself is the + // wire-visible outcome). InvocationReceipt admission_receipt = 14; Error error = 100; } @@ -482,6 +482,12 @@ message EnvelopeOpen { // four AXIOM gates as the other two RPCs (signature_policy → // admission → membership → delegation). map metadata = 6; + + // Full content contract for `initial_args`. Unary and server-stream + // requests already carry this field; bidi frame-0 needs the same + // contract so encrypted or schema-bound session opens do not degrade + // into opaque bytes when routed through InvokeBidi / invoke_remote. + ContentEnvelope content_envelope = 7; } message StreamDescriptor { @@ -704,8 +710,8 @@ message InvocationReceipt { // - signer_binding present + DIFFERENT from callee_binding ⇒ // hosted (Model B). callee_signature MUST verify under // signer_binding's pubkey, AND host_attestation MUST be a - // signature over canonical_host_attestation_bytes(callee_uri, - // signer_uri) by the same signer_binding pubkey. + // signature over canonical_host_attestation_bytes(callee_ura, + // signer_ura) by the same signer_binding pubkey. // // - signer_binding absent OR equal to callee_binding ⇒ // self-signed (Model A). callee_signature verifies under diff --git a/core/proto/axon/v1/observe.proto b/core/proto/axon/v1/observe.proto index 3ffb66d8..c082da93 100644 --- a/core/proto/axon/v1/observe.proto +++ b/core/proto/axon/v1/observe.proto @@ -135,13 +135,13 @@ message GetSLOStatusRequest { enum SLOIndicatorKind { SLO_INDICATOR_KIND_UNSPECIFIED = 0; SLO_INDICATOR_KIND_THRESHOLD = 1; // compared against threshold_target - SLO_INDICATOR_KIND_COUNTER = 2; // monotonic/process counter; target is legacy mirror - SLO_INDICATOR_KIND_GAUGE = 3; // point-in-time value; target is legacy mirror + SLO_INDICATOR_KIND_COUNTER = 2; // monotonic/process counter; target is a scalar mirror + SLO_INDICATOR_KIND_GAUGE = 3; // point-in-time value; target is a scalar mirror } message SLOIndicator { string name = 1; // "invoke_success_rate" | "p99_latency_ms" | "stream_cancel_latency_ms" - double target = 2; // legacy target mirror for compatibility with existing clients + double target = 2; // scalar target mirror for existing clients double current = 3; // actual measured value bool in_compliance = 4; string window = 5; // "1h" | "24h" | "7d" diff --git a/core/proto/axon/v1/transfer.proto b/core/proto/axon/v1/transfer.proto index b20f91c4..09cdbcaf 100644 --- a/core/proto/axon/v1/transfer.proto +++ b/core/proto/axon/v1/transfer.proto @@ -9,7 +9,7 @@ import "axon/v1/types.proto"; // // Part of the Axon content contract: every payload that // exceeds inline gRPC limits is stored as a protocol-level -// resource addressed via axon://payloads/. +// resource addressed via EasyNet URA /r//resource//payloads/. // // Any Axon subsystem (invocation, mission, capability, stream) // can reference PayloadRef objects managed by this service. @@ -68,7 +68,7 @@ message UploadFinalBody { message UploadPayloadResponse { ResponseHeader header = 1; - PayloadRef ref = 2; // complete PayloadRef with axon://payloads/ URI + PayloadRef ref = 2; // complete PayloadRef with EasyNet URA /r//resource//payloads/ URA Error error = 100; } @@ -76,7 +76,7 @@ message UploadPayloadResponse { message DownloadPayloadRequest { Envelope envelope = 1; - string uri = 2; // axon://payloads/ + string ura = 2; // EasyNet URA /r//resource//payloads/ int64 offset = 3; // byte offset for resume (protocol resumability); 0 = start int64 limit = 4; // max bytes to return; 0 = all remaining } @@ -94,7 +94,7 @@ message DownloadPayloadResponse { message GetPayloadMetaRequest { Envelope envelope = 1; - string uri = 2; // axon://payloads/ + string ura = 2; // EasyNet URA /r//resource//payloads/ } message GetPayloadMetaResponse { @@ -107,7 +107,7 @@ message GetPayloadMetaResponse { message DeletePayloadRequest { Envelope envelope = 1; - string uri = 2; // axon://payloads/ + string ura = 2; // EasyNet URA /r//resource//payloads/ } message DeletePayloadResponse { diff --git a/core/proto/axon/v1/types.proto b/core/proto/axon/v1/types.proto index f4cd48c8..5e59232f 100644 --- a/core/proto/axon/v1/types.proto +++ b/core/proto/axon/v1/types.proto @@ -38,8 +38,8 @@ package axon.v1; // // ─── Protocol Guarantees ───────────────────────────────── // -// Addressable: every resource has a canonical URI -// axon:/// +// Addressable: every identity/resource has a canonical URA +// EasyNet URA /r/// // Decidable: every operation terminates in a known state // Explainable: every scheduling decision carries a reason // Auditable: every mutation produces an AuditEntry @@ -47,14 +47,14 @@ package axon.v1; // // ─── Resource Namespace ────────────────────────────────── // -// axon://nodes/ -// axon://capabilities/ -// axon://invocations/ -// axon://missions/ -// axon://streams/ -// axon://payloads/ -// axon://policies/ -// axon://keys/ +// EasyNet URA /r//device/ +// EasyNet URA /r//ability/.. +// EasyNet URA /r//resource//invocations/ +// EasyNet URA /r//resource//missions/ +// EasyNet URA /r//resource/device./streams/ +// EasyNet URA /r//resource//payloads/ +// EasyNet URA /r//resource//policies/ +// EasyNet URA /r//resource//keys/ // // ─── Execution Modes ───────────────────────────────────── // @@ -66,9 +66,9 @@ package axon.v1; // ─── Content Contract ──────────────────────────────────── // // Every payload (arguments, results, stream chunks) carries -// a ContentEnvelope that declares MIME type, encoding, and -// optional schema. Large or multimedia payloads use PayloadRef -// with axon://payloads/ addressing + ContentMeta. +// a ContentEnvelope that declares MIME type, encoding, encryption, +// and optional schema. Large or multimedia payloads use PayloadRef +// with a full EasyNet URA + ContentMeta. // // ─── Security Contract ────────────────────────────────── // @@ -116,28 +116,30 @@ package axon.v1; // ─── Protocol: Resource Addressing ────────────────────── // Exhaustive list of first-class Axon resource kinds. -// Each kind maps to a canonical URI: axon:/// +// Each kind maps to a canonical URA. `ResourceRef.ura` carries the +// complete `EasyNet URA /r//...` locator; do not reconstruct it +// from fragments in application code. enum ResourceType { RESOURCE_TYPE_UNSPECIFIED = 0; - RESOURCE_TYPE_NODE = 1; // axon://nodes/ - RESOURCE_TYPE_CAPABILITY = 2; // axon://capabilities/ - RESOURCE_TYPE_INVOCATION = 3; // axon://invocations/ - RESOURCE_TYPE_MISSION = 4; // axon://missions/ - RESOURCE_TYPE_STREAM = 5; // axon://streams/ - RESOURCE_TYPE_PAYLOAD = 6; // axon://payloads/ - RESOURCE_TYPE_POLICY = 7; // axon://policies/ - RESOURCE_TYPE_KEY = 8; // axon://keys/ + RESOURCE_TYPE_NODE = 1; // EasyNet URA /r//device/ + RESOURCE_TYPE_CAPABILITY = 2; // EasyNet URA /r//ability/.. + RESOURCE_TYPE_INVOCATION = 3; // EasyNet URA /r//resource//invocations/ + RESOURCE_TYPE_MISSION = 4; // EasyNet URA /r//resource//missions/ + RESOURCE_TYPE_STREAM = 5; // EasyNet URA /r//resource/device./streams/ + RESOURCE_TYPE_PAYLOAD = 6; // EasyNet URA /r//resource//payloads/ + RESOURCE_TYPE_POLICY = 7; // EasyNet URA /r//resource//policies/ + RESOURCE_TYPE_KEY = 8; // EasyNet URA /r//resource//keys/ } // Typed reference to any Axon-managed resource. -// The canonical URI is: axon:///[/] -// Example: axon://missions/m-42/steps/step-3 +// The canonical locator is always the full URA in `ura`. +// Example: EasyNet URA /r/acme/resource/alice.invocations/req-42 message ResourceRef { ResourceType type = 1; string resource_id = 2; // primary identifier string sub_id = 3; // optional: step_id, rule_id, key_version, etc. string tenant_id = 4; - string uri = 5; // canonical form (computed from type + id) + string ura = 5; // full canonical URA supplied by the URA builder } // ─── Protocol: Execution Semantics ────────────────────── @@ -247,7 +249,7 @@ message SchedulingScore { message ContentEnvelope { string content_type = 1; // MIME: "application/json", "image/png", ... string encoding = 2; // "identity" | "gzip" | "zstd" - string schema_uri = 3; // optional: axon://schemas/ + string schema_ura = 3; // optional full URA for schema resource ContentMeta meta = 4; // multimedia metadata (when applicable) EncryptionAlgorithm encryption = 5; // UNSPECIFIED = plaintext string key_id = 6; // session key used for E2E encryption @@ -276,11 +278,11 @@ message ChannelSecurity { // can decrypt. Key exchange uses ECDH via Identity.NegotiateSessionKey. // // Flow: -// 1. Source calls Identity.NegotiateSessionKey → session_key_id -// 2. Source encrypts payload → EncryptedPayload +// 1. Source negotiates or obtains a recipient encryption public key +// 2. Source encrypts payload → EncryptedPayload bytes // 3. ContentEnvelope.encryption + key_id declare the scheme // 4. Intermediaries forward ciphertext without access -// 5. Destination retrieves session key → decrypts +// 5. Destination retrieves the key material → decrypts enum EncryptionAlgorithm { ENCRYPTION_UNSPECIFIED = 0; // plaintext — no encryption applied @@ -292,17 +294,18 @@ enum EncryptionAlgorithm { // end-to-end confidentiality across intermediary nodes. message EncryptedPayload { EncryptionAlgorithm algorithm = 1; - string key_id = 2; // axon://keys/session/ + string key_id = 2; // full URA or stable key identifier for the recipient key bytes nonce = 3; // unique per encryption operation (12 bytes for GCM/Poly1305) bytes ciphertext = 4; // encrypted data bytes auth_tag = 5; // authentication tag bytes aad = 6; // additional authenticated data (e.g. serialized Envelope) + bytes ephemeral_public_key = 7; // sender ephemeral X25519 public key } // ─── Protocol: Axiom Identity (RFC 001 §3.1) ──────────── // // URA v2 composite identity. The `profile` selector is structurally bound -// to the URI it profiles — see AXIOM.tex §5.4 Axis B. +// to the URA it profiles — see AXIOM.tex §5.4 Axis B. // // Canonicalisation: URA §3 verbatim. Axon does not re-specify. // @@ -310,8 +313,8 @@ message EncryptedPayload { message AgentIdentity { // URA canonical form per URA §3. Example: - // "easynet:///r/silan/agents/quote-bot@1.0" - string uri = 1; + // "EasyNet URA /r/silan/agent/alice.quote-bot" + string ura = 1; // URA profile selector. Known values: // "easynet-strict-v2" — RFC 001 default. @@ -326,7 +329,7 @@ message AgentIdentity { } message SubjectIdentity { - string uri = 1; + string ura = 1; string profile = 2; reserved 3, 4; } @@ -352,7 +355,7 @@ message ReceiptRef { // SHA-256 over the referenced receipt's canonical bytes. 32 bytes. bytes receipt_hash = 1; // URA locator for auditor fetch. Required. - string receipt_uri = 2; + string receipt_ura = 2; } message ReceiptList { @@ -363,7 +366,7 @@ message ReceiptList { message MerkleRoot { bytes root = 1; // 32 bytes - string proof_uri = 2; // URA of the published proof artefact + string proof_ura = 2; // URA of the published proof artefact } // ─── Protocol: Axiom Signatures (RFC 001 §3.5, §3.6) ──── @@ -395,7 +398,7 @@ message CalleeSignature { // idempotency, deadline, trace). See document/concepts/AXIOM.tex §2 and // RFC 001 §3.2. // -// Pre-release notice (RFC 001 v0.2 overlay). Four legacy fields — field +// Pre-release notice (RFC 001 v0.2 overlay). Four compatibility fields — field // numbers 3, 4, 5, 12 — have been removed. They were superseded by the // axiom 7-tuple, and since Axon is pre-release there is no v1 wire to // keep compatible: @@ -459,6 +462,137 @@ message Error { map context = 4; } +// ─── Protocol: Invocation Ledger ──────────────────────── +// +// Invocation ledger records are the participant-facing audit surface for +// invoke history. They carry full URAs from the original envelope and +// store content as either digests or recipient-sealed encrypted payloads. +// Operators may index request/trace/state metadata, but plaintext args, +// results, and logs must be visible only to authorised participants. + +enum LedgerEventPayloadKind { + LEDGER_EVENT_PAYLOAD_KIND_UNSPECIFIED = 0; + LEDGER_EVENT_PAYLOAD_KIND_DIGEST = 1; + LEDGER_EVENT_PAYLOAD_KIND_SEALED = 2; + LEDGER_EVENT_PAYLOAD_KIND_MULTI_SEALED = 3; +} + +message SealedLedgerEventPayload { + string algorithm = 1; // e.g. x25519-chacha20poly1305-sha256-aad-v1 + bytes recipient_public_key = 2; // encryption key, not signing key + bytes ephemeral_public_key = 3; + bytes nonce = 4; + string aad_sha256 = 5; + string plaintext_sha256 = 6; + bytes ciphertext = 7; +} + +message LedgerEventPayload { + LedgerEventPayloadKind kind = 1; + string content_type = 2; + string sha256 = 3; // present for digest payloads + uint64 size_bytes = 4; // present for digest payloads + SealedLedgerEventPayload sealed = 5; + repeated RecipientSealedLedgerEventPayload recipients = 6; +} + +message RecipientSealedLedgerEventPayload { + string recipient_ura = 1; + SealedLedgerEventPayload payload = 2; +} + +message LedgerPayloadVisibility { + string policy = 1; // digest_only | sealed_single_recipient | sealed_explicit_recipients + string content_type = 2; + bool encrypted = 3; + bool recoverable = 4; + repeated string recipient_uras = 5; + uint64 size_bytes = 6; +} + +message LedgerVisibilitySummary { + LedgerPayloadVisibility args = 1; + LedgerPayloadVisibility result = 2; + repeated LedgerPayloadVisibility diagnostics = 3; +} + +message LedgerErrorRecord { + string source = 1; + string code = 2; + string message = 3; + bool retryable = 4; + map context = 5; +} + +message LedgerDiagnosticRecord { + int64 timestamp_unix_ms = 1; + string level = 2; + string source = 3; + string code = 4; + string message = 5; + bool retryable = 6; + LedgerEventPayload payload = 7; +} + +message InvocationReceiptAnchor { + string receipt_ura = 1; + string receipt_hash = 2; + string receipt_type = 3; + string state = 4; + int64 timestamp_unix_ms = 5; +} + +message InvocationReceiptChainSummary { + repeated InvocationReceiptAnchor anchors = 1; + bool verified = 2; + string head_receipt_hash = 3; + string verification_detail = 4; +} + +message InvocationCausalLink { + string source_invocation_ura = 1; + string source_receipt_ura = 2; + string source_receipt_hash = 3; + string relation = 4; +} + +message InvocationTraceEdge { + string from_invocation_ura = 1; + string from_receipt_ura = 2; + string from_receipt_hash = 3; + string to_invocation_ura = 4; + string relation = 5; +} + +message InvocationTraceGraph { + string trace_id = 1; + repeated InvocationLedgerRecord records = 2; + repeated InvocationTraceEdge edges = 3; +} + +message InvocationLedgerRecord { + string invocation_ura = 1; + string request_id = 2; + string trace_id = 3; + string span_id = 4; + string caller_ura = 5; + string callee_ura = 6; + string subject_ura = 7; + string ability_ura = 8; + string ability_name = 9; + string state = 10; + int64 started_unix_ms = 11; + int64 completed_unix_ms = 12; + uint64 elapsed_ms = 13; + LedgerEventPayload args = 14; + LedgerEventPayload result = 15; + LedgerErrorRecord error = 16; + repeated LedgerDiagnosticRecord diagnostics = 17; + repeated InvocationCausalLink causal_links = 18; + InvocationReceiptChainSummary receipt_chain = 19; + LedgerVisibilitySummary visibility = 20; +} + // ─── Node ─────────────────────────────────────────────── // Node lifecycle state machine: @@ -831,7 +965,7 @@ message ContentMeta { // ─── Protocol: Large Payload Reference ────────────────── // Reference to a large or out-of-band payload managed by the -// Axon protocol. Addressed via axon://payloads/. +// Axon protocol. Addressed via EasyNet URA /r//resource//payloads/. // // Used instead of inline bytes when payload exceeds practical // gRPC message limits or needs independent lifecycle management. @@ -839,9 +973,9 @@ message ContentMeta { // PayloadRef over inline request/response bytes to keep RPC frames small // and to make retries/resume semantics independent from a single call. // Storage backends are an implementation detail invisible to callers — -// the protocol only exposes the axon:// URI. +// the protocol only exposes the full EasyNet URA. message PayloadRef { - string uri = 1; // axon://payloads/ + string ura = 1; // EasyNet URA /r//resource//payloads/ string digest = 2; // "sha256:" integrity hash int64 size_bytes = 3; ContentEnvelope content = 4; // content negotiation (type + encoding + schema + meta) @@ -876,7 +1010,7 @@ enum EasyNetHook { message EasyNetContext { string intent_id = 1; // future: intent that triggered this operation - string plan_graph_ref = 2; // future: axon://plans/ + string plan_graph_ref = 2; // future: EasyNet URA /r//resource//plans/ ObjectiveWeights objectives = 3; // future: multi-objective weights double budget_limit = 4; // future: max credit spend for this operation double reputation_min_score = 5; // future: minimum reputation score for node selection diff --git a/core/proto/axon/v1/voice.proto b/core/proto/axon/v1/voice.proto index 80c702ec..f49cf26e 100644 --- a/core/proto/axon/v1/voice.proto +++ b/core/proto/axon/v1/voice.proto @@ -167,7 +167,7 @@ message CallParticipant { string node_id = 3; bool muted = 4; VoiceTransportKind transport = 5; - string stream_session_id = 6; // axon://streams/ materialized id + string stream_session_id = 6; // EasyNet URA /r//resource/device./streams/ materialized id VoiceCodecProfile codec_profile = 7; VoiceNetworkMetrics latest_metrics = 8; int64 joined_at_unix_ms = 9; diff --git a/core/runtime-rs/Cargo.lock b/core/runtime-rs/Cargo.lock index a6f27157..945620f4 100644 --- a/core/runtime-rs/Cargo.lock +++ b/core/runtime-rs/Cargo.lock @@ -473,6 +473,7 @@ version = "0.55.2" dependencies = [ "anyhow", "base64", + "chacha20poly1305", "ed25519-dalek", "hex", "hkdf", @@ -488,6 +489,7 @@ dependencies = [ "tonic", "tonic-build", "uuid", + "x25519-dalek", ] [[package]] diff --git a/core/runtime-rs/README.md b/core/runtime-rs/README.md index d29d0a6b..9b79e46c 100644 --- a/core/runtime-rs/README.md +++ b/core/runtime-rs/README.md @@ -46,7 +46,7 @@ Agent-native platforms need more than fast RPC handlers. They need deterministic The runtime distinguishes implementation logic from network contract: - Skill: local code path inside a node. -- Ability: typed protocol object (`axon://capabilities/`) with schema, policy, trust posture, and execution semantics. +- Ability: typed protocol object (`easynet:///r//ability/`) with schema, policy, trust posture, and execution semantics. - Capability: the runtime/proto name used by descriptors, lifecycle RPCs, and scheduler metadata for that ability contract. - Install: the node-scoped realization of one capability package version after materialization. diff --git a/core/runtime-rs/client-sdk/Cargo.lock b/core/runtime-rs/client-sdk/Cargo.lock index 5c6c9a6a..26464550 100644 --- a/core/runtime-rs/client-sdk/Cargo.lock +++ b/core/runtime-rs/client-sdk/Cargo.lock @@ -2,6 +2,16 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -154,6 +164,41 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -176,6 +221,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -233,6 +279,7 @@ version = "0.55.2" dependencies = [ "anyhow", "base64", + "chacha20poly1305", "ed25519-dalek", "hex", "hkdf", @@ -248,6 +295,7 @@ dependencies = [ "tonic", "tonic-build", "uuid", + "x25519-dalek", ] [[package]] @@ -597,6 +645,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "itertools" version = "0.14.0" @@ -687,6 +744,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -739,6 +802,17 @@ dependencies = [ "spki", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1327,6 +1401,16 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "uuid" version = "1.23.0" @@ -1632,6 +1716,18 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core", + "serde", + "zeroize", +] + [[package]] name = "zerocopy" version = "0.8.48" @@ -1657,6 +1753,20 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "zmij" diff --git a/core/runtime-rs/client-sdk/Cargo.toml b/core/runtime-rs/client-sdk/Cargo.toml index 200e137a..459bdac9 100644 --- a/core/runtime-rs/client-sdk/Cargo.toml +++ b/core/runtime-rs/client-sdk/Cargo.toml @@ -22,6 +22,7 @@ include = [ [dependencies] anyhow = "1.0" base64 = "0.22" +chacha20poly1305 = "0.10" ed25519-dalek = "2.1" hex = "0.4" # HKDF + HMAC drive the InvokeBidi frame-chain MAC per @@ -39,6 +40,7 @@ tonic = { version = "0.12", features = ["transport"] } tokio = { version = "1.42", features = ["rt-multi-thread", "macros"] } tokio-stream = "0.1" uuid = { version = "1.11", features = ["v4"] } +x25519-dalek = { version = "2.0", features = ["static_secrets"] } [build-dependencies] protoc-bin-vendored = "3.2.0" diff --git a/core/runtime-rs/client-sdk/README.md b/core/runtime-rs/client-sdk/README.md index 4b8fd422..e8cd32f1 100644 --- a/core/runtime-rs/client-sdk/README.md +++ b/core/runtime-rs/client-sdk/README.md @@ -65,7 +65,7 @@ Low-level form: ```rust let options = AbilityCallOptions::default(); let resp = client - .call_ability_uri_json( + .call_ability_ura_json( "tenant-test", "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", br#"{"sku":"A1","qty":2}"#.to_vec(), diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/capability.proto b/core/runtime-rs/client-sdk/proto/axon/v1/capability.proto index 434ccc44..f7297990 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/capability.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/capability.proto @@ -51,7 +51,7 @@ service CapabilityLifecycle { // This proof is generated from protocol-level payload transfer metadata // plus package signature fingerprinting and is re-validated at install time. message CapabilityPackageProof { - string payload_uri = 1; // must be axon://payloads/ + string payload_ura = 1; // must be EasyNet URA /r//resource//payloads/ string payload_digest = 2; // sha256: int64 payload_size_bytes = 3; // immutable payload size string signature_fingerprint = 4; // sha256 of signature bytes @@ -71,7 +71,7 @@ message PublishPackageRequest { map requirements = 8; // "gpu": "optional", "python": ">=3.10" map metadata = 9; // Payload is uploaded separately via object store; this is metadata only. - string payload_uri = 10; // reference to payload in object store + string payload_ura = 10; // reference to payload in object store uint32 publisher_key_version = 11; // key version used to produce the signature CapabilityPackageProof proof = 12; // integrity + security proof (required in vNext) } @@ -93,7 +93,7 @@ message GetPackageRequest { message GetPackageResponse { ResponseHeader header = 1; CapabilityDescriptor descriptor = 2; - string payload_uri = 3; + string payload_ura = 3; CapabilityPackageProof proof = 4; Error error = 100; } diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/control.proto b/core/runtime-rs/client-sdk/proto/axon/v1/control.proto index 1f25951f..50858dba 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/control.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/control.proto @@ -79,7 +79,7 @@ message RegisterNodeRequest { string owner_id = 11; // principal_id of the owning user string device_group = 12; // "home" | "office" | "lab" | custom DeviceMeta device = 13; // device hardware/OS metadata - // Structured runtime role. UNSPECIFIED defaults to FULL. Legacy callers may + // Structured runtime role. UNSPECIFIED defaults to FULL. Existing callers may // instead set `labels["axon.role"]`; that fallback is honored only when this // field is UNSPECIFIED. NodeRole role = 14; diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/federation.proto b/core/runtime-rs/client-sdk/proto/axon/v1/federation.proto index 8c09730b..5ca65b23 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/federation.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/federation.proto @@ -123,7 +123,7 @@ message FederationHeartbeatResponse { // `false` value means "no action required" and a `true` value means // "refresh your join token out-of-band, then re-join". bool token_refresh_hint = 4; - // Legacy scalar mirror for older clients. + // Scalar mirror for clients that do not read structured membership URA fields. // Semantics: the Hub returns the caller member's own spec version here, // not a federation-global counter. This avoids waking unrelated peers when // some other member changes its ability set. diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/invoke.proto b/core/runtime-rs/client-sdk/proto/axon/v1/invoke.proto index 19eeeb52..286d00c4 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/invoke.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/invoke.proto @@ -94,8 +94,8 @@ service Invocation { // Bidirectional invocation (P5-rewrite-15) — realtime multimodal // sessions. PTY uses the session-as-subject pattern: unary - // `fleet.session_create` mints the session URA, then a single - // InvokeBidi against `fleet.session_attach` carries the + // `device.terminal.create` mints the session URA, then a single + // InvokeBidi against `device.terminal.attach` carries the // bidirectional binary stream until close. rpc InvokeBidi(stream InvokeBidiUp) returns (stream InvokeBidiDown); } @@ -139,9 +139,9 @@ message InvokeResponse { // callee's public key (no runtime contact) can re-compute the // canonical bytes and check the signature independently. // - // Absent for legacy unsigned invocations (no admission ⇒ no signed - // receipt). Absent on admission-reject paths (the Error message - // itself is the wire-visible outcome). + // Absent when no signed admission receipt exists. Absent on + // admission-reject paths (the Error message itself is the + // wire-visible outcome). InvocationReceipt admission_receipt = 14; Error error = 100; } @@ -482,6 +482,12 @@ message EnvelopeOpen { // four AXIOM gates as the other two RPCs (signature_policy → // admission → membership → delegation). map metadata = 6; + + // Full content contract for `initial_args`. Unary and server-stream + // requests already carry this field; bidi frame-0 needs the same + // contract so encrypted or schema-bound session opens do not degrade + // into opaque bytes when routed through InvokeBidi / invoke_remote. + ContentEnvelope content_envelope = 7; } message StreamDescriptor { @@ -704,8 +710,8 @@ message InvocationReceipt { // - signer_binding present + DIFFERENT from callee_binding ⇒ // hosted (Model B). callee_signature MUST verify under // signer_binding's pubkey, AND host_attestation MUST be a - // signature over canonical_host_attestation_bytes(callee_uri, - // signer_uri) by the same signer_binding pubkey. + // signature over canonical_host_attestation_bytes(callee_ura, + // signer_ura) by the same signer_binding pubkey. // // - signer_binding absent OR equal to callee_binding ⇒ // self-signed (Model A). callee_signature verifies under diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/observe.proto b/core/runtime-rs/client-sdk/proto/axon/v1/observe.proto index 3ffb66d8..c082da93 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/observe.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/observe.proto @@ -135,13 +135,13 @@ message GetSLOStatusRequest { enum SLOIndicatorKind { SLO_INDICATOR_KIND_UNSPECIFIED = 0; SLO_INDICATOR_KIND_THRESHOLD = 1; // compared against threshold_target - SLO_INDICATOR_KIND_COUNTER = 2; // monotonic/process counter; target is legacy mirror - SLO_INDICATOR_KIND_GAUGE = 3; // point-in-time value; target is legacy mirror + SLO_INDICATOR_KIND_COUNTER = 2; // monotonic/process counter; target is a scalar mirror + SLO_INDICATOR_KIND_GAUGE = 3; // point-in-time value; target is a scalar mirror } message SLOIndicator { string name = 1; // "invoke_success_rate" | "p99_latency_ms" | "stream_cancel_latency_ms" - double target = 2; // legacy target mirror for compatibility with existing clients + double target = 2; // scalar target mirror for existing clients double current = 3; // actual measured value bool in_compliance = 4; string window = 5; // "1h" | "24h" | "7d" diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/transfer.proto b/core/runtime-rs/client-sdk/proto/axon/v1/transfer.proto index b20f91c4..09cdbcaf 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/transfer.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/transfer.proto @@ -9,7 +9,7 @@ import "axon/v1/types.proto"; // // Part of the Axon content contract: every payload that // exceeds inline gRPC limits is stored as a protocol-level -// resource addressed via axon://payloads/. +// resource addressed via EasyNet URA /r//resource//payloads/. // // Any Axon subsystem (invocation, mission, capability, stream) // can reference PayloadRef objects managed by this service. @@ -68,7 +68,7 @@ message UploadFinalBody { message UploadPayloadResponse { ResponseHeader header = 1; - PayloadRef ref = 2; // complete PayloadRef with axon://payloads/ URI + PayloadRef ref = 2; // complete PayloadRef with EasyNet URA /r//resource//payloads/ URA Error error = 100; } @@ -76,7 +76,7 @@ message UploadPayloadResponse { message DownloadPayloadRequest { Envelope envelope = 1; - string uri = 2; // axon://payloads/ + string ura = 2; // EasyNet URA /r//resource//payloads/ int64 offset = 3; // byte offset for resume (protocol resumability); 0 = start int64 limit = 4; // max bytes to return; 0 = all remaining } @@ -94,7 +94,7 @@ message DownloadPayloadResponse { message GetPayloadMetaRequest { Envelope envelope = 1; - string uri = 2; // axon://payloads/ + string ura = 2; // EasyNet URA /r//resource//payloads/ } message GetPayloadMetaResponse { @@ -107,7 +107,7 @@ message GetPayloadMetaResponse { message DeletePayloadRequest { Envelope envelope = 1; - string uri = 2; // axon://payloads/ + string ura = 2; // EasyNet URA /r//resource//payloads/ } message DeletePayloadResponse { diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/types.proto b/core/runtime-rs/client-sdk/proto/axon/v1/types.proto index f4cd48c8..5e59232f 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/types.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/types.proto @@ -38,8 +38,8 @@ package axon.v1; // // ─── Protocol Guarantees ───────────────────────────────── // -// Addressable: every resource has a canonical URI -// axon:/// +// Addressable: every identity/resource has a canonical URA +// EasyNet URA /r/// // Decidable: every operation terminates in a known state // Explainable: every scheduling decision carries a reason // Auditable: every mutation produces an AuditEntry @@ -47,14 +47,14 @@ package axon.v1; // // ─── Resource Namespace ────────────────────────────────── // -// axon://nodes/ -// axon://capabilities/ -// axon://invocations/ -// axon://missions/ -// axon://streams/ -// axon://payloads/ -// axon://policies/ -// axon://keys/ +// EasyNet URA /r//device/ +// EasyNet URA /r//ability/.. +// EasyNet URA /r//resource//invocations/ +// EasyNet URA /r//resource//missions/ +// EasyNet URA /r//resource/device./streams/ +// EasyNet URA /r//resource//payloads/ +// EasyNet URA /r//resource//policies/ +// EasyNet URA /r//resource//keys/ // // ─── Execution Modes ───────────────────────────────────── // @@ -66,9 +66,9 @@ package axon.v1; // ─── Content Contract ──────────────────────────────────── // // Every payload (arguments, results, stream chunks) carries -// a ContentEnvelope that declares MIME type, encoding, and -// optional schema. Large or multimedia payloads use PayloadRef -// with axon://payloads/ addressing + ContentMeta. +// a ContentEnvelope that declares MIME type, encoding, encryption, +// and optional schema. Large or multimedia payloads use PayloadRef +// with a full EasyNet URA + ContentMeta. // // ─── Security Contract ────────────────────────────────── // @@ -116,28 +116,30 @@ package axon.v1; // ─── Protocol: Resource Addressing ────────────────────── // Exhaustive list of first-class Axon resource kinds. -// Each kind maps to a canonical URI: axon:/// +// Each kind maps to a canonical URA. `ResourceRef.ura` carries the +// complete `EasyNet URA /r//...` locator; do not reconstruct it +// from fragments in application code. enum ResourceType { RESOURCE_TYPE_UNSPECIFIED = 0; - RESOURCE_TYPE_NODE = 1; // axon://nodes/ - RESOURCE_TYPE_CAPABILITY = 2; // axon://capabilities/ - RESOURCE_TYPE_INVOCATION = 3; // axon://invocations/ - RESOURCE_TYPE_MISSION = 4; // axon://missions/ - RESOURCE_TYPE_STREAM = 5; // axon://streams/ - RESOURCE_TYPE_PAYLOAD = 6; // axon://payloads/ - RESOURCE_TYPE_POLICY = 7; // axon://policies/ - RESOURCE_TYPE_KEY = 8; // axon://keys/ + RESOURCE_TYPE_NODE = 1; // EasyNet URA /r//device/ + RESOURCE_TYPE_CAPABILITY = 2; // EasyNet URA /r//ability/.. + RESOURCE_TYPE_INVOCATION = 3; // EasyNet URA /r//resource//invocations/ + RESOURCE_TYPE_MISSION = 4; // EasyNet URA /r//resource//missions/ + RESOURCE_TYPE_STREAM = 5; // EasyNet URA /r//resource/device./streams/ + RESOURCE_TYPE_PAYLOAD = 6; // EasyNet URA /r//resource//payloads/ + RESOURCE_TYPE_POLICY = 7; // EasyNet URA /r//resource//policies/ + RESOURCE_TYPE_KEY = 8; // EasyNet URA /r//resource//keys/ } // Typed reference to any Axon-managed resource. -// The canonical URI is: axon:///[/] -// Example: axon://missions/m-42/steps/step-3 +// The canonical locator is always the full URA in `ura`. +// Example: EasyNet URA /r/acme/resource/alice.invocations/req-42 message ResourceRef { ResourceType type = 1; string resource_id = 2; // primary identifier string sub_id = 3; // optional: step_id, rule_id, key_version, etc. string tenant_id = 4; - string uri = 5; // canonical form (computed from type + id) + string ura = 5; // full canonical URA supplied by the URA builder } // ─── Protocol: Execution Semantics ────────────────────── @@ -247,7 +249,7 @@ message SchedulingScore { message ContentEnvelope { string content_type = 1; // MIME: "application/json", "image/png", ... string encoding = 2; // "identity" | "gzip" | "zstd" - string schema_uri = 3; // optional: axon://schemas/ + string schema_ura = 3; // optional full URA for schema resource ContentMeta meta = 4; // multimedia metadata (when applicable) EncryptionAlgorithm encryption = 5; // UNSPECIFIED = plaintext string key_id = 6; // session key used for E2E encryption @@ -276,11 +278,11 @@ message ChannelSecurity { // can decrypt. Key exchange uses ECDH via Identity.NegotiateSessionKey. // // Flow: -// 1. Source calls Identity.NegotiateSessionKey → session_key_id -// 2. Source encrypts payload → EncryptedPayload +// 1. Source negotiates or obtains a recipient encryption public key +// 2. Source encrypts payload → EncryptedPayload bytes // 3. ContentEnvelope.encryption + key_id declare the scheme // 4. Intermediaries forward ciphertext without access -// 5. Destination retrieves session key → decrypts +// 5. Destination retrieves the key material → decrypts enum EncryptionAlgorithm { ENCRYPTION_UNSPECIFIED = 0; // plaintext — no encryption applied @@ -292,17 +294,18 @@ enum EncryptionAlgorithm { // end-to-end confidentiality across intermediary nodes. message EncryptedPayload { EncryptionAlgorithm algorithm = 1; - string key_id = 2; // axon://keys/session/ + string key_id = 2; // full URA or stable key identifier for the recipient key bytes nonce = 3; // unique per encryption operation (12 bytes for GCM/Poly1305) bytes ciphertext = 4; // encrypted data bytes auth_tag = 5; // authentication tag bytes aad = 6; // additional authenticated data (e.g. serialized Envelope) + bytes ephemeral_public_key = 7; // sender ephemeral X25519 public key } // ─── Protocol: Axiom Identity (RFC 001 §3.1) ──────────── // // URA v2 composite identity. The `profile` selector is structurally bound -// to the URI it profiles — see AXIOM.tex §5.4 Axis B. +// to the URA it profiles — see AXIOM.tex §5.4 Axis B. // // Canonicalisation: URA §3 verbatim. Axon does not re-specify. // @@ -310,8 +313,8 @@ message EncryptedPayload { message AgentIdentity { // URA canonical form per URA §3. Example: - // "easynet:///r/silan/agents/quote-bot@1.0" - string uri = 1; + // "EasyNet URA /r/silan/agent/alice.quote-bot" + string ura = 1; // URA profile selector. Known values: // "easynet-strict-v2" — RFC 001 default. @@ -326,7 +329,7 @@ message AgentIdentity { } message SubjectIdentity { - string uri = 1; + string ura = 1; string profile = 2; reserved 3, 4; } @@ -352,7 +355,7 @@ message ReceiptRef { // SHA-256 over the referenced receipt's canonical bytes. 32 bytes. bytes receipt_hash = 1; // URA locator for auditor fetch. Required. - string receipt_uri = 2; + string receipt_ura = 2; } message ReceiptList { @@ -363,7 +366,7 @@ message ReceiptList { message MerkleRoot { bytes root = 1; // 32 bytes - string proof_uri = 2; // URA of the published proof artefact + string proof_ura = 2; // URA of the published proof artefact } // ─── Protocol: Axiom Signatures (RFC 001 §3.5, §3.6) ──── @@ -395,7 +398,7 @@ message CalleeSignature { // idempotency, deadline, trace). See document/concepts/AXIOM.tex §2 and // RFC 001 §3.2. // -// Pre-release notice (RFC 001 v0.2 overlay). Four legacy fields — field +// Pre-release notice (RFC 001 v0.2 overlay). Four compatibility fields — field // numbers 3, 4, 5, 12 — have been removed. They were superseded by the // axiom 7-tuple, and since Axon is pre-release there is no v1 wire to // keep compatible: @@ -459,6 +462,137 @@ message Error { map context = 4; } +// ─── Protocol: Invocation Ledger ──────────────────────── +// +// Invocation ledger records are the participant-facing audit surface for +// invoke history. They carry full URAs from the original envelope and +// store content as either digests or recipient-sealed encrypted payloads. +// Operators may index request/trace/state metadata, but plaintext args, +// results, and logs must be visible only to authorised participants. + +enum LedgerEventPayloadKind { + LEDGER_EVENT_PAYLOAD_KIND_UNSPECIFIED = 0; + LEDGER_EVENT_PAYLOAD_KIND_DIGEST = 1; + LEDGER_EVENT_PAYLOAD_KIND_SEALED = 2; + LEDGER_EVENT_PAYLOAD_KIND_MULTI_SEALED = 3; +} + +message SealedLedgerEventPayload { + string algorithm = 1; // e.g. x25519-chacha20poly1305-sha256-aad-v1 + bytes recipient_public_key = 2; // encryption key, not signing key + bytes ephemeral_public_key = 3; + bytes nonce = 4; + string aad_sha256 = 5; + string plaintext_sha256 = 6; + bytes ciphertext = 7; +} + +message LedgerEventPayload { + LedgerEventPayloadKind kind = 1; + string content_type = 2; + string sha256 = 3; // present for digest payloads + uint64 size_bytes = 4; // present for digest payloads + SealedLedgerEventPayload sealed = 5; + repeated RecipientSealedLedgerEventPayload recipients = 6; +} + +message RecipientSealedLedgerEventPayload { + string recipient_ura = 1; + SealedLedgerEventPayload payload = 2; +} + +message LedgerPayloadVisibility { + string policy = 1; // digest_only | sealed_single_recipient | sealed_explicit_recipients + string content_type = 2; + bool encrypted = 3; + bool recoverable = 4; + repeated string recipient_uras = 5; + uint64 size_bytes = 6; +} + +message LedgerVisibilitySummary { + LedgerPayloadVisibility args = 1; + LedgerPayloadVisibility result = 2; + repeated LedgerPayloadVisibility diagnostics = 3; +} + +message LedgerErrorRecord { + string source = 1; + string code = 2; + string message = 3; + bool retryable = 4; + map context = 5; +} + +message LedgerDiagnosticRecord { + int64 timestamp_unix_ms = 1; + string level = 2; + string source = 3; + string code = 4; + string message = 5; + bool retryable = 6; + LedgerEventPayload payload = 7; +} + +message InvocationReceiptAnchor { + string receipt_ura = 1; + string receipt_hash = 2; + string receipt_type = 3; + string state = 4; + int64 timestamp_unix_ms = 5; +} + +message InvocationReceiptChainSummary { + repeated InvocationReceiptAnchor anchors = 1; + bool verified = 2; + string head_receipt_hash = 3; + string verification_detail = 4; +} + +message InvocationCausalLink { + string source_invocation_ura = 1; + string source_receipt_ura = 2; + string source_receipt_hash = 3; + string relation = 4; +} + +message InvocationTraceEdge { + string from_invocation_ura = 1; + string from_receipt_ura = 2; + string from_receipt_hash = 3; + string to_invocation_ura = 4; + string relation = 5; +} + +message InvocationTraceGraph { + string trace_id = 1; + repeated InvocationLedgerRecord records = 2; + repeated InvocationTraceEdge edges = 3; +} + +message InvocationLedgerRecord { + string invocation_ura = 1; + string request_id = 2; + string trace_id = 3; + string span_id = 4; + string caller_ura = 5; + string callee_ura = 6; + string subject_ura = 7; + string ability_ura = 8; + string ability_name = 9; + string state = 10; + int64 started_unix_ms = 11; + int64 completed_unix_ms = 12; + uint64 elapsed_ms = 13; + LedgerEventPayload args = 14; + LedgerEventPayload result = 15; + LedgerErrorRecord error = 16; + repeated LedgerDiagnosticRecord diagnostics = 17; + repeated InvocationCausalLink causal_links = 18; + InvocationReceiptChainSummary receipt_chain = 19; + LedgerVisibilitySummary visibility = 20; +} + // ─── Node ─────────────────────────────────────────────── // Node lifecycle state machine: @@ -831,7 +965,7 @@ message ContentMeta { // ─── Protocol: Large Payload Reference ────────────────── // Reference to a large or out-of-band payload managed by the -// Axon protocol. Addressed via axon://payloads/. +// Axon protocol. Addressed via EasyNet URA /r//resource//payloads/. // // Used instead of inline bytes when payload exceeds practical // gRPC message limits or needs independent lifecycle management. @@ -839,9 +973,9 @@ message ContentMeta { // PayloadRef over inline request/response bytes to keep RPC frames small // and to make retries/resume semantics independent from a single call. // Storage backends are an implementation detail invisible to callers — -// the protocol only exposes the axon:// URI. +// the protocol only exposes the full EasyNet URA. message PayloadRef { - string uri = 1; // axon://payloads/ + string ura = 1; // EasyNet URA /r//resource//payloads/ string digest = 2; // "sha256:" integrity hash int64 size_bytes = 3; ContentEnvelope content = 4; // content negotiation (type + encoding + schema + meta) @@ -876,7 +1010,7 @@ enum EasyNetHook { message EasyNetContext { string intent_id = 1; // future: intent that triggered this operation - string plan_graph_ref = 2; // future: axon://plans/ + string plan_graph_ref = 2; // future: EasyNet URA /r//resource//plans/ ObjectiveWeights objectives = 3; // future: multi-objective weights double budget_limit = 4; // future: max credit spend for this operation double reputation_min_score = 5; // future: minimum reputation score for node selection diff --git a/core/runtime-rs/client-sdk/proto/axon/v1/voice.proto b/core/runtime-rs/client-sdk/proto/axon/v1/voice.proto index 80c702ec..f49cf26e 100644 --- a/core/runtime-rs/client-sdk/proto/axon/v1/voice.proto +++ b/core/runtime-rs/client-sdk/proto/axon/v1/voice.proto @@ -167,7 +167,7 @@ message CallParticipant { string node_id = 3; bool muted = 4; VoiceTransportKind transport = 5; - string stream_session_id = 6; // axon://streams/ materialized id + string stream_session_id = 6; // EasyNet URA /r//resource/device./streams/ materialized id VoiceCodecProfile codec_profile = 7; VoiceNetworkMetrics latest_metrics = 8; int64 joined_at_unix_ms = 9; diff --git a/core/runtime-rs/client-sdk/src/api/fluent.rs b/core/runtime-rs/client-sdk/src/api/fluent.rs index ee49fe59..70d4872a 100644 --- a/core/runtime-rs/client-sdk/src/api/fluent.rs +++ b/core/runtime-rs/client-sdk/src/api/fluent.rs @@ -10,7 +10,7 @@ //! //! Implementation Approach: //! - Uses lightweight builder structs with chained setters and defaulted call options. -//! - Delegates execution to `call_ability_uri_json` to avoid duplicating invoke semantics. +//! - Delegates execution to `call_ability_ura_json` to avoid duplicating invoke semantics. //! //! Usage Contract: //! - Intended for ergonomic call composition: `tenant(...).ability(...).call_json(...)`. @@ -36,11 +36,11 @@ impl AxonClient { } impl<'a> TenantAbilityClient<'a> { - pub fn ability(self, resource_uri: impl Into) -> AbilityInvocationBuilder<'a> { + pub fn ability(self, resource_ura: impl Into) -> AbilityInvocationBuilder<'a> { AbilityInvocationBuilder { client: self.client, tenant_id: self.tenant_id, - resource_uri: resource_uri.into(), + resource_ura: resource_ura.into(), options: AbilityCallOptions::default(), invoke_context: AbilityInvokeContext::default(), } @@ -88,11 +88,16 @@ impl<'a> AbilityInvocationBuilder<'a> { self } + pub fn content_envelope(mut self, content_envelope: pb::ContentEnvelope) -> Self { + self.options.content_envelope = Some(content_envelope); + self + } + pub async fn call_json(self, payload: impl Into>) -> Result { self.client - .call_ability_uri_json_with_context( + .call_ability_ura_json_with_context( self.tenant_id, - self.resource_uri, + self.resource_ura, payload, self.options, self.invoke_context, diff --git a/core/runtime-rs/client-sdk/src/domain/admission.rs b/core/runtime-rs/client-sdk/src/domain/admission.rs index 85de5605..16f39771 100644 --- a/core/runtime-rs/client-sdk/src/domain/admission.rs +++ b/core/runtime-rs/client-sdk/src/domain/admission.rs @@ -89,7 +89,7 @@ pub enum AdmissionMode<'a> { /// matches the SDK-side trait exactly so a future file-based or /// registry-backed resolver can be installed without churn. pub trait KeyResolver: Send + Sync { - fn resolve(&self, caller_uri: &str) -> Result; + fn resolve(&self, caller_ura: &str) -> Result; } /// A typed admission rejection. Maps directly to `pb::Error` at the @@ -172,20 +172,20 @@ fn canonical_causal_bytes(ctx: Option<&pb::CausalContext>) -> Vec { Some(pb::causal_context::Form::Scalar(s)) => { out.push(0x01); out.extend_from_slice(&s.receipt_hash); - put_str(&mut out, &s.receipt_uri); + put_str(&mut out, &s.receipt_ura); } Some(pb::causal_context::Form::List(l)) => { out.push(0x02); out.extend_from_slice(&(l.prior.len() as u32).to_be_bytes()); for r in &l.prior { out.extend_from_slice(&r.receipt_hash); - put_str(&mut out, &r.receipt_uri); + put_str(&mut out, &r.receipt_ura); } } Some(pb::causal_context::Form::Merkle(m)) => { out.push(0x03); out.extend_from_slice(&m.root); - put_str(&mut out, &m.proof_uri); + put_str(&mut out, &m.proof_ura); } } out @@ -207,9 +207,9 @@ pub fn canonical_invocation_bytes( let callee = envelope.callee.as_ref().expect("callee must be set"); let subject = envelope.subject.as_ref().expect("subject must be set"); let mut out = Vec::with_capacity(512); - put_identity(&mut out, &caller.uri, &caller.profile); - put_identity(&mut out, &callee.uri, &callee.profile); - put_identity(&mut out, &subject.uri, &subject.profile); + put_identity(&mut out, &caller.ura, &caller.profile); + put_identity(&mut out, &callee.ura, &callee.profile); + put_identity(&mut out, &subject.ura, &subject.profile); put_str(&mut out, ability); out.extend_from_slice(args_digest); out.extend_from_slice(&envelope.invocation_nonce); @@ -283,7 +283,7 @@ pub struct ReceiptSigningInput<'a> { /// `signer_binding` is the host's URA + profile (the entity whose /// pubkey verifies `callee_signature`). `host_attestation` is a /// signature by that same key over the canonical bytes -/// `canonical_host_attestation_bytes(callee_uri, signer_uri)`, +/// `canonical_host_attestation_bytes(callee_ura, signer_ura)`, /// proving the host claims to host this specific callee. pub struct HostedAttestation<'a> { pub signer_binding: &'a pb::AgentIdentity, @@ -291,21 +291,21 @@ pub struct HostedAttestation<'a> { } /// Canonical bytes covering the host→callee attestation. The host -/// signs these bytes once per host_uri/callee_uri pairing; an +/// signs these bytes once per host_ura/callee_ura pairing; an /// offline verifier re-derives them from the receipt's /// signer_binding + callee_binding URAs and checks the /// host_attestation signature against signer_binding's pubkey. /// /// Layout: prefix tag "host-attest:v1\n" (15 bytes, fixed) + -/// length-prefixed callee_uri + length-prefixed signer_uri. +/// length-prefixed callee_ura + length-prefixed signer_ura. /// The version tag is load-bearing — it lets a future amendment /// extend the attestation surface without colliding with v1 /// signatures. -pub fn canonical_host_attestation_bytes(callee_uri: &str, signer_uri: &str) -> Vec { - let mut out = Vec::with_capacity(64 + callee_uri.len() + signer_uri.len()); +pub fn canonical_host_attestation_bytes(callee_ura: &str, signer_ura: &str) -> Vec { + let mut out = Vec::with_capacity(64 + callee_ura.len() + signer_ura.len()); out.extend_from_slice(b"host-attest:v1\n"); - put_str(&mut out, callee_uri); - put_str(&mut out, signer_uri); + put_str(&mut out, callee_ura); + put_str(&mut out, signer_ura); out } @@ -331,9 +331,9 @@ pub fn canonical_receipt_bytes(r: &ReceiptSigningInput<'_>) -> Vec { put_str(&mut out, r.state); out.extend_from_slice(&r.timestamp_unix_ms.to_be_bytes()); out.extend_from_slice(r.prev_receipt_hash); - put_identity(&mut out, &r.caller_binding.uri, &r.caller_binding.profile); - put_identity(&mut out, &r.callee_binding.uri, &r.callee_binding.profile); - put_identity(&mut out, &r.subject_binding.uri, &r.subject_binding.profile); + put_identity(&mut out, &r.caller_binding.ura, &r.caller_binding.profile); + put_identity(&mut out, &r.callee_binding.ura, &r.callee_binding.profile); + put_identity(&mut out, &r.subject_binding.ura, &r.subject_binding.profile); out.extend_from_slice(r.invocation_nonce); let causal = canonical_causal_bytes(r.causal_binding); put_bytes(&mut out, &causal); @@ -345,7 +345,7 @@ pub fn canonical_receipt_bytes(r: &ReceiptSigningInput<'_>) -> Vec { None => out.push(0x00), Some(h) => { out.push(0x01); - put_identity(&mut out, &h.signer_binding.uri, &h.signer_binding.profile); + put_identity(&mut out, &h.signer_binding.ura, &h.signer_binding.profile); put_bytes(&mut out, h.host_attestation); } } @@ -416,14 +416,14 @@ pub fn validate_envelope( .subject .as_ref() .ok_or_else(|| AdmissionError::envelope_incomplete("subject_missing"))?; - if caller.uri.is_empty() { - return Err(AdmissionError::envelope_incomplete("caller_uri_empty")); + if caller.ura.is_empty() { + return Err(AdmissionError::envelope_incomplete("caller_ura_empty")); } - if callee.uri.is_empty() { - return Err(AdmissionError::envelope_incomplete("callee_uri_empty")); + if callee.ura.is_empty() { + return Err(AdmissionError::envelope_incomplete("callee_ura_empty")); } - if subject.uri.is_empty() { - return Err(AdmissionError::envelope_incomplete("subject_uri_empty")); + if subject.ura.is_empty() { + return Err(AdmissionError::envelope_incomplete("subject_ura_empty")); } if args_digest.len() != 32 { return Err(AdmissionError::envelope_incomplete( @@ -496,13 +496,13 @@ pub fn verify_signature( resolver: &dyn KeyResolver, ) -> Result<(), AdmissionError> { // Structural invariant — caller must be present if we got here. - let caller_uri = envelope + let caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); let key = resolver - .resolve(caller_uri) + .resolve(caller_ura) .map_err(|e| AdmissionError::signature_invalid(format!("resolver_failed:{}", e.detail)))?; let sig_bytes: [u8; SIGNATURE_LENGTH] = sig .signature @@ -519,7 +519,7 @@ pub fn verify_signature( // Admission step 4: nonce replay store (server-owned) // ═══════════════════════════════════════════════════════════════════════ -/// Dedup key: `(caller.uri, ability, nonce)`. Including `ability` in +/// Dedup key: `(caller.ura, ability, nonce)`. Including `ability` in /// the key avoids false-positive dedup when the same caller reuses a /// nonce on two distinct abilities (rare but legitimate). type ReplayKey = (String, String, [u8; 16]); @@ -561,13 +561,13 @@ impl NonceReplayStore { } } - /// Register a `(caller.uri, ability, nonce)` observation. Returns + /// Register a `(caller.ura, ability, nonce)` observation. Returns /// [`REASON_NONCE_REPLAY`] on collision inside the current window. /// Out-of-window entries are pruned opportunistically so the store /// bounds itself. pub fn check_and_record( &self, - caller_uri: &str, + caller_ura: &str, ability: &str, nonce: [u8; 16], now_ms: i64, @@ -576,7 +576,7 @@ impl NonceReplayStore { let cutoff = now_ms - inner.window_ms; inner.seen.retain(|_, ts| *ts >= cutoff); - let key: ReplayKey = (caller_uri.to_string(), ability.to_string(), nonce); + let key: ReplayKey = (caller_ura.to_string(), ability.to_string(), nonce); if let Some(&prev_ts) = inner.seen.get(&key) { if prev_ts >= cutoff { return Err(AdmissionError::nonce_replay(format!( @@ -650,12 +650,12 @@ pub fn run_admission( .as_slice() .try_into() .map_err(|_| AdmissionError::envelope_incomplete("invocation_nonce_wrong_length"))?; - let caller_uri = envelope + let caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); - replay.check_and_record(caller_uri, ability, nonce_arr, now_ms)?; + replay.check_and_record(caller_ura, ability, nonce_arr, now_ms)?; Ok(()) } @@ -676,7 +676,7 @@ mod tests { const WORKED_SEED: [u8; SECRET_KEY_LENGTH] = [0x01; SECRET_KEY_LENGTH]; const WORKED_NONCE: [u8; 16] = [0x22; 16]; const WORKED_CANONICAL_SHA256_HEX: &str = - "132aacb0e21a0159a187fc7d71f204f58ecf12feab06eec9f61d3769321820f7"; + "68464c0da3500e842ece4d3e6e539ec74d12b741160bd5174b13234b02b1eb28"; const WORKED_PAYLOAD: &[u8] = b"{}"; fn worked_envelope() -> pb::Envelope { @@ -690,15 +690,15 @@ mod tests { priority: 3, easynet: None, caller: Some(pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer@1.0".to_string(), + ura: "easynet:///r/openai/agent/openai.reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: WORKED_NONCE.to_vec(), @@ -755,20 +755,20 @@ mod tests { // so every existing receipt's SHA shifts by one trailing byte. // Cross-SDK encoder ports MUST reproduce the new value. const RECEIPT_WORKED_SHA256_HEX: &str = - "2e6efc5cdf4d5b68fdb94e345eac674b2d058618eb3e9ac57b89f5f3d383fded"; + "f1941d0562f76700987300f991be25e6e65f703849092ae3e5817fa201eaba54"; #[test] fn receipt_canonical_bytes_match_worked_example_pin() { let caller = pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }; let callee = pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer@1.0".to_string(), + ura: "easynet:///r/openai/agent/openai.reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }; let subject = pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }; let prev_hash = [0u8; 32]; @@ -872,25 +872,25 @@ mod tests { // b01161f9; the rewrite appended a 0x00 self-signed marker to // canonical_receipt_bytes so every form's SHA shifts. const RECEIPT_FORM_NONE_SHA256_HEX: &str = - "2e6efc5cdf4d5b68fdb94e345eac674b2d058618eb3e9ac57b89f5f3d383fded"; + "f1941d0562f76700987300f991be25e6e65f703849092ae3e5817fa201eaba54"; const RECEIPT_FORM_SCALAR_SHA256_HEX: &str = - "08694de4ab7ee104bdca1c0f5f70888bd55c841078675ae595bb30b6c6b0e8c7"; + "72588e01aa37d80b81df221ac070ce5ee011499f3b28f564db46f21f2488252f"; const RECEIPT_FORM_LIST_SHA256_HEX: &str = - "a37d0630eab07c1cf1960a6a929f3ef6e3445d66b49787a5a02da675ceeac8d7"; + "75ad192a33250042595853317bc08cef12b43491d15060219837947d465b3a9b"; const RECEIPT_FORM_MERKLE_SHA256_HEX: &str = - "4fa61ebcdcca9828e14ba33eb13b31f5622afc715a3eb46693e7627eda8704e9"; + "6e7d66743eeb8ef940033e713c5cbba606be566b596734b324aaabd6cb011978"; fn run_receipt_form_pin(form: pb::causal_context::Form, anchor: &str, form_label: &str) { let caller = pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }; let callee = pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer@1.0".to_string(), + ura: "easynet:///r/openai/agent/openai.reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }; let subject = pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }; let prev_hash = [0u8; 32]; @@ -944,7 +944,7 @@ mod tests { // A single predecessor — minimal canonical Scalar shape. let scalar = pb::ReceiptRef { receipt_hash: [0xAB; 32].to_vec(), - receipt_uri: "easynet:///r/silan/receipts/01R-prev".to_string(), + receipt_ura: "easynet:///r/silan/receipts/01R-prev".to_string(), }; run_receipt_form_pin( pb::causal_context::Form::Scalar(scalar), @@ -962,11 +962,11 @@ mod tests { prior: vec![ pb::ReceiptRef { receipt_hash: [0xAA; 32].to_vec(), - receipt_uri: "easynet:///r/silan/receipts/01R-A".to_string(), + receipt_ura: "easynet:///r/silan/receipts/01R-A".to_string(), }, pb::ReceiptRef { receipt_hash: [0xBB; 32].to_vec(), - receipt_uri: "easynet:///r/silan/receipts/01R-B".to_string(), + receipt_ura: "easynet:///r/silan/receipts/01R-B".to_string(), }, ], }; @@ -981,7 +981,7 @@ mod tests { fn receipt_pins_form_merkle() { let merkle = pb::MerkleRoot { root: [0xCD; 32].to_vec(), - proof_uri: "easynet:///r/silan/proofs/01PRF-1".to_string(), + proof_ura: "easynet:///r/silan/proofs/01PRF-1".to_string(), }; run_receipt_form_pin( pb::causal_context::Form::Merkle(merkle), @@ -998,24 +998,24 @@ mod tests { // assertion below); collapsing the two forms would defeat // §A12. const RECEIPT_HOSTED_NONE_SHA256_HEX: &str = - "b173a4622b3d7137fe978311262ebb3b9eec8488d7289d8051a98054618f561d"; + "d329e37bb139e8c6ad15990bd88567ba85ce99d6e1c5b651daac27e6ab0e904f"; #[test] fn receipt_pins_hosted_form_none() { let caller = pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }; let callee = pb::AgentIdentity { - uri: "easynet:///r/silan/hosted/llm/claude".to_string(), + ura: "easynet:///r/silan/hosted/llm/claude".to_string(), profile: "easynet-strict-v2".to_string(), }; let signer = pb::AgentIdentity { - uri: "easynet:///r/silan/device/macbook".to_string(), + ura: "easynet:///r/silan/device/macbook".to_string(), profile: "easynet-strict-v2".to_string(), }; let subject = pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }; let prev_hash = [0u8; 32]; @@ -1078,7 +1078,7 @@ mod tests { #[test] fn canonical_host_attestation_bytes_includes_version_tag() { // Spec layout: prefix tag "host-attest:v1\n" + length- - // prefixed callee_uri + length-prefixed signer_uri. + // prefixed callee_ura + length-prefixed signer_ura. // Pin the tag so a future amendment cannot silently // change the surface in a way that lets v1 attestations // verify against a v2 encoder. @@ -1142,30 +1142,30 @@ mod tests { } #[test] - fn validate_envelope_rejects_empty_caller_uri() { + fn validate_envelope_rejects_empty_caller_ura() { let mut env = worked_envelope(); - env.caller.as_mut().unwrap().uri = String::new(); + env.caller.as_mut().unwrap().ura = String::new(); let err = validate_envelope(&env, "review", &sha256(WORKED_PAYLOAD)).unwrap_err(); assert_eq!(err.reason, REASON_ENVELOPE_INCOMPLETE); - assert!(err.detail.contains("caller_uri_empty")); + assert!(err.detail.contains("caller_ura_empty")); } #[test] - fn validate_envelope_rejects_empty_callee_uri() { + fn validate_envelope_rejects_empty_callee_ura() { let mut env = worked_envelope(); - env.callee.as_mut().unwrap().uri = String::new(); + env.callee.as_mut().unwrap().ura = String::new(); let err = validate_envelope(&env, "review", &sha256(WORKED_PAYLOAD)).unwrap_err(); assert_eq!(err.reason, REASON_ENVELOPE_INCOMPLETE); - assert!(err.detail.contains("callee_uri_empty")); + assert!(err.detail.contains("callee_ura_empty")); } #[test] - fn validate_envelope_rejects_empty_subject_uri() { + fn validate_envelope_rejects_empty_subject_ura() { let mut env = worked_envelope(); - env.subject.as_mut().unwrap().uri = String::new(); + env.subject.as_mut().unwrap().ura = String::new(); let err = validate_envelope(&env, "review", &sha256(WORKED_PAYLOAD)).unwrap_err(); assert_eq!(err.reason, REASON_ENVELOPE_INCOMPLETE); - assert!(err.detail.contains("subject_uri_empty")); + assert!(err.detail.contains("subject_ura_empty")); } #[test] @@ -1264,7 +1264,7 @@ mod tests { #[test] fn verify_signature_wrong_pubkey_rejects() { - // Identity spoof: caller_uri resolves to a DIFFERENT pubkey + // Identity spoof: caller_ura resolves to a DIFFERENT pubkey // than the one that actually signed. Row 05 of the PR2 // negative matrix. let mut env = worked_envelope(); @@ -1368,7 +1368,7 @@ mod tests { #[test] fn run_admission_rejects_envelope_before_replay_touched() { let mut env = worked_envelope(); - env.caller.as_mut().unwrap().uri = String::new(); + env.caller.as_mut().unwrap().ura = String::new(); sign_worked(&mut env); let s = NonceReplayStore::new(); let err = run_admission( @@ -1456,7 +1456,7 @@ mod tests { // here breaks the whole chain loudly. // // Row naming mirrors the bridge tests: - // row01 — tamper caller.uri after sign + // row01 — tamper caller.ura after sign // row02 — tamper payload after sign // row03 — tamper subject after sign // row04 — tamper causal_context after sign @@ -1507,14 +1507,14 @@ mod tests { ) } - // ── Row 01: tamper caller.uri after sign ────────────────────────── + // ── Row 01: tamper caller.ura after sign ────────────────────────── // expected: AXON_CALLER_SIGNATURE_INVALID // layer: callee admission step 3 (crypto verify) #[test] - fn row01_tampered_caller_uri_is_caller_signature_invalid() { + fn row01_tampered_caller_ura_is_caller_signature_invalid() { let mut env = worked_envelope(); let vk = sign_and_return_vk(&mut env); - env.caller.as_mut().unwrap().uri = "easynet:///r/silan/agents/mallory".to_string(); + env.caller.as_mut().unwrap().ura = "easynet:///r/silan/agent/silan.mallory".to_string(); let err = run_federated(&env, "review", vk).unwrap_err(); assert_eq!(err.reason, REASON_CALLER_SIGNATURE_INVALID); } @@ -1545,7 +1545,8 @@ mod tests { fn row03_tampered_subject_is_caller_signature_invalid() { let mut env = worked_envelope(); let vk = sign_and_return_vk(&mut env); - env.subject.as_mut().unwrap().uri = "easynet:///r/mallory/papers/evil@1".to_string(); + env.subject.as_mut().unwrap().ura = + "easynet:///r/mallory/resource/mallory.papers/evil".to_string(); let err = run_federated(&env, "review", vk).unwrap_err(); assert_eq!(err.reason, REASON_CALLER_SIGNATURE_INVALID); } @@ -1563,7 +1564,7 @@ mod tests { env.causal_context = Some(pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: vec![0xEEu8; 32], - receipt_uri: "easynet:///r/mallory/receipts/fake".to_string(), + receipt_ura: "easynet:///r/mallory/receipts/fake".to_string(), })), }); let err = run_federated(&env, "review", vk).unwrap_err(); diff --git a/core/runtime-rs/client-sdk/src/domain/capability/lifecycle.rs b/core/runtime-rs/client-sdk/src/domain/capability/lifecycle.rs index 609e7eb5..db1c18ea 100644 --- a/core/runtime-rs/client-sdk/src/domain/capability/lifecycle.rs +++ b/core/runtime-rs/client-sdk/src/domain/capability/lifecycle.rs @@ -47,12 +47,12 @@ impl AxonClient { package_id: &str, version: &str, payload_digest: &str, - payload_uri: &str, + payload_ura: &str, payload_size_bytes: i64, signature_fingerprint: &str, ) -> String { let canonical = format!( - "{package_id}\n{version}\n{payload_digest}\n{payload_uri}\n{payload_size_bytes}\n{signature_fingerprint}" + "{package_id}\n{version}\n{payload_digest}\n{payload_ura}\n{payload_size_bytes}\n{signature_fingerprint}" ); Self::sdk_sha256_prefixed(canonical.as_bytes()) } @@ -109,7 +109,7 @@ impl AxonClient { content: Some(pb::ContentEnvelope { content_type, encoding: "identity".to_string(), - schema_uri: String::new(), + schema_ura: String::new(), meta: None, encryption: pb::EncryptionAlgorithm::EncryptionUnspecified as i32, key_id: String::new(), @@ -144,11 +144,11 @@ impl AxonClient { pub async fn get_payload_meta( &mut self, tenant_id: impl Into, - uri: impl Into, + ura: impl Into, ) -> Result { let req = pb::GetPayloadMetaRequest { envelope: Some(self.default_envelope("sdk-get-payload-meta", tenant_id)), - uri: uri.into(), + ura: ura.into(), }; let mut transfer = pb::payload_transfer_client::PayloadTransferClient::new(self.channel.clone()); @@ -178,8 +178,8 @@ impl AxonClient { mut spec: AbilityPackageSpec, ) -> Result<(pb::CapabilityPackageRef, pb::CapabilityPackageProof)> { let tenant_id = tenant_id.into(); - if spec.payload_uri.trim().is_empty() { - return Err(anyhow!("publish_capability requires non-empty payload_uri")); + if spec.payload_ura.trim().is_empty() { + return Err(anyhow!("publish_capability requires non-empty payload_ura")); } if spec.payload_size_bytes < 0 { return Err(anyhow!( @@ -192,7 +192,7 @@ impl AxonClient { let needs_meta = spec.digest.trim().is_empty() || spec.payload_size_bytes == 0; if needs_meta { let payload_ref = self - .get_payload_meta(tenant_id.clone(), spec.payload_uri.clone()) + .get_payload_meta(tenant_id.clone(), spec.payload_ura.clone()) .await?; if spec.digest.trim().is_empty() { spec.digest = payload_ref.digest.clone(); @@ -212,7 +212,7 @@ impl AxonClient { payload_ref.size_bytes )); } - spec.payload_uri = payload_ref.uri; + spec.payload_ura = payload_ref.ura; } if spec.signature_fingerprint.trim().is_empty() { spec.signature_fingerprint = Self::sdk_sha256_prefixed(spec.signature.as_slice()); @@ -222,13 +222,13 @@ impl AxonClient { spec.package_id.as_str(), spec.version.as_str(), spec.digest.as_str(), - spec.payload_uri.as_str(), + spec.payload_ura.as_str(), spec.payload_size_bytes, spec.signature_fingerprint.as_str(), ); } let proof = pb::CapabilityPackageProof { - payload_uri: spec.payload_uri.clone(), + payload_ura: spec.payload_ura.clone(), payload_digest: spec.digest.clone(), payload_size_bytes: spec.payload_size_bytes, signature_fingerprint: spec.signature_fingerprint.clone(), @@ -244,7 +244,7 @@ impl AxonClient { tags: spec.tags, requirements: spec.requirements, metadata: spec.metadata, - payload_uri: spec.payload_uri, + payload_ura: spec.payload_ura, publisher_key_version: spec.publisher_key_version, proof: Some(proof), }; diff --git a/core/runtime-rs/client-sdk/src/domain/content.rs b/core/runtime-rs/client-sdk/src/domain/content.rs new file mode 100644 index 00000000..76ab1224 --- /dev/null +++ b/core/runtime-rs/client-sdk/src/domain/content.rs @@ -0,0 +1,257 @@ +//! EasyNet Axon for AgentNet +//! ========================= +//! +//! File: client-sdk/src/domain/content.rs +//! Description: ContentEnvelope validation and EncryptedPayload +//! sealing helpers for invocation payload bytes. +//! +//! Protocol Responsibility: +//! - Makes `ContentEnvelope.encryption` executable protocol state, +//! not a passive label that can accidentally travel with plaintext. +//! - Encodes encrypted invocation bodies as `axon.v1.EncryptedPayload` +//! prost bytes, with AEAD AAD bound to the canonical envelope or a +//! stable caller-provided envelope hash. +//! - Provides fail-closed validation for InvokeRequest, +//! InvokeServerStreamRequest, and EnvelopeOpen builders. +//! +//! Implementation Approach: +//! - Uses X25519 for ephemeral-static key agreement and +//! ChaCha20-Poly1305 for payload encryption. +//! - Keeps Ed25519 signing keys out of encryption; callers must supply +//! explicit recipient encryption public keys. +//! - Derives the AEAD key from the shared secret and AAD with SHA-256. +//! +//! Usage Contract: +//! - If `ContentEnvelope.encryption != UNSPECIFIED`, payload bytes must +//! decode as `EncryptedPayload`, and its algorithm/key_id must match +//! the envelope. +//! - Plaintext callers use `plaintext_json_envelope`. +//! - Encrypted callers use `seal_chacha20poly1305_payload` before +//! dispatch and `open_chacha20poly1305_payload` at the recipient. +//! +//! Architectural Position: +//! - Domain-layer protocol helper shared by SDK builders and tests. + +use anyhow::{anyhow, Result}; +use chacha20poly1305::aead::{Aead, Payload}; +use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce}; +use prost::Message; +use rand::RngCore; +use sha2::{Digest, Sha256}; +use x25519_dalek::{PublicKey, StaticSecret}; + +use crate::pb; + +const CHACHA20_POLY1305_NONCE_LEN: usize = 12; + +#[derive(Clone)] +pub struct PayloadEncryptionKeypair { + secret: StaticSecret, + public: [u8; 32], +} + +impl PayloadEncryptionKeypair { + pub fn generate() -> Self { + let secret = StaticSecret::random_from_rng(rand::rngs::OsRng); + let public = PublicKey::from(&secret).to_bytes(); + Self { secret, public } + } + + pub fn from_secret_bytes(secret_bytes: [u8; 32]) -> Self { + let secret = StaticSecret::from(secret_bytes); + let public = PublicKey::from(&secret).to_bytes(); + Self { secret, public } + } + + pub fn public_key(&self) -> [u8; 32] { + self.public + } +} + +pub fn plaintext_json_envelope() -> pb::ContentEnvelope { + pb::ContentEnvelope { + content_type: "application/json".to_string(), + encoding: "identity".to_string(), + schema_ura: String::new(), + meta: None, + encryption: pb::EncryptionAlgorithm::EncryptionUnspecified as i32, + key_id: String::new(), + } +} + +pub fn content_envelope_is_encrypted(env: &pb::ContentEnvelope) -> bool { + env.encryption != pb::EncryptionAlgorithm::EncryptionUnspecified as i32 +} + +pub fn seal_chacha20poly1305_payload( + recipient_public_key: &[u8], + key_id: impl Into, + aad: &[u8], + plaintext: &[u8], +) -> Result<(Vec, pb::ContentEnvelope)> { + let key_id = key_id.into(); + if key_id.trim().is_empty() { + return Err(anyhow!("encrypted payload key_id is required")); + } + let recipient_public_key = public_key_from_slice(recipient_public_key)?; + let ephemeral_secret = StaticSecret::random_from_rng(rand::rngs::OsRng); + let ephemeral_public_key = PublicKey::from(&ephemeral_secret); + let shared = ephemeral_secret.diffie_hellman(&recipient_public_key); + let key = derive_payload_key(shared.as_bytes(), aad); + let cipher = ChaCha20Poly1305::new_from_slice(&key) + .map_err(|_| anyhow!("failed to initialise payload cipher"))?; + let mut nonce = [0_u8; CHACHA20_POLY1305_NONCE_LEN]; + rand::rngs::OsRng.fill_bytes(&mut nonce); + let ciphertext = cipher + .encrypt( + Nonce::from_slice(&nonce), + Payload { + msg: plaintext, + aad, + }, + ) + .map_err(|_| anyhow!("payload encryption failed"))?; + + let encrypted = pb::EncryptedPayload { + algorithm: pb::EncryptionAlgorithm::EncryptionChacha20Poly1305 as i32, + key_id: key_id.clone(), + nonce: nonce.to_vec(), + ciphertext, + auth_tag: Vec::new(), + aad: aad.to_vec(), + ephemeral_public_key: ephemeral_public_key.to_bytes().to_vec(), + }; + Ok(( + encrypted.encode_to_vec(), + pb::ContentEnvelope { + content_type: "application/octet-stream".to_string(), + encoding: "identity".to_string(), + schema_ura: String::new(), + meta: None, + encryption: pb::EncryptionAlgorithm::EncryptionChacha20Poly1305 as i32, + key_id, + }, + )) +} + +pub fn open_chacha20poly1305_payload( + recipient: &PayloadEncryptionKeypair, + aad: &[u8], + encoded_encrypted_payload: &[u8], +) -> Result> { + let encrypted = pb::EncryptedPayload::decode(encoded_encrypted_payload) + .map_err(|err| anyhow!("encrypted payload decode failed: {err}"))?; + if encrypted.algorithm != pb::EncryptionAlgorithm::EncryptionChacha20Poly1305 as i32 { + return Err(anyhow!("encrypted payload algorithm mismatch")); + } + if encrypted.nonce.len() != CHACHA20_POLY1305_NONCE_LEN { + return Err(anyhow!("encrypted payload nonce must be 12 bytes")); + } + if encrypted.aad.as_slice() != aad { + return Err(anyhow!("encrypted payload AAD mismatch")); + } + let ephemeral = public_key_from_slice(&encrypted.ephemeral_public_key)?; + let shared = recipient.secret.diffie_hellman(&ephemeral); + let key = derive_payload_key(shared.as_bytes(), aad); + let cipher = ChaCha20Poly1305::new_from_slice(&key) + .map_err(|_| anyhow!("failed to initialise payload cipher"))?; + cipher + .decrypt( + Nonce::from_slice(&encrypted.nonce), + Payload { + msg: encrypted.ciphertext.as_slice(), + aad, + }, + ) + .map_err(|_| anyhow!("payload decryption failed")) +} + +pub fn validate_payload_matches_content_envelope( + env: Option<&pb::ContentEnvelope>, + payload: &[u8], +) -> Result<()> { + let Some(env) = env else { + return Ok(()); + }; + if !content_envelope_is_encrypted(env) { + return Ok(()); + } + if env.key_id.trim().is_empty() { + return Err(anyhow!("encrypted ContentEnvelope requires key_id")); + } + let encrypted = pb::EncryptedPayload::decode(payload).map_err(|err| { + anyhow!("encrypted ContentEnvelope payload is not EncryptedPayload: {err}") + })?; + if encrypted.algorithm != env.encryption { + return Err(anyhow!( + "EncryptedPayload algorithm {} does not match ContentEnvelope encryption {}", + encrypted.algorithm, + env.encryption + )); + } + if encrypted.key_id != env.key_id { + return Err(anyhow!( + "EncryptedPayload key_id {:?} does not match ContentEnvelope key_id {:?}", + encrypted.key_id, + env.key_id + )); + } + if encrypted.nonce.len() != CHACHA20_POLY1305_NONCE_LEN { + return Err(anyhow!("EncryptedPayload nonce must be 12 bytes")); + } + if encrypted.ciphertext.is_empty() { + return Err(anyhow!("EncryptedPayload ciphertext is empty")); + } + public_key_from_slice(&encrypted.ephemeral_public_key)?; + Ok(()) +} + +fn public_key_from_slice(bytes: &[u8]) -> Result { + let array: [u8; 32] = bytes + .try_into() + .map_err(|_| anyhow!("recipient encryption public key must be 32 bytes"))?; + Ok(PublicKey::from(array)) +} + +fn derive_payload_key(shared_secret: &[u8; 32], aad: &[u8]) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(b"easynet-axon-encrypted-payload:v1"); + hasher.update(shared_secret); + hasher.update(Sha256::digest(aad)); + hasher.finalize().into() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encrypted_payload_round_trips_for_recipient_only() { + let recipient = PayloadEncryptionKeypair::from_secret_bytes([7; 32]); + let other = PayloadEncryptionKeypair::from_secret_bytes([8; 32]); + let aad = b"canonical-envelope-digest"; + let (sealed, envelope) = seal_chacha20poly1305_payload( + &recipient.public_key(), + "easynet:///r/acme/resource/alice.keys/session-1", + aad, + b"secret args", + ) + .expect("seal"); + + validate_payload_matches_content_envelope(Some(&envelope), &sealed).expect("valid"); + let opened = open_chacha20poly1305_payload(&recipient, aad, &sealed).expect("open"); + assert_eq!(opened, b"secret args"); + assert!(open_chacha20poly1305_payload(&other, aad, &sealed).is_err()); + } + + #[test] + fn encrypted_content_envelope_rejects_plaintext_payload() { + let envelope = pb::ContentEnvelope { + encryption: pb::EncryptionAlgorithm::EncryptionChacha20Poly1305 as i32, + key_id: "key-1".to_string(), + ..plaintext_json_envelope() + }; + let err = validate_payload_matches_content_envelope(Some(&envelope), b"{}").unwrap_err(); + assert!(err.to_string().contains("payload is not EncryptedPayload")); + } +} diff --git a/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs b/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs index a698ffe0..8bda3f70 100644 --- a/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs +++ b/core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs @@ -2,18 +2,18 @@ //! ========================= //! //! File: core/runtime-rs/client-sdk/src/domain/easynet/semantic.rs -//! Description: EasyNet subject/auth derivation, URI canonicalization, metadata signing, and invoke-by-URI. +//! Description: EasyNet subject/auth derivation, URI canonicalization, metadata signing, and invoke-by-URA. //! //! Protocol Responsibility: //! - Produces canonical EasyNet resource semantics and deterministic signed metadata. -//! - Implements the fluent invoke-by-resource-uri path over the Axon invocation service. +//! - Implements the fluent invoke-by-resource-ura path over the Axon invocation service. //! //! Implementation Approach: -//! - Canonicalizes resource URI and query components under strict visibility and tenant rules. +//! - Canonicalizes resource URA and query components under strict visibility and tenant rules. //! - Builds deterministic signature inputs and EasyNet metadata with stable hashing and signing primitives. //! //! Usage Contract: -//! - Callers must provide syntactically valid EasyNet resource URIs and tenant context. +//! - Callers must provide syntactically valid EasyNet resource URAs and tenant context. //! - Subject auth may be caller-supplied or deterministically derived when absent. //! //! Architectural Position: @@ -44,29 +44,29 @@ impl AxonClient { encoded } - fn split_resource_path_query(resource_uri: &str) -> Result<(String, String)> { - let raw = resource_uri + fn split_resource_path_query(resource_ura: &str) -> Result<(String, String)> { + let raw = resource_ura .strip_prefix("easynet://") - .ok_or_else(|| anyhow!("resource_uri must start with easynet://"))?; + .ok_or_else(|| anyhow!("resource_ura must start with easynet://"))?; let (without_query, query) = raw.split_once('?').unwrap_or((raw, "")); if without_query.is_empty() { - return Err(anyhow!("resource_uri cannot be empty")); + return Err(anyhow!("resource_ura cannot be empty")); } if !without_query.starts_with('/') { - return Err(anyhow!("resource_uri must use easynet:///r/... form")); + return Err(anyhow!("resource_ura must use easynet:///r/... form")); } if without_query.starts_with("//") { return Err(anyhow!( - "resource_uri must use canonical easynet:/// prefix" + "resource_ura must use canonical easynet:/// prefix" )); } let trimmed = without_query.trim_start_matches('/'); let (namespace, remainder) = trimmed .split_once('/') - .ok_or_else(|| anyhow!("resource_uri path namespace is required"))?; + .ok_or_else(|| anyhow!("resource_ura path namespace is required"))?; if !namespace.eq_ignore_ascii_case("r") { return Err(anyhow!( - "only /r namespace is supported in easynet resource_uri" + "only /r namespace is supported in easynet resource_ura" )); } Ok((remainder.to_string(), query.to_string())) @@ -135,21 +135,21 @@ impl AxonClient { subject_value.strip_prefix("agent.").map(|v| v.to_string()) } - pub fn canonicalize_easynet_resource_uri( - resource_uri: &str, + pub fn canonicalize_easynet_resource_ura( + resource_ura: &str, tenant_id: &str, ) -> Result { - let (path, query) = Self::split_resource_path_query(resource_uri)?; + let (path, query) = Self::split_resource_path_query(resource_ura)?; if path.contains('%') || query.contains('%') { return Err(anyhow!( - "percent-encoding is not allowed in easynet resource URI" + "percent-encoding is not allowed in easynet resource URA" )); } - Self::canonicalize_r_path_uri(&path, &query, tenant_id) + Self::canonicalize_r_path_ura(&path, &query, tenant_id) } - pub fn ability_name_from_resource_uri(resource_uri: &str) -> Result { - let (path, _) = Self::split_resource_path_query(resource_uri)?; + pub fn ability_name_from_resource_ura(resource_ura: &str) -> Result { + let (path, _) = Self::split_resource_path_query(resource_ura)?; if let Some((_realm, ability_name)) = Self::parse_canonical_hub_ability_path(&path)? { return Ok(ability_name); } @@ -161,41 +161,41 @@ impl AxonClient { .filter(|name| !name.is_empty()) .map(ToString::to_string) .ok_or_else(|| { - anyhow!("resource_uri route must include resource//ability/") + anyhow!("resource_ura route must include resource//ability/") }); } let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() < 5 || !parts[3].eq_ignore_ascii_case("abilities") { return Err(anyhow!( - "resource_uri must include /r////abilities/@" + "resource_ura must include /r////abilities/@" )); } let ability_with_ver = parts[4..].join("/"); let (ability_name, version) = ability_with_ver .split_once('@') - .ok_or_else(|| anyhow!("resource_uri ability must include @version"))?; + .ok_or_else(|| anyhow!("resource_ura ability must include @version"))?; if ability_name.is_empty() || version.is_empty() { return Err(anyhow!( - "resource_uri ability name and version must both be non-empty" + "resource_ura ability name and version must both be non-empty" )); } Ok(ability_name.to_string()) } - pub fn default_subject_id_for_resource_uri( - resource_uri: &str, + pub fn default_subject_id_for_resource_ura( + resource_ura: &str, tenant_id: &str, ) -> Result { - let (path, _) = Self::split_resource_path_query(resource_uri)?; + let (path, _) = Self::split_resource_path_query(resource_ura)?; if let Some((realm, _ability_name)) = Self::parse_canonical_hub_ability_path(&path)? { if tenant_id.is_empty() { return Err(anyhow!( - "canonical hub ability URI requires non-empty envelope tenant_id" + "canonical hub ability URA requires non-empty envelope tenant_id" )); } if realm != tenant_id { return Err(anyhow!( - "canonical hub ability URI realm must match envelope tenant_id" + "canonical hub ability URA realm must match envelope tenant_id" )); } return Ok(format!("easynet:prv:hub:{realm}")); @@ -204,12 +204,12 @@ impl AxonClient { { if tenant_id.is_empty() { return Err(anyhow!( - "canonical resource URI requires non-empty envelope tenant_id" + "canonical resource URA requires non-empty envelope tenant_id" )); } if realm != tenant_id { return Err(anyhow!( - "canonical resource URI realm must match envelope tenant_id" + "canonical resource URA realm must match envelope tenant_id" )); } return Ok(format!("easynet:prv:resource:{owner_id}")); @@ -235,7 +235,7 @@ impl AxonClient { request_id: &str, tenant_id: &str, subject_id: &str, - resource_uri: &str, + resource_ura: &str, payload: &[u8], auth: &EasyNetUserAuth, ) -> Result { @@ -246,7 +246,7 @@ impl AxonClient { request_id, tenant_id, subject_id, - resource_uri, + resource_ura, payload_sha256, issued_at_unix_ms, nonce, @@ -254,16 +254,16 @@ impl AxonClient { }) } - pub async fn call_ability_uri_json( + pub async fn call_ability_ura_json( &mut self, tenant_id: impl Into, - resource_uri: impl Into, + resource_ura: impl Into, payload: impl Into>, options: AbilityCallOptions, ) -> Result { - self.call_ability_uri_json_with_context( + self.call_ability_ura_json_with_context( tenant_id, - resource_uri, + resource_ura, payload, options, AbilityInvokeContext::default(), @@ -271,10 +271,10 @@ impl AxonClient { .await } - pub async fn call_ability_uri_json_with_context( + pub async fn call_ability_ura_json_with_context( &mut self, tenant_id: impl Into, - resource_uri: impl Into, + resource_ura: impl Into, payload: impl Into>, mut options: AbilityCallOptions, context: AbilityInvokeContext, @@ -284,13 +284,18 @@ impl AxonClient { principal_id, } = context; let tenant_id = tenant_id.into(); - let resource_uri = resource_uri.into(); + let resource_ura = resource_ura.into(); let payload = payload.into(); - let canonical_uri = Self::canonicalize_easynet_resource_uri(&resource_uri, &tenant_id)?; - // Fill subject default deterministically from URI so semantic ownership remains queryable. + let content_envelope = options + .content_envelope + .clone() + .unwrap_or_else(crate::plaintext_json_envelope); + crate::validate_payload_matches_content_envelope(Some(&content_envelope), &payload)?; + let canonical_ura = Self::canonicalize_easynet_resource_ura(&resource_ura, &tenant_id)?; + // Fill subject default deterministically from URA so semantic ownership remains queryable. let subject_id = match options.subject_id.take() { Some(subject_id) => subject_id, - None => Self::default_subject_id_for_resource_uri(&canonical_uri, &tenant_id)?, + None => Self::default_subject_id_for_resource_ura(&canonical_ura, &tenant_id)?, }; let auth = options .auth @@ -301,38 +306,25 @@ impl AxonClient { .map(|value| !value.trim().is_empty()) .unwrap_or(false); let mut envelope = self.default_envelope_with( - "sdk-invoke-uri", + "sdk-invoke-ura", tenant_id.clone(), idempotency_key, principal_id, ); // If the caller didn't pin an explicit principal and the auto // generated fallback starts with "client-sdk:", rebuild the - // caller URA with the subject's owner as principal (RFC 001: - // principal = subject-value of caller URA). + // caller URA with the subject's owner as the user portion of + // the current agent URA. if !explicit_principal { - // Inline URA principal-extraction to avoid a cross-crate helper - // dependency. See RFC 001 §3.1: principal = subject-value of - // the caller URA, minus any `@version` suffix. let current_principal = envelope .caller .as_ref() - .and_then(|c| c.uri.strip_prefix("easynet:///r/")) - .and_then(|tail| { - let mut segs = tail.split('/'); - segs.next(); // scope - segs.next(); // subject-type - segs.next() - .map(|v| v.split('@').next().unwrap_or(v).to_string()) - }) + .and_then(|c| crate::ura::parse_ura(&c.ura).ok()) + .map(|parsed| parsed.user_id) .unwrap_or_default(); if current_principal.starts_with("client-sdk:") { if let Some(owner) = Self::subject_owner_id(&subject_id) { - let new_uri = format!("easynet:///r/{}/agents/{}", tenant_id.as_str(), owner); - envelope.caller = Some(pb::AgentIdentity { - uri: new_uri, - profile: "easynet-strict-v2".to_string(), - }); + envelope.caller = crate::ura::agent_identity(&tenant_id, &owner, "sdk"); } } } @@ -341,14 +333,14 @@ impl AxonClient { &request_id, &tenant_id, &subject_id, - &canonical_uri, + &canonical_ura, &payload, &auth, )?; let capability_name = options .capability_name .take() - .unwrap_or(Self::ability_name_from_resource_uri(&canonical_uri)?); + .unwrap_or(Self::ability_name_from_resource_ura(&canonical_ura)?); // Strategy=1 means direct node route; Strategy=2 defers to server-side routing. let strategy = if options.target_node_id.is_some() { 1 @@ -379,11 +371,15 @@ impl AxonClient { }), function_name: String::new(), arguments: payload, - content_type: options.content_type, + content_type: if options.content_type.is_empty() { + content_envelope.content_type.clone() + } else { + options.content_type + }, timeout_seconds: options.timeout_seconds.max(1), metadata, payload_ref: None, - content_envelope: None, + content_envelope: Some(content_envelope), }; self.invoke_raw(req).await @@ -406,7 +402,7 @@ impl AxonClient { } if k.contains('%') || v.contains('%') { return Err(anyhow!( - "percent-encoding is not allowed in easynet resource URI" + "percent-encoding is not allowed in easynet resource URA" )); } if items.iter().any(|(existing, _)| existing == k) { @@ -417,15 +413,15 @@ impl AxonClient { Ok(items) } - fn canonical_hub_ability_uri(realm: &str, ability_name: &str) -> String { - format!("easynet:///r/{realm}/ability/hub.{ability_name}") + fn canonical_hub_ability_ura(realm: &str, ability_name: &str) -> String { + crate::ura::hub_ability_ura(realm, ability_name) } fn parse_canonical_hub_ability_path(path: &str) -> Result> { let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() == 2 && parts[1].eq_ignore_ascii_case("hub") { return Err(anyhow!( - "resource_uri must reference /ability/hub.., not /hub" + "resource_ura must reference /ability/hub.., not /hub" )); } if parts.len() != 3 || !parts[1].eq_ignore_ascii_case("ability") { @@ -433,7 +429,7 @@ impl AxonClient { } let realm = parts[0].trim(); if realm.is_empty() { - return Err(anyhow!("canonical hub ability URI is missing realm")); + return Err(anyhow!("canonical hub ability URA is missing realm")); } let mut tail = parts[2].splitn(3, '.'); let owner = tail.next().unwrap_or(""); @@ -441,12 +437,12 @@ impl AxonClient { let member = tail.next().unwrap_or(""); if owner.is_empty() || namespace.is_empty() || member.is_empty() { return Err(anyhow!( - "canonical ability URI must be /r//ability/.." + "canonical ability URA must be /r//ability/.." )); } if owner != "hub" { return Err(anyhow!( - "canonical /r//ability/.. URIs are only supported for owner=hub in this Axon release" + "canonical /r//ability/.. URAs are only supported for owner=hub in this Axon release" )); } Ok(Some((realm.to_string(), format!("{namespace}.{member}")))) @@ -460,10 +456,10 @@ impl AxonClient { let realm = parts[0].trim(); let owner_id = parts[2].trim(); if realm.is_empty() { - return Err(anyhow!("canonical resource URI is missing realm")); + return Err(anyhow!("canonical resource URA is missing realm")); } if owner_id.is_empty() { - return Err(anyhow!("canonical resource URI is missing owner id")); + return Err(anyhow!("canonical resource URA is missing owner id")); } if !owner_id.contains('.') { return Ok(None); @@ -475,39 +471,39 @@ impl AxonClient { ))) } - fn canonicalize_r_path_uri(path: &str, query: &str, tenant_id: &str) -> Result { + fn canonicalize_r_path_ura(path: &str, query: &str, tenant_id: &str) -> Result { if let Some((realm, ability_name)) = Self::parse_canonical_hub_ability_path(path)? { if !query.is_empty() { return Err(anyhow!( - "canonical hub ability URI must not include query parameters" + "canonical hub ability URA must not include query parameters" )); } if tenant_id.is_empty() { return Err(anyhow!( - "canonical hub ability URI requires non-empty envelope tenant_id" + "canonical hub ability URA requires non-empty envelope tenant_id" )); } if realm != tenant_id { return Err(anyhow!( - "canonical hub ability URI realm must match envelope tenant_id" + "canonical hub ability URA realm must match envelope tenant_id" )); } - return Ok(Self::canonical_hub_ability_uri(&realm, &ability_name)); + return Ok(Self::canonical_hub_ability_ura(&realm, &ability_name)); } if let Some((realm, owner_id, resource_path)) = Self::parse_canonical_resource_path(path)? { if !query.is_empty() { return Err(anyhow!( - "canonical resource URI must not include query parameters" + "canonical resource URA must not include query parameters" )); } if tenant_id.is_empty() { return Err(anyhow!( - "canonical resource URI requires non-empty envelope tenant_id" + "canonical resource URA requires non-empty envelope tenant_id" )); } if realm != tenant_id { return Err(anyhow!( - "canonical resource URI realm must match envelope tenant_id" + "canonical resource URA realm must match envelope tenant_id" )); } let suffix = if resource_path.is_empty() { @@ -515,7 +511,7 @@ impl AxonClient { } else { format!("/{resource_path}") }; - return Ok(format!("easynet:///r/{realm}/resource/{owner_id}{suffix}")); + return Ok(crate::ura::resource_dot_ura(&realm, &owner_id, &suffix)); } let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); @@ -524,7 +520,7 @@ impl AxonClient { } let visibility = parts[0].to_ascii_lowercase(); if !matches!(visibility.as_str(), "pub" | "org" | "prv") { - return Err(anyhow!("invalid visibility for r easynet URI")); + return Err(anyhow!("invalid visibility for r easynet URA")); } let subject_type = parts[1].to_ascii_lowercase(); let subject_value = parts[2]; @@ -562,7 +558,7 @@ impl AxonClient { let found = items[idx].1.clone(); if found.is_empty() || found != tenant_id { return Err(anyhow!( - "tenant_id mismatch between envelope and resource_uri" + "tenant_id mismatch between envelope and resource_ura" )); } found @@ -595,15 +591,15 @@ impl AxonClient { pub(crate) fn build_signed_easynet_metadata_with_values( input: SignedMetadataInput<'_>, ) -> Result { - let canonical_uri = - Self::canonicalize_easynet_resource_uri(input.resource_uri, input.tenant_id)?; + let canonical_ura = + Self::canonicalize_easynet_resource_ura(input.resource_ura, input.tenant_id)?; let issued_at = input.issued_at_unix_ms.to_string(); let signature_input = Self::encode_canonical_security_fields(&[ "1", input.request_id, input.subject_id, input.tenant_id, - &canonical_uri, + &canonical_ura, &issued_at, input.nonce.as_str(), input.payload_sha256.as_str(), @@ -617,7 +613,7 @@ impl AxonClient { "easynet.subject_id".to_string(), input.subject_id.to_string(), ); - metadata.insert("easynet.resource_uri".to_string(), canonical_uri.clone()); + metadata.insert("easynet.resource_ura".to_string(), canonical_ura.clone()); metadata.insert("easynet.envelope_version".to_string(), "1".to_string()); metadata.insert( "easynet.issued_at_unix_ms".to_string(), @@ -631,7 +627,7 @@ impl AxonClient { input.auth.public_key_b64url.clone(), ); Ok(EasyNetSignedMetadata { - canonical_resource_uri: canonical_uri, + canonical_resource_ura: canonical_ura, metadata, }) } diff --git a/core/runtime-rs/client-sdk/src/domain/mod.rs b/core/runtime-rs/client-sdk/src/domain/mod.rs index daaf948f..545430d5 100644 --- a/core/runtime-rs/client-sdk/src/domain/mod.rs +++ b/core/runtime-rs/client-sdk/src/domain/mod.rs @@ -33,12 +33,11 @@ pub mod admission; /// canonical bytes cannot diverge across the gRPC boundary. pub mod bidi; mod capability; +pub mod content; mod easynet; pub(crate) mod identity; -/// RFC 001 §3.1 URA v2 identity primitive. The single canonical -/// implementation for the entire workspace — see the module docs for -/// the three hard rules and the drift cases that motivated extracting -/// it. Runtime-rs, the dendrite bridge, and every outbound envelope -/// construction path must route through here. +/// Current URA identity primitive. Runtime-rs, the dendrite bridge, +/// and every outbound envelope construction path must route through +/// this module. pub mod ura; mod voice; diff --git a/core/runtime-rs/client-sdk/src/domain/ura.rs b/core/runtime-rs/client-sdk/src/domain/ura.rs index 60d44e3c..3c653e6c 100644 --- a/core/runtime-rs/client-sdk/src/domain/ura.rs +++ b/core/runtime-rs/client-sdk/src/domain/ura.rs @@ -1,1152 +1,604 @@ -//! EasyNet Axon for AgentNet -//! ========================= +//! Current EasyNet URA grammar and proto identity conversion. //! -//! File: client-sdk/src/domain/ura.rs -//! Description: Single canonical implementation of the Universal Resource -//! Agent (URA v2) identity primitive for the entire workspace. +//! URA is Axon protocol state. It is the stable identity/address form +//! carried by envelopes, receipts, trace records, directory entries, +//! resource dialogs, and invocation targets. Runtime code should parse +//! full URAs here and pass full URAs across boundaries; it should not +//! reconstruct URAs from fragments. //! -//! # Why this module exists -//! -//! URA is a protocol primitive, not a utility. It is the **canonical -//! byte representation** of an agent identity and it flows verbatim into -//! three cryptographic primitives: -//! -//! 1. `caller_binding.uri` in canonical invocation bytes -//! (RFC 001 §4.1). The caller signs over these bytes. -//! 2. `callee_binding.uri` / `subject_binding.uri` in canonical -//! receipt bytes (RFC 001 §4.3). The callee signs over these. -//! 3. The replay-store composite key: `(caller_uri, ability, nonce)`. -//! -//! If two call sites produce subtly different canonical forms for "the -//! same" identity — one trims whitespace, one does not; one NFC-normalises -//! Unicode, one does not; one lowercases the scheme, one does not — -//! three things break in sequence: -//! -//! * caller and callee sign different byte strings → signature fails -//! * tenant isolation scopes a trimmed copy → cross-tenant leak -//! * replay store keys off the untrimmed copy → replay admitted -//! -//! The pre-release audit of this branch found three parallel -//! implementations drifting on exactly these dimensions (`runtime::mod` -//! trimmed; `client-sdk::infra::client` did not; admission canonical -//! encoder pass-through preserved the raw bytes). Collapsing them into -//! this single module is the pre-release fix. -//! -//! # Three hard rules (enforced by this module) -//! -//! Rule 1 — **No silent normalisation on build.** `Ura::build` rejects -//! any component containing leading/trailing whitespace, embedded -//! ASCII whitespace, ASCII control characters, or path-reserved -//! characters (`/ \ ? # @`). The rationale is that canonical form -//! cannot depend on a permissive parse — if the input looks wrong, -//! the call must fail fast rather than produce two different valid -//! strings for "the same" identity. -//! -//! Rule 2 — **parse ∘ build is the identity on valid inputs.** Any URA -//! that `build` accepts must round-trip through `to_canonical_string` -//! and `parse` without mutation. The `round_trip_preserves_components` -//! test pins this against a corpus including Unicode, percent-escapes, -//! and case-sensitive segments. -//! -//! Rule 3 — **One canonical-bytes getter.** Every signing/verification -//! call site MUST go through [`Ura::to_canonical_string`]. The -//! `Display` implementation delegates there too, so `format!`-style -//! use is correct by construction. -//! -//! # Normalization policy — NONE -//! -//! URA is a **strict, non-normalizing identity format.** Any deviation -//! from the canonical grammar is rejected at [`Ura::parse`] or -//! [`Ura::build`] time — never normalized. In particular, this module -//! does **not** do any of the following, even where it would be -//! "convenient": -//! -//! * Trim leading / trailing whitespace on components. Whitespace is -//! a Rule 1 rejection, not a normalization target. -//! * Lowercase the scope (or any other segment). Case is significant -//! — `silan` and `Silan` are different identities. -//! * Decode or re-encode percent-escapes. `a%20b` and `a b` are -//! different identities; `a%20b` is valid, `a b` is rejected. -//! * NFC-normalize Unicode. `café` (NFC) and `cafe\u{0301}` (NFD) -//! hash to different bytes under this module. The signer is -//! responsible for their own normalization discipline — whatever -//! bytes they signed over are what the verifier sees. -//! * Strip the `@` before an empty version. `alice@` is rejected -//! rather than treated as `alice`. -//! -//! This policy is deliberate: every "helpful" normalization creates a -//! second path to the same logical identity, and therefore a second -//! set of canonical bytes for an attacker or a buggy peer to diverge -//! against. The single source of truth for an identity is the bytes -//! the caller signed over — which means the bytes this module -//! produces, which means the bytes the caller literally supplied. -//! -//! A future version of this grammar MAY introduce normalization (e.g. -//! NFC for Unicode segments) as a mandatory pre-processing step at -//! the signer boundary. That would be a profile bump -//! (`easynet-strict-v3`) and would co-commit with spec updates and -//! new axiom vectors. It is explicitly **not** a silent in-place -//! softening of the strict-v2 rules. -//! -//! # Grammar (RFC 001 §3.1 composite identity, v2 overlay) +//! ## Canonical shapes //! //! ```text -//! ura = "easynet:///r/" scope "/" subject-type "/" subject-value -//! [ "@" version ] -//! scope = 1*segment-char -//! subject-type = 1*segment-char -//! subject-value= 1*segment-char -//! version = 1*segment-char ; first '@' after subject-value -//! segment-char = ALPHA / DIGIT / "-" / "_" / "." / "~" -//! / pct-encoded / unicode-letter +//! user easynet:///r//user/ +//! device easynet:///r//device/ +//! agent easynet:///r//agent/. +//! ability easynet:///r//ability/.. +//! hub easynet:///r//hub +//! resource easynet:///r//resource// //! ``` //! -//! The profile selector (`easynet-strict-v2` / `web-safe-v2`) is carried -//! *alongside* the URI on [`pb::AgentIdentity`], not inside the URI -//! itself. This module is opinionated about `easynet-strict-v2` — the -//! only profile the runtime implements today. `web-safe-v2` is the -//! RFC-3986-compatible subset and is accepted for forward compatibility, -//! but [`Ura::build_with_profile`] refuses to construct it from raw -//! components; callers that need `web-safe-v2` must supply a pre-built -//! URI. -//! -//! # Relationship to [`pb::AgentIdentity`] / [`pb::SubjectIdentity`] -//! -//! [`Ura`] is the **typed form**; `pb::AgentIdentity { uri, profile }` -//! is the **wire form**. Conversions live in [`Ura::into_agent_identity`] -//! and [`Ura::try_from_agent_identity`]. The typed form is what every -//! non-transport call site should pass around; the wire form only -//! appears when crossing the proto boundary. +//! ## Examples //! -//! # Why parse returns Result instead of Option +//! ```text +//! easynet:///r/localhost/user/u-9f4 +//! easynet:///r/localhost/device/8315ea5c-7cfd-473e-8fef-95340af6d971 +//! easynet:///r/localhost/agent/u-9f4.frontend-engineer +//! easynet:///r/localhost/ability/u-9f4.frontend-engineer.chat +//! easynet:///r/localhost/ability/hub.federation.resolve +//! easynet:///r/localhost/hub +//! easynet:///r/localhost/resource/agent.u-9f4.frontend-engineer/skill/alive-video +//! easynet:///r/localhost/resource/device.8315ea5c-7cfd-473e-8fef-95340af6d971/ability/device.skill.tree +//! ``` //! -//! A parse failure carries information the caller needs: which -//! component was wrong, what the hard rule being violated is. The -//! error type [`UraError`] is typed, not stringly-wrapped, so call sites -//! can branch on the specific rejection and map it to either -//! `AXON_AXIOM_ENVELOPE_INCOMPLETE` (malformed caller URI inbound) or -//! `VALIDATION` (local client-side pre-check). +//! ## Semantics //! -//! Author: Silan.Hu -//! Email: silan.hu@u.nus.edu -//! Copyright (c) 2026-2027 easynet. All rights reserved. +//! - `realm` names the federation authority, such as `localhost` or +//! `easynet.run`. +//! - `user` is ownership identity. A user owns agents and user-scoped +//! resources. +//! - `device` is runtime placement identity. A device hosts sessions, +//! local abilities, terminal/PTY operations, and file substrate access. +//! - `agent` is user-owned logical execution identity. Device placement +//! is directory metadata, not part of the agent URA. +//! - `ability` is the callable identity. Hub-owned abilities use owner +//! token `hub`, for example `hub.federation.resolve`. +//! - `hub` is a realm singleton and never has a tail. +//! - `resource` is the concrete substrate or inspectable object. Its +//! first tail segment is an owner id such as `device.`, +//! `agent..`, `api_key.`, or `.files`; the +//! remaining slash path is interpreted by that owner namespace. +//! - `membership_ura` is the join-time identity returned by +//! `federation.join`. A device member uses a device URA; an agent +//! member uses an agent URA. use std::fmt; use crate::pb; -// ─── Canonical constants ──────────────────────────────────────────── - -/// URA v2 scheme+authority prefix. Every canonical URA starts with this. -/// -/// The triple-slash (`///`) is intentional: URA is an authority-less URI -/// by design (resolution happens inside the EasyNet federation, not via -/// DNS), and the leading `/r/` path segment locks the scheme to -/// "resource" addressing to reserve room for future schemes (`/s/` for -/// sessions, `/k/` for key bundles, etc.) per RFC 001 §3.1. -pub const URA_V2_PREFIX: &str = "easynet:///r/"; - -/// The RFC 001 default profile selector. All canonical-bytes sites -/// must use this exact string — it is the value the caller signs over, -/// and the callee verifies character-for-character. +pub const REALM_EASYNET: &str = "easynet.run"; +pub const URA_SCHEME: &str = "easynet:///r/"; pub const PROFILE_STRICT_V2: &str = "easynet-strict-v2"; - -/// The RFC-3986-compatible profile selector. Accepted for forward -/// compatibility but not constructable from raw components by this -/// module; callers must supply a pre-built URI. pub const PROFILE_WEB_SAFE_V2: &str = "web-safe-v2"; -/// Default subject-type segment for "agent" principals. AXIOM.tex §3.2 -/// names this the SystemAgent convention. [`Ura::build`] uses this -/// when the subject type is elided at the call site, which is the -/// overwhelmingly common case in client-sdk. -pub const SUBJECT_TYPE_AGENT: &str = "agents"; - -// ─── Error taxonomy ───────────────────────────────────────────────── - -/// Typed rejection reason for [`Ura::parse`] and [`Ura::build`]. -/// -/// These map 1:1 to user-facing failure modes: -/// -/// * Shape errors (missing prefix, wrong segment count) are -/// canonical-form violations. They flag that the input was not a -/// URA at all. -/// * Component errors (empty/whitespace/control/reserved) are Rule 1 -/// violations. They flag that the caller passed data that **looks -/// close** but would have drifted from other call sites. -/// -/// Call sites map `UraError` to error codes as follows: -/// -/// * Inbound envelopes (runtime gateway) → -/// `AXON_AXIOM_ENVELOPE_INCOMPLETE` with the `UraError` attached -/// in the `detail` field. The caller fixed the URI at sign time, -/// so admission has nothing to verify against. -/// * Client-sdk pre-check (before sending) → `VALIDATION`. The local -/// call is malformed and never makes it to the wire. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum UraError { - /// Input does not start with [`URA_V2_PREFIX`]. - MissingPrefix, - /// Input has the prefix but fewer than three path segments - /// (scope / subject-type / subject-value). A URA without all three - /// is not a canonical identity — tenant isolation and signature - /// verification both assume the 3-segment shape. - TooFewSegments { got: usize }, - /// Input has more than three path segments before the optional - /// `@version` suffix. URA v2 does not allow nested paths; a future - /// `v3` may. - TooManySegments { got: usize }, - /// A component is empty. Empty scope ("`easynet:///r//agents/x`") - /// or empty subject-value would create ambiguous canonical bytes. - EmptyComponent { which: ComponentKind }, - /// A component contains leading/trailing ASCII whitespace, embedded - /// ASCII whitespace, or ASCII control characters. Rule 1: no - /// silent trim. - ContainsWhitespace { which: ComponentKind }, - /// A component contains a path-reserved character (`/ \ ? # @`) - /// that would re-interpret the segment boundary. Rule 1: the - /// component stays atomic. - ContainsReserved { - which: ComponentKind, - /// The specific offending character, for diagnostics. - char_found: char, - }, - /// The `@version` suffix is empty (`"foo@"`). Either include a - /// version or omit the `@`. - EmptyVersionSuffix, - /// More than one `@` appears in the subject-value. RFC 001 §3.1 - /// reserves the first `@` as the version separator; a second one - /// is a canonical-form violation. - MultipleVersionSeparators, - /// The profile field on an [`pb::AgentIdentity`] is neither - /// `easynet-strict-v2` nor `web-safe-v2`. Unknown profiles fail - /// closed so a future `v3` cannot be silently routed through the - /// `v2` verifier. - UnknownProfile { got: String }, - /// [`Ura::try_from_agent_identity`] saw an empty URI field on an - /// otherwise-populated identity. Treat as anonymous / caller-absent. - EmptyUri, +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum URAKind { + Hub, + Device, + User, + Agent, + Ability, + Resource, + #[default] + Unknown, } -impl fmt::Display for UraError { +impl fmt::Display for URAKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - UraError::MissingPrefix => { - write!(f, "ura: missing scheme prefix (expected {URA_V2_PREFIX:?})") - } - UraError::TooFewSegments { got } => { - write!(f, "ura: too few path segments (got {got}, need 3)") - } - UraError::TooManySegments { got } => { - write!(f, "ura: too many path segments (got {got}, max 3)") - } - UraError::EmptyComponent { which } => { - write!(f, "ura: empty {which} component") - } - UraError::ContainsWhitespace { which } => { - write!(f, "ura: {which} contains whitespace or control bytes") - } - UraError::ContainsReserved { which, char_found } => { - write!(f, "ura: {which} contains reserved character {char_found:?}") - } - UraError::EmptyVersionSuffix => { - write!(f, "ura: version suffix after '@' is empty") - } - UraError::MultipleVersionSeparators => { - write!(f, "ura: multiple '@' separators in subject-value") - } - UraError::UnknownProfile { got } => { - write!(f, "ura: unknown profile {got:?}") - } - UraError::EmptyUri => write!(f, "ura: uri is empty"), - } + f.write_str(match self { + URAKind::Hub => "hub", + URAKind::Device => "device", + URAKind::User => "user", + URAKind::Agent => "agent", + URAKind::Ability => "ability", + URAKind::Resource => "resource", + URAKind::Unknown => "unknown", + }) } } -impl std::error::Error for UraError {} - -/// Identifies which component of a URA failed validation. Used by -/// [`UraError`] variants so diagnostics can point at the exact field. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ComponentKind { - Scope, - SubjectType, - SubjectValue, - Version, +pub enum ResourceNamespace { + Fs, + Process, + Pty, + Shell, + Http, +} + +impl ResourceNamespace { + pub fn as_str(self) -> &'static str { + match self { + ResourceNamespace::Fs => "fs", + ResourceNamespace::Process => "process", + ResourceNamespace::Pty => "pty", + ResourceNamespace::Shell => "shell", + ResourceNamespace::Http => "http", + } + } } -impl fmt::Display for ComponentKind { +impl fmt::Display for ResourceNamespace { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match self { - ComponentKind::Scope => "scope", - ComponentKind::SubjectType => "subject-type", - ComponentKind::SubjectValue => "subject-value", - ComponentKind::Version => "version", - }; - f.write_str(s) + f.write_str(self.as_str()) } } -// ─── The typed URA ────────────────────────────────────────────────── - -/// A parsed, validated URA v2 identity. -/// -/// The fields are private so callers cannot construct invariant- -/// violating instances. All construction paths go through [`Ura::parse`] -/// or [`Ura::build`] / [`Ura::build_agent`], each of which enforces -/// the three hard rules in full. -/// -/// `Ura` intentionally does **not** implement `Default` — there is no -/// canonical default URA, only the explicit "anonymous" signalled by -/// the absence of an identity (`Option::None`). -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct Ura { - /// Tenant scope. Required, non-empty, no whitespace / reserved chars. - scope: String, - /// Subject type. Required. Defaults to [`SUBJECT_TYPE_AGENT`] when - /// omitted at construction. - subject_type: String, - /// Subject value. Required, non-empty. - subject_value: String, - /// Optional version suffix (after `@`). When `Some`, must be - /// non-empty per [`UraError::EmptyVersionSuffix`]. - version: Option, - /// Profile selector. Defaults to [`PROFILE_STRICT_V2`] at - /// construction time. - profile: String, - /// Memoised canonical string. Computed at construction and returned - /// verbatim by [`Ura::to_canonical_string`] so signing call sites - /// pay zero per-call cost. - canonical: String, +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ParsedURA { + pub realm: String, + pub kind: URAKind, + pub user_id: String, + pub device_id: String, + pub agent_id: String, + pub ability_id: String, + pub namespace: Option, + pub path: String, + pub raw: String, } -impl Ura { - // ── Construction ──────────────────────────────────────────────── - - /// Parse a canonical URA string, rejecting any shape that drifts - /// from the grammar. Strict by design — see the module docs. - /// - /// Use this when you receive a URA from a wire format (envelope, - /// receipt, caller-supplied config). For constructing a URA from - /// local `(tenant, principal)` pairs, prefer [`Ura::build_agent`] - /// so the subject-type defaulting is explicit. - pub fn parse(input: &str) -> Result { - Self::parse_with_profile(input, PROFILE_STRICT_V2) - } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ParseError { + BadScheme, + EmptyRealm, + EmptyRole, + UserMissingTail, + UserBadShape, + DeviceMissingTail, + DeviceBadShape, + AgentMissingTail, + AgentBadShape, + AbilityMissingTail, + AbilityBadShape, + HubUnexpectedTail(String), + ResourceMissingTail, + ResourceEmptyOwner, + UnknownRole(String), + EmptyIdentityURA, + UnknownProfile(String), +} - /// Parse a URA string with a caller-supplied profile selector. - /// Both known profile strings ([`PROFILE_STRICT_V2`] and - /// [`PROFILE_WEB_SAFE_V2`]) are accepted; any other value yields - /// [`UraError::UnknownProfile`]. - pub fn parse_with_profile(input: &str, profile: &str) -> Result { - let profile = Self::validate_profile(profile)?; - let tail = input - .strip_prefix(URA_V2_PREFIX) - .ok_or(UraError::MissingPrefix)?; - - // Split into segments. We collect into a Vec first because we - // need the count to detect both "too few" and "too many". - let segs: Vec<&str> = tail.split('/').collect(); - if segs.len() < 3 { - return Err(UraError::TooFewSegments { got: segs.len() }); - } - if segs.len() > 3 { - return Err(UraError::TooManySegments { got: segs.len() }); - } - let scope_raw = segs[0]; - let subject_type_raw = segs[1]; - let subject_value_raw = segs[2]; - - // Split off the version suffix from subject-value, if present. - // `splitn(2, '@')` gives us [value, version] or [value] and - // deliberately treats the second `@` as part of `version` — - // we then reject the multi-`@` case explicitly below so the - // error is nameable. - let (subject_value_part, version_part) = match subject_value_raw.split_once('@') { - None => (subject_value_raw, None), - // Empty right side of `@` — the version suffix is empty. - // We reject here rather than recording `Some("")`, because a - // missing version MUST look different on the wire from a - // present-but-empty one; otherwise canonical bytes drift - // between producers that strip the trailing `@` and those - // that keep it. - Some((_, "")) => return Err(UraError::EmptyVersionSuffix), - Some((v, ver)) => { - if ver.contains('@') { - return Err(UraError::MultipleVersionSeparators); - } - (v, Some(ver)) +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ParseError::BadScheme => f.write_str("URA must start with easynet:///r/"), + ParseError::EmptyRealm => f.write_str("URA missing segment"), + ParseError::EmptyRole => f.write_str("URA missing segment"), + ParseError::UserMissingTail => f.write_str("user URA requires tail"), + ParseError::UserBadShape => f.write_str("user-id must be a single path segment"), + ParseError::DeviceMissingTail => f.write_str("device URA requires tail"), + ParseError::DeviceBadShape => f.write_str("device-id must be a single path segment"), + ParseError::AgentMissingTail => { + f.write_str("agent URA requires . tail") } - }; - - // Validate each component. Errors carry the `which` - // identifier so the diagnostic points at the exact field. - Self::validate_component(scope_raw, ComponentKind::Scope)?; - Self::validate_component(subject_type_raw, ComponentKind::SubjectType)?; - Self::validate_component(subject_value_part, ComponentKind::SubjectValue)?; - if let Some(v) = version_part { - Self::validate_component(v, ComponentKind::Version)?; + ParseError::AgentBadShape => f.write_str("agent tail must be ."), + ParseError::AbilityMissingTail => { + f.write_str("ability URA requires .. tail") + } + ParseError::AbilityBadShape => { + f.write_str("ability tail must have three non-empty dot-separated parts") + } + ParseError::HubUnexpectedTail(tail) => { + write!(f, "hub is a realm singleton; unexpected tail {tail:?}") + } + ParseError::ResourceMissingTail => f.write_str("resource URA requires tail"), + ParseError::ResourceEmptyOwner => f.write_str("resource owner segment is empty"), + ParseError::UnknownRole(role) => write!( + f, + "unknown URA role {role:?} (allowed: user/device/agent/ability/hub/resource)" + ), + ParseError::EmptyIdentityURA => f.write_str("identity URA is empty"), + ParseError::UnknownProfile(profile) => write!(f, "unknown URA profile {profile:?}"), } + } +} - let canonical = Self::compose_canonical( - scope_raw, - subject_type_raw, - subject_value_part, - version_part, - ); +impl std::error::Error for ParseError {} - Ok(Self { - scope: scope_raw.to_string(), - subject_type: subject_type_raw.to_string(), - subject_value: subject_value_part.to_string(), - version: version_part.map(str::to_string), - profile, - canonical, - }) - } +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Ura(String); - /// Build a URA from explicit `(scope, subject_type, subject_value)` - /// plus an optional version. Enforces all three hard rules on each - /// component. - /// - /// Use this when the caller already knows the subject-type - /// (`papers`, `tools`, `models`, …). For the default "agent" - /// case, [`Ura::build_agent`] is the three-argument shortcut. - pub fn build( - scope: &str, - subject_type: &str, - subject_value: &str, - version: Option<&str>, - ) -> Result { - Self::validate_component(scope, ComponentKind::Scope)?; - Self::validate_component(subject_type, ComponentKind::SubjectType)?; - Self::validate_component(subject_value, ComponentKind::SubjectValue)?; - if let Some(v) = version { - Self::validate_component(v, ComponentKind::Version)?; - } - let canonical = Self::compose_canonical(scope, subject_type, subject_value, version); - Ok(Self { - scope: scope.to_string(), - subject_type: subject_type.to_string(), - subject_value: subject_value.to_string(), - version: version.map(str::to_string), - profile: PROFILE_STRICT_V2.to_string(), - canonical, - }) +impl Ura { + pub fn parse(input: impl Into) -> Result { + let input = input.into(); + parse_ura(&input)?; + Ok(Self(input)) } - /// Build an agent URA from `(scope, subject_value)` — the most - /// common client-sdk construction path. Subject type is fixed to - /// [`SUBJECT_TYPE_AGENT`] per AXIOM.tex §3.2. - pub fn build_agent(scope: &str, subject_value: &str) -> Result { - Self::build(scope, SUBJECT_TYPE_AGENT, subject_value, None) + pub fn user(realm: &str, user_id: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/user/{user_id}")) } - /// Build with a caller-supplied profile selector. The scope / - /// subject-type / subject-value components still go through the - /// strict validator — the profile only gates which selector string - /// is recorded on the wire. - pub fn build_with_profile( - scope: &str, - subject_type: &str, - subject_value: &str, - version: Option<&str>, - profile: &str, - ) -> Result { - let profile = Self::validate_profile(profile)?; - let mut u = Self::build(scope, subject_type, subject_value, version)?; - u.profile = profile; - Ok(u) + pub fn device(realm: &str, device_id: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/device/{device_id}")) } - // ── Accessors ─────────────────────────────────────────────────── - - /// The canonical string form. **This is the byte sequence that - /// enters canonical invocation / receipt bytes.** Every signing - /// or verification site MUST read through this accessor; direct - /// field access is not public for exactly this reason. - pub fn to_canonical_string(&self) -> &str { - &self.canonical + pub fn agent(realm: &str, user_id: &str, agent_id: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/agent/{user_id}.{agent_id}")) } - /// Tenant scope segment. - pub fn scope(&self) -> &str { - &self.scope + pub fn ability(realm: &str, user_id: &str, agent_id: &str, ability_id: &str) -> Self { + Self(format!( + "{URA_SCHEME}{realm}/ability/{user_id}.{agent_id}.{ability_id}" + )) } - /// Subject type segment (e.g. `agents`, `papers`, `tools`). - pub fn subject_type(&self) -> &str { - &self.subject_type + pub fn hub_ability(realm: &str, full_ability_name: &str) -> Self { + let (namespace, tail) = full_ability_name + .split_once('.') + .expect("hub-owned ability names must include a namespace prefix"); + Self::ability(realm, "hub", namespace, tail) } - /// Subject value segment (the principal id for agents, the resource - /// id for other subject types). - pub fn subject_value(&self) -> &str { - &self.subject_value + pub fn hub(realm: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/hub")) } - /// Optional version suffix (after `@`). - pub fn version(&self) -> Option<&str> { - self.version.as_deref() + pub fn resource(realm: &str, owner_id: &str, ns: ResourceNamespace, path: &str) -> Self { + let owner = if owner_id.contains('.') { + owner_id.to_string() + } else { + format!("{owner_id}.{}", ns.as_str()) + }; + Self::resource_dot(realm, &owner, path) } - /// Profile selector string. Either [`PROFILE_STRICT_V2`] or - /// [`PROFILE_WEB_SAFE_V2`]; no other value is ever stored. - pub fn profile(&self) -> &str { - &self.profile + pub fn resource_dot(realm: &str, owner_id: &str, path: &str) -> Self { + let clean = path.strip_prefix('/').unwrap_or(path); + if clean.is_empty() { + return Self(format!("{URA_SCHEME}{realm}/resource/{owner_id}")); + } + Self(format!("{URA_SCHEME}{realm}/resource/{owner_id}/{clean}")) } - // ── Proto boundary ────────────────────────────────────────────── + pub fn device_ability_resource(realm: &str, device_id: &str, ability_id: &str) -> Self { + Self::resource_dot( + realm, + &format!("device.{device_id}"), + &format!("ability/{ability_id}"), + ) + } - /// Convert to the wire form used by `pb::Envelope.caller` / - /// `pb::Envelope.callee`. The memoised canonical string is reused, - /// so this is a cheap clone. - pub fn into_agent_identity(self) -> pb::AgentIdentity { - pb::AgentIdentity { - uri: self.canonical, - profile: self.profile, - } + pub fn payload_resource(realm: &str, owner_id: &str, payload_id: &str) -> Self { + Self::resource_dot(realm, owner_id, &format!("payload/{payload_id}")) } - /// Convert to the wire form used by `pb::Envelope.subject`. - /// `SubjectIdentity` has the same two fields on the wire — the - /// distinct proto message exists so the signing region can - /// tag the binding role (Q5, the acted-on resource, vs Q1/Q2). - pub fn into_subject_identity(self) -> pb::SubjectIdentity { - pb::SubjectIdentity { - uri: self.canonical, - profile: self.profile, - } + pub fn invocation_history_resource( + realm: &str, + owner_id: &str, + invocation_id: &str, + ) -> Self { + Self::resource_dot( + realm, + owner_id, + &format!("invocation/{invocation_id}/history"), + ) } - /// Parse back from the wire form. Returns [`UraError::EmptyUri`] - /// when the URI field is empty; callers treat that as "identity - /// absent" (anonymous caller, subject-less invocation, etc.) and - /// do not error — it is only an error if they expected an - /// identity. - pub fn try_from_agent_identity(id: &pb::AgentIdentity) -> Result { - if id.uri.is_empty() { - return Err(UraError::EmptyUri); - } - Self::parse_with_profile(&id.uri, &id.profile) + pub fn as_str(&self) -> &str { + &self.0 } - /// Parse back from a `SubjectIdentity`. Identical wire shape to - /// [`Self::try_from_agent_identity`] — the distinction is - /// semantic, not structural. - pub fn try_from_subject_identity(id: &pb::SubjectIdentity) -> Result { - if id.uri.is_empty() { - return Err(UraError::EmptyUri); - } - Self::parse_with_profile(&id.uri, &id.profile) + pub fn into_string(self) -> String { + self.0 } - // ── Internals ─────────────────────────────────────────────────── + pub fn parsed(&self) -> Result { + parse_ura(&self.0) + } - /// Enforce Rule 1 on a single component. Public as - /// `pub(crate)` so the conversion tests in `admission_gate` can - /// call it directly against wire-inbound data without going - /// through a full `parse`. - fn validate_component(s: &str, which: ComponentKind) -> Result<(), UraError> { - if s.is_empty() { - return Err(UraError::EmptyComponent { which }); - } - for ch in s.chars() { - // Reject all ASCII whitespace (space, tab, CR, LF, FF, VT) - // and all ASCII control bytes. Unicode whitespace beyond - // ASCII (e.g. NBSP U+00A0, ZWSP U+200B) is deliberately - // not rejected here — Unicode normalisation is the - // signer's concern; our job is to refuse ambiguities we - // can detect cheaply and deterministically. - if ch.is_ascii_whitespace() || ch.is_ascii_control() { - return Err(UraError::ContainsWhitespace { which }); - } - // Path-reserved characters would re-interpret the segment - // boundary. `/` and `\` break the split; `?` and `#` - // introduce URI query/fragment ambiguity; `@` is our - // version separator and must only appear at the - // subject-value/version boundary (enforced at parse time, - // so this check covers other components and any literal - // `@` inside a component value). - if matches!(ch, '/' | '\\' | '?' | '#' | '@') { - return Err(UraError::ContainsReserved { - which, - char_found: ch, - }); - } - } - Ok(()) + pub fn kind(&self) -> URAKind { + kind_from_ura(&self.0) } - fn validate_profile(profile: &str) -> Result { - match profile { - PROFILE_STRICT_V2 | PROFILE_WEB_SAFE_V2 => Ok(profile.to_string()), - // Empty profile is treated as strict-v2 for - // backwards-compatibility with callers that forgot to set - // it. An explicit non-empty unknown value fails closed — - // that is how future profiles (`v3`, etc.) signal - // incompatibility with the current verifier. - "" => Ok(PROFILE_STRICT_V2.to_string()), - other => Err(UraError::UnknownProfile { - got: other.to_string(), - }), - } + pub fn realm(&self) -> String { + realm_from_ura(&self.0) } - /// The single canonical-form composer. All construction paths - /// funnel through here so the string layout is written down in - /// exactly one place. Any future grammar change (new segment - /// order, new separator, etc.) is a one-line edit to this function. - fn compose_canonical( - scope: &str, - subject_type: &str, - subject_value: &str, - version: Option<&str>, - ) -> String { - let mut out = String::with_capacity( - URA_V2_PREFIX.len() + scope.len() + subject_type.len() + subject_value.len() + 4, - ); - out.push_str(URA_V2_PREFIX); - out.push_str(scope); - out.push('/'); - out.push_str(subject_type); - out.push('/'); - out.push_str(subject_value); - if let Some(v) = version { - out.push('@'); - out.push_str(v); - } - out + pub fn display_id(&self) -> String { + display_id(&self.0) } } impl fmt::Display for Ura { - /// Delegates to [`Self::to_canonical_string`]. `format!("{ura}")` - /// is therefore always the canonical byte form — Rule 3 is enforced - /// even for pretty-printing paths. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.canonical) + f.write_str(&self.0) } } -// ─── Convenience top-level helpers ────────────────────────────────── - -/// Extract the scope (tenant) from a canonical URA string. Returns an -/// empty string when the input is not a valid URA — call sites at the -/// runtime gateway rely on this forgiving behaviour to treat malformed -/// or absent callers as "anonymous / no tenant" without needing a -/// match arm per call. Strict parsing should go through -/// [`Ura::parse`] directly. -/// -/// This function is the single authority for "give me the tenant from -/// a URI string"; both the runtime's [`envelope_tenant_id`] helper and -/// any future CLI/debug path should call here. -/// -/// [`envelope_tenant_id`]: (runtime-rs-internal) -pub fn scope_from_uri(uri: &str) -> String { - Ura::parse(uri).map(|u| u.scope).unwrap_or_default() +impl AsRef for Ura { + fn as_ref(&self) -> &str { + self.as_str() + } } -/// Extract the subject-value (principal id, for agent URAs) from a -/// canonical URA string. See [`scope_from_uri`] for the -/// empty-on-failure rationale. -pub fn subject_value_from_uri(uri: &str) -> String { - Ura::parse(uri).map(|u| u.subject_value).unwrap_or_default() -} +impl TryFrom<&str> for Ura { + type Error = ParseError; -/// Build a canonical agent URA string from `(tenant, principal)`. -/// Returns an empty string iff both inputs are empty (the "anonymous" -/// sentinel); any other validation failure **panics** — callers at the -/// construction boundary are expected to have pre-validated their -/// inputs, and silently producing `""` on a bad principal would hide -/// a drift bug. Use [`Ura::build_agent`] directly if you need typed -/// error handling. -/// -/// The panic path is a deliberate design choice: the only production -/// call sites (runtime-rs outbound envelope construction, -/// client-sdk base-envelope) have their own upstream validation, and -/// a drift between them silently producing identical-but-empty URAs -/// is exactly the class of bug this module was created to prevent. -pub fn build_agent_uri(tenant: &str, principal: &str) -> String { - if tenant.is_empty() && principal.is_empty() { - return String::new(); + fn try_from(value: &str) -> Result { + Self::parse(value) } - Ura::build_agent(tenant, principal) - .map(|u| u.to_canonical_string().to_string()) - .unwrap_or_else(|e| { - panic!( - "build_agent_uri: invalid components tenant={tenant:?} principal={principal:?}: {e}" - ) - }) } -/// Build an [`pb::AgentIdentity`] from `(tenant, principal)`. Returns -/// `None` for the anonymous case, matching the upstream semantics of -/// `pb::Envelope.caller: Option`. -pub fn build_agent_identity(tenant: &str, principal: &str) -> Option { - if tenant.is_empty() && principal.is_empty() { - return None; +impl From for String { + fn from(value: Ura) -> Self { + value.into_string() } - Ura::build_agent(tenant, principal) - .map(|u| u.into_agent_identity()) - .ok() } -// ═══════════════════════════════════════════════════════════════════════ -// Tests — industrial-grade coverage of the three hard rules. -// -// Structure: -// 1. Rule 1 tests: construction rejects whitespace / controls / -// reserved chars. Each negative case pins a specific error variant -// so future grammar changes surface as test diffs. -// 2. Rule 2 tests: round-trip property. parse ∘ build = id, for every -// valid combination in the corpus. Includes Unicode, percent -// escapes (accepted as opaque characters — we don't decode), and -// case-sensitivity. -// 3. Rule 3 tests: Display, canonical-string, and proto conversion -// all produce the same bytes. A single "canonical oracle" test -// confirms this equivalence. -// 4. Error-taxonomy tests: each UraError variant is reachable. -// 5. Regression guards for the three drift cases that motivated the -// module (trim asymmetry, multi-@, empty-version). -// ═══════════════════════════════════════════════════════════════════════ +pub fn user_ura(realm: &str, user_id: &str) -> String { + Ura::user(realm, user_id).into_string() +} -#[cfg(test)] -mod tests { - use super::*; +pub fn device_ura(realm: &str, device_id: &str) -> String { + Ura::device(realm, device_id).into_string() +} - // ── Rule 1 — strict construction ───────────────────────────────── +pub fn agent_ura(realm: &str, user_id: &str, agent_id: &str) -> String { + Ura::agent(realm, user_id, agent_id).into_string() +} - #[test] - fn build_rejects_leading_whitespace_in_scope() { - let err = Ura::build_agent(" silan", "alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsWhitespace { - which: ComponentKind::Scope - } - ); - } +pub fn ability_ura(realm: &str, user_id: &str, agent_id: &str, ability_id: &str) -> String { + Ura::ability(realm, user_id, agent_id, ability_id).into_string() +} - #[test] - fn build_rejects_trailing_whitespace_in_scope() { - let err = Ura::build_agent("silan ", "alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsWhitespace { - which: ComponentKind::Scope - } - ); - } +pub fn hub_ability_ura(realm: &str, full_ability_name: &str) -> String { + Ura::hub_ability(realm, full_ability_name).into_string() +} - #[test] - fn build_rejects_embedded_whitespace_in_subject_value() { - let err = Ura::build_agent("silan", "al ice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsWhitespace { - which: ComponentKind::SubjectValue - } - ); - } +pub fn hub_ura(realm: &str) -> String { + Ura::hub(realm).into_string() +} - #[test] - fn build_rejects_tab_in_scope() { - let err = Ura::build_agent("sil\tan", "alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsWhitespace { - which: ComponentKind::Scope - } - ); - } +pub fn resource_ura(realm: &str, owner_id: &str, ns: ResourceNamespace, path: &str) -> String { + Ura::resource(realm, owner_id, ns, path).into_string() +} - #[test] - fn build_rejects_control_bytes() { - let err = Ura::build_agent("silan\x07", "alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsWhitespace { - which: ComponentKind::Scope - } - ); - } +pub fn resource_dot_ura(realm: &str, owner_id: &str, path: &str) -> String { + Ura::resource_dot(realm, owner_id, path).into_string() +} - #[test] - fn build_rejects_slash_in_component() { - let err = Ura::build_agent("silan/rogue", "alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsReserved { - which: ComponentKind::Scope, - char_found: '/', - } - ); - } +pub fn device_ability_resource_ura(realm: &str, device_id: &str, ability_id: &str) -> String { + Ura::device_ability_resource(realm, device_id, ability_id).into_string() +} - #[test] - fn build_rejects_at_sign_in_scope() { - let err = Ura::build_agent("si@lan", "alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsReserved { - which: ComponentKind::Scope, - char_found: '@', - } - ); - } +pub fn payload_resource_ura(realm: &str, owner_id: &str, payload_id: &str) -> String { + Ura::payload_resource(realm, owner_id, payload_id).into_string() +} - #[test] - fn build_rejects_question_mark_hash_backslash() { - for (ch, scope) in [('?', "si?lan"), ('#', "si#lan"), ('\\', "si\\lan")] { - let err = Ura::build_agent(scope, "alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsReserved { - which: ComponentKind::Scope, - char_found: ch, - } - ); - } - } +pub fn invocation_history_resource_ura(realm: &str, owner_id: &str, invocation_id: &str) -> String { + Ura::invocation_history_resource(realm, owner_id, invocation_id).into_string() +} - #[test] - fn build_rejects_empty_scope() { - let err = Ura::build_agent("", "alice").unwrap_err(); - assert_eq!( - err, - UraError::EmptyComponent { - which: ComponentKind::Scope +pub fn parse_ura(ura: &str) -> Result { + let rest = ura.strip_prefix(URA_SCHEME).ok_or(ParseError::BadScheme)?; + let (realm, after_realm) = rest.split_once('/').ok_or(ParseError::EmptyRealm)?; + if realm.is_empty() { + return Err(ParseError::EmptyRealm); + } + let (role, tail) = match after_realm.split_once('/') { + Some((role, tail)) => (role, tail), + None => (after_realm, ""), + }; + if role.is_empty() { + return Err(ParseError::EmptyRole); + } + + let mut parsed = ParsedURA { + realm: realm.to_string(), + raw: ura.to_string(), + ..Default::default() + }; + + match role { + "user" => { + if tail.is_empty() { + return Err(ParseError::UserMissingTail); } - ); - } - - #[test] - fn build_rejects_empty_subject_value() { - let err = Ura::build_agent("silan", "").unwrap_err(); - assert_eq!( - err, - UraError::EmptyComponent { - which: ComponentKind::SubjectValue + if tail.contains('/') || tail.contains('.') { + return Err(ParseError::UserBadShape); } - ); - } - - // ── Rule 2 — round-trip property ──────────────────────────────── - - #[test] - fn round_trip_preserves_components_ascii() { - let corpus: &[(&str, &str, Option<&str>)] = &[ - ("silan", "alice", None), - ("silan", "alice", Some("1.0")), - ("tenant-a", "reviewer-1", Some("v2.7.3")), - ("t.with.dots", "p-with-dashes", None), - ("t_1", "p_2", Some("3.2.1")), - ("123", "456", None), - ]; - for (scope, subj, ver) in corpus { - let built = Ura::build("silan_ignored", SUBJECT_TYPE_AGENT, "ignored", None).is_ok(); - assert!(built); // sanity - let u = Ura::build(scope, SUBJECT_TYPE_AGENT, subj, *ver).unwrap(); - let s = u.to_canonical_string().to_string(); - let reparsed = Ura::parse(&s).unwrap(); - assert_eq!(reparsed.scope(), u.scope()); - assert_eq!(reparsed.subject_type(), u.subject_type()); - assert_eq!(reparsed.subject_value(), u.subject_value()); - assert_eq!(reparsed.version(), u.version()); - assert_eq!(reparsed.to_canonical_string(), u.to_canonical_string()); + parsed.kind = URAKind::User; + parsed.user_id = tail.to_string(); } + "device" => { + if tail.is_empty() { + return Err(ParseError::DeviceMissingTail); + } + if tail.contains('/') || tail.contains('.') { + return Err(ParseError::DeviceBadShape); + } + parsed.kind = URAKind::Device; + parsed.device_id = tail.to_string(); + } + "agent" => { + if tail.is_empty() { + return Err(ParseError::AgentMissingTail); + } + let (user_id, agent_id) = tail.split_once('.').ok_or(ParseError::AgentBadShape)?; + if user_id.is_empty() + || agent_id.is_empty() + || user_id.contains('/') + || agent_id.contains('/') + || agent_id.contains('.') + { + return Err(ParseError::AgentBadShape); + } + parsed.kind = URAKind::Agent; + parsed.user_id = user_id.to_string(); + parsed.agent_id = agent_id.to_string(); + } + "ability" => { + if tail.is_empty() { + return Err(ParseError::AbilityMissingTail); + } + let mut parts = tail.splitn(3, '.'); + let user_id = parts.next().unwrap_or(""); + let agent_id = parts.next().unwrap_or(""); + let ability_id = parts.next().unwrap_or(""); + if user_id.is_empty() + || agent_id.is_empty() + || ability_id.is_empty() + || user_id.contains('/') + || agent_id.contains('/') + || agent_id.contains('.') + { + return Err(ParseError::AbilityBadShape); + } + parsed.kind = URAKind::Ability; + parsed.user_id = user_id.to_string(); + parsed.agent_id = agent_id.to_string(); + parsed.ability_id = ability_id.to_string(); + } + "hub" => { + if !tail.is_empty() { + return Err(ParseError::HubUnexpectedTail(tail.to_string())); + } + parsed.kind = URAKind::Hub; + } + "resource" => { + if tail.is_empty() { + return Err(ParseError::ResourceMissingTail); + } + let (owner, path) = match tail.split_once('/') { + Some((owner, path)) => (owner, path), + None => (tail, ""), + }; + if owner.is_empty() { + return Err(ParseError::ResourceEmptyOwner); + } + parsed.kind = URAKind::Resource; + parsed.user_id = owner.to_string(); + parsed.path = path.to_string(); + } + other => return Err(ParseError::UnknownRole(other.to_string())), } - #[test] - fn round_trip_preserves_unicode_letters() { - // Unicode letters in segments are accepted (no ASCII - // whitespace / control / reserved); they round-trip byte-for- - // byte because we do not NFC-normalise — that is the signer's - // responsibility and canonical bytes preserve the signer's - // choice exactly. - let u = Ura::build_agent("café", "résumé").unwrap(); - let s = u.to_canonical_string().to_string(); - assert_eq!(s, "easynet:///r/café/agents/résumé"); - let r = Ura::parse(&s).unwrap(); - assert_eq!(r.scope(), "café"); - assert_eq!(r.subject_value(), "résumé"); - } - - #[test] - fn round_trip_preserves_percent_encoded_opaque() { - // Percent escapes are treated as opaque characters (we neither - // decode nor re-encode). Two URAs that decode to the same - // logical value but differ in encoding are DIFFERENT canonical - // identities — that is the correct strict-v2 behaviour. - let u = Ura::build_agent("a%20b", "alice").unwrap(); - let s = u.to_canonical_string().to_string(); - assert_eq!(s, "easynet:///r/a%20b/agents/alice"); - let r = Ura::parse(&s).unwrap(); - assert_eq!(r.scope(), "a%20b"); - } - - #[test] - fn round_trip_preserves_case() { - // Scope is case-sensitive. `Silan` and `silan` are DIFFERENT - // canonical identities. This test pins the decision explicitly - // because case-folding is a classic source of canonical-form - // drift (see RFC 3986 §6.2.2.1 for the wider discussion). - let upper = Ura::build_agent("Silan", "alice").unwrap(); - let lower = Ura::build_agent("silan", "alice").unwrap(); - assert_ne!(upper.to_canonical_string(), lower.to_canonical_string()); - } - - // ── Rule 3 — single canonical-bytes accessor ──────────────────── - - #[test] - fn display_equals_to_canonical_string() { - let u = Ura::build_agent("silan", "alice").unwrap(); - assert_eq!(format!("{u}"), u.to_canonical_string()); - } - - #[test] - fn into_agent_identity_round_trips_through_wire() { - let u = Ura::build_agent("silan", "alice").unwrap(); - let wire = u.clone().into_agent_identity(); - assert_eq!(wire.uri, u.to_canonical_string()); - assert_eq!(wire.profile, PROFILE_STRICT_V2); - let back = Ura::try_from_agent_identity(&wire).unwrap(); - assert_eq!(back, u); - } - - #[test] - fn into_subject_identity_preserves_canonical_bytes() { - let u = Ura::build("silan", "papers", "draft-1", Some("v0.2")).unwrap(); - let wire = u.clone().into_subject_identity(); - assert_eq!(wire.uri, "easynet:///r/silan/papers/draft-1@v0.2"); - let back = Ura::try_from_subject_identity(&wire).unwrap(); - assert_eq!(back.to_canonical_string(), u.to_canonical_string()); - } - - // ── Parse-side rejections ─────────────────────────────────────── - - #[test] - fn parse_rejects_missing_prefix() { - assert_eq!( - Ura::parse("http://example/r/silan/agents/alice").unwrap_err(), - UraError::MissingPrefix - ); - assert_eq!(Ura::parse("").unwrap_err(), UraError::MissingPrefix); - assert_eq!( - Ura::parse("not a url").unwrap_err(), - UraError::MissingPrefix - ); - } - - #[test] - fn parse_rejects_too_few_segments() { - let err = Ura::parse("easynet:///r/silan/agents").unwrap_err(); - assert_eq!(err, UraError::TooFewSegments { got: 2 }); - let err = Ura::parse("easynet:///r/silan").unwrap_err(); - assert_eq!(err, UraError::TooFewSegments { got: 1 }); - } + Ok(parsed) +} - #[test] - fn parse_rejects_too_many_segments() { - let err = Ura::parse("easynet:///r/silan/agents/alice/extra").unwrap_err(); - assert_eq!(err, UraError::TooManySegments { got: 4 }); - } +pub fn kind_from_ura(ura: &str) -> URAKind { + parse_ura(ura).map(|parsed| parsed.kind).unwrap_or_default() +} - #[test] - fn parse_rejects_whitespace_in_scope() { - let err = Ura::parse("easynet:///r/ silan /agents/alice").unwrap_err(); - assert_eq!( - err, - UraError::ContainsWhitespace { - which: ComponentKind::Scope - } - ); - } +pub fn realm_from_ura(ura: &str) -> String { + parse_ura(ura) + .map(|parsed| parsed.realm) + .unwrap_or_default() +} - #[test] - fn parse_rejects_empty_scope() { - let err = Ura::parse("easynet:///r//agents/alice").unwrap_err(); - assert_eq!( - err, - UraError::EmptyComponent { - which: ComponentKind::Scope +pub fn display_id(ura: &str) -> String { + match parse_ura(ura) { + Err(_) => ura.to_string(), + Ok(parsed) => match parsed.kind { + URAKind::Device => parsed.device_id, + URAKind::User => parsed.user_id, + URAKind::Agent => format!("{}.{}", parsed.user_id, parsed.agent_id), + URAKind::Ability => { + format!( + "{}.{}.{}", + parsed.user_id, parsed.agent_id, parsed.ability_id + ) } - ); - } - - #[test] - fn parse_rejects_empty_version_suffix() { - let err = Ura::parse("easynet:///r/silan/agents/alice@").unwrap_err(); - assert_eq!(err, UraError::EmptyVersionSuffix); + URAKind::Hub => "hub".to_string(), + URAKind::Resource if parsed.path.is_empty() => parsed.user_id, + URAKind::Resource => format!("{}/{}", parsed.user_id, parsed.path), + URAKind::Unknown => ura.to_string(), + }, } +} - #[test] - fn parse_rejects_multiple_at_signs_in_subject_value() { - let err = Ura::parse("easynet:///r/silan/agents/alice@v@inner").unwrap_err(); - assert_eq!(err, UraError::MultipleVersionSeparators); +pub fn qualified_ability_name(ura: &str) -> Option { + let parsed = parse_ura(ura).ok()?; + if parsed.kind != URAKind::Ability { + return None; } + Some(format!("{}.{}", parsed.agent_id, parsed.ability_id)) +} - #[test] - fn parse_accepts_version_with_dots_and_dashes() { - let u = Ura::parse("easynet:///r/silan/agents/alice@1.0.0-rc.2").unwrap(); - assert_eq!(u.version(), Some("1.0.0-rc.2")); +pub fn agent_identity(realm: &str, user_id: &str, agent_id: &str) -> Option { + if realm.is_empty() || user_id.is_empty() || agent_id.is_empty() { + return None; } + Some(pb::AgentIdentity { + ura: agent_ura(realm, user_id, agent_id), + profile: PROFILE_STRICT_V2.to_string(), + }) +} - // ── Profile handling ──────────────────────────────────────────── +pub fn agent_identity_from_ura(ura: &str) -> Result { + parse_ura(ura)?; + Ok(pb::AgentIdentity { + ura: ura.to_string(), + profile: PROFILE_STRICT_V2.to_string(), + }) +} - #[test] - fn parse_with_unknown_profile_fails_closed() { - let err = Ura::parse_with_profile("easynet:///r/silan/agents/alice", "easynet-strict-v3") - .unwrap_err(); - assert_eq!( - err, - UraError::UnknownProfile { - got: "easynet-strict-v3".to_string() - } - ); - } +pub fn subject_identity_from_ura(ura: &str) -> Result { + parse_ura(ura)?; + Ok(pb::SubjectIdentity { + ura: ura.to_string(), + profile: PROFILE_STRICT_V2.to_string(), + }) +} - #[test] - fn parse_with_empty_profile_defaults_to_strict_v2() { - // The wire field may be elided by legacy callers; we treat that - // as strict-v2 rather than failing closed, because failing here - // would regress the signed-envelope onboarding story for SDKs - // that forget to set it. - let u = Ura::parse_with_profile("easynet:///r/silan/agents/alice", "").unwrap(); - assert_eq!(u.profile(), PROFILE_STRICT_V2); +pub fn parse_agent_identity(identity: &pb::AgentIdentity) -> Result { + if identity.ura.is_empty() { + return Err(ParseError::EmptyIdentityURA); } + validate_profile(&identity.profile)?; + parse_ura(&identity.ura) +} - #[test] - fn web_safe_v2_profile_is_accepted_on_parse() { - let u = Ura::parse_with_profile("easynet:///r/silan/agents/alice", PROFILE_WEB_SAFE_V2) - .unwrap(); - assert_eq!(u.profile(), PROFILE_WEB_SAFE_V2); +pub fn parse_subject_identity(identity: &pb::SubjectIdentity) -> Result { + if identity.ura.is_empty() { + return Err(ParseError::EmptyIdentityURA); } + validate_profile(&identity.profile)?; + parse_ura(&identity.ura) +} - // ── Proto conversion error paths ──────────────────────────────── - - #[test] - fn try_from_agent_identity_empty_uri_is_typed_error() { - let id = pb::AgentIdentity { - uri: String::new(), - profile: PROFILE_STRICT_V2.to_string(), - }; - assert_eq!( - Ura::try_from_agent_identity(&id).unwrap_err(), - UraError::EmptyUri - ); +fn validate_profile(profile: &str) -> Result<(), ParseError> { + match profile { + "" | PROFILE_STRICT_V2 | PROFILE_WEB_SAFE_V2 => Ok(()), + other => Err(ParseError::UnknownProfile(other.to_string())), } +} - // ── Top-level helpers ─────────────────────────────────────────── +#[cfg(test)] +mod tests { + use super::*; #[test] - fn scope_from_uri_tolerates_malformed() { - // By design — runtime hot path treats malformed as anonymous, - // not as error. Strict parsing goes through Ura::parse. - assert_eq!(scope_from_uri(""), ""); - assert_eq!(scope_from_uri("garbage"), ""); - assert_eq!(scope_from_uri("easynet:///r//agents/x"), ""); - assert_eq!(scope_from_uri("easynet:///r/silan/agents/alice"), "silan"); - assert_eq!( - scope_from_uri("easynet:///r/silan/agents/alice@1.0"), - "silan" - ); + fn rejects_unknown_roles() { + assert!(matches!( + parse_ura("easynet:///r/localhost/widget/alice"), + Err(ParseError::UnknownRole(role)) if role == "widget" + )); } #[test] - fn subject_value_from_uri_strips_version() { - assert_eq!( - subject_value_from_uri("easynet:///r/silan/agents/alice@3.2.1"), - "alice" - ); + fn builds_and_parses_current_agent_identity() { + let identity = agent_identity("localhost", "alice", "frontend-engineer").unwrap(); assert_eq!( - subject_value_from_uri("easynet:///r/silan/agents/alice"), - "alice" + identity.ura, + "easynet:///r/localhost/agent/alice.frontend-engineer" ); - assert_eq!(subject_value_from_uri(""), ""); - } - - #[test] - fn build_agent_uri_empty_pair_yields_empty_string() { - assert_eq!(build_agent_uri("", ""), ""); + assert_eq!(identity.profile, PROFILE_STRICT_V2); + let parsed = parse_agent_identity(&identity).unwrap(); + assert_eq!(parsed.realm, "localhost"); + assert_eq!(parsed.user_id, "alice"); + assert_eq!(parsed.agent_id, "frontend-engineer"); } #[test] - fn build_agent_uri_happy_path() { - assert_eq!( - build_agent_uri("silan", "alice"), - "easynet:///r/silan/agents/alice" + fn resource_ura_carries_owner_and_path() { + let ura = resource_dot_ura( + "localhost", + "agent.dev.frontend-engineer", + "skill/alive-video", ); + let parsed = parse_ura(&ura).unwrap(); + assert_eq!(parsed.kind, URAKind::Resource); + assert_eq!(parsed.user_id, "agent.dev.frontend-engineer"); + assert_eq!(parsed.path, "skill/alive-video"); } #[test] - #[should_panic(expected = "build_agent_uri: invalid components")] - fn build_agent_uri_panics_on_drift_preventing_bad_input() { - // This is the regression-protection that makes silent drift - // impossible. A caller that constructs a malformed URA hits - // this panic instead of producing an unsigned-capable - // "almost right" string that would later fail admission with - // a confusing message. - let _ = build_agent_uri("has space", "alice"); - } - - #[test] - fn build_agent_identity_returns_none_for_anonymous() { - assert!(build_agent_identity("", "").is_none()); - } - - #[test] - fn build_agent_identity_happy_path() { - let id = build_agent_identity("silan", "alice").unwrap(); - assert_eq!(id.uri, "easynet:///r/silan/agents/alice"); - assert_eq!(id.profile, PROFILE_STRICT_V2); - } - - // ── Regression guards for the three drift cases that motivated - // this module's creation. Each one pins a specific pre-release - // behaviour change so a future refactor cannot re-introduce the - // issue silently. - - /// Drift case 1 (pre-refactor): `runtime::mod::ura_scope` trimmed - /// whitespace; `client-sdk::infra::client::base_envelope_with` - /// built the URI from un-trimmed inputs. Result: signatures - /// verified (canonical bytes matched at both ends because they - /// both saw the un-trimmed form) but tenant isolation leaked - /// across the trimmed/untrimmed pair. - #[test] - fn regression_rule1_no_asymmetric_trim() { - // Must fail at build time, not silently trim. - assert!(Ura::build_agent(" silan", "alice").is_err()); - // And parsing a pre-trimmed URA MUST NOT be treated as the - // same identity as parsing an un-trimmed one. - let trimmed = Ura::parse("easynet:///r/silan/agents/alice"); - let spaced = Ura::parse("easynet:///r/ silan /agents/alice"); - assert!(trimmed.is_ok()); - assert!(spaced.is_err()); - } - - /// Drift case 2: pre-refactor code sometimes treated - /// `"easynet:///r/silan/agents/alice@v@inner"` as subject-value= - /// "alice" and version="v" by splitting on the first `@` only - /// — which silently discarded the trailing segment. Signing over - /// the full URI but keying storage off the truncated value would - /// mis-route receipts. - #[test] - fn regression_rule1_no_silent_multi_at() { - let err = Ura::parse("easynet:///r/silan/agents/alice@v@inner").unwrap_err(); - assert_eq!(err, UraError::MultipleVersionSeparators); - } - - /// Drift case 3: an empty version suffix (`"alice@"`) was - /// previously accepted by the permissive split with - /// `version = Some("")`, which then produced non-equal canonical - /// bytes across SDKs that either kept or stripped the trailing - /// `@`. Reject at parse time so the ambiguity cannot reach the - /// signer. - #[test] - fn regression_rule1_no_empty_version() { - let err = Ura::parse("easynet:///r/silan/agents/alice@").unwrap_err(); - assert_eq!(err, UraError::EmptyVersionSuffix); + fn hub_is_singleton() { + assert_eq!(hub_ura("localhost"), "easynet:///r/localhost/hub"); + assert!(matches!( + parse_ura("easynet:///r/localhost/hub/01HUB"), + Err(ParseError::HubUnexpectedTail(tail)) if tail == "01HUB" + )); } } diff --git a/core/runtime-rs/client-sdk/src/infra/client.rs b/core/runtime-rs/client-sdk/src/infra/client.rs index 7ebdb461..c1dc8b02 100644 --- a/core/runtime-rs/client-sdk/src/infra/client.rs +++ b/core/runtime-rs/client-sdk/src/infra/client.rs @@ -132,16 +132,7 @@ impl AxonClient { let fallback_principal_id = format!("client-sdk:{request_id}"); let tenant: String = tenant_id.into(); let principal = Self::normalize_non_empty(principal_id).unwrap_or(fallback_principal_id); - // RFC 001: tenant + principal live inside the caller URA. - // The construction goes through the single canonical builder - // in `crate::ura` so the bytes that land in the envelope are - // byte-identical to every other call site in the workspace. - // The builder panics on trim-able inputs (Rule 1 of the URA - // hard-rule set) — which is the correct failure mode, because - // a whitespace-bearing (tenant, principal) at this layer would - // later sign canonical bytes that disagree with any peer's - // canonical bytes and fail admission with a confusing error. - let caller = crate::ura::build_agent_identity(&tenant, &principal); + let caller = crate::ura::agent_identity(&tenant, &principal, "sdk"); pb::Envelope { request_id, idempotency_key: Self::normalize_non_empty(idempotency_key).unwrap_or_default(), @@ -179,15 +170,13 @@ impl AxonClient { } // ═══════════════════════════════════════════════════════════════════════ -// RFC 001 — base_envelope_with boundary tests. +// base_envelope_with boundary tests. // // This helper is the single gate where client-sdk translates caller-side -// `(tenant, principal)` arguments into a wire-level `caller: AgentIdentity`. -// Its correctness is load-bearing for authentication and authorisation at -// the server; malformed output would mean silently anonymous calls. +// realm/user arguments into a wire-level current `caller: AgentIdentity`. // // Per-test coverage: -// * happy path with explicit (tenant, principal) +// * happy path with explicit realm/user // * auto-fallback principal when principal_id is None or whitespace // * anonymous-caller path when tenant is empty (see behaviour-change // note below) @@ -196,14 +185,12 @@ impl AxonClient { // ──────────────────────────────────────────────────────────────────── // Behaviour change vs. pre-PR2.5: // -// * The pre-refactor helper built a URI like `easynet:///r//agents/alice` -// whenever tenant was empty, handing the server a half-formed -// identity. The new helper routes through `crate::ura`, whose -// Rule 1 rejects partial components. As a result: +// * Empty realm yields no caller identity. The current URA grammar +// has no tenant-less or scope-less identity. // -// tenant="" + principal=anything → caller: None (anonymous) -// tenant=anything + principal="" → caller: None (anonymous) -// tenant="" + principal="" → caller: None (anonymous) +// realm="" + user=anything → caller: None (anonymous) +// realm=anything + user="" → caller: None (anonymous) +// realm="" + user="" → caller: None (anonymous) // // This is strictly more honest: a call with no tenant claim is // anonymous on the wire, not a tenant-less-but-identified caller @@ -221,12 +208,14 @@ mod base_envelope_tests { /// Delegates to the single canonical parser. Used by these tests /// to decompose the `caller.uri` bytes the helper produced, rather /// than maintaining a parallel parser that could drift. - fn parse_ura_tenant(uri: &str) -> String { - crate::ura::scope_from_uri(uri) + fn parse_ura_realm(uri: &str) -> String { + crate::ura::realm_from_ura(uri) } - fn parse_ura_principal(uri: &str) -> String { - crate::ura::subject_value_from_uri(uri) + fn parse_ura_user(ura: &str) -> String { + crate::ura::parse_ura(ura) + .map(|parsed| parsed.user_id) + .unwrap_or_default() } #[test] @@ -239,8 +228,9 @@ mod base_envelope_tests { ); let caller = env.caller.as_ref().expect("caller must be populated"); assert_eq!(caller.profile, crate::ura::PROFILE_STRICT_V2); - assert_eq!(parse_ura_tenant(&caller.uri), "tenant-a"); - assert_eq!(parse_ura_principal(&caller.uri), "alice"); + assert_eq!(caller.ura, "easynet:///r/tenant-a/agent/alice.sdk"); + assert_eq!(parse_ura_realm(&caller.ura), "tenant-a"); + assert_eq!(parse_ura_user(&caller.ura), "alice"); assert_eq!(env.idempotency_key, "key-1"); } @@ -248,8 +238,8 @@ mod base_envelope_tests { fn empty_principal_falls_back_to_auto_request_id_form() { let env = AxonClient::base_envelope_with("op", "tenant-a", None, None); let caller = env.caller.as_ref().expect("caller must be populated"); - assert_eq!(parse_ura_tenant(&caller.uri), "tenant-a"); - let principal = parse_ura_principal(&caller.uri); + assert_eq!(parse_ura_realm(&caller.ura), "tenant-a"); + let principal = parse_ura_user(&caller.ura); assert!( principal.starts_with("client-sdk:"), "auto fallback must use the 'client-sdk:' prefix, got: {principal}" @@ -258,8 +248,7 @@ mod base_envelope_tests { /// Behaviour change: `(empty tenant, empty principal)` now yields /// `caller: None` unambiguously. Previously the helper produced an - /// ill-formed `easynet:///r//agents/client-sdk:` URI via - /// the auto-fallback, which: + /// ill-formed caller URI via the auto-fallback, which: /// /// * rendered the tenant segment empty inside the canonical bytes, /// * caused the server's tenant-scope parser to return `""`, @@ -296,7 +285,7 @@ mod base_envelope_tests { // auto-generated `client-sdk:` takes over. let env = AxonClient::base_envelope_with("op", "tenant-a", None, Some(" ".to_string())); let caller = env.caller.as_ref().unwrap(); - let principal = parse_ura_principal(&caller.uri); + let principal = parse_ura_user(&caller.ura); assert!(principal.starts_with("client-sdk:")); } diff --git a/core/runtime-rs/client-sdk/src/lib.rs b/core/runtime-rs/client-sdk/src/lib.rs index 8aadab42..79648279 100644 --- a/core/runtime-rs/client-sdk/src/lib.rs +++ b/core/runtime-rs/client-sdk/src/lib.rs @@ -91,10 +91,9 @@ mod model; /// one encoder and one set of rejection codes drive every call site. pub use domain::admission; -/// RFC 001 §3.1 URA v2 identity primitive. Re-exported at the crate -/// root so the runtime-rs gRPC server can `use easynet_run_axon_client::ura` -/// rather than reaching into `domain::`. Every URA parse/build/convert -/// call in the workspace must come through this single module. +/// Current URA identity primitive. Re-exported at the crate root so +/// runtime-rs can `use easynet_run_axon_client::ura` rather than +/// reaching into `domain::`. pub use domain::ura; /// RFC 001 §A16 InvokeBidi frame chain primitives — HKDF key @@ -102,6 +101,11 @@ pub use domain::ura; /// encoding. Both the runtime-rs receiver and the dendrite-bridge /// producer link this module so encoders cannot drift. pub use domain::bidi; +pub use domain::content::{ + content_envelope_is_encrypted, open_chacha20poly1305_payload, plaintext_json_envelope, + seal_chacha20poly1305_payload, validate_payload_matches_content_envelope, + PayloadEncryptionKeypair, +}; pub(crate) use model::SignedMetadataInput; pub use model::{ diff --git a/core/runtime-rs/client-sdk/src/model/mod.rs b/core/runtime-rs/client-sdk/src/model/mod.rs index cff0daae..8b43008b 100644 --- a/core/runtime-rs/client-sdk/src/model/mod.rs +++ b/core/runtime-rs/client-sdk/src/model/mod.rs @@ -38,8 +38,8 @@ pub struct EasyNetUserAuth { /// Canonicalized URI plus signature metadata that can be attached to invoke requests. #[derive(Clone, Debug)] pub struct EasyNetSignedMetadata { - /// Canonical EasyNet resource URI after normalization/validation. - pub canonical_resource_uri: String, + /// Canonical EasyNet resource URA after normalization/validation. + pub canonical_resource_ura: String, /// Signature envelope metadata entries (`easynet.*` keys plus caller-extended keys). pub metadata: HashMap, } @@ -49,7 +49,7 @@ pub(crate) struct SignedMetadataInput<'a> { pub(crate) request_id: &'a str, pub(crate) tenant_id: &'a str, pub(crate) subject_id: &'a str, - pub(crate) resource_uri: &'a str, + pub(crate) resource_ura: &'a str, pub(crate) payload_sha256: String, pub(crate) issued_at_unix_ms: i64, pub(crate) nonce: String, @@ -75,8 +75,8 @@ pub struct AbilityPackageSpec { pub requirements: HashMap, /// Arbitrary metadata key/value map. pub metadata: HashMap, - /// Payload URI where package content can be fetched. - pub payload_uri: String, + /// Payload URA where package content can be fetched. + pub payload_ura: String, /// Payload size bytes from transfer metadata. pub payload_size_bytes: i64, /// Optional explicit signature fingerprint (`sha256:`). Empty means auto-compute. @@ -104,7 +104,7 @@ impl AbilityPackageSpec { tags: Vec::new(), requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: String::new(), + payload_ura: String::new(), payload_size_bytes: 0, signature_fingerprint: String::new(), package_fingerprint: String::new(), @@ -113,14 +113,14 @@ impl AbilityPackageSpec { } } -/// Invoke-time options for URI-based ability invocation. +/// Invoke-time options for URA-based ability invocation. #[derive(Clone, Debug)] pub struct AbilityCallOptions { - /// Optional explicit subject id; if omitted SDK derives from resource URI. + /// Optional explicit subject id; if omitted SDK derives from resource URA. pub subject_id: Option, /// Optional explicit auth key pair; if omitted SDK derives deterministic subject auth. pub auth: Option, - /// Optional capability name override derived from resource URI otherwise. + /// Optional capability name override derived from resource URA otherwise. pub capability_name: Option, /// Optional direct node route; absence enables normal routing strategy. pub target_node_id: Option, @@ -128,6 +128,10 @@ pub struct AbilityCallOptions { pub timeout_seconds: i32, /// Request content type for payload bytes. pub content_type: String, + /// Full content contract. When encryption is set, payload bytes + /// must be an encoded `EncryptedPayload`; SDK validation rejects + /// plaintext before any network call. + pub content_envelope: Option, /// Additional metadata merged into signed metadata (without overriding signed keys). pub metadata: HashMap, } @@ -141,6 +145,7 @@ impl Default for AbilityCallOptions { target_node_id: None, timeout_seconds: 30, content_type: "application/json".to_string(), + content_envelope: None, metadata: HashMap::new(), } } @@ -229,11 +234,11 @@ pub struct TenantAbilityClient<'a> { pub(crate) tenant_id: String, } -/// Fluent invoke builder state for a single resource URI. +/// Fluent invoke builder state for a single resource URA. pub struct AbilityInvocationBuilder<'a> { pub(crate) client: &'a mut AxonClient, pub(crate) tenant_id: String, - pub(crate) resource_uri: String, + pub(crate) resource_ura: String, pub(crate) options: AbilityCallOptions, pub(crate) invoke_context: AbilityInvokeContext, } diff --git a/core/runtime-rs/client-sdk/src/tests.rs b/core/runtime-rs/client-sdk/src/tests.rs index 6ce8e582..14e8d591 100644 --- a/core/runtime-rs/client-sdk/src/tests.rs +++ b/core/runtime-rs/client-sdk/src/tests.rs @@ -5,7 +5,7 @@ //! Description: Unit tests for EasyNet canonicalization/signing and node-id lock lifecycle behavior. //! //! Protocol Responsibility: -//! - Verifies deterministic behavior of URI canonicalization, signature metadata, and node-id lock safety. +//! - Verifies deterministic behavior of URA canonicalization, signature metadata, and node-id lock safety. //! - Guards regression boundaries for stale-lock reclaim, liveness checks, and fluent semantic helpers. //! //! Implementation Approach: @@ -36,12 +36,12 @@ fn with_env_lock(f: impl FnOnce() -> T) -> T { } #[test] -fn canonicalize_r_uri_orders_tenant_first_and_sorts_ext_query() { - let canonical = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_r_ura_orders_tenant_first_and_sorts_ext_query() { + let canonical = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?z=9&tenant_id=tenant-test&a=1", "tenant-test", ) - .expect("agent URI should canonicalize"); + .expect("agent URA should canonicalize"); assert_eq!( canonical, "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test&a=1&z=9" @@ -49,12 +49,12 @@ fn canonicalize_r_uri_orders_tenant_first_and_sorts_ext_query() { } #[test] -fn canonicalize_accepts_canonical_hub_ability_uri() { - let canonical = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_accepts_canonical_hub_ability_ura() { + let canonical = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/acme/ability/hub.runtime.register_local_tool", "acme", ) - .expect("canonical hub URI should canonicalize"); + .expect("canonical hub URA should canonicalize"); assert_eq!( canonical, "easynet:///r/acme/ability/hub.runtime.register_local_tool" @@ -62,8 +62,8 @@ fn canonicalize_accepts_canonical_hub_ability_uri() { } #[test] -fn canonicalize_accepts_device_ability_resource_route_uri() { - let canonical = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_accepts_device_ability_resource_route_ura() { + let canonical = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/acme/resource/device.dev-1/ability/device.shell.run", "acme", ) @@ -73,32 +73,32 @@ fn canonicalize_accepts_device_ability_resource_route_uri() { "easynet:///r/acme/resource/device.dev-1/ability/device.shell.run" ); assert_eq!( - AxonClient::ability_name_from_resource_uri(&canonical).unwrap(), + AxonClient::ability_name_from_resource_ura(&canonical).unwrap(), "device.shell.run" ); assert_eq!( - AxonClient::default_subject_id_for_resource_uri(&canonical, "acme").unwrap(), + AxonClient::default_subject_id_for_resource_ura(&canonical, "acme").unwrap(), "easynet:prv:resource:device.dev-1" ); } #[test] -fn canonicalize_rejects_legacy_hub_ability_uri() { - let err = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_rejects_retired_hub_ability_ura() { + let err = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/prv/hub/acme/abilities/runtime.register_local_tool@1?tenant_id=acme", "acme", ) - .expect_err("legacy hub URI must be rejected"); + .expect_err("legacy hub URA must be rejected"); assert!( err.to_string() - .contains("legacy hub /abilities/... URI is retired"), + .contains("legacy hub /abilities/... URA is retired"), "unexpected error: {err}" ); } #[test] fn canonicalize_rejects_legacy_authority_forms() { - let err_r = AxonClient::canonicalize_easynet_resource_uri( + let err_r = AxonClient::canonicalize_easynet_resource_ura( "easynet://r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", "tenant-test", ) @@ -106,11 +106,11 @@ fn canonicalize_rejects_legacy_authority_forms() { assert!( err_r .to_string() - .contains("resource_uri must use easynet:///r/... form"), + .contains("resource_ura must use easynet:///r/... form"), "unexpected error: {err_r}" ); - let err_agent = AxonClient::canonicalize_easynet_resource_uri( + let err_agent = AxonClient::canonicalize_easynet_resource_ura( "easynet://agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", "tenant-test", ) @@ -118,18 +118,18 @@ fn canonicalize_rejects_legacy_authority_forms() { assert!( err_agent .to_string() - .contains("resource_uri must use easynet:///r/... form"), + .contains("resource_ura must use easynet:///r/... form"), "unexpected error: {err_agent}" ); } #[test] -fn canonicalize_r_uri_pub_rejects_tenant_query() { - let err = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_r_ura_pub_rejects_tenant_query() { + let err = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/pub/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", "", ) - .expect_err("pub URI must reject tenant_id query"); + .expect_err("pub URA must reject tenant_id query"); assert!( err.to_string() .contains("pub visibility must not include tenant_id"), @@ -138,12 +138,12 @@ fn canonicalize_r_uri_pub_rejects_tenant_query() { } #[test] -fn canonicalize_r_uri_pub_requires_non_empty_envelope_tenant() { - let err = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_r_ura_pub_requires_non_empty_envelope_tenant() { + let err = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/pub/reg/agent.quote-bot/abilities/order.quote@1", "", ) - .expect_err("pub URI without envelope tenant should fail"); + .expect_err("pub URA without envelope tenant should fail"); assert!( err.to_string() .contains("pub visibility requires non-empty envelope tenant_id"), @@ -152,12 +152,12 @@ fn canonicalize_r_uri_pub_requires_non_empty_envelope_tenant() { } #[test] -fn canonicalize_r_uri_pub_accepts_non_empty_tenant_without_query() { - let canonical = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_r_ura_pub_accepts_non_empty_tenant_without_query() { + let canonical = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/pub/reg/agent.quote-bot/abilities/order.quote@1", "tenant-test", ) - .expect("pub URI should canonicalize with caller tenant context"); + .expect("pub URA should canonicalize with caller tenant context"); assert_eq!( canonical, "easynet:///r/pub/reg/agent.quote-bot/abilities/order.quote@1" @@ -165,45 +165,45 @@ fn canonicalize_r_uri_pub_accepts_non_empty_tenant_without_query() { } #[test] -fn canonicalize_r_uri_org_requires_matching_tenant() { - let err = AxonClient::canonicalize_easynet_resource_uri( +fn canonicalize_r_ura_org_requires_matching_tenant() { + let err = AxonClient::canonicalize_easynet_resource_ura( "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=beta", "tenant-test", ) - .expect_err("org URI with mismatched tenant should fail"); + .expect_err("org URA with mismatched tenant should fail"); assert!( err.to_string() - .contains("tenant_id mismatch between envelope and resource_uri"), + .contains("tenant_id mismatch between envelope and resource_ura"), "unexpected error: {err}" ); } #[test] -fn default_subject_id_can_be_derived_from_agent_uri() { - let subject = AxonClient::default_subject_id_for_resource_uri( +fn default_subject_id_can_be_derived_from_agent_ura() { + let subject = AxonClient::default_subject_id_for_resource_ura( "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", "tenant-test", ) - .expect("subject should derive from agent URI"); + .expect("subject should derive from agent URA"); assert_eq!(subject, "easynet:org:reg:agent.quote-bot"); } #[test] -fn default_subject_id_derives_hub_subject_from_canonical_hub_uri() { - let subject = AxonClient::default_subject_id_for_resource_uri( +fn default_subject_id_derives_hub_subject_from_canonical_hub_ura() { + let subject = AxonClient::default_subject_id_for_resource_ura( "easynet:///r/acme/ability/hub.runtime.register_local_tool", "acme", ) - .expect("subject should derive from canonical hub URI"); + .expect("subject should derive from canonical hub URA"); assert_eq!(subject, "easynet:prv:hub:acme"); } #[test] -fn ability_name_derives_from_canonical_hub_uri() { - let ability = AxonClient::ability_name_from_resource_uri( +fn ability_name_derives_from_canonical_hub_ura() { + let ability = AxonClient::ability_name_from_resource_ura( "easynet:///r/acme/ability/hub.runtime.bootstrap_self_identity", ) - .expect("ability name should derive from canonical hub URI"); + .expect("ability name should derive from canonical hub URA"); assert_eq!(ability, "runtime.bootstrap_self_identity"); } @@ -214,7 +214,7 @@ fn build_signed_metadata_contains_required_fields() { request_id: "req-1", tenant_id: "tenant-test", subject_id: "easynet:org:reg:agent.quote-bot", - resource_uri: "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?z=9&tenant_id=tenant-test&a=1", + resource_ura: "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?z=9&tenant_id=tenant-test&a=1", payload_sha256: AxonClient::sha256_hex(br#"{"sku":"A1"}"#), issued_at_unix_ms: 1_700_000_000_000, nonce: "bm9uY2UtMDEyMzQ1Njc4OWFiY2RlZg".to_string(), @@ -223,12 +223,12 @@ fn build_signed_metadata_contains_required_fields() { .expect("signed metadata should be generated"); assert_eq!( - signed.canonical_resource_uri, + signed.canonical_resource_ura, "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test&a=1&z=9" ); for key in [ "easynet.subject_id", - "easynet.resource_uri", + "easynet.resource_ura", "easynet.envelope_version", "easynet.issued_at_unix_ms", "easynet.nonce", @@ -265,21 +265,17 @@ fn base_envelope_generates_unique_request_ids() { assert!(second.request_id.starts_with("sdk-test-op-")); } -/// Pull the URA subject-value from `envelope.caller.uri` for test +/// Pull the URA subject-value from `envelope.caller.ura` for test /// assertions. RFC 001: principal lives inside the caller URA's /// subject-value segment; no separate field on the envelope. fn caller_principal(env: &pb::Envelope) -> String { - let uri = env + let ura = env .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or_default(); - let tail = uri.strip_prefix("easynet:///r/").unwrap_or(""); - let mut segs = tail.split('/'); - segs.next(); // scope - segs.next(); // subject-type - segs.next() - .map(|v| v.split('@').next().unwrap_or(v).to_string()) + crate::ura::parse_ura(ura) + .map(|parsed| parsed.user_id) .unwrap_or_default() } diff --git a/core/runtime-rs/client-sdk/tests/invocation_envelope_interop.rs b/core/runtime-rs/client-sdk/tests/invocation_envelope_interop.rs index 3d2fca85..5ea885e0 100644 --- a/core/runtime-rs/client-sdk/tests/invocation_envelope_interop.rs +++ b/core/runtime-rs/client-sdk/tests/invocation_envelope_interop.rs @@ -65,14 +65,14 @@ use serde::Deserialize; // JSON shape. // ══════════════════════════════════════════════════════════════════ -const ENV_FIXTURE_NONE_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01HUB"},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01USR-alice"}}"#; -const ENV_FIXTURE_SCALAR_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01HUB"},"causal_context":{"form":"scalar","receipt_hash_hex":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","receipt_uri":"easynet:///r/acme/receipt/01R-A"},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01USR-alice"}}"#; -const ENV_FIXTURE_LIST_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01HUB"},"causal_context":{"form":"list","prior":[{"receipt_hash_hex":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","receipt_uri":"easynet:///r/acme/receipt/01R-A"},{"receipt_hash_hex":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","receipt_uri":"easynet:///r/acme/receipt/01R-B"}]},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01USR-alice"}}"#; -const ENV_FIXTURE_MERKLE_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01HUB"},"causal_context":{"form":"merkle","proof_uri":"easynet:///r/acme/proof/01PRF-1","root_hex":"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","uri":"easynet:///r/acme/agent/01USR-alice"}}"#; +const ENV_FIXTURE_NONE_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01HUB"},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01USR-alice"}}"#; +const ENV_FIXTURE_SCALAR_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01HUB"},"causal_context":{"form":"scalar","receipt_hash_hex":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","receipt_ura":"easynet:///r/acme/receipt/01R-A"},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01USR-alice"}}"#; +const ENV_FIXTURE_LIST_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01HUB"},"causal_context":{"form":"list","prior":[{"receipt_hash_hex":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","receipt_ura":"easynet:///r/acme/receipt/01R-A"},{"receipt_hash_hex":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","receipt_ura":"easynet:///r/acme/receipt/01R-B"}]},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01USR-alice"}}"#; +const ENV_FIXTURE_MERKLE_JSON: &str = r#"{"ability":"federation.resolve","callee":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01HUB"},"causal_context":{"form":"merkle","proof_ura":"easynet:///r/acme/proof/01PRF-1","root_hex":"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"},"nonce_base64":"QkJCQkJCQkJCQkJCQkJCQg==","payload_json":{"filter":{}},"subject":{"profile":"easynet-strict-v2","ura":"easynet:///r/acme/agent/01USR-alice"}}"#; -/// Caller URI is constant across forms — emitted on a separate +/// Caller URA is constant across forms — emitted on a separate /// line by the Go dumper. -const ENV_FIXTURE_CALLER_URI: &str = "easynet:///r/acme/agent/01BAK"; +const ENV_FIXTURE_CALLER_URA: &str = "easynet:///r/acme/agent/01BAK"; const ENV_FIXTURE_CALLER_PROFILE: &str = "easynet-strict-v2"; const ENV_FIXTURE_ABILITY: &str = "federation.resolve"; @@ -131,7 +131,7 @@ struct FixtureRequest { #[derive(Deserialize)] struct FixtureAgent { - uri: String, + ura: String, profile: String, } @@ -141,21 +141,21 @@ enum FixtureCausalContext { None, Scalar { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, }, List { prior: Vec, }, Merkle { root_hex: String, - proof_uri: String, + proof_ura: String, }, } #[derive(Deserialize)] struct FixtureScalarRef { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, } fn parse_fixture(json: &str) -> FixtureRequest { @@ -168,15 +168,15 @@ fn fixture_to_envelope(fixture: &FixtureRequest) -> pb::Envelope { .expect("nonce_base64 must decode"); pb::Envelope { caller: Some(pb::AgentIdentity { - uri: ENV_FIXTURE_CALLER_URI.to_string(), + ura: ENV_FIXTURE_CALLER_URA.to_string(), profile: ENV_FIXTURE_CALLER_PROFILE.to_string(), }), callee: Some(pb::AgentIdentity { - uri: fixture.callee.uri.clone(), + ura: fixture.callee.ura.clone(), profile: fixture.callee.profile.clone(), }), subject: Some(pb::SubjectIdentity { - uri: fixture.subject.uri.clone(), + ura: fixture.subject.ura.clone(), profile: fixture.subject.profile.clone(), }), invocation_nonce: nonce, @@ -186,11 +186,11 @@ fn fixture_to_envelope(fixture: &FixtureRequest) -> pb::Envelope { }, FixtureCausalContext::Scalar { receipt_hash_hex, - receipt_uri, + receipt_ura, } => pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: hex::decode(receipt_hash_hex).expect("hex"), - receipt_uri: receipt_uri.clone(), + receipt_ura: receipt_ura.clone(), })), }, FixtureCausalContext::List { prior } => pb::CausalContext { @@ -199,18 +199,18 @@ fn fixture_to_envelope(fixture: &FixtureRequest) -> pb::Envelope { .iter() .map(|r| pb::ReceiptRef { receipt_hash: hex::decode(&r.receipt_hash_hex).expect("hex"), - receipt_uri: r.receipt_uri.clone(), + receipt_ura: r.receipt_ura.clone(), }) .collect(), })), }, FixtureCausalContext::Merkle { root_hex, - proof_uri, + proof_ura, } => pb::CausalContext { form: Some(pb::causal_context::Form::Merkle(pb::MerkleRoot { root: hex::decode(root_hex).expect("hex"), - proof_uri: proof_uri.clone(), + proof_ura: proof_ura.clone(), })), }, }), diff --git a/core/runtime-rs/dendrite-bridge/Cargo.lock b/core/runtime-rs/dendrite-bridge/Cargo.lock index 0d29a7c9..3931fb96 100644 --- a/core/runtime-rs/dendrite-bridge/Cargo.lock +++ b/core/runtime-rs/dendrite-bridge/Cargo.lock @@ -2,6 +2,16 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -208,6 +218,30 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "ciborium" version = "0.2.2" @@ -235,6 +269,17 @@ dependencies = [ "half", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + [[package]] name = "clap" version = "4.6.1" @@ -322,6 +367,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -379,6 +425,7 @@ version = "0.55.2" dependencies = [ "anyhow", "base64", + "chacha20poly1305", "ed25519-dalek", "hex", "hkdf", @@ -394,6 +441,7 @@ dependencies = [ "tonic", "tonic-build", "uuid", + "x25519-dalek", ] [[package]] @@ -766,6 +814,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "is-terminal" version = "0.4.17" @@ -891,6 +948,12 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -943,6 +1006,17 @@ dependencies = [ "spki", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1626,6 +1700,16 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -1956,6 +2040,18 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core", + "serde", + "zeroize", +] + [[package]] name = "zerocopy" version = "0.8.48" diff --git a/core/runtime-rs/dendrite-bridge/benches/bench_signed_mcp.rs b/core/runtime-rs/dendrite-bridge/benches/bench_signed_mcp.rs index a072d166..06798d34 100644 --- a/core/runtime-rs/dendrite-bridge/benches/bench_signed_mcp.rs +++ b/core/runtime-rs/dendrite-bridge/benches/bench_signed_mcp.rs @@ -35,15 +35,15 @@ fn build_bench_envelope() -> pb::Envelope { pb::Envelope { priority: 3, caller: Some(pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agents/alice".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: "easynet:///r/silan/agents/reviewer".to_string(), + ura: "easynet:///r/silan/agents/reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: "easynet:///r/silan/agents/reviewer".to_string(), + ura: "easynet:///r/silan/agents/reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0x22u8; 16], diff --git a/core/runtime-rs/dendrite-bridge/docs/AUTHENTICATED_INVOCATION.md b/core/runtime-rs/dendrite-bridge/docs/AUTHENTICATED_INVOCATION.md index 7ca46b98..5952a9bb 100644 --- a/core/runtime-rs/dendrite-bridge/docs/AUTHENTICATED_INVOCATION.md +++ b/core/runtime-rs/dendrite-bridge/docs/AUTHENTICATED_INVOCATION.md @@ -59,7 +59,7 @@ top-level block: "signing": { "algorithm": "ed25519", "seed_base64": "", - "caller_uri": "easynet:///r/silan/agents/alice", + "caller_ura": "easynet:///r/silan/agents/alice", "caller_profile": "easynet-strict-v2" } } @@ -71,7 +71,7 @@ top-level block: |---|---|---|---| | `algorithm` | string | yes | Currently `"ed25519"` is the only accepted value. Unknown ⇒ `BRIDGE_SIGNING_INTERNAL`. | | `seed_base64` | string | yes | 32 bytes base64-decoded. Shorter or longer ⇒ `BRIDGE_SIGNING_INTERNAL`. | -| `caller_uri` | string | yes | RFC 001 §3.1 URA. Must be non-empty. | +| `caller_ura` | string | yes | RFC 001 §3.1 URA. Must be non-empty. | | `caller_profile` | string | yes | URA profile selector; MUST be `"easynet-strict-v2"` (other profiles reserved). | When `signing` is absent, the session operates in **legacy @@ -88,24 +88,24 @@ return `BRIDGE_SESSION_UNSIGNED`. ### 3.2 Identity binding rule (security-critical) -The `caller_uri` passed in `signing` is declarative; it becomes +The `caller_ura` passed in `signing` is declarative; it becomes **effective identity** only after it is bound to the signing seed. The bridge enforces two constraints: 1. **Self-consistency**: every invocation on an authenticated session emits a `caller_signature` produced by the seed, with - `envelope.caller.uri = caller_uri` from the session config. The - caller cannot override `caller_uri` on a per-call basis — there is + `envelope.caller.uri = caller_ura` from the session config. The + caller cannot override `caller_ura` on a per-call basis — there is no request field for it. 2. **Resolver-agreement (federated side, enforced by runtime not bridge)**: when admission runs in Federated mode and the - `KeyResolver` resolves `caller_uri` to a public key different from + `KeyResolver` resolves `caller_ura` to a public key different from `public_key(seed)`, the invocation MUST be rejected with `AXON_CALLER_SIGNATURE_INVALID`. This is RFC 001 §5.2 step 3. The bridge does not itself verify the seed-to-URI binding. That is the Federated-mode runtime's job. But the bridge structurally prevents -spoofing by refusing per-call `caller_uri` overrides. +spoofing by refusing per-call `caller_ura` overrides. ### 3.3 One session, one caller @@ -178,7 +178,7 @@ Six-SDK parity requires exact agreement on generation, validation, and uniqueness scope. **Uniqueness scope.** The nonce MUST be unique within the tuple -`(caller_uri, ability)` over the server-side replay window (default +`(caller_ura, ability)` over the server-side replay window (default 7 days; configurable per runtime via `setAdmissionDedupWindowMs`). This is the same tuple the runtime's `NonceReplayStore` keys on (admission §5.2 step 4). Uniqueness is NOT required across callers, @@ -298,10 +298,10 @@ caller_pubkey (Ed25519 from seed, RFC 8032 §5.1.5, raw 32 bytes) = 8a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c canonical_invocation_sha256 - = 132aacb0e21a0159a187fc7d71f204f58ecf12feab06eec9f61d3769321820f7 + = 68464c0da3500e842ece4d3e6e539ec74d12b741160bd5174b13234b02b1eb28 caller_signature (Ed25519, 64 bytes, base64) - = onZ3dvtXDf66nw+I5xe1QPDH5Vm8uqxzELiuX79mNV5uPvvnoddClhFiDemXlF4gS5zWPXhZ4QGQ45FVuhdjBQ== + = N78HErlFC7s7NiUumMf7s7mpaBiH+yV8rYo0m0YDxIzZf0d9i/7lMb0mTxMNVwHpP61mN5swqnPH/2WQUsO/AQ== ``` **Pinning procedure.** These values are the cross-SDK parity anchor. diff --git a/core/runtime-rs/dendrite-bridge/docs/BRIDGE_ERROR_CODES.md b/core/runtime-rs/dendrite-bridge/docs/BRIDGE_ERROR_CODES.md index c67eaef5..c30822ca 100644 --- a/core/runtime-rs/dendrite-bridge/docs/BRIDGE_ERROR_CODES.md +++ b/core/runtime-rs/dendrite-bridge/docs/BRIDGE_ERROR_CODES.md @@ -120,7 +120,7 @@ caller. Possible root causes: - The Federated-mode `KeyResolver` resolves `caller.uri` to a different public key than `public_key(seed)`. This is the identity-spoofing guard from the authenticated-invocation spec §3.2. -- The session's `caller_uri` is not what the resolver knows about. +- The session's `caller_ura` is not what the resolver knows about. - Network man-in-the-middle (if TLS is not pinned). **Caller action:** verify key provisioning. Do not retry blindly — diff --git a/core/runtime-rs/dendrite-bridge/include/axon_dendrite_bridge.h b/core/runtime-rs/dendrite-bridge/include/axon_dendrite_bridge.h index 48621143..033d577a 100644 --- a/core/runtime-rs/dendrite-bridge/include/axon_dendrite_bridge.h +++ b/core/runtime-rs/dendrite-bridge/include/axon_dendrite_bridge.h @@ -119,7 +119,7 @@ char *axon_dendrite_bidi_stream_call_json(uint64_t handle, // input JSON: // { // "tenant_id":"tenant-test", -// "resource_uri":"easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", +// "resource_ura":"easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", // "payload_json":{"sku":"A1","qty":2}, // "timeout_ms":30000 // } diff --git a/core/runtime-rs/dendrite-bridge/src/ability.rs b/core/runtime-rs/dendrite-bridge/src/ability.rs index 32acc6bf..1aaa63fb 100644 --- a/core/runtime-rs/dendrite-bridge/src/ability.rs +++ b/core/runtime-rs/dendrite-bridge/src/ability.rs @@ -5,7 +5,7 @@ //! Description: Ability invocation helper capability over raw protocol transport. //! //! Protocol Responsibility: -//! - Canonicalizes resource URI and signed metadata for tenant-safe invocation. +//! - Canonicalizes resource URA and signed metadata for tenant-safe invocation. //! - Encodes `InvokeRequest` and decodes `InvokeResponse` with a stable JSON envelope. //! //! Implementation Approach: @@ -13,13 +13,13 @@ //! - Delegates wire dispatch to raw unary transport to keep protobuf fidelity unchanged. //! //! Usage Contract: -//! - Requires `tenant_id`, `resource_uri`, and one of `payload_json` or `payload_base64`. +//! - Requires `tenant_id`, `resource_ura`, and one of `payload_json` or `payload_base64`. //! - Returns typed convenience fields plus raw base64 payload for cross-language parity. //! //! Compatibility Mode (PR2 §2): //! - This module is the UNSIGNED legacy path. After the RFC 001 proto cleanup //! (types.proto Envelope `reserved 3, 4, 5`), the tenant/agent/principal -//! scalars moved into `caller.uri` (URA). This file constructs the new +//! scalars moved into `caller.ura` (URA). This file constructs the new //! structural envelope shape but intentionally leaves `caller_signature` //! unset. Signed invocation lives in a separate FFI (see §3 / §4 of //! `docs/AUTHENTICATED_INVOCATION.md`); do NOT graft any signing behavior @@ -36,6 +36,7 @@ use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use base64::Engine; use easynet_run_axon_client::pb; +use easynet_run_axon_client::ura; use easynet_run_axon_client::AxonClient; use prost::Message; use serde::Deserialize; @@ -51,7 +52,7 @@ use crate::raw_transport::{unary_call_impl, RawCallRequest}; #[derive(Debug, Deserialize)] pub(crate) struct AbilityInvokeRequest { tenant_id: String, - resource_uri: String, + resource_ura: String, payload_json: Option, payload_base64: Option, metadata: Option>, @@ -88,23 +89,23 @@ pub(crate) fn ability_invoke_impl( let timeout_ms = parse_timeout_ms(req.timeout_ms); let timeout_seconds = timeout_ms.div_ceil(1000).min(i32::MAX as u64) as i32; - let canonical_resource_uri = - AxonClient::canonicalize_easynet_resource_uri(&req.resource_uri, &tenant_id) - .map_err(|e| format!("invalid resource_uri: {e}"))?; + let canonical_resource_ura = + AxonClient::canonicalize_easynet_resource_ura(&req.resource_ura, &tenant_id) + .map_err(|e| format!("invalid resource_ura: {e}"))?; let subject_id = match normalize_opt_string(req.subject_id) { Some(v) => v, None => { - AxonClient::default_subject_id_for_resource_uri(&canonical_resource_uri, &tenant_id) + AxonClient::default_subject_id_for_resource_ura(&canonical_resource_ura, &tenant_id) .map_err(|e| format!("failed to derive subject_id: {e}"))? } }; let auth = AxonClient::default_auth_for_subject(&subject_id, &tenant_id); - let request_id = format!("dendrite-invoke-uri-{}", Uuid::new_v4().simple()); + let request_id = format!("dendrite-invoke-ura-{}", Uuid::new_v4().simple()); let signed_metadata = AxonClient::build_signed_easynet_metadata( &request_id, &tenant_id, &subject_id, - &canonical_resource_uri, + &canonical_resource_ura, &payload, &auth, ) @@ -112,7 +113,7 @@ pub(crate) fn ability_invoke_impl( let capability_name = match normalize_opt_string(req.capability_name) { Some(v) => v, - None => AxonClient::ability_name_from_resource_uri(&canonical_resource_uri) + None => AxonClient::ability_name_from_resource_ura(&canonical_resource_ura) .map_err(|e| format!("failed to derive capability_name: {e}"))?, }; let target_node_id = normalize_opt_string(req.target_node_id).unwrap_or_default(); @@ -128,45 +129,45 @@ pub(crate) fn ability_invoke_impl( // None. Runtime admission treats this as local-fast mode (no crypto // verify). Signed invocation has its own FFI; do NOT sign here. // - // Caller URI derivation: + // Caller URA derivation: // // * Agent subject (`easynet::reg:agent.`) — caller is - // the agent itself: `easynet:///r//agents/`. + // the SDK agent itself: `easynet:///r//agent/.sdk`. // // * Hub subject (`easynet::hub:`) — the daemon is // dialing the realm hub on its OWN behalf (federation.advertise_*, // federation.resolve, runtime.bootstrap_self_identity). The // hub-profile checks at hub_profile.rs (advertise_agent's // "self-signed must equal caller") need the caller to be the - // daemon's agent URI, NOT the hub's. Without this branch the - // caller URI was synthesised as - // `easynet:///r//agents/easynet:prv:hub:` (literal + // daemon's agent URA, NOT the hub's. Without this branch the + // caller URA was synthesised as + // `easynet:///r//agent/easynet:prv:hub:.sdk` (literal // subject_id stuffed into the path), which fails every host- // match check downstream. // - // The metadata bag's `easynet.caller_uri_override` lets the - // caller pin a specific Agent URI for this case — the daemon + // The metadata bag's `easynet.caller_ura_override` lets the + // caller pin a specific Agent URA for this case — the daemon // sets it to its own `easynet:///r//agent/` // before each federation call. When absent we fall back to // the subject literal (preserves old behaviour for callers // that haven't migrated yet). - let caller_uri = if let Some(override_uri) = metadata - .get("easynet.caller_uri_override") + let caller_ura = if let Some(override_ura) = metadata + .get("easynet.caller_ura_override") .filter(|s| !s.is_empty()) .cloned() { - override_uri + override_ura } else { let principal = AxonClient::subject_owner_id(&subject_id).unwrap_or_else(|| subject_id.clone()); - format!("easynet:///r/{tenant_id}/agents/{principal}") + ura::agent_ura(&tenant_id, &principal, "sdk") }; // Strip the override so it doesn't leak into the runtime // metadata bag (the override is purely a bridge-side caller- // synthesis hint, not something the runtime needs to see). - metadata.remove("easynet.caller_uri_override"); + metadata.remove("easynet.caller_ura_override"); let caller = pb::AgentIdentity { - uri: caller_uri, + ura: caller_ura, profile: "easynet-strict-v2".to_string(), }; @@ -244,7 +245,7 @@ pub(crate) fn ability_invoke_impl( Ok(ok_json(json!({ "request_id": request_id, "tenant_id": tenant_id, - "canonical_resource_uri": canonical_resource_uri, + "canonical_resource_ura": canonical_resource_ura, "state": invoke_response.state, "selected_node_id": invoke_response.selected_node_id, "scheduling_reason": invoke_response.scheduling_reason, diff --git a/core/runtime-rs/dendrite-bridge/src/common.rs b/core/runtime-rs/dendrite-bridge/src/common.rs index 57571d43..a9c0f92b 100644 --- a/core/runtime-rs/dendrite-bridge/src/common.rs +++ b/core/runtime-rs/dendrite-bridge/src/common.rs @@ -896,14 +896,14 @@ mod tests { "signing": { "algorithm": "ed25519", "seed_base64": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=", - "caller_uri": "easynet:///r/silan/agents/alice", + "caller_ura": "easynet:///r/silan/agents/alice", "caller_profile": "easynet-strict-v2" } }"#; let req: DendriteOpenRequest = serde_json::from_str(raw).unwrap(); let s = req.signing.as_ref().expect("signing block must parse"); assert_eq!(s.algorithm, "ed25519"); - assert_eq!(s.caller_uri, "easynet:///r/silan/agents/alice"); + assert_eq!(s.caller_ura, "easynet:///r/silan/agents/alice"); assert_eq!(s.caller_profile, "easynet-strict-v2"); } @@ -942,7 +942,7 @@ mod tests { let cfg = SigningConfig::new(SigningConfigRequest { algorithm: "ed25519".to_string(), seed_base64: "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=".to_string(), - caller_uri: "easynet:///r/silan/agents/alice".to_string(), + caller_ura: "easynet:///r/silan/agents/alice".to_string(), caller_profile: "easynet-strict-v2".to_string(), }) .unwrap(); @@ -971,7 +971,7 @@ mod tests { let cfg = SigningConfig::new(SigningConfigRequest { algorithm: "ed25519".to_string(), seed_base64: "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=".to_string(), - caller_uri: "easynet:///r/silan/agents/alice".to_string(), + caller_ura: "easynet:///r/silan/agents/alice".to_string(), caller_profile: "easynet-strict-v2".to_string(), }) .unwrap(); diff --git a/core/runtime-rs/dendrite-bridge/src/control/capability/package.rs b/core/runtime-rs/dendrite-bridge/src/control/capability/package.rs index ec30aa4a..527d202b 100644 --- a/core/runtime-rs/dendrite-bridge/src/control/capability/package.rs +++ b/core/runtime-rs/dendrite-bridge/src/control/capability/package.rs @@ -41,9 +41,9 @@ pub(crate) fn publish_capability_helper_impl( let tags = req.tags.unwrap_or_default(); let requirements = req.requirements.unwrap_or_default(); let metadata = req.metadata.unwrap_or_default(); - let payload_uri_hint = normalize_opt_string(req.payload_uri); - if package_bytes.is_none() && payload_uri_hint.is_none() { - return Err("publish_capability requires payload_uri or package_bytes_base64".to_string()); + let payload_ura_hint = normalize_opt_string(req.payload_ura); + if package_bytes.is_none() && payload_ura_hint.is_none() { + return Err("publish_capability requires payload_ura or package_bytes_base64".to_string()); } let payload_size_hint = req.payload_size_bytes.unwrap_or_default(); let signature_fingerprint = normalize_opt_string(req.signature_fingerprint).unwrap_or_default(); @@ -61,9 +61,9 @@ pub(crate) fn publish_capability_helper_impl( .await .map_err(|e| format!("sdk upload_payload_bytes failed: {e}"))? } else { - let payload_uri = - required_trimmed(&payload_uri_hint.unwrap_or_default(), "payload_uri")?; - sdk.get_payload_meta(tenant_id.clone(), payload_uri) + let payload_ura = + required_trimmed(&payload_ura_hint.unwrap_or_default(), "payload_ura")?; + sdk.get_payload_meta(tenant_id.clone(), payload_ura) .await .map_err(|e| format!("sdk get_payload_meta failed: {e}"))? }; @@ -85,7 +85,7 @@ pub(crate) fn publish_capability_helper_impl( spec.tags = tags; spec.requirements = requirements; spec.metadata = metadata; - spec.payload_uri = payload_ref.uri.clone(); + spec.payload_ura = payload_ref.ura.clone(); spec.payload_size_bytes = if payload_size_hint > 0 { if payload_size_hint != payload_ref.size_bytes { return Err(format!( @@ -110,7 +110,7 @@ pub(crate) fn publish_capability_helper_impl( validate_publish_proof(&publish_proof)?; let proof_json = json!({ - "payload_uri": publish_proof.payload_uri, + "payload_ura": publish_proof.payload_ura, "payload_digest": publish_proof.payload_digest, "payload_size_bytes": publish_proof.payload_size_bytes, "signature_fingerprint": publish_proof.signature_fingerprint, diff --git a/core/runtime-rs/dendrite-bridge/src/control/requests.rs b/core/runtime-rs/dendrite-bridge/src/control/requests.rs index 7a5877b8..15cc8a91 100644 --- a/core/runtime-rs/dendrite-bridge/src/control/requests.rs +++ b/core/runtime-rs/dendrite-bridge/src/control/requests.rs @@ -67,7 +67,7 @@ pub(crate) struct PublishCapabilityHelperRequest { pub(crate) tags: Option>, pub(crate) requirements: Option>, pub(crate) metadata: Option>, - pub(crate) payload_uri: Option, + pub(crate) payload_ura: Option, pub(crate) payload_size_bytes: Option, pub(crate) package_bytes_base64: Option, pub(crate) signature_fingerprint: Option, diff --git a/core/runtime-rs/dendrite-bridge/src/control/shared.rs b/core/runtime-rs/dendrite-bridge/src/control/shared.rs index e4837d93..f51e5fdd 100644 --- a/core/runtime-rs/dendrite-bridge/src/control/shared.rs +++ b/core/runtime-rs/dendrite-bridge/src/control/shared.rs @@ -116,8 +116,8 @@ fn looks_like_json_payload(bytes: &[u8]) -> bool { /// Validate that a publish proof contains non-empty URI, digest, and positive size. pub(crate) fn validate_publish_proof(proof: &pb::CapabilityPackageProof) -> Result<(), String> { - if proof.payload_uri.trim().is_empty() { - return Err("publish_capability returned empty proof.payload_uri".to_string()); + if proof.payload_ura.trim().is_empty() { + return Err("publish_capability returned empty proof.payload_ura".to_string()); } if proof.payload_digest.trim().is_empty() { return Err("publish_capability returned empty proof.payload_digest".to_string()); @@ -186,7 +186,7 @@ mod tests { #[test] fn validate_publish_proof_rejects_empty_digest() { let proof = pb::CapabilityPackageProof { - payload_uri: "payload://uri".to_string(), + payload_ura: "payload://uri".to_string(), payload_digest: "".to_string(), payload_size_bytes: 1, signature_fingerprint: "".to_string(), @@ -199,7 +199,7 @@ mod tests { #[test] fn validate_publish_proof_rejects_zero_payload_size() { let proof = pb::CapabilityPackageProof { - payload_uri: "payload://uri".to_string(), + payload_ura: "payload://uri".to_string(), payload_digest: "sha256:abc".to_string(), payload_size_bytes: 0, signature_fingerprint: "".to_string(), @@ -213,7 +213,7 @@ mod tests { #[test] fn validate_publish_proof_accepts_valid_proof() { let proof = pb::CapabilityPackageProof { - payload_uri: "payload://bucket/obj".to_string(), + payload_ura: "payload://bucket/obj".to_string(), payload_digest: "sha256:deadbeef".to_string(), payload_size_bytes: 1024, signature_fingerprint: "".to_string(), @@ -225,14 +225,14 @@ mod tests { #[test] fn validate_publish_proof_rejects_empty_uri() { let proof = pb::CapabilityPackageProof { - payload_uri: " ".to_string(), + payload_ura: " ".to_string(), payload_digest: "sha256:abc".to_string(), payload_size_bytes: 1, signature_fingerprint: "".to_string(), package_fingerprint: "".to_string(), }; let err = validate_publish_proof(&proof).expect_err("empty URI must be rejected"); - assert!(err.contains("proof.payload_uri")); + assert!(err.contains("proof.payload_ura")); } #[test] diff --git a/core/runtime-rs/dendrite-bridge/src/errors.rs b/core/runtime-rs/dendrite-bridge/src/errors.rs index c1207a70..f59f6359 100644 --- a/core/runtime-rs/dendrite-bridge/src/errors.rs +++ b/core/runtime-rs/dendrite-bridge/src/errors.rs @@ -77,14 +77,14 @@ pub(crate) enum BridgeErrorCode { // ── Pass-through (RFC 001 §5.2 admission taxonomy) ───────── /// Envelope structurally invalid per RFC 001 §5.2 step 1. May - /// originate at bridge preflight (empty callee.uri, bad nonce + /// originate at bridge preflight (empty callee.ura, bad nonce /// shape) or at the callee (everything else). AxonAxiomEnvelopeIncomplete, /// Signature structure wrong or cryptographic verify failed per /// RFC 001 §5.2 steps 2–3. `source` is always `"callee"` — the /// bridge trusts its own signing output. AxonCallerSignatureInvalid, - /// `(caller.uri, ability, nonce)` seen within the dedup window + /// `(caller.ura, ability, nonce)` seen within the dedup window /// per RFC 001 §5.2 step 4. `source` is always `"callee"`. This /// is a bad-request rejection, not an auth failure; it does NOT /// consume quota. diff --git a/core/runtime-rs/dendrite-bridge/src/ffi_exports.rs b/core/runtime-rs/dendrite-bridge/src/ffi_exports.rs index bd5f45d1..3120a2c4 100644 --- a/core/runtime-rs/dendrite-bridge/src/ffi_exports.rs +++ b/core/runtime-rs/dendrite-bridge/src/ffi_exports.rs @@ -796,7 +796,7 @@ pub extern "C" fn axon_dendrite_protocol_coverage_json() -> *mut c_char { }, "ability_helper": { "entrypoint": "axon_dendrite_invoke_ability_json", - "request": ["tenant_id", "resource_uri", "payload_json|payload_base64"], + "request": ["tenant_id", "resource_ura", "payload_json|payload_base64"], "response": ["result_json", "result_base64", "state", "selected_node_id"] }, "ability_helper_signed": { @@ -934,7 +934,7 @@ mod tests { SigningConfig::new(SigningConfigRequest { algorithm: "ed25519".to_string(), seed_base64: "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=".to_string(), - caller_uri: "easynet:///r/silan/agents/alice".to_string(), + caller_ura: "easynet:///r/silan/agents/alice".to_string(), caller_profile: "easynet-strict-v2".to_string(), }) .expect("valid signing config") @@ -963,7 +963,7 @@ mod tests { let body = CString::new( r#"{ "tenant_id": "silan", - "resource_uri": "easynet:///r/silan/agents/reviewer/abilities/echo@1", + "resource_ura": "easynet:///r/silan/agents/reviewer/abilities/echo@1", "payload_json": {} }"#, ) @@ -1000,7 +1000,7 @@ mod tests { let body = CString::new( r#"{ "callee": { - "uri": "easynet:///r/silan/agents/reviewer", + "ura": "easynet:///r/silan/agents/reviewer", "profile": "easynet-strict-v2" }, "ability": "echo", @@ -1039,7 +1039,7 @@ mod tests { let body = CString::new( r#"{ "tenant_id": "silan", - "resource_uri": "easynet:///r/silan/agents/reviewer/abilities/echo@1", + "resource_ura": "easynet:///r/silan/agents/reviewer/abilities/echo@1", "payload_json": {} }"#, ) diff --git a/core/runtime-rs/dendrite-bridge/src/invoke_signed.rs b/core/runtime-rs/dendrite-bridge/src/invoke_signed.rs index c27491d8..c7ed9bc1 100644 --- a/core/runtime-rs/dendrite-bridge/src/invoke_signed.rs +++ b/core/runtime-rs/dendrite-bridge/src/invoke_signed.rs @@ -28,7 +28,7 @@ //! - The preflight validation table matches spec §4.2 one-to-one; every //! row has a dedicated rejection arm returning the prescribed code //! with `source = "bridge"`. -//! - No per-call caller identity override. The caller URI and profile +//! - No per-call caller identity override. The caller URA and profile //! come from `session.signing` only; the request struct has no field //! for them. Identity binding is session-scoped by construction //! (spec §3.3). @@ -66,7 +66,7 @@ use crate::errors::{BridgeError, BridgeErrorCode}; /// FFI request shape for the signed invocation path. /// -/// Note the deliberate ABSENCE of `caller` / `caller_uri` / +/// Note the deliberate ABSENCE of `caller` / `caller_ura` / /// `caller_profile` / `seed` fields: identity is session-bound and /// the FFI has no per-call override. A hypothetical caller trying to /// spoof identity would have to open a new session with a different @@ -105,7 +105,7 @@ pub(crate) use crate::invoke_signed_common::{AgentIdentityField, CausalContextFi // produced byte-identical output to the client-sdk encoder at // `client-sdk/src/domain/admission.rs::canonical_invocation_bytes`. // #17's parity sweep verified the equivalence across CausalContext -// variants × URI lengths × Unicode × nonce edges (300+ combos). +// variants × URA lengths × Unicode × nonce edges (300+ combos). // // With the equivalence proven, the duplicate is now removed. The // only in-tree implementation lives in client-sdk and is reused by @@ -318,11 +318,11 @@ pub(crate) fn invoke_ability_signed_impl( // from `session.signing` per §3.3 session-scoped binding; the // FFI request has no caller field. let callee = pb::AgentIdentity { - uri: req.callee.uri.trim().to_string(), + ura: req.callee.ura.trim().to_string(), profile: req.callee.profile.trim().to_string(), }; let subject = req.subject.as_ref().map(|s| pb::SubjectIdentity { - uri: s.uri.trim().to_string(), + ura: s.ura.trim().to_string(), profile: s.profile.trim().to_string(), }); @@ -385,7 +385,7 @@ mod tests { // Worked-example anchor — the §1 parity pin. pub(super) const WORKED_SEED_B64: &str = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE="; - pub(super) const WORKED_CALLER_URI: &str = "easynet:///r/silan/agents/alice"; + pub(super) const WORKED_CALLER_URA: &str = "easynet:///r/silan/agents/alice"; pub(super) const WORKED_CALLEE_URI: &str = "easynet:///r/openai/agents/reviewer@1.0"; pub(super) const WORKED_SUBJECT_URI: &str = "easynet:///r/silan/papers/paper@draft-1"; pub(super) const WORKED_ABILITY: &str = "review"; @@ -393,9 +393,9 @@ mod tests { pub(super) const WORKED_ARGS_DIGEST_HEX: &str = "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"; pub(super) const WORKED_CANONICAL_SHA256: &str = - "132aacb0e21a0159a187fc7d71f204f58ecf12feab06eec9f61d3769321820f7"; + "68464c0da3500e842ece4d3e6e539ec74d12b741160bd5174b13234b02b1eb28"; pub(super) const WORKED_SIGNATURE_B64: &str = - "onZ3dvtXDf66nw+I5xe1QPDH5Vm8uqxzELiuX79mNV5uPvvnoddClhFiDemXlF4gS5zWPXhZ4QGQ45FVuhdjBQ=="; + "N78HErlFC7s7NiUumMf7s7mpaBiH+yV8rYo0m0YDxIzZf0d9i/7lMb0mTxMNVwHpP61mN5swqnPH/2WQUsO/AQ=="; fn worked_envelope() -> pb::Envelope { let nonce = hex::decode(WORKED_NONCE_HEX).unwrap(); @@ -409,15 +409,15 @@ mod tests { priority: 3, easynet: None, caller: Some(pb::AgentIdentity { - uri: WORKED_CALLER_URI.to_string(), + ura: WORKED_CALLER_URA.to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: WORKED_CALLEE_URI.to_string(), + ura: WORKED_CALLEE_URI.to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: WORKED_SUBJECT_URI.to_string(), + ura: WORKED_SUBJECT_URI.to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: nonce, @@ -445,8 +445,8 @@ mod tests { // local encoder is now deleted (Commit B) — the parity assertion // degenerated to `a == a`. The sweep still has value as a // drift-detection net against the shared encoder: it exercises - // CausalContext variants × URI length edges (0/1/255/4097/65536) - // × Unicode URIs × nonce edges × 100 OsRng samples against the + // CausalContext variants × URA length edges (0/1/255/4097/65536) + // × Unicode URAs × nonce edges × 100 OsRng samples against the // §1 worked-example anchor. If the client-sdk encoder ever // mutates its byte layout, the worked-example assertion inside // the sweep fires on the first iteration that touches that code @@ -488,7 +488,7 @@ mod tests { Some(pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: vec![0xaa; 32], - receipt_uri: "easynet:///r/t/receipts/r@1".to_string(), + receipt_ura: "easynet:///r/t/receipts/r@1".to_string(), })), }), Some(pb::CausalContext { @@ -496,11 +496,11 @@ mod tests { prior: vec![ pb::ReceiptRef { receipt_hash: vec![0xbb; 32], - receipt_uri: "easynet:///r/t/receipts/r@2".to_string(), + receipt_ura: "easynet:///r/t/receipts/r@2".to_string(), }, pb::ReceiptRef { receipt_hash: vec![0xcc; 32], - receipt_uri: "easynet:///r/t/receipts/r@3".to_string(), + receipt_ura: "easynet:///r/t/receipts/r@3".to_string(), }, ], })), @@ -508,17 +508,17 @@ mod tests { Some(pb::CausalContext { form: Some(pb::causal_context::Form::Merkle(pb::MerkleRoot { root: vec![0xdd; 32], - proof_uri: "easynet:///r/t/merkle/proof@1".to_string(), + proof_ura: "easynet:///r/t/merkle/proof@1".to_string(), })), }), None, ]; - // URI length edges — includes 4097 (page boundary) and 65536 + // URA length edges — includes 4097 (page boundary) and 65536 // (u16 boundary). put_str uses u32 length prefix so these // should all round-trip, but a future "optimisation" that // narrows the length type would trip here. - let uri_lengths = [0usize, 1, 255, 4097, 65536]; + let ura_lengths = [0usize, 1, 255, 4097, 65536]; // Nonce edges covering constant-fill, alternating, and 100 // OsRng samples. The encoder treats nonce as fixed 16 bytes @@ -546,10 +546,10 @@ mod tests { d }]; - // Unicode URIs: 4-byte UTF-8 codepoint (emoji), BOM, ZWJ. + // Unicode URAs: 4-byte UTF-8 codepoint (emoji), BOM, ZWJ. // put_str uses byte length, not char count — a future // "optimisation" to char count would silently corrupt. - let unicode_uris = [ + let unicode_uras = [ "easynet:///r/tenant/agents/👤", // 4-byte UTF-8 "\u{feff}easynet:///r/tenant/agents/alice", // BOM "easynet:///r/tenant/agents/a\u{200d}b", // ZWJ @@ -558,7 +558,7 @@ mod tests { let mut combinations_tested = 0usize; for causal in &causal_variants { - for &len in &uri_lengths { + for &len in &ura_lengths { // Avoid 65 KiB × every nonce × every digest (would be // ~400 KB × 102 × 4 ≈ 160 MB test); trim the outer // combinatorial at the extreme length. @@ -574,22 +574,22 @@ mod tests { }; for nonce in nonce_sample { for digest in digest_sample { - let uri = if len == 0 { + let ura = if len == 0 { String::new() } else { "a".repeat(len) }; let env = pb::Envelope { caller: Some(pb::AgentIdentity { - uri: uri.clone(), + ura: ura.clone(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: uri.clone(), + ura: ura.clone(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: uri.clone(), + ura: ura.clone(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: nonce.clone(), @@ -597,7 +597,7 @@ mod tests { ..Default::default() }; // Exercise the shared encoder — any panic - // (e.g. array-bounds on a large URI, UTF-8 + // (e.g. array-bounds on a large URA, UTF-8 // slice on a multibyte boundary) surfaces // here. The output must also be non-empty // (serializes at least the length prefix). @@ -606,7 +606,7 @@ mod tests { ); assert!( !bytes.is_empty(), - "canonical_invocation_bytes returned empty for causal={:?}, uri_len={}, nonce_head={:02x?}, digest_head={:02x?}", + "canonical_invocation_bytes returned empty for causal={:?}, ura_len={}, nonce_head={:02x?}, digest_head={:02x?}", causal.as_ref().and_then(|c| c.form.as_ref()).map(std::mem::discriminant), len, &nonce[..4], @@ -618,19 +618,19 @@ mod tests { } } - // Unicode URIs — separate sweep, shallower combinatorial. - for uri in unicode_uris { + // Unicode URAs — separate sweep, shallower combinatorial. + for ura in unicode_uras { let env = pb::Envelope { caller: Some(pb::AgentIdentity { - uri: uri.to_string(), + ura: ura.to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: uri.to_string(), + ura: ura.to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: uri.to_string(), + ura: ura.to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0x33; 16], @@ -646,8 +646,8 @@ mod tests { ); assert!( !bytes.is_empty(), - "canonical_invocation_bytes returned empty on Unicode URI: {:?}", - uri, + "canonical_invocation_bytes returned empty on Unicode URA: {:?}", + ura, ); combinations_tested += 1; } @@ -685,7 +685,7 @@ mod tests { let cfg = SigningConfig::new(SigningConfigRequest { algorithm: "ed25519".to_string(), seed_base64: WORKED_SEED_B64.to_string(), - caller_uri: WORKED_CALLER_URI.to_string(), + caller_ura: WORKED_CALLER_URA.to_string(), caller_profile: "easynet-strict-v2".to_string(), }) .unwrap(); @@ -748,7 +748,7 @@ mod tests { fn parse_payload_rejects_both() { let req = SignedInvokeRequest { callee: AgentIdentityField { - uri: "x".to_string(), + ura: "x".to_string(), profile: "y".to_string(), }, subject: None, @@ -768,7 +768,7 @@ mod tests { fn parse_payload_rejects_neither() { let req = SignedInvokeRequest { callee: AgentIdentityField { - uri: "x".to_string(), + ura: "x".to_string(), profile: "y".to_string(), }, subject: None, @@ -865,7 +865,7 @@ mod tests { let cfg = SigningConfig::new(SigningConfigRequest { algorithm: "ed25519".to_string(), seed_base64: WORKED_SEED_B64.to_string(), - caller_uri: WORKED_CALLER_URI.to_string(), + caller_ura: WORKED_CALLER_URA.to_string(), caller_profile: "easynet-strict-v2".to_string(), }) .unwrap(); @@ -881,7 +881,7 @@ mod tests { pub(super) fn minimal_signed_req() -> SignedInvokeRequest { SignedInvokeRequest { callee: AgentIdentityField { - uri: WORKED_CALLEE_URI.to_string(), + ura: WORKED_CALLEE_URI.to_string(), profile: "easynet-strict-v2".to_string(), }, subject: None, @@ -907,16 +907,16 @@ mod tests { } #[test] - fn signed_session_with_empty_callee_uri_is_envelope_incomplete() { + fn signed_session_with_empty_callee_ura_is_envelope_incomplete() { // Constraint #5: missing required fields on a signed session // fail with AXON_AXIOM_ENVELOPE_INCOMPLETE at source=bridge. let sess = signed_session_worked(); let mut req = minimal_signed_req(); - req.callee.uri = " ".to_string(); + req.callee.ura = " ".to_string(); let err = invoke_ability_signed_impl(req, &sess).unwrap_err(); assert_eq!(err.code, BridgeErrorCode::AxonAxiomEnvelopeIncomplete); assert_eq!(err.source, ErrorSource::Bridge); - assert!(err.message.contains("callee.uri")); + assert!(err.message.contains("callee.ura")); } #[test] @@ -970,8 +970,8 @@ mod tests { // SignedInvokeRequest must find nothing. This test exists // as the machine-readable version of that grep. let raw = r#"{ - "caller": { "uri": "spoof", "profile": "easynet-strict-v2" }, - "callee": { "uri": "e", "profile": "p" }, + "caller": { "ura": "spoof", "profile": "easynet-strict-v2" }, + "callee": { "ura": "e", "profile": "p" }, "ability": "a", "payload_base64": "e30=" }"#; @@ -980,7 +980,7 @@ mod tests { // field capturing `caller`. We assert by confirming the struct // deserializes cleanly and the `callee` field reads correctly. let req: SignedInvokeRequest = serde_json::from_str(raw).unwrap(); - assert_eq!(req.callee.uri, "e"); + assert_eq!(req.callee.ura, "e"); // No `caller` field exists on SignedInvokeRequest by design; // if someone ever adds one, the compiler forces an update // here. This line is the canary. @@ -996,7 +996,7 @@ mod tests { // so a reviewer can pair each test with its checklist entry at a // glance: // -// row08_* — malformed envelope (empty callee.uri) +// row08_* — malformed envelope (empty callee.ura) // row09_* — malformed envelope (all-zero nonce) // row10_* — unsigned session calls signed FFI // row11_* — signed session calls legacy FFI @@ -1022,18 +1022,18 @@ mod negative_matrix { use super::*; use crate::signing::{SigningConfig, SigningConfigRequest}; - // ── Row 08: Malformed envelope — empty callee.uri ───────────────── + // ── Row 08: Malformed envelope — empty callee.ura ───────────────── // expected: AXON_AXIOM_ENVELOPE_INCOMPLETE, source="bridge" // layer: bridge preflight (no RPC leaves) #[test] - fn row08_empty_callee_uri_is_bridge_envelope_incomplete() { + fn row08_empty_callee_ura_is_bridge_envelope_incomplete() { let sess = signed_session_worked(); let mut req = minimal_signed_req(); - req.callee.uri = String::new(); + req.callee.ura = String::new(); let err = invoke_ability_signed_impl(req, &sess).unwrap_err(); assert_eq!(err.code, BridgeErrorCode::AxonAxiomEnvelopeIncomplete); assert_eq!(err.source, ErrorSource::Bridge); - assert!(err.message.contains("callee.uri")); + assert!(err.message.contains("callee.ura")); } // ── Row 09: Malformed envelope — caller-supplied all-zero nonce ── @@ -1105,7 +1105,7 @@ mod negative_matrix { let err = SigningConfig::new(SigningConfigRequest { algorithm: "ecdsa-p256".to_string(), seed_base64: WORKED_SEED_B64.to_string(), - caller_uri: WORKED_CALLER_URI.to_string(), + caller_ura: WORKED_CALLER_URA.to_string(), caller_profile: "easynet-strict-v2".to_string(), }) .expect_err("ecdsa-p256 must be rejected"); @@ -1181,11 +1181,11 @@ mod negative_matrix { } } - // ── Row 01: tamper caller.uri → CALLER_SIGNATURE_INVALID ───────── + // ── Row 01: tamper caller.ura → CALLER_SIGNATURE_INVALID ───────── // expected: AXON_CALLER_SIGNATURE_INVALID, source="callee" // layer: bridge propagation (classify_callee_error) #[test] - fn row01_tampered_caller_uri_after_sign_is_callee_caller_signature_invalid() { + fn row01_tampered_caller_ura_after_sign_is_callee_caller_signature_invalid() { let callee_err = admission_error("AXON_CALLER_SIGNATURE_INVALID", "caller_signature_invalid"); let be = classify_callee_error(&callee_err); diff --git a/core/runtime-rs/dendrite-bridge/src/invoke_signed_bidi.rs b/core/runtime-rs/dendrite-bridge/src/invoke_signed_bidi.rs index 37ff38bb..2fdd71aa 100644 --- a/core/runtime-rs/dendrite-bridge/src/invoke_signed_bidi.rs +++ b/core/runtime-rs/dendrite-bridge/src/invoke_signed_bidi.rs @@ -332,22 +332,22 @@ pub(crate) fn invoke_bidi_open_signed_impl( // ── Step 3: envelope assembly + sign ── let caller = pb::AgentIdentity { - uri: signing.caller_uri().to_string(), + ura: signing.caller_ura().to_string(), profile: signing.caller_profile().to_string(), }; let callee = pb::AgentIdentity { - uri: req.callee.uri.trim().to_string(), + ura: req.callee.ura.trim().to_string(), profile: req.callee.profile.trim().to_string(), }; let subject = req .subject .as_ref() .map(|s| pb::SubjectIdentity { - uri: s.uri.trim().to_string(), + ura: s.ura.trim().to_string(), profile: s.profile.trim().to_string(), }) .unwrap_or_else(|| pb::SubjectIdentity { - uri: callee.uri.clone(), + ura: callee.ura.clone(), profile: callee.profile.clone(), }); let request_id = format!("dendrite-bidi-signed-{}", uuid::Uuid::new_v4().simple()); @@ -409,6 +409,7 @@ pub(crate) fn invoke_bidi_open_signed_impl( target: Some(target), initial_args: initial_args.clone(), args_content_type: req.args_content_type.clone().unwrap_or_default(), + content_envelope: None, streams: stream_descriptors, metadata: envelope_metadata, }; @@ -938,7 +939,7 @@ mod tests { fn parse_initial_args_rejects_both_payloads() { let req = SignedInvokeBidiOpenRequest { callee: AgentIdentityField { - uri: "easynet:///r/test/agent/a".into(), + ura: "easynet:///r/test/agent/a".into(), profile: String::new(), }, subject: None, @@ -968,7 +969,7 @@ mod tests { fn parse_initial_args_empty_when_neither_set() { let req = SignedInvokeBidiOpenRequest { callee: AgentIdentityField { - uri: "easynet:///r/test/agent/a".into(), + ura: "easynet:///r/test/agent/a".into(), profile: String::new(), }, subject: None, @@ -993,7 +994,7 @@ mod tests { fn parse_initial_args_decodes_base64() { let req = SignedInvokeBidiOpenRequest { callee: AgentIdentityField { - uri: "easynet:///r/test/agent/a".into(), + ura: "easynet:///r/test/agent/a".into(), profile: String::new(), }, subject: None, diff --git a/core/runtime-rs/dendrite-bridge/src/invoke_signed_common.rs b/core/runtime-rs/dendrite-bridge/src/invoke_signed_common.rs index 592845e8..33611c0d 100644 --- a/core/runtime-rs/dendrite-bridge/src/invoke_signed_common.rs +++ b/core/runtime-rs/dendrite-bridge/src/invoke_signed_common.rs @@ -85,7 +85,7 @@ use crate::signing::SigningConfig; /// enforces that. #[derive(Debug, Deserialize)] pub(crate) struct AgentIdentityField { - pub(crate) uri: String, + pub(crate) ura: String, pub(crate) profile: String, } @@ -100,36 +100,36 @@ pub(crate) enum CausalContextField { None, Scalar { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, }, List { prior: Vec, }, Merkle { root_hex: String, - proof_uri: String, + proof_ura: String, }, } #[derive(Debug, Deserialize)] pub(crate) struct ScalarRef { pub(crate) receipt_hash_hex: String, - pub(crate) receipt_uri: String, + pub(crate) receipt_ura: String, } -/// Non-empty trimmed-URI + trimmed-profile check. Both halves of the +/// Non-empty trimmed-URA + trimmed-profile check. Both halves of the /// identity must be present; whitespace-only is treated as empty. /// /// Rejection: `AXON_AXIOM_ENVELOPE_INCOMPLETE` with the exact field -/// path in the message (`"callee.uri"`, `"subject.profile"`, ...). +/// path in the message (`"callee.ura"`, `"subject.profile"`, ...). pub(crate) fn preflight_identity( field: &AgentIdentityField, label: &str, ) -> Result<(), BridgeError> { - if field.uri.trim().is_empty() { + if field.ura.trim().is_empty() { return Err(BridgeError::bridge( BridgeErrorCode::AxonAxiomEnvelopeIncomplete, - format!("{label}.uri must be non-empty"), + format!("{label}.ura must be non-empty"), )); } if field.profile.trim().is_empty() { @@ -209,13 +209,13 @@ pub(crate) fn parse_causal( })), CausalContextField::Scalar { receipt_hash_hex, - receipt_uri, + receipt_ura, } => { let hash = decode_hex_32(receipt_hash_hex, "causal_context.scalar.receipt_hash_hex")?; Ok(Some(pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: hash.to_vec(), - receipt_uri: receipt_uri.clone(), + receipt_ura: receipt_ura.clone(), })), })) } @@ -228,7 +228,7 @@ pub(crate) fn parse_causal( )?; refs.push(pb::ReceiptRef { receipt_hash: h.to_vec(), - receipt_uri: r.receipt_uri.clone(), + receipt_ura: r.receipt_ura.clone(), }); } Ok(Some(pb::CausalContext { @@ -239,13 +239,13 @@ pub(crate) fn parse_causal( } CausalContextField::Merkle { root_hex, - proof_uri, + proof_ura, } => { let root = decode_hex_32(root_hex, "causal_context.merkle.root_hex")?; Ok(Some(pb::CausalContext { form: Some(pb::causal_context::Form::Merkle(pb::MerkleRoot { root: root.to_vec(), - proof_uri: proof_uri.clone(), + proof_ura: proof_ura.clone(), })), })) } @@ -297,19 +297,19 @@ pub(crate) fn receipt_to_verifier_json( Some(pb::causal_context::Form::Scalar(s)) => json!({ "form": "scalar", "receipt_hash_hex": hex::encode(&s.receipt_hash), - "receipt_uri": s.receipt_uri, + "receipt_ura": s.receipt_ura, }), Some(pb::causal_context::Form::List(l)) => json!({ "form": "list", "prior": l.prior.iter().map(|p| json!({ "receipt_hash_hex": hex::encode(&p.receipt_hash), - "receipt_uri": p.receipt_uri, + "receipt_ura": p.receipt_ura, })).collect::>(), }), Some(pb::causal_context::Form::Merkle(m)) => json!({ "form": "merkle", "root_hex": hex::encode(&m.root), - "proof_uri": m.proof_uri, + "proof_ura": m.proof_ura, }), }); json!({ @@ -320,13 +320,13 @@ pub(crate) fn receipt_to_verifier_json( "timestamp_unix_ms": r.timestamp_unix_ms, "prev_receipt_hash_hex": hex::encode(&r.prev_receipt_hash), "caller_binding": caller.map(|c| json!({ - "uri": c.uri, "profile": c.profile, + "ura": c.ura, "profile": c.profile, })), "callee_binding": callee.map(|c| json!({ - "uri": c.uri, "profile": c.profile, + "ura": c.ura, "profile": c.profile, })), "subject_binding": subject.map(|s| json!({ - "uri": s.uri, "profile": s.profile, + "ura": s.ura, "profile": s.profile, })), "invocation_nonce_base64": BASE64_STANDARD.encode(&r.invocation_nonce), "causal_binding": causal, @@ -624,12 +624,12 @@ pub(crate) fn sign_and_dispatch( // ── Step 2: envelope assembly ── let caller = pb::AgentIdentity { - uri: signing.caller_uri().to_string(), + ura: signing.caller_ura().to_string(), profile: signing.caller_profile().to_string(), }; // RFC 001 §5.1 default: subject = callee when not explicitly given. let subject = axiom.subject.unwrap_or_else(|| pb::SubjectIdentity { - uri: axiom.callee.uri.clone(), + ura: axiom.callee.ura.clone(), profile: axiom.callee.profile.clone(), }); @@ -929,7 +929,7 @@ mod tests { // The point is to prove the trait + pipeline wire up correctly: // a mock binding's `build_request` observes a fully-signed // envelope with all seven-tuple fields populated, the caller - // matches `signing.caller_uri()`, callee comes from axiom, + // matches `signing.caller_ura()`, callee comes from axiom, // subject defaults to callee, nonce/causal round-trip, and the // signature verifies under the session's pubkey. // @@ -1001,11 +1001,11 @@ mod tests { axiom: AxiomInputs<'_>, ) -> (pb::Envelope, Vec, [u8; 64]) { let caller = pb::AgentIdentity { - uri: signing.caller_uri().to_string(), + ura: signing.caller_ura().to_string(), profile: signing.caller_profile().to_string(), }; let subject = axiom.subject.unwrap_or_else(|| pb::SubjectIdentity { - uri: axiom.callee.uri.clone(), + ura: axiom.callee.ura.clone(), profile: axiom.callee.profile.clone(), }); let mut envelope = pb::Envelope { @@ -1041,7 +1041,7 @@ mod tests { SigningConfig::new(SigningConfigRequest { algorithm: "ed25519".to_string(), seed_base64: seed_b64, - caller_uri: "easynet:///r/silan/agents/alice".to_string(), + caller_ura: "easynet:///r/silan/agents/alice".to_string(), caller_profile: "easynet-strict-v2".to_string(), }) .expect("valid signing config") @@ -1057,7 +1057,7 @@ mod tests { }; let axiom = AxiomInputs::new( pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer".to_string(), + ura: "easynet:///r/openai/agents/reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }, None, // subject will default to callee per §5.1 @@ -1073,16 +1073,16 @@ mod tests { // Step 2: caller comes from signing config, NOT from axiom. let caller = envelope.caller.as_ref().expect("caller populated"); - assert_eq!(caller.uri, "easynet:///r/silan/agents/alice"); + assert_eq!(caller.ura, "easynet:///r/silan/agents/alice"); assert_eq!(caller.profile, "easynet-strict-v2"); // Callee preserved from axiom input. let callee = envelope.callee.as_ref().expect("callee populated"); - assert_eq!(callee.uri, "easynet:///r/openai/agents/reviewer"); + assert_eq!(callee.ura, "easynet:///r/openai/agents/reviewer"); // Subject defaulted to callee per §5.1. let subject = envelope.subject.as_ref().expect("subject populated"); - assert_eq!(subject.uri, callee.uri); + assert_eq!(subject.ura, callee.ura); assert_eq!(subject.profile, callee.profile); // Nonce round-trips unchanged. @@ -1113,7 +1113,7 @@ mod tests { }; let axiom = AxiomInputs::new( pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer".to_string(), + ura: "easynet:///r/openai/agents/reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }, None, @@ -1146,11 +1146,11 @@ mod tests { }; let axiom = AxiomInputs::new( pb::AgentIdentity { - uri: "callee://uri".to_string(), + ura: "callee://uri".to_string(), profile: "p1".to_string(), }, Some(pb::SubjectIdentity { - uri: "subject://explicit".to_string(), + ura: "subject://explicit".to_string(), profile: "p2".to_string(), }), b"{}".to_vec(), @@ -1162,7 +1162,7 @@ mod tests { let (envelope, _c, _s) = pre_dispatch_probe(&binding, &signing, axiom); let subject = envelope.subject.expect("subject populated"); - assert_eq!(subject.uri, "subject://explicit"); + assert_eq!(subject.ura, "subject://explicit"); assert_eq!(subject.profile, "p2"); } diff --git a/core/runtime-rs/dendrite-bridge/src/invoke_signed_stream.rs b/core/runtime-rs/dendrite-bridge/src/invoke_signed_stream.rs index 6c3aaadd..d038a389 100644 --- a/core/runtime-rs/dendrite-bridge/src/invoke_signed_stream.rs +++ b/core/runtime-rs/dendrite-bridge/src/invoke_signed_stream.rs @@ -73,7 +73,7 @@ use crate::raw_transport::{server_stream_open_impl, StreamOpenRequest}; /// FFI request shape for the signed streaming invocation path. /// /// Identical layout to `SignedInvokeRequest` (the unary signed -/// shape). The intentional ABSENCE of `caller` / `caller_uri` / +/// shape). The intentional ABSENCE of `caller` / `caller_ura` / /// `caller_profile` / `seed` fields is the spec §3.3 "one session, /// one caller" pin: identity is session-bound and the FFI has no /// per-call override. The AST-based no-caller-field canary in @@ -191,11 +191,11 @@ pub(crate) fn invoke_ability_stream_signed_impl( // ── Step 3: envelope assembly ── let caller = pb::AgentIdentity { - uri: signing.caller_uri().to_string(), + ura: signing.caller_ura().to_string(), profile: signing.caller_profile().to_string(), }; let callee = pb::AgentIdentity { - uri: req.callee.uri.trim().to_string(), + ura: req.callee.ura.trim().to_string(), profile: req.callee.profile.trim().to_string(), }; // RFC 001 §5.1 default: subject = callee when not given. @@ -203,11 +203,11 @@ pub(crate) fn invoke_ability_stream_signed_impl( .subject .as_ref() .map(|s| pb::SubjectIdentity { - uri: s.uri.trim().to_string(), + ura: s.ura.trim().to_string(), profile: s.profile.trim().to_string(), }) .unwrap_or_else(|| pb::SubjectIdentity { - uri: callee.uri.clone(), + ura: callee.ura.clone(), profile: callee.profile.clone(), }); let request_id = format!("dendrite-stream-signed-{}", uuid::Uuid::new_v4().simple()); @@ -336,7 +336,7 @@ mod tests { #[test] fn signed_invoke_stream_request_has_no_caller_field() { let json = r#"{ - "callee": {"uri": "easynet:///r/test/agent/A", "profile": "easynet-strict-v2"}, + "callee": {"ura": "easynet:///r/test/agent/A", "profile": "easynet-strict-v2"}, "ability": "fleet.session_read", "payload_json": {} }"#; @@ -358,7 +358,7 @@ mod tests { fn parse_stream_payload_rejects_both_forms() { let req = SignedInvokeStreamRequest { callee: AgentIdentityField { - uri: "x".into(), + ura: "x".into(), profile: "easynet-strict-v2".into(), }, subject: None, @@ -380,7 +380,7 @@ mod tests { fn parse_stream_payload_rejects_neither_form() { let req = SignedInvokeStreamRequest { callee: AgentIdentityField { - uri: "x".into(), + ura: "x".into(), profile: "easynet-strict-v2".into(), }, subject: None, @@ -402,7 +402,7 @@ mod tests { fn parse_stream_payload_accepts_json_form() { let req = SignedInvokeStreamRequest { callee: AgentIdentityField { - uri: "x".into(), + ura: "x".into(), profile: "easynet-strict-v2".into(), }, subject: None, @@ -460,15 +460,15 @@ mod tests { priority: 3, easynet: None, caller: Some(pb::AgentIdentity { - uri: "easynet:///r/acme/agent/01BAK".to_string(), + ura: "easynet:///r/acme/agent/01BAK".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: "easynet:///r/acme/agent/01DEV-host-A".to_string(), + ura: "easynet:///r/acme/agent/01DEV-host-A".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: "easynet:///r/acme/agent/01USR-alice".to_string(), + ura: "easynet:///r/acme/agent/01USR-alice".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0xab; 16], diff --git a/core/runtime-rs/dendrite-bridge/src/signing.rs b/core/runtime-rs/dendrite-bridge/src/signing.rs index 0b5a4398..b7f7dce5 100644 --- a/core/runtime-rs/dendrite-bridge/src/signing.rs +++ b/core/runtime-rs/dendrite-bridge/src/signing.rs @@ -29,7 +29,7 @@ //! - Construct via `SigningConfig::new` at session open. Any error //! returned from `new` MUST propagate to the caller as a fully- //! failed session creation — there is no partially-signed session. -//! - Once constructed, `signing_key()`, `caller_uri()`, and +//! - Once constructed, `signing_key()`, `caller_ura()`, and //! `caller_profile()` are the only reads. These return borrows, //! not clones — the session struct keeps ownership. //! @@ -81,7 +81,7 @@ pub(crate) const URA_PROFILE_EASYNET_STRICT_V2: &str = "easynet-strict-v2"; pub struct SigningConfigRequest { pub algorithm: String, pub seed_base64: String, - pub caller_uri: String, + pub caller_ura: String, pub caller_profile: String, } @@ -95,13 +95,13 @@ impl SigningConfigRequest { /// the struct back should hold onto them separately; this /// helper's purpose is to spare every consumer a 5-line base64 /// dance at every call site. - pub fn from_seed(seed: [u8; 32], caller_uri: impl Into) -> Self { + pub fn from_seed(seed: [u8; 32], caller_ura: impl Into) -> Self { use base64::engine::general_purpose::STANDARD as B64; use base64::Engine as _; Self { algorithm: "ed25519".to_string(), seed_base64: B64.encode(seed), - caller_uri: caller_uri.into(), + caller_ura: caller_ura.into(), caller_profile: URA_PROFILE_EASYNET_STRICT_V2.to_string(), } } @@ -112,7 +112,7 @@ impl SigningConfigRequest { /// another round-trip to the helper API. pub fn from_seed_with_profile( seed: [u8; 32], - caller_uri: impl Into, + caller_ura: impl Into, caller_profile: impl Into, ) -> Self { use base64::engine::general_purpose::STANDARD as B64; @@ -120,7 +120,7 @@ impl SigningConfigRequest { Self { algorithm: "ed25519".to_string(), seed_base64: B64.encode(seed), - caller_uri: caller_uri.into(), + caller_ura: caller_ura.into(), caller_profile: caller_profile.into(), } } @@ -141,8 +141,8 @@ pub(crate) enum SigningConfigError { SeedNotBase64(String), /// Decoded seed is not exactly 32 bytes. SeedWrongLength(usize), - /// `caller_uri` is empty after trimming. - CallerUriEmpty, + /// `caller_ura` is empty after trimming. + CallerUraEmpty, /// `caller_profile` is empty or not `"easynet-strict-v2"`. CallerProfileUnsupported(String), } @@ -166,8 +166,8 @@ impl SigningConfigError { SigningConfigError::SeedWrongLength(got) => { format!("signing.seed_base64 must decode to 32 bytes, got {got}") } - SigningConfigError::CallerUriEmpty => { - "signing.caller_uri must be a non-empty URA".to_string() + SigningConfigError::CallerUraEmpty => { + "signing.caller_ura must be a non-empty URA".to_string() } SigningConfigError::CallerProfileUnsupported(got) => { format!( @@ -195,8 +195,8 @@ pub(crate) struct SigningConfig { signing_key: SigningKey, /// URA bound to `signing_key` for this session. Spec §3.2 /// self-consistency: every invocation on this session emits - /// `envelope.caller.uri = caller_uri`. - caller_uri: String, + /// `envelope.caller.ura = caller_ura`. + caller_ura: String, /// URA profile selector. Constrained to EASYNET_STRICT_V2. caller_profile: String, } @@ -207,7 +207,7 @@ impl std::fmt::Debug for SigningConfig { /// hygiene: seed SHALL NOT appear in any debug print. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SigningConfig") - .field("caller_uri", &self.caller_uri) + .field("caller_ura", &self.caller_ura) .field("caller_profile", &self.caller_profile) .field("signing_key", &"") .finish() @@ -227,12 +227,12 @@ impl SigningConfig { return Err(SigningConfigError::UnknownAlgorithm(req.algorithm)); } - // Caller URI — non-empty after trim. No further URA parsing + // Caller URA — non-empty after trim. No further URA parsing // here; the runtime admission pipeline enforces URA structure // when it verifies the signature. - let caller_uri = req.caller_uri.trim().to_string(); - if caller_uri.is_empty() { - return Err(SigningConfigError::CallerUriEmpty); + let caller_ura = req.caller_ura.trim().to_string(); + if caller_ura.is_empty() { + return Err(SigningConfigError::CallerUraEmpty); } // Caller profile — must match the supported URA profile. @@ -270,7 +270,7 @@ impl SigningConfig { Ok(SigningConfig { signing_key, - caller_uri, + caller_ura, caller_profile, }) } @@ -282,8 +282,8 @@ impl SigningConfig { &self.signing_key } - pub(crate) fn caller_uri(&self) -> &str { - &self.caller_uri + pub(crate) fn caller_ura(&self) -> &str { + &self.caller_ura } pub(crate) fn caller_profile(&self) -> &str { @@ -309,13 +309,13 @@ mod tests { const WORKED_SEED_B64: &str = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE="; const WORKED_PUBKEY_HEX: &str = "8a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c"; - const WORKED_CALLER_URI: &str = "easynet:///r/silan/agents/alice"; + const WORKED_CALLER_URA: &str = "easynet:///r/silan/agents/alice"; - fn req(seed_b64: &str, caller_uri: &str, profile: &str) -> SigningConfigRequest { + fn req(seed_b64: &str, caller_ura: &str, profile: &str) -> SigningConfigRequest { SigningConfigRequest { algorithm: "ed25519".to_string(), seed_base64: seed_b64.to_string(), - caller_uri: caller_uri.to_string(), + caller_ura: caller_ura.to_string(), caller_profile: profile.to_string(), } } @@ -328,12 +328,12 @@ mod tests { // its key derivation — both are PR2 stop-the-world events. let cfg = SigningConfig::new(req( WORKED_SEED_B64, - WORKED_CALLER_URI, + WORKED_CALLER_URA, URA_PROFILE_EASYNET_STRICT_V2, )) .expect("valid worked-example signing config must construct"); assert_eq!(hex::encode(cfg.public_key_bytes()), WORKED_PUBKEY_HEX); - assert_eq!(cfg.caller_uri(), WORKED_CALLER_URI); + assert_eq!(cfg.caller_ura(), WORKED_CALLER_URA); assert_eq!(cfg.caller_profile(), URA_PROFILE_EASYNET_STRICT_V2); } @@ -342,7 +342,7 @@ mod tests { let err = SigningConfig::new(SigningConfigRequest { algorithm: "ecdsa-p256".to_string(), seed_base64: WORKED_SEED_B64.to_string(), - caller_uri: WORKED_CALLER_URI.to_string(), + caller_ura: WORKED_CALLER_URA.to_string(), caller_profile: URA_PROFILE_EASYNET_STRICT_V2.to_string(), }) .expect_err("unknown algorithm must reject"); @@ -354,7 +354,7 @@ mod tests { let err = SigningConfig::new(SigningConfigRequest { algorithm: "".to_string(), seed_base64: WORKED_SEED_B64.to_string(), - caller_uri: WORKED_CALLER_URI.to_string(), + caller_ura: WORKED_CALLER_URA.to_string(), caller_profile: URA_PROFILE_EASYNET_STRICT_V2.to_string(), }) .expect_err("empty algorithm must reject"); @@ -365,7 +365,7 @@ mod tests { fn seed_base64_malformed_rejected() { let err = SigningConfig::new(req( "not_base64!!!", - WORKED_CALLER_URI, + WORKED_CALLER_URA, URA_PROFILE_EASYNET_STRICT_V2, )) .expect_err("malformed base64 must reject"); @@ -378,7 +378,7 @@ mod tests { let short_b64 = BASE64_STANDARD.encode([0u8; 16]); let err = SigningConfig::new(req( &short_b64, - WORKED_CALLER_URI, + WORKED_CALLER_URA, URA_PROFILE_EASYNET_STRICT_V2, )) .expect_err("short seed must reject"); @@ -389,15 +389,15 @@ mod tests { } #[test] - fn caller_uri_empty_rejected() { + fn caller_ura_empty_rejected() { let err = SigningConfig::new(req(WORKED_SEED_B64, " ", URA_PROFILE_EASYNET_STRICT_V2)) - .expect_err("empty caller_uri must reject"); - assert!(matches!(err, SigningConfigError::CallerUriEmpty)); + .expect_err("empty caller_ura must reject"); + assert!(matches!(err, SigningConfigError::CallerUraEmpty)); } #[test] fn caller_profile_unsupported_rejected() { - let err = SigningConfig::new(req(WORKED_SEED_B64, WORKED_CALLER_URI, "web-safe-v2")) + let err = SigningConfig::new(req(WORKED_SEED_B64, WORKED_CALLER_URA, "web-safe-v2")) .expect_err("unsupported profile must reject"); assert!(matches!( err, @@ -412,7 +412,7 @@ mod tests { // "0101…01" repeated. The `{:?}` output MUST NOT contain it. let cfg = SigningConfig::new(req( WORKED_SEED_B64, - WORKED_CALLER_URI, + WORKED_CALLER_URA, URA_PROFILE_EASYNET_STRICT_V2, )) .unwrap(); @@ -429,14 +429,14 @@ mod tests { /// Task 91 — the seed must NEVER appear as plaintext in any /// public observable on `SigningConfig`. This test exhaustively /// enumerates every public accessor (`signing_key` returns a - /// reference only, not a clone; `caller_uri`, `caller_profile`, + /// reference only, not a clone; `caller_ura`, `caller_profile`, /// `public_key_bytes`) and confirms none of them return the raw /// seed bytes. #[test] fn task91_no_public_accessor_returns_raw_seed() { let cfg = SigningConfig::new(req( WORKED_SEED_B64, - WORKED_CALLER_URI, + WORKED_CALLER_URA, URA_PROFILE_EASYNET_STRICT_V2, )) .unwrap(); @@ -452,9 +452,9 @@ mod tests { haystack.windows(seed.len()).any(|w| w == seed) } - // caller_uri / caller_profile — strings, obviously don't + // caller_ura / caller_profile — strings, obviously don't // contain the seed. - assert!(!contains_seed(cfg.caller_uri().as_bytes(), &seed_pattern)); + assert!(!contains_seed(cfg.caller_ura().as_bytes(), &seed_pattern)); assert!(!contains_seed( cfg.caller_profile().as_bytes(), &seed_pattern @@ -481,14 +481,14 @@ mod tests { // could have swapped them). let cfg = SigningConfig::new(req( WORKED_SEED_B64, - WORKED_CALLER_URI, + WORKED_CALLER_URA, URA_PROFILE_EASYNET_STRICT_V2, )) .unwrap(); - let u1 = cfg.caller_uri().to_string(); + let u1 = cfg.caller_ura().to_string(); let p1 = cfg.caller_profile().to_string(); let pk1 = cfg.public_key_bytes(); - let u2 = cfg.caller_uri().to_string(); + let u2 = cfg.caller_ura().to_string(); let p2 = cfg.caller_profile().to_string(); let pk2 = cfg.public_key_bytes(); assert_eq!(u1, u2); diff --git a/core/runtime-rs/dendrite-bridge/tests/signed_verification_matrix.rs b/core/runtime-rs/dendrite-bridge/tests/signed_verification_matrix.rs index 90aab75c..9c2858c7 100644 --- a/core/runtime-rs/dendrite-bridge/tests/signed_verification_matrix.rs +++ b/core/runtime-rs/dendrite-bridge/tests/signed_verification_matrix.rs @@ -50,15 +50,15 @@ fn tenant_scoped_slot_differs_from_bare_ability_name() { let env = pb::Envelope { priority: 3, caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-a/agents/alice".to_string(), + ura: "easynet:///r/tenant-a/agents/alice".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-a/agents/reviewer".to_string(), + ura: "easynet:///r/tenant-a/agents/reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: "easynet:///r/tenant-a/agents/reviewer".to_string(), + ura: "easynet:///r/tenant-a/agents/reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0x33u8; 16], @@ -161,7 +161,7 @@ fn large_binary_args_hash_is_deterministic() { // Structural approach — parse invoke_signed.rs via syn and // assert the struct's named fields do NOT include any name // starting with "caller" (case-insensitive, to also reject -// variants like `Caller`, `caller_uri`, etc.). +// variants like `Caller`, `caller_ura`, etc.). /// Walks one source file's structs and reports any caller-ish /// field on the named target struct. Reusable across the unary diff --git a/core/runtime-rs/easynet-verify/Cargo.lock b/core/runtime-rs/easynet-verify/Cargo.lock index b71c68b4..06fceaa4 100644 --- a/core/runtime-rs/easynet-verify/Cargo.lock +++ b/core/runtime-rs/easynet-verify/Cargo.lock @@ -2,6 +2,16 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -154,6 +164,41 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -176,6 +221,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -233,6 +279,7 @@ version = "0.55.2" dependencies = [ "anyhow", "base64", + "chacha20poly1305", "ed25519-dalek", "hex", "hkdf", @@ -248,6 +295,7 @@ dependencies = [ "tonic", "tonic-build", "uuid", + "x25519-dalek", ] [[package]] @@ -609,6 +657,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "itertools" version = "0.14.0" @@ -699,6 +756,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -751,6 +814,17 @@ dependencies = [ "spki", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1339,6 +1413,16 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "uuid" version = "1.23.1" @@ -1650,6 +1734,18 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core", + "serde", + "zeroize", +] + [[package]] name = "zerocopy" version = "0.8.48" @@ -1675,6 +1771,20 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "zmij" diff --git a/core/runtime-rs/easynet-verify/src/main.rs b/core/runtime-rs/easynet-verify/src/main.rs index 5c439d18..57b54bdc 100644 --- a/core/runtime-rs/easynet-verify/src/main.rs +++ b/core/runtime-rs/easynet-verify/src/main.rs @@ -6,11 +6,11 @@ //! //! Protocol Responsibility: //! - Accepts a JSON-serialised `InvocationReceipt` and a set of -//! trusted `(agent_uri, hex-pubkey)` mappings. Reconstructs the +//! trusted `(agent_ura, hex-pubkey)` mappings. Reconstructs the //! canonical signing bytes per RFC 001 §4.3 and verifies the //! `callee_signature` against the pubkey declared for the -//! receipt's `callee_binding.uri`. -//! - On success prints `ok: receipt signed by ` and +//! receipt's `callee_binding.ura`. +//! - On success prints `ok: receipt signed by ` and //! exits 0. On failure prints a single-line diagnostic and exits 1. //! //! Implementation Approach: @@ -26,7 +26,7 @@ //! Usage Contract: //! easynet-verify \ //! --receipt path/to/receipt.json \ -//! --pubkey = [--pubkey = …] +//! --pubkey = [--pubkey = …] //! //! Architectural Position: //! - Lives outside the runtime and the bridge on purpose. A user @@ -104,41 +104,41 @@ fn verify_single_receipt( // callee_binding. callee_signature verifies under // signer_binding's pubkey, AND host_attestation_base64 // MUST be a valid signature over - // canonical_host_attestation_bytes(callee_uri, signer_uri) + // canonical_host_attestation_bytes(callee_ura, signer_ura) // by that same key. This proves the host claims to host // this specific callee — without it, a host could sign // receipts impersonating any callee URA. - let callee_uri = receipt.callee_binding.uri.clone(); - let signer_uri_opt: Option = receipt + let callee_ura = receipt.callee_binding.ura.clone(); + let signer_ura_opt: Option = receipt .signer_binding .as_ref() - .map(|s| s.uri.clone()) - .filter(|u| !u.is_empty() && u != &callee_uri); + .map(|s| s.ura.clone()) + .filter(|u| !u.is_empty() && u != &callee_ura); let host_attestation_bytes: Vec = match &receipt.host_attestation_base64 { Some(s) if !s.is_empty() => parse_base64(s, "host_attestation_base64")?, _ => Vec::new(), }; - let is_hosted = signer_uri_opt.is_some(); + let is_hosted = signer_ura_opt.is_some(); if is_hosted && host_attestation_bytes.is_empty() { return Err(format!( "hosted-Agent receipt missing host_attestation_base64 \ - (signer={signer_uri_opt:?}, callee={callee_uri:?})" + (signer={signer_ura_opt:?}, callee={callee_ura:?})" )); } if !is_hosted && !host_attestation_bytes.is_empty() { return Err(format!( "self-signed receipt MUST NOT carry host_attestation_base64 \ - (callee={callee_uri:?}); presence of host_attestation \ + (callee={callee_ura:?}); presence of host_attestation \ without a distinct signer is malformed" )); } - let signing_uri = signer_uri_opt + let signing_uri = signer_ura_opt .clone() - .unwrap_or_else(|| callee_uri.clone()); + .unwrap_or_else(|| callee_ura.clone()); let pubkey_hex = pubkeys.get(&signing_uri).ok_or_else(|| { format!( - "no pubkey provided for signing-authority uri={signing_uri:?}; \ + "no pubkey provided for signing-authority ura={signing_uri:?}; \ pass --pubkey {signing_uri}= on the command line" ) })?; @@ -207,11 +207,11 @@ fn verify_single_receipt( // callee_signature — preventing a hosting key from being // re-used to forge attestations under a different callee URA // is the whole point of the attestation. - if let Some(signer_uri) = signer_uri_opt.as_deref() { + if let Some(signer_ura) = signer_ura_opt.as_deref() { use ed25519_dalek::{Signature, Verifier, SIGNATURE_LENGTH}; let attest_bytes = easynet_run_axon_client::admission::canonical_host_attestation_bytes( - &callee_uri, - signer_uri, + &callee_ura, + signer_ura, ); let attest_sig: [u8; SIGNATURE_LENGTH] = host_attestation_bytes .as_slice() @@ -229,20 +229,20 @@ fn verify_single_receipt( .map_err(|_| { format!( "host_attestation signature does not verify under \ - signer pubkey (signer={signer_uri:?}, callee={callee_uri:?}); \ + signer pubkey (signer={signer_ura:?}, callee={callee_ura:?}); \ refusing to attribute receipt to this callee" ) })?; } - let signed_by = signer_uri_opt.unwrap_or_else(|| callee_uri.clone()); + let signed_by = signer_ura_opt.unwrap_or_else(|| callee_ura.clone()); let mode = if is_hosted { "hosted" } else { "self-signed" }; Ok(format!( - "ok ({mode}): receipt {idx} signed by {signed_by} attributing callee {callee_uri} \ - for caller {caller_uri} on subject {subject_uri}", + "ok ({mode}): receipt {idx} signed by {signed_by} attributing callee {callee_ura} \ + for caller {caller_ura} on subject {subject_ura}", idx = receipt.index, - caller_uri = receipt.caller_binding.uri, - subject_uri = receipt.subject_binding.uri, + caller_ura = receipt.caller_binding.ura, + subject_ura = receipt.subject_binding.ura, )) } @@ -284,7 +284,7 @@ fn verify_single_receipt( // List → resolve every entry; verify every match; // recurse on each. // Merkle → out-of-scope for v1; the proof artefact lives -// at proof_uri but resolving it requires fetching +// at proof_ura but resolving it requires fetching // a separate receipt artefact. v1 returns // TerminatedAtMerkle so the caller knows the walk // stopped without contradiction. @@ -399,12 +399,12 @@ fn walk_from( } Some(CausalJson::Scalar { receipt_hash_hex, - receipt_uri, + receipt_ura, }) => { let prior_sha = parse_hex32(receipt_hash_hex, "Scalar.receipt_hash_hex")?; let prior_id = by_canonical_sha.get(&prior_sha).ok_or_else(|| { format!( - "Scalar predecessor (uri={receipt_uri:?}, hash={receipt_hash_hex}) \ + "Scalar predecessor (ura={receipt_ura:?}, hash={receipt_hash_hex}) \ not found in bundle — causal_binding references a receipt \ whose canonical SHA does not match any bundle entry" ) @@ -431,8 +431,8 @@ fn walk_from( parse_hex32(&entry.receipt_hash_hex, "List.prior[].receipt_hash_hex")?; let prior_id = by_canonical_sha.get(&prior_sha).ok_or_else(|| { format!( - "List predecessor (uri={:?}, hash={}) not found in bundle", - entry.receipt_uri, entry.receipt_hash_hex + "List predecessor (ura={:?}, hash={}) not found in bundle", + entry.receipt_ura, entry.receipt_hash_hex ) })?; walk_from( @@ -448,7 +448,7 @@ fn walk_from( } Some(CausalJson::Merkle { root_hex, - proof_uri, + proof_ura, }) => { // v1: terminate without contradiction. AXIOM // §"Merkle root with URA proof pointer" says the @@ -458,8 +458,8 @@ fn walk_from( // the cleanest behaviour is to verify the receipt's // own signature (already done above) and stop. steps.push(format!( - " · merkle predecessor: root={root_hex} proof_uri={proof_uri:?} \ - (chain walk terminates here; resolve proof_uri separately for \ + " · merkle predecessor: root={root_hex} proof_ura={proof_ura:?} \ + (chain walk terminates here; resolve proof_ura separately for \ unbounded-fan-in audit)" )); } @@ -491,7 +491,7 @@ fn compute_canonical_sha(receipt: &ReceiptJson) -> Result<[u8; 32], String> { }; let is_hosted = signer_pb .as_ref() - .filter(|s| !s.uri.is_empty() && s.uri != receipt.callee_binding.uri) + .filter(|s| !s.ura.is_empty() && s.ura != receipt.callee_binding.ura) .is_some(); let hosted = if is_hosted { Some(easynet_run_axon_client::admission::HostedAttestation { @@ -567,7 +567,7 @@ enum Mode { struct Args { mode: Mode, - /// agent_uri → hex-encoded 32-byte Ed25519 pubkey. + /// agent_ura → hex-encoded 32-byte Ed25519 pubkey. pubkeys: HashMap, } @@ -600,11 +600,11 @@ fn parse_args() -> Result { "--pubkey" => { let v = iter .next() - .ok_or("--pubkey requires a = argument")?; - let (uri, hex) = v + .ok_or("--pubkey requires a = argument")?; + let (ura, hex) = v .split_once('=') - .ok_or_else(|| format!("--pubkey needs =, got {v:?}"))?; - pubkeys.insert(uri.to_string(), hex.to_string()); + .ok_or_else(|| format!("--pubkey needs =, got {v:?}"))?; + pubkeys.insert(ura.to_string(), hex.to_string()); } "--help" | "-h" => { return Err(usage()); @@ -644,8 +644,8 @@ fn parse_args() -> Result { fn usage() -> String { "usage: \n \ - easynet-verify --receipt --pubkey = [--pubkey ...]\n \ - easynet-verify --chain --start --pubkey = [--pubkey ...]" + easynet-verify --receipt --pubkey = [--pubkey ...]\n \ + easynet-verify --chain --start --pubkey = [--pubkey ...]" .to_string() } @@ -692,7 +692,7 @@ struct ReceiptJson { #[derive(Deserialize)] struct AgentJson { - uri: String, + ura: String, profile: String, } @@ -702,21 +702,21 @@ enum CausalJson { None, Scalar { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, }, List { prior: Vec, }, Merkle { root_hex: String, - proof_uri: String, + proof_ura: String, }, } #[derive(Deserialize)] struct ScalarRefJson { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, } #[derive(Deserialize)] @@ -737,14 +737,14 @@ struct CalleeSignatureJson { fn to_pb_agent(a: &AgentJson) -> pb::AgentIdentity { pb::AgentIdentity { - uri: a.uri.clone(), + ura: a.ura.clone(), profile: a.profile.clone(), } } fn to_pb_subject(s: &AgentJson) -> pb::SubjectIdentity { pb::SubjectIdentity { - uri: s.uri.clone(), + ura: s.ura.clone(), profile: s.profile.clone(), } } @@ -759,13 +759,13 @@ fn to_pb_causal(c: &Option) -> Result, Str }, CausalJson::Scalar { receipt_hash_hex, - receipt_uri, + receipt_ura, } => { let h = parse_hex32(receipt_hash_hex, "causal_binding.scalar.receipt_hash_hex")?; pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: h.to_vec(), - receipt_uri: receipt_uri.clone(), + receipt_ura: receipt_ura.clone(), })), } } @@ -778,7 +778,7 @@ fn to_pb_causal(c: &Option) -> Result, Str )?; refs.push(pb::ReceiptRef { receipt_hash: h.to_vec(), - receipt_uri: r.receipt_uri.clone(), + receipt_ura: r.receipt_ura.clone(), }); } pb::CausalContext { @@ -787,13 +787,13 @@ fn to_pb_causal(c: &Option) -> Result, Str } CausalJson::Merkle { root_hex, - proof_uri, + proof_ura, } => { let r = parse_hex32(root_hex, "causal_binding.merkle.root_hex")?; pb::CausalContext { form: Some(pb::causal_context::Form::Merkle(pb::MerkleRoot { root: r.to_vec(), - proof_uri: proof_uri.clone(), + proof_ura: proof_ura.clone(), })), } } diff --git a/core/runtime-rs/easynet-verify/tests/e2e_receipt_verify.rs b/core/runtime-rs/easynet-verify/tests/e2e_receipt_verify.rs index 2a813152..079e134b 100644 --- a/core/runtime-rs/easynet-verify/tests/e2e_receipt_verify.rs +++ b/core/runtime-rs/easynet-verify/tests/e2e_receipt_verify.rs @@ -539,11 +539,11 @@ fn build_chain_receipt( }, "scalar" => { let hash_hex = causal_form["receipt_hash_hex"].as_str().unwrap(); - let uri = causal_form["receipt_uri"].as_str().unwrap(); + let uri = causal_form["receipt_ura"].as_str().unwrap(); pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: hex::decode(hash_hex).unwrap(), - receipt_uri: uri.to_string(), + receipt_ura: uri.to_string(), })), } } @@ -620,7 +620,7 @@ fn chain_walk_verifies_three_hop_scalar_chain() { serde_json::json!({ "form": "scalar", "receipt_hash_hex": hex::encode(a_sha), - "receipt_uri": format!("easynet:///r/silan/receipts/{}", "inv-chain-A"), + "receipt_ura": format!("easynet:///r/silan/receipts/{}", "inv-chain-A"), }), &key, ); @@ -629,7 +629,7 @@ fn chain_walk_verifies_three_hop_scalar_chain() { serde_json::json!({ "form": "scalar", "receipt_hash_hex": hex::encode(b_sha), - "receipt_uri": format!("easynet:///r/silan/receipts/{}", "inv-chain-B"), + "receipt_ura": format!("easynet:///r/silan/receipts/{}", "inv-chain-B"), }), &key, ); @@ -681,7 +681,7 @@ fn chain_walk_rejects_tampered_predecessor_hash() { serde_json::json!({ "form": "scalar", "receipt_hash_hex": hex::encode(bogus_hash), - "receipt_uri": "easynet:///r/silan/receipts/inv-chain-A", + "receipt_ura": "easynet:///r/silan/receipts/inv-chain-A", }), &key, ); @@ -766,7 +766,7 @@ fn chain_walk_rejects_genesis_receipt_signature_mismatch() { serde_json::json!({ "form": "scalar", "receipt_hash_hex": hex::encode(a_sha), - "receipt_uri": "easynet:///r/silan/receipts/inv-chain-A", + "receipt_ura": "easynet:///r/silan/receipts/inv-chain-A", }), &main_key, ); diff --git a/core/runtime-rs/scripts/check-rfc-001-conformance.sh b/core/runtime-rs/scripts/check-rfc-001-conformance.sh index 851b28d3..b6914eb3 100755 --- a/core/runtime-rs/scripts/check-rfc-001-conformance.sh +++ b/core/runtime-rs/scripts/check-rfc-001-conformance.sh @@ -272,8 +272,8 @@ echo " [info] AbilityDescriptor schema lands in CLI P4; check moves there" echo # ───────────────────────────────────────────────────────────────── -# Rule 8: Hosted Agent receipt schema must include signer_agent_uri -# distinct from callee_agent_uri + host_attestation field. +# Rule 8: Hosted Agent receipt schema must include signer_agent_ura +# distinct from callee_agent_ura + host_attestation field. # (P0: feature not implemented yet; defer enforcement to P4.) # ───────────────────────────────────────────────────────────────── echo "Rule 8 — Hosted Agent receipt schema (deferred to P4)" diff --git a/core/runtime-rs/src/errors/security.rs b/core/runtime-rs/src/errors/security.rs index 3a725f78..43b31790 100644 --- a/core/runtime-rs/src/errors/security.rs +++ b/core/runtime-rs/src/errors/security.rs @@ -7,7 +7,7 @@ pub(crate) const ERR_SESSION_KEY_INVALID: &str = "AXON_SESSION_KEY_INVALID"; pub(crate) const ERR_ENCRYPTION_ERROR: &str = "AXON_ENCRYPTION_ERROR"; // ── EasyNet Security ────────────────────────────────────────────────────── -pub(crate) const ERR_EASYNET_RESOURCE_URI_INVALID: &str = "AXON_EASYNET_RESOURCE_URI_INVALID"; +pub(crate) const ERR_EASYNET_RESOURCE_URA_INVALID: &str = "AXON_EASYNET_RESOURCE_URA_INVALID"; pub(crate) const ERR_EASYNET_TENANT_REQUIRED: &str = "AXON_EASYNET_TENANT_REQUIRED"; pub(crate) const ERR_EASYNET_TENANT_MISMATCH: &str = "AXON_EASYNET_TENANT_MISMATCH"; pub(crate) const ERR_EASYNET_SUBJECT_MISMATCH: &str = "AXON_EASYNET_SUBJECT_MISMATCH"; diff --git a/core/runtime-rs/src/interop_native/metadata.rs b/core/runtime-rs/src/interop_native/metadata.rs index 54cf6b04..ac3f7f22 100644 --- a/core/runtime-rs/src/interop_native/metadata.rs +++ b/core/runtime-rs/src/interop_native/metadata.rs @@ -548,7 +548,7 @@ impl AxonRuntime { mcp_tools: vec![spec.clone()], ..Default::default() }, - payload_uri: String::new(), + payload_ura: String::new(), digest: String::new(), proof: pb::CapabilityPackageProof::default(), metadata: HashMap::new(), diff --git a/core/runtime-rs/src/main.rs b/core/runtime-rs/src/main.rs index 5a6ed3e4..ed9d8127 100644 --- a/core/runtime-rs/src/main.rs +++ b/core/runtime-rs/src/main.rs @@ -111,7 +111,7 @@ async fn main() -> anyhow::Result<()> { // AXON_CALLEE_URI — URA of the callee identity this // server signs receipts as // AXON_CALLEE_PROFILE — defaults to "easynet-strict-v2" - if let (Ok(seed_hex), Ok(callee_uri)) = ( + if let (Ok(seed_hex), Ok(callee_ura)) = ( std::env::var("AXON_CALLEE_SEED_HEX"), std::env::var("AXON_CALLEE_URI"), ) { @@ -130,14 +130,14 @@ async fn main() -> anyhow::Result<()> { let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed_arr); state.admission.callee_signer = Some(Arc::new(crate::state::CalleeSigner { identity: pb::AgentIdentity { - uri: callee_uri.trim().to_string(), + ura: callee_ura.trim().to_string(), profile, }, key: signing_key, })); log.info(format!( - "admission: callee signer installed (uri={})", - callee_uri.trim() + "admission: callee signer installed (ura={})", + callee_ura.trim() )); } diff --git a/core/runtime-rs/src/runtime/federation.rs b/core/runtime-rs/src/runtime/federation.rs index 04b4db7d..29fe2e06 100644 --- a/core/runtime-rs/src/runtime/federation.rs +++ b/core/runtime-rs/src/runtime/federation.rs @@ -247,9 +247,9 @@ impl AxonRuntime { .state .agents .sweep_stale(runtime.now_unix_ms(), stale_ms); - for (uri, elapsed) in &demoted { + for (ura, elapsed) in &demoted { tracing::info!( - agent_uri = %uri, + agent_ura = %ura, elapsed_ms = *elapsed, "agents: sweep demoted stale Active record to Suspended (heartbeat stale)" ); diff --git a/core/runtime-rs/src/runtime/federation_client.rs b/core/runtime-rs/src/runtime/federation_client.rs index 6d74314d..ec8e5e34 100644 --- a/core/runtime-rs/src/runtime/federation_client.rs +++ b/core/runtime-rs/src/runtime/federation_client.rs @@ -9,25 +9,25 @@ //! in this process and signs subsequent envelopes. //! 2. Dials the hub's gRPC `Invocation` service. //! 3. Sends `federation.join` with envelope caller=`provisional:`, -//! callee=hub URI. The hub mints a canonical agent URI of the +//! callee=hub URA. The hub mints a canonical agent URA of the //! form `easynet:///r//agent/` and returns it. //! 4. Sends `federation.advertise_agent` so the hub records this -//! runtime's pubkey + canonical URI in the realm directory — +//! runtime's pubkey + canonical URA in the realm directory — //! that's what makes `federation.resolve` see this node. //! 5. Periodically sends `federation.heartbeat` to keep the entry //! Active. On disconnect, the loop sleeps and reconnects, re- //! sending join + advertise (the hub's join handler is keyed by //! pubkey; a duplicate pubkey rejects with `AXON_HUB_PUBLIC_KEY_ALREADY_BOUND`, //! so on reconnect we instead skip join and go straight to -//! heartbeat with the canonical URI we cached). +//! heartbeat with the canonical URA we cached). //! //! What this does NOT do //! --------------------- -//! * Does not persist the canonical URI / keypair to disk. A daemon +//! * Does not persist the canonical URA / keypair to disk. A daemon //! restart picks a new pubkey and joins fresh. That's fine for //! the first cut — the hub records both rows, only the latest //! is Active. A future revision will persist them so restarts -//! keep the same canonical URI. +//! keep the same canonical URA. //! * Does not implement signed envelopes. Federation.* is the //! genesis-exception namespace per the admission gate; the //! v1 wire shape uses unsigned envelopes plus the @@ -46,6 +46,7 @@ use std::time::Duration; +use easynet_run_axon_client::ura; use ed25519_dalek::SigningKey; use rand::RngCore; use tonic::transport::Channel; @@ -105,38 +106,35 @@ pub(crate) fn start_federation_client( let signing_key = SigningKey::from_bytes(&seed); let public_key_hex = hex::encode(signing_key.verifying_key().to_bytes()); let provisional_caller = format!("provisional:{}", config.runtime_id); - // URI v4.1.4 ontology: hub is its own role-segment, NOT an + // URA v4.1.4 ontology: hub is its own role-segment, NOT an // agent-with-id. Pre-v4.1.4 this was `/agent/01HUB` // (treating hub as an agent in the realm directory); v4.1.4 // collapses to the bare `/hub` segment because there is // exactly one hub per realm by definition. The daemon-side // session_initiator + EasyNet backend's HubURI helper both // construct this same shape; advertise / forward calls - // must agree or the caller URI never matches what the + // must agree or the caller URA never matches what the // membership gate looks up. - let hub_callee = format!("easynet:///r/{}/hub", config.tenant_id); - // URI v4.1.4: device URIs use the `/device/` role- + let hub_callee = ura::hub_ura(&config.tenant_id); + // URA v4.1.4: device URAs use the `/device/` role- // segment, NOT `/agent/`. Pre-v4.1.4 we advertised // under `/agent/` so backend listDevices could // match its device_pairings row against the directory // entry. Post-v4.1.4 the directory entry MUST be // `/device/` because that is the same shape // the daemon's `.session` bidi presents in caller - // URI; anything else and the membership gate at the hub + // URA; anything else and the membership gate at the hub // rejects with AXON_MEMBERSHIP_REQUIRED. Backend's // listDevicesLogic matches on the trailing UUID either // way, so the rename is forward-only with no DB schema // change. // - // The hub's `federation.advertise_agent` accepts any URI + // The hub's `federation.advertise_agent` accepts any URA // the caller is willing to self-sign — it just requires - // envelope.caller == agent_uri. v4.1.4's strict ParseURA + // envelope.caller == agent_ura. v4.1.4's strict ParseURA // accepts `/device/` as a legal device-shape URA so // the advertise call's wire shape is unchanged. - let canonical_self_uri = format!( - "easynet:///r/{}/device/{}", - config.tenant_id, config.runtime_id - ); + let canonical_self_uri = ura::device_ura(&config.tenant_id, &config.runtime_id); tracing::info!( hub_endpoint = %config.hub_endpoint, @@ -148,7 +146,7 @@ pub(crate) fn start_federation_client( // hard-fatal condition (hub permanently rejects join with // a non-retryable error). let mut backoff = RECONNECT_BACKOFF_INITIAL; - // Cached canonical URI from the hub's first successful join. + // Cached canonical URA from the hub's first successful join. // Empty until first join lands; on reconnect we still re-issue // join because the keypair is per-process and the hub may have // garbage-collected the old entry. @@ -196,16 +194,16 @@ pub(crate) fn start_federation_client( ) .await; let canonical = match join_outcome { - Ok(uri) => uri, + Ok(ura) => ura, Err(JoinError::PubkeyAlreadyBound) => { // We already have an active row. Reuse the - // canonical URI we cached; if we somehow lost + // canonical URA we cached; if we somehow lost // it (process restarted with same key — should // not happen since we generate fresh), bail. if canonical_uri.is_empty() { tracing::error!( "federation_client: hub says pubkey is bound but \ - we have no cached canonical URI; aborting" + we have no cached canonical URA; aborting" ); return; } @@ -238,18 +236,18 @@ pub(crate) fn start_federation_client( // Two directory rows go in: // // 1. Self-signed advertise of the hub-minted canonical - // URI (`agent/a-xxx`). This is just the host's own + // URA (`agent/a-xxx`). This is just the host's own // membership row — required because membership gate - // checks caller URI against the directory before any + // checks caller URA against the directory before any // subsequent federation.* call can run, and the hub- - // minted URI is the one `federation.join` registered. + // minted URA is the one `federation.join` registered. // // 2. Hosted-by advertise of `agent/` (e.g. // `en-13c91508-...`). This is the row the EasyNet // backend's `listDevices` looks up by `axon_node_id` - // to compute ONLINE/REMOVED. host_uri == the row from - // step 1; caller URI is also that row, so the hub's - // `caller_uri == host_uri` guard passes. + // to compute ONLINE/REMOVED. host_ura == the row from + // step 1; caller URA is also that row, so the hub's + // `caller_ura == host_ura` guard passes. // // The `host_node_id` field on the hosted advertise lets // RFC-002.2 forward_invoke route subsequent calls back to @@ -274,7 +272,7 @@ pub(crate) fn start_federation_client( if let Err(e) = invoke_federation_advertise_hosted( channel.clone(), &canonical_self_uri, - &canonical, // host_uri = hub-minted membership URI + &canonical, // host_ura = hub-minted membership URA &hub_callee, &public_key_hex, &config.runtime_id, @@ -301,7 +299,7 @@ pub(crate) fn start_federation_client( // ── Heartbeat loop ───────────────────────────────── // - // Heartbeat uses the hub-minted membership URI (the row + // Heartbeat uses the hub-minted membership URA (the row // from join). The hosted child row tracks its host's // liveness automatically per the hub's directory model — // no separate ping needed. @@ -333,14 +331,14 @@ enum JoinError { /// rest of the envelope is shape-only (no causal context, no signed /// metadata — the federation.* genesis-exception path doesn't need /// it). -fn build_envelope(caller_uri: &str, callee_uri: &str) -> pb::Envelope { +fn build_envelope(caller_ura: &str, callee_ura: &str) -> pb::Envelope { pb::Envelope { caller: Some(pb::AgentIdentity { - uri: caller_uri.to_string(), + ura: caller_ura.to_string(), profile: String::new(), }), callee: Some(pb::AgentIdentity { - uri: callee_uri.to_string(), + ura: callee_ura.to_string(), profile: String::new(), }), ..Default::default() @@ -382,11 +380,11 @@ fn build_invoke(envelope: pb::Envelope, ability: &str, arguments: Vec) -> pb async fn invoke_federation_join( channel: Channel, config: &FederationClientConfig, - caller_uri: &str, - callee_uri: &str, + caller_ura: &str, + callee_ura: &str, public_key_hex: &str, ) -> Result { - let envelope = build_envelope(caller_uri, callee_uri); + let envelope = build_envelope(caller_ura, callee_ura); let mut args = serde_json::json!({ "realm": config.tenant_id, "public_key_hex": public_key_hex, @@ -416,20 +414,20 @@ async fn invoke_federation_join( return Err(JoinError::HubRejected(err)); } - // Receipt body is `JoinReceiptBody { canonical_agent_uri, realm, + // Receipt body is `JoinReceiptBody { membership_ura, realm, // join_receipt_hash }`. #[derive(serde::Deserialize)] struct JoinReceipt { - canonical_agent_uri: String, + membership_ura: String, } let body: JoinReceipt = serde_json::from_slice(&resp.result) .map_err(|e| JoinError::Transport(format!("parse join receipt: {e}")))?; - Ok(body.canonical_agent_uri) + Ok(body.membership_ura) } -/// Self-advertise: the hub-minted membership URI (`agent/a-xxx`) +/// Self-advertise: the hub-minted membership URA (`agent/a-xxx`) /// publishes itself with the runtime's pubkey + host_node_id. caller -/// URI == agent_uri so the hub's "self-signed advertise" check passes. +/// URA == agent_ura so the hub's "self-signed advertise" check passes. async fn invoke_federation_advertise_self( channel: Channel, canonical_uri: &str, @@ -439,7 +437,7 @@ async fn invoke_federation_advertise_self( ) -> Result<(), String> { let envelope = build_envelope(canonical_uri, hub_callee); let args = serde_json::json!({ - "agent_uri": canonical_uri, + "agent_ura": canonical_uri, "public_key_hex": public_key_hex, "signing_authority": { "kind": "self_signed" }, "host_node_id": host_node_id, @@ -463,28 +461,28 @@ async fn invoke_federation_advertise_self( /// Hosted-by advertise: the runtime publishes a directory row at /// `agent/` (e.g. `en-13c91508-...`) marked as hosted by -/// the membership URI from step 1. The EasyNet backend's -/// `listDevices` looks for exactly this URI shape (its +/// the membership URA from step 1. The EasyNet backend's +/// `listDevices` looks for exactly this URA shape (its /// `device_pairings.axon_node_id` column stores the same string), /// so without this row every device shows up as REMOVED in the UI. /// -/// caller URI == host_uri so the hub's +/// caller URA == host_ura so the hub's /// "hosted Agent must be advertised by its host" check passes. async fn invoke_federation_advertise_hosted( channel: Channel, - hosted_agent_uri: &str, - host_uri: &str, + hosted_agent_ura: &str, + host_ura: &str, hub_callee: &str, public_key_hex: &str, host_node_id: &str, ) -> Result<(), String> { - let envelope = build_envelope(host_uri, hub_callee); + let envelope = build_envelope(host_ura, hub_callee); let args = serde_json::json!({ - "agent_uri": hosted_agent_uri, + "agent_ura": hosted_agent_ura, "public_key_hex": public_key_hex, "signing_authority": { "kind": "hosted_by", - "host_uri": host_uri, + "host_ura": host_ura, }, "host_node_id": host_node_id, }); @@ -513,7 +511,7 @@ async fn invoke_federation_heartbeat( ) -> Result<(), String> { let envelope = build_envelope(canonical_uri, hub_callee); let args = serde_json::json!({ - "agent_uri": canonical_uri, + "agent_ura": canonical_uri, }); let arg_bytes = serde_json::to_vec(&args).map_err(|e| format!("encode heartbeat: {e}"))?; let req = build_invoke(envelope, "federation.heartbeat", arg_bytes); diff --git a/core/runtime-rs/src/runtime/mod.rs b/core/runtime-rs/src/runtime/mod.rs index 5b7ad709..255e4f82 100644 --- a/core/runtime-rs/src/runtime/mod.rs +++ b/core/runtime-rs/src/runtime/mod.rs @@ -260,54 +260,104 @@ impl AxonRuntime { crate::pb_error_retryable(code, message, retryable) } - /// Extract the tenant scope for an envelope by parsing the caller's - /// URA (RFC 001 §3.1 composite identity). - /// - /// URA v2 format: `easynet:///r/{scope}/{subject-type}/{subject-value}[@{version}]` - /// The `{scope}` segment is the tenant. - /// - /// Returns an empty string when either the envelope or the caller - /// URA is absent — callers already handle the empty case - /// (typically by treating it as "anonymous" / no-tenant). - /// - /// Delegates to [`easynet_run_axon_client::ura::scope_from_uri`] - /// — the single canonical parser for the whole workspace. Do not - /// inline a second parser here; any drift between them is exactly - /// the class of bug the shared module was created to prevent. + /// Extract the realm for an envelope by parsing the caller's + /// current URA. Returns empty when the envelope has no caller or + /// the caller URA is malformed. pub(crate) fn envelope_tenant_id(envelope: Option<&pb::Envelope>) -> String { - let caller_uri = envelope + let caller_ura = envelope .and_then(|e| e.caller.as_ref()) - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); - easynet_run_axon_client::ura::scope_from_uri(caller_uri) + let realm = easynet_run_axon_client::ura::realm_from_ura(caller_ura); + if Self::validate_tenant_id(&realm).is_ok() { + realm + } else { + String::new() + } } - /// Extract the caller's principal identifier (subject-value segment of - /// the caller URA, minus any `@version` suffix). Empty when caller is + /// Extract the caller's current agent user-id. Empty when caller is /// absent or the URA cannot be parsed. - /// - /// Delegates to - /// [`easynet_run_axon_client::ura::subject_value_from_uri`]. See - /// [`Self::envelope_tenant_id`] for the rationale. pub(crate) fn envelope_principal_id(envelope: Option<&pb::Envelope>) -> String { - let caller_uri = envelope + let caller_ura = envelope .and_then(|e| e.caller.as_ref()) - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); - easynet_run_axon_client::ura::subject_value_from_uri(caller_uri) + match easynet_run_axon_client::ura::parse_ura(caller_ura) { + Ok(parsed) if Self::validate_tenant_id(&parsed.realm).is_ok() => parsed.user_id, + _ => String::new(), + } } - /// Inverse helper: given `(tenant, principal)` reconstruct a URA for - /// use as `caller.uri` when building an outbound Envelope. Defaults - /// subject-type to `agents` — this matches AXIOM.tex §3.2 - /// SystemAgent convention. Callers with explicit subject-types - /// should build the URI directly. - /// - /// Thin delegate to [`easynet_run_axon_client::ura::build_agent_uri`]. - /// The behaviour contract (empty pair ⇒ empty string, invalid pair - /// ⇒ panic) is documented on the underlying helper. - pub(crate) fn build_caller_uri(tenant: &str, principal: &str) -> String { - easynet_run_axon_client::ura::build_agent_uri(tenant, principal) + pub(crate) fn envelope_resource_owner_id( + envelope: Option<&pb::Envelope>, + ) -> Result { + let caller_ura = envelope + .and_then(|e| e.caller.as_ref()) + .map(|c| c.ura.as_str()) + .unwrap_or(""); + let parsed = easynet_run_axon_client::ura::parse_ura(caller_ura).map_err(|err| { + Self::axon_error( + ERR_UNAUTHENTICATED, + format!("caller URA is not a canonical EasyNet URA: {err}"), + false, + ) + })?; + let owner_id = match parsed.kind { + easynet_run_axon_client::ura::URAKind::User => format!("user.{}", parsed.user_id), + easynet_run_axon_client::ura::URAKind::Device => { + format!("device.{}", parsed.device_id) + } + easynet_run_axon_client::ura::URAKind::Agent => { + format!("agent.{}.{}", parsed.user_id, parsed.agent_id) + } + easynet_run_axon_client::ura::URAKind::Hub => "hub".to_string(), + _ => { + return Err(Self::axon_error( + ERR_UNAUTHENTICATED, + "caller URA cannot own protocol resources", + false, + )); + } + }; + Ok(owner_id) + } + + pub(crate) fn payload_resource_ura_for_envelope( + envelope: Option<&pb::Envelope>, + payload_id: &str, + ) -> Result { + let realm = Self::require_envelope_tenant(envelope)?; + let owner_id = Self::envelope_resource_owner_id(envelope)?; + Ok(easynet_run_axon_client::ura::payload_resource_ura( + &realm, &owner_id, payload_id, + )) + } + + pub(crate) fn is_payload_resource_ura(ura: &str) -> bool { + let Ok(parsed) = easynet_run_axon_client::ura::parse_ura(ura) else { + return false; + }; + if parsed.kind != easynet_run_axon_client::ura::URAKind::Resource { + return false; + } + let Some(payload_id) = parsed.path.strip_prefix("payload/") else { + return false; + }; + !payload_id.is_empty() && !payload_id.contains('/') + } + + /// Build a current caller agent URA for runtime-originated + /// envelopes. Runtime callers use the reserved local agent id + /// `runtime`. + pub(crate) fn build_caller_ura(tenant: &str, principal: &str) -> String { + if tenant.is_empty() && principal.is_empty() { + return String::new(); + } + if tenant.is_empty() || principal.is_empty() { + panic!("build_caller_ura: realm and user_id must both be non-empty"); + } + easynet_run_axon_client::ura::agent_ura(tenant, principal, "runtime") } /// Build a minimal `AgentIdentity` for an outbound caller, given a @@ -315,19 +365,19 @@ impl AxonRuntime { /// /// Returns a runtime-rs-local `pb::AgentIdentity` (distinct from /// client-sdk's `pb::AgentIdentity` until proto consolidation lands - /// in PR2.5 step 1a). The URI is produced by the single canonical + /// in PR2.5 step 1a). The URA is produced by the single canonical /// builder so the bytes that land in the envelope are identical to /// what the client-sdk would have produced for the same input. pub(crate) fn build_caller_identity( tenant: &str, principal: &str, ) -> Option { - let uri = Self::build_caller_uri(tenant, principal); - if uri.is_empty() { + let ura = Self::build_caller_ura(tenant, principal); + if ura.is_empty() { return None; } Some(pb::AgentIdentity { - uri, + ura: ura, profile: easynet_run_axon_client::ura::PROFILE_STRICT_V2.to_string(), }) } @@ -356,6 +406,13 @@ impl AxonRuntime { false, )); } + if normalized != tenant_id { + return Err(Self::axon_error( + ERR_INVALID_TENANT, + "tenant_id must not contain surrounding whitespace", + false, + )); + } if normalized.contains(':') { return Err(Self::axon_error( ERR_INVALID_TENANT, @@ -564,7 +621,7 @@ impl AxonRuntime { // segment that used to round-trip as `"silan"` via trim now // returns `""` from `envelope_tenant_id`, which in turn routes // the call through the "anonymous / no-tenant" path. That is the -// correct behaviour — a signed envelope whose caller URI was +// correct behaviour — a signed envelope whose caller URA was // constructed with trim-able inputs has canonical bytes that // disagree with any other call site's bytes, so admission would // fail downstream anyway. The tests below pin this change @@ -575,10 +632,10 @@ impl AxonRuntime { mod tests { use super::*; - fn envelope_with_caller(uri: &str) -> pb::Envelope { + fn envelope_with_caller(ura: &str) -> pb::Envelope { pb::Envelope { caller: Some(pb::AgentIdentity { - uri: uri.to_string(), + ura: ura.to_string(), profile: easynet_run_axon_client::ura::PROFILE_STRICT_V2.to_string(), }), ..Default::default() @@ -588,8 +645,8 @@ mod tests { // ── envelope_tenant_id / envelope_principal_id ─────────────────── #[test] - fn envelope_tenant_id_reads_from_caller_uri() { - let env = envelope_with_caller("easynet:///r/tenant-a/agents/alice@1.0"); + fn envelope_tenant_id_reads_from_caller_ura() { + let env = envelope_with_caller("easynet:///r/tenant-a/agent/alice.runtime"); assert_eq!(AxonRuntime::envelope_tenant_id(Some(&env)), "tenant-a"); assert_eq!(AxonRuntime::envelope_principal_id(Some(&env)), "alice"); } @@ -608,20 +665,20 @@ mod tests { } #[test] - fn envelope_tenant_id_empty_when_caller_uri_malformed() { + fn envelope_tenant_id_empty_when_caller_ura_malformed() { let env = envelope_with_caller("garbage-not-a-ura"); assert_eq!(AxonRuntime::envelope_tenant_id(Some(&env)), ""); assert_eq!(AxonRuntime::envelope_principal_id(Some(&env)), ""); } /// Regression guard for the Rule 1 ("no silent trim") behaviour - /// change. A caller URI with embedded ASCII whitespace is now + /// change. A caller URA with embedded ASCII whitespace is now /// treated as malformed (→ anonymous), not as a whitespace- /// tolerating version of the trimmed identity. Any reversion of /// this test is a protocol-layer regression. #[test] fn envelope_tenant_id_rejects_whitespace_and_returns_empty() { - let env = envelope_with_caller("easynet:///r/ silan /agents/alice"); + let env = envelope_with_caller("easynet:///r/ silan /agent/alice.runtime"); assert_eq!(AxonRuntime::envelope_tenant_id(Some(&env)), ""); assert_eq!(AxonRuntime::envelope_principal_id(Some(&env)), ""); } @@ -632,43 +689,43 @@ mod tests { /// `envelope_*` returns the anonymous sentinel. #[test] fn envelope_principal_id_rejects_multiple_at_signs_and_returns_empty() { - let env = envelope_with_caller("easynet:///r/silan/agents/alice@v@inner"); + let env = envelope_with_caller("easynet:///r/silan/agent/alice.runtime/extra"); assert_eq!(AxonRuntime::envelope_principal_id(Some(&env)), ""); } - // ── build_caller_uri / build_caller_identity ───────────────────── + // ── build_caller_ura / build_caller_identity ───────────────────── #[test] - fn build_caller_uri_assembles_canonical_form() { + fn build_caller_ura_assembles_canonical_form() { assert_eq!( - AxonRuntime::build_caller_uri("tenant-a", "alice"), - "easynet:///r/tenant-a/agents/alice" + AxonRuntime::build_caller_ura("tenant-a", "alice"), + "easynet:///r/tenant-a/agent/alice.runtime" ); } #[test] - fn build_caller_uri_returns_empty_when_both_empty() { - // Invariant: empty (t,p) ⇒ empty URI ⇒ downstream callers + fn build_caller_ura_returns_empty_when_both_empty() { + // Invariant: empty (t,p) ⇒ empty URA ⇒ downstream callers // produce None for caller (anonymous). - assert_eq!(AxonRuntime::build_caller_uri("", ""), ""); + assert_eq!(AxonRuntime::build_caller_ura("", ""), ""); } /// Regression guard: the pre-PR2.5 helper accepted partial inputs - /// and built malformed URAs like `easynet:///r//agents/alice`. The + /// and built malformed URAs like `easynet:///r//agent/alice`. The /// new canonical builder panics on such input because there is no /// well-defined canonical form for "half an identity" — a downstream /// signature over the half-URA would disagree with any peer who /// drops or preserves the empty segment differently. #[test] - #[should_panic(expected = "build_agent_uri: invalid components")] - fn build_caller_uri_rejects_empty_tenant_with_non_empty_principal() { - let _ = AxonRuntime::build_caller_uri("", "alice"); + #[should_panic(expected = "build_caller_ura: realm and user_id must both be non-empty")] + fn build_caller_ura_rejects_empty_tenant_with_non_empty_principal() { + let _ = AxonRuntime::build_caller_ura("", "alice"); } #[test] - #[should_panic(expected = "build_agent_uri: invalid components")] - fn build_caller_uri_rejects_empty_principal_with_non_empty_tenant() { - let _ = AxonRuntime::build_caller_uri("tenant-a", ""); + #[should_panic(expected = "build_caller_ura: realm and user_id must both be non-empty")] + fn build_caller_ura_rejects_empty_principal_with_non_empty_tenant() { + let _ = AxonRuntime::build_caller_ura("tenant-a", ""); } #[test] @@ -679,7 +736,7 @@ mod tests { #[test] fn build_caller_identity_defaults_to_strict_v2() { let id = AxonRuntime::build_caller_identity("silan", "alice").unwrap(); - assert_eq!(id.uri, "easynet:///r/silan/agents/alice"); + assert_eq!(id.ura, "easynet:///r/silan/agent/alice.runtime"); assert_eq!(id.profile, easynet_run_axon_client::ura::PROFILE_STRICT_V2); } diff --git a/core/runtime-rs/src/runtime/security.rs b/core/runtime-rs/src/runtime/security.rs index c70478d5..cd8eeeb7 100644 --- a/core/runtime-rs/src/runtime/security.rs +++ b/core/runtime-rs/src/runtime/security.rs @@ -29,6 +29,7 @@ use anyhow::{anyhow, Context}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use chacha20poly1305::{ChaCha20Poly1305, Nonce as ChaChaNonce}; +use easynet_run_axon_client::ura; use ed25519_dalek::{Signature, Verifier as _, VerifyingKey}; use p256::ecdsa::{Signature as P256Signature, VerifyingKey as P256VerifyingKey}; use prost::Message; @@ -45,7 +46,7 @@ const ENCRYPTION_CHACHA20_POLY1305: i32 = EncryptionAlgorithm::Chacha20Poly1305 #[derive(Clone, Debug)] pub(crate) struct EasyNetVerifiedResource { - pub(crate) canonical_uri: String, + pub(crate) canonical_ura: String, pub(crate) ability_name: String, pub(crate) tenant_id: String, } @@ -119,26 +120,26 @@ impl AxonRuntime { } let (k, v) = item.split_once('=').ok_or_else(|| { Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, + ERR_EASYNET_RESOURCE_URA_INVALID, "query item must use key=value", ) })?; if k.is_empty() || v.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, + ERR_EASYNET_RESOURCE_URA_INVALID, "query key/value must be non-empty", )); } if items.iter().any(|(existing, _)| existing == k) { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, + ERR_EASYNET_RESOURCE_URA_INVALID, "duplicate query key is not allowed", )); } if k.contains('%') || v.contains('%') { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "percent-encoding is not allowed in easynet URI", + ERR_EASYNET_RESOURCE_URA_INVALID, + "percent-encoding is not allowed in easynet URA", )); } items.push((k.to_string(), v.to_string())); @@ -146,16 +147,16 @@ impl AxonRuntime { Ok(items) } - fn canonical_hub_ability_uri(realm: &str, ability_name: &str) -> String { - format!("easynet:///r/{realm}/ability/hub.{ability_name}") + fn canonical_hub_ability_ura(realm: &str, ability_name: &str) -> String { + ura::hub_ability_ura(realm, ability_name) } fn parse_canonical_hub_ability_path(path: &str) -> Result, pb::Error> { let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() == 2 && parts[1].eq_ignore_ascii_case("hub") { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "resource_uri must reference /ability/hub.., not /hub", + ERR_EASYNET_RESOURCE_URA_INVALID, + "resource_ura must reference /ability/hub.., not /hub", )); } if parts.len() != 3 || !parts[1].eq_ignore_ascii_case("ability") { @@ -164,8 +165,8 @@ impl AxonRuntime { let realm = parts[0].trim(); if realm.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "canonical hub ability URI is missing realm", + ERR_EASYNET_RESOURCE_URA_INVALID, + "canonical hub ability URA is missing realm", )); } let mut tail = parts[2].splitn(3, '.'); @@ -174,14 +175,14 @@ impl AxonRuntime { let member = tail.next().unwrap_or(""); if owner.is_empty() || namespace.is_empty() || member.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "canonical ability URI must be /r//ability/..", + ERR_EASYNET_RESOURCE_URA_INVALID, + "canonical ability URA must be /r//ability/..", )); } if owner != "hub" { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "canonical /r//ability/.. URIs are only supported for owner=hub in this Axon release", + ERR_EASYNET_RESOURCE_URA_INVALID, + "canonical /r//ability/.. URAs are only supported for owner=hub in this Axon release", )); } Ok(Some((realm.to_string(), format!("{namespace}.{member}")))) @@ -198,14 +199,14 @@ impl AxonRuntime { let owner_id = parts[2].trim(); if realm.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "canonical resource URI is missing realm", + ERR_EASYNET_RESOURCE_URA_INVALID, + "canonical resource URA is missing realm", )); } if owner_id.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "canonical resource URI is missing owner id", + ERR_EASYNET_RESOURCE_URA_INVALID, + "canonical resource URA is missing owner id", )); } if !owner_id.contains('.') { @@ -218,7 +219,7 @@ impl AxonRuntime { ))) } - fn canonicalize_r_path_uri( + fn canonicalize_r_path_ura( path: &str, query: &str, envelope_tenant_id: &str, @@ -227,31 +228,31 @@ impl AxonRuntime { if let Some((realm, ability_name)) = Self::parse_canonical_hub_ability_path(path)? { if !query.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "canonical hub ability URI must not include query parameters", + ERR_EASYNET_RESOURCE_URA_INVALID, + "canonical hub ability URA must not include query parameters", )); } if envelope_tenant_id.is_empty() { return Err(Self::easynet_err( ERR_EASYNET_TENANT_REQUIRED, - "canonical hub ability URI requires non-empty envelope tenant_id", + "canonical hub ability URA requires non-empty envelope tenant_id", )); } if realm != envelope_tenant_id { return Err(Self::easynet_err( ERR_EASYNET_TENANT_MISMATCH, - "canonical hub ability URI realm must match envelope tenant_id", + "canonical hub ability URA realm must match envelope tenant_id", )); } let expected_subject = format!("easynet:prv:hub:{realm}"); if subject_id != expected_subject { return Err(Self::easynet_err( ERR_EASYNET_SUBJECT_MISMATCH, - "subject_id does not match canonical hub ability URI subject", + "subject_id does not match canonical hub ability URA subject", )); } return Ok(EasyNetVerifiedResource { - canonical_uri: Self::canonical_hub_ability_uri(&realm, &ability_name), + canonical_ura: Self::canonical_hub_ability_ura(&realm, &ability_name), ability_name, tenant_id: realm, }); @@ -259,27 +260,27 @@ impl AxonRuntime { if let Some((realm, owner_id, resource_path)) = Self::parse_canonical_resource_path(path)? { if !query.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "canonical resource URI must not include query parameters", + ERR_EASYNET_RESOURCE_URA_INVALID, + "canonical resource URA must not include query parameters", )); } if envelope_tenant_id.is_empty() { return Err(Self::easynet_err( ERR_EASYNET_TENANT_REQUIRED, - "canonical resource URI requires non-empty envelope tenant_id", + "canonical resource URA requires non-empty envelope tenant_id", )); } if realm != envelope_tenant_id { return Err(Self::easynet_err( ERR_EASYNET_TENANT_MISMATCH, - "canonical resource URI realm must match envelope tenant_id", + "canonical resource URA realm must match envelope tenant_id", )); } let expected_subject = format!("easynet:prv:resource:{owner_id}"); if subject_id != expected_subject { return Err(Self::easynet_err( ERR_EASYNET_SUBJECT_MISMATCH, - "subject_id does not match canonical resource URI subject", + "subject_id does not match canonical resource URA subject", )); } let ability_name = resource_path @@ -287,7 +288,7 @@ impl AxonRuntime { .filter(|name| !name.is_empty()) .ok_or_else(|| { Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, + ERR_EASYNET_RESOURCE_URA_INVALID, "canonical resource route must include resource//ability/", ) })? @@ -298,7 +299,7 @@ impl AxonRuntime { format!("/{resource_path}") }; return Ok(EasyNetVerifiedResource { - canonical_uri: format!("easynet:///r/{realm}/resource/{owner_id}{suffix}"), + canonical_ura: ura::resource_dot_ura(&realm, &owner_id, &suffix), ability_name, tenant_id: realm, }); @@ -307,15 +308,15 @@ impl AxonRuntime { let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); if parts.len() < 5 { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "r URI path is incomplete", + ERR_EASYNET_RESOURCE_URA_INVALID, + "r URA path is incomplete", )); } let visibility = parts[0].to_ascii_lowercase(); if !matches!(visibility.as_str(), "pub" | "org" | "prv") { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "invalid visibility for r easynet URI", + ERR_EASYNET_RESOURCE_URA_INVALID, + "invalid visibility for r easynet URA", )); } let subject_type = parts[1].to_ascii_lowercase(); @@ -323,26 +324,26 @@ impl AxonRuntime { let kind = parts[3].to_ascii_lowercase(); if kind != "abilities" { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, + ERR_EASYNET_RESOURCE_URA_INVALID, "only /abilities kind is accepted in EasyNet verification", )); } if subject_type == "hub" { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "legacy hub /abilities/... URI is retired; use easynet:///r//ability/hub..", + ERR_EASYNET_RESOURCE_URA_INVALID, + "noncanonical hub /abilities/... URA is retired; use easynet:///r//ability/hub..", )); } let ability_with_ver = parts[4..].join("/"); let (ability_name, version) = ability_with_ver.split_once('@').ok_or_else(|| { Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, + ERR_EASYNET_RESOURCE_URA_INVALID, "ability path must include @version", ) })?; if ability_name.is_empty() || version.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, + ERR_EASYNET_RESOURCE_URA_INVALID, "ability name and version must be non-empty", )); } @@ -352,8 +353,8 @@ impl AxonRuntime { let tenant_id = if visibility == "pub" { if tenant_pos.is_some() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "pub URI must omit tenant_id query", + ERR_EASYNET_RESOURCE_URA_INVALID, + "pub URA must omit tenant_id query", )); } if envelope_tenant_id.is_empty() { @@ -371,7 +372,7 @@ impl AxonRuntime { if tenant.is_empty() || tenant != envelope_tenant_id { return Err(Self::easynet_err( ERR_EASYNET_TENANT_MISMATCH, - "tenant_id mismatch between envelope and resource_uri", + "tenant_id mismatch between envelope and resource_ura", )); } tenant @@ -381,7 +382,7 @@ impl AxonRuntime { if subject_id != expected_subject { return Err(Self::easynet_err( ERR_EASYNET_SUBJECT_MISMATCH, - "subject_id does not match resource URI subject", + "subject_id does not match resource URA subject", )); } @@ -404,7 +405,7 @@ impl AxonRuntime { }; Ok(EasyNetVerifiedResource { - canonical_uri: format!( + canonical_ura: format!( "easynet:///r/{visibility}/{subject_type}/{subject_value}/abilities/{ability_name}@{version}{query_suffix}" ), ability_name: ability_name.to_string(), @@ -412,7 +413,7 @@ impl AxonRuntime { }) } - fn canonicalize_v2_path_uri( + fn canonicalize_v2_path_ura( path: &str, query: &str, envelope_tenant_id: &str, @@ -421,57 +422,57 @@ impl AxonRuntime { let trimmed = path.trim_start_matches('/'); let (namespace, remainder) = trimmed.split_once('/').ok_or_else(|| { Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "resource_uri path namespace is required", + ERR_EASYNET_RESOURCE_URA_INVALID, + "resource_ura path namespace is required", ) })?; if !namespace.eq_ignore_ascii_case("r") { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "only /r namespace is supported for easynet URI verification", + ERR_EASYNET_RESOURCE_URA_INVALID, + "only /r namespace is supported for easynet URA verification", )); } - Self::canonicalize_r_path_uri(remainder, query, envelope_tenant_id, subject_id) + Self::canonicalize_r_path_ura(remainder, query, envelope_tenant_id, subject_id) } - fn canonicalize_easynet_resource_uri( + fn canonicalize_easynet_resource_ura( &self, - resource_uri: &str, + resource_ura: &str, envelope_tenant_id: &str, subject_id: &str, ) -> Result { - if resource_uri.contains('%') { + if resource_ura.contains('%') { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "percent-encoding is not allowed in easynet URI", + ERR_EASYNET_RESOURCE_URA_INVALID, + "percent-encoding is not allowed in easynet URA", )); } - let raw = resource_uri.strip_prefix("easynet://").ok_or_else(|| { + let raw = resource_ura.strip_prefix("easynet://").ok_or_else(|| { Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "resource_uri must start with easynet://", + ERR_EASYNET_RESOURCE_URA_INVALID, + "resource_ura must start with easynet://", ) })?; let (raw_without_query, query) = raw.split_once('?').unwrap_or((raw, "")); if raw_without_query.is_empty() { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "resource_uri cannot be empty", + ERR_EASYNET_RESOURCE_URA_INVALID, + "resource_ura cannot be empty", )); } if !raw_without_query.starts_with('/') { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "resource_uri must use easynet:///r/... form", + ERR_EASYNET_RESOURCE_URA_INVALID, + "resource_ura must use easynet:///r/... form", )); } if raw_without_query.starts_with("//") { return Err(Self::easynet_err( - ERR_EASYNET_RESOURCE_URI_INVALID, - "resource_uri must use canonical easynet:/// prefix", + ERR_EASYNET_RESOURCE_URA_INVALID, + "resource_ura must use canonical easynet:/// prefix", )); } - Self::canonicalize_v2_path_uri(raw_without_query, query, envelope_tenant_id, subject_id) + Self::canonicalize_v2_path_ura(raw_without_query, query, envelope_tenant_id, subject_id) } fn subject_owner_id(subject_id: &str) -> Option<&str> { @@ -794,7 +795,7 @@ impl AxonRuntime { arguments: &[u8], metadata: &HashMap, ) -> Result, pb::Error> { - let Some(resource_uri) = metadata.get("easynet.resource_uri") else { + let Some(resource_ura) = metadata.get("easynet.resource_ura") else { return Ok(None); }; @@ -863,7 +864,7 @@ impl AxonRuntime { let tenant_id_owned = Self::envelope_tenant_id(envelope); let tenant_id = tenant_id_owned.as_str(); let canonical = - self.canonicalize_easynet_resource_uri(resource_uri, tenant_id, &subject_id)?; + self.canonicalize_easynet_resource_ura(resource_ura, tenant_id, &subject_id)?; if let (Some(envelope), Some(owner_id)) = (envelope, Self::subject_owner_id(&subject_id)) { let principal_id = Self::envelope_principal_id(Some(envelope)); if !principal_id.is_empty() && principal_id != owner_id { @@ -899,7 +900,7 @@ impl AxonRuntime { request_id, &subject_id, &canonical.tenant_id, - &canonical.canonical_uri, + &canonical.canonical_ura, &issued_at_text, &nonce, &payload_hash, @@ -933,7 +934,7 @@ impl AxonRuntime { if !target.ability_name.is_empty() && target.ability_name != canonical.ability_name { return Err(Self::easynet_err( ERR_EASYNET_RESOURCE_TARGET_MISMATCH, - "target.ability_name does not match resource_uri ability", + "target.ability_name does not match resource_ura ability", )); } if function_name != canonical.ability_name @@ -942,7 +943,7 @@ impl AxonRuntime { { return Err(Self::easynet_err( ERR_EASYNET_RESOURCE_TARGET_MISMATCH, - "function_name is inconsistent with resource_uri ability", + "function_name is inconsistent with resource_ura ability", )); } } @@ -1111,11 +1112,12 @@ impl AxonRuntime { let payload = pb::EncryptedPayload { algorithm, - key_id: format!("axon://keys/session/{key_id}"), + key_id: ura::resource_dot_ura("local", "session-key", &key_id), nonce: nonce.to_vec(), ciphertext: ciphertext.to_vec(), auth_tag: auth_tag.to_vec(), aad: aad.to_vec(), + ephemeral_public_key: Vec::new(), }; Ok(payload.encode_to_vec()) } @@ -1594,16 +1596,16 @@ mod tests { } #[test] - fn canonicalize_r_path_accepts_canonical_hub_ability_uri() { - let verified = AxonRuntime::canonicalize_r_path_uri( + fn canonicalize_r_path_accepts_canonical_hub_ability_ura() { + let verified = AxonRuntime::canonicalize_r_path_ura( "acme/ability/hub.federation.resolve", "", "acme", "easynet:prv:hub:acme", ) - .expect("canonical hub ability URI should verify structurally"); + .expect("canonical hub ability URA should verify structurally"); assert_eq!( - verified.canonical_uri, + verified.canonical_ura, "easynet:///r/acme/ability/hub.federation.resolve" ); assert_eq!(verified.ability_name, "federation.resolve"); @@ -1611,8 +1613,8 @@ mod tests { } #[test] - fn canonicalize_r_path_accepts_device_ability_resource_route_uri() { - let verified = AxonRuntime::canonicalize_r_path_uri( + fn canonicalize_r_path_accepts_device_ability_resource_route_ura() { + let verified = AxonRuntime::canonicalize_r_path_ura( "acme/resource/device.dev-1/ability/device.shell.run", "", "acme", @@ -1620,7 +1622,7 @@ mod tests { ) .expect("device ability resource route should verify structurally"); assert_eq!( - verified.canonical_uri, + verified.canonical_ura, "easynet:///r/acme/resource/device.dev-1/ability/device.shell.run" ); assert_eq!(verified.ability_name, "device.shell.run"); @@ -1628,18 +1630,18 @@ mod tests { } #[test] - fn canonicalize_r_path_rejects_legacy_hub_ability_uri() { - let err = AxonRuntime::canonicalize_r_path_uri( + fn canonicalize_r_path_rejects_retired_hub_ability_ura() { + let err = AxonRuntime::canonicalize_r_path_ura( "prv/hub/acme/abilities/federation.resolve@1", "tenant_id=acme", "acme", "easynet:prv:hub:acme", ) - .expect_err("legacy hub ability URI must be rejected"); - assert_eq!(err.code, ERR_EASYNET_RESOURCE_URI_INVALID); + .expect_err("noncanonical hub ability URA must be rejected"); + assert_eq!(err.code, ERR_EASYNET_RESOURCE_URA_INVALID); assert!( err.message - .contains("legacy hub /abilities/... URI is retired"), + .contains("noncanonical hub /abilities/... URA is retired"), "unexpected error: {err:?}" ); } diff --git a/core/runtime-rs/src/services/capability/materialize.rs b/core/runtime-rs/src/services/capability/materialize.rs index a06bb78b..d0c18b4a 100644 --- a/core/runtime-rs/src/services/capability/materialize.rs +++ b/core/runtime-rs/src/services/capability/materialize.rs @@ -140,7 +140,7 @@ impl AxonRuntime { && existing.descriptor.requirements == req.requirements && existing.descriptor.signature == req.signature && existing.metadata == req.metadata - && existing.payload_uri == normalized_proof.payload_uri + && existing.payload_ura == normalized_proof.payload_ura && existing.digest == normalized_proof.payload_digest && existing.proof == *normalized_proof } @@ -208,8 +208,8 @@ impl AxonRuntime { if read_required_string("version")? != package_version { return Err("install metadata version mismatch".to_string()); } - if read_required_string("payload_uri")? != package.proof.payload_uri { - return Err("install metadata payload_uri mismatch".to_string()); + if read_required_string("payload_ura")? != package.proof.payload_ura { + return Err("install metadata payload_ura mismatch".to_string()); } let stored_digest = read_required_string("payload_digest")?; if stored_digest != package.proof.payload_digest { @@ -380,7 +380,7 @@ impl AxonRuntime { "package_id": package_id, "version": package_version, "ability_name": package.descriptor.name, - "payload_uri": package.proof.payload_uri, + "payload_ura": package.proof.payload_ura, "payload_digest": package.proof.payload_digest, "payload_size_bytes": package.proof.payload_size_bytes, "signature_fingerprint": package.proof.signature_fingerprint, diff --git a/core/runtime-rs/src/services/capability/proof.rs b/core/runtime-rs/src/services/capability/proof.rs index df844382..428facc4 100644 --- a/core/runtime-rs/src/services/capability/proof.rs +++ b/core/runtime-rs/src/services/capability/proof.rs @@ -45,12 +45,12 @@ impl AxonRuntime { package_id: &str, version: &str, payload_digest: &str, - payload_uri: &str, + payload_ura: &str, payload_size_bytes: i64, signature_fingerprint: &str, ) -> String { let canonical = format!( - "{package_id}\n{version}\n{payload_digest}\n{payload_uri}\n{payload_size_bytes}\n{signature_fingerprint}" + "{package_id}\n{version}\n{payload_digest}\n{payload_ura}\n{payload_size_bytes}\n{signature_fingerprint}" ); format!("sha256:{}", Self::sha256_hex(canonical.as_bytes())) } diff --git a/core/runtime-rs/src/services/capability/rpc_install.rs b/core/runtime-rs/src/services/capability/rpc_install.rs index fe8de731..098b9fb1 100644 --- a/core/runtime-rs/src/services/capability/rpc_install.rs +++ b/core/runtime-rs/src/services/capability/rpc_install.rs @@ -79,18 +79,18 @@ impl AxonRuntime { ))); } if let Some(expected_proof) = req.expected_proof.as_ref() { - if expected_proof.payload_uri.trim().is_empty() + if expected_proof.payload_ura.trim().is_empty() || expected_proof.payload_digest.trim().is_empty() || expected_proof.signature_fingerprint.trim().is_empty() || expected_proof.package_fingerprint.trim().is_empty() { return Ok(install_error(Self::axon_error( ERR_CAPABILITY_INSTALL_PROOF_INVALID, - "expected_proof fields payload_uri/payload_digest/signature_fingerprint/package_fingerprint are required", + "expected_proof fields payload_ura/payload_digest/signature_fingerprint/package_fingerprint are required", false, ))); } - if expected_proof.payload_uri != package.proof.payload_uri + if expected_proof.payload_ura != package.proof.payload_ura || expected_proof.payload_digest != package.proof.payload_digest || expected_proof.payload_size_bytes != package.proof.payload_size_bytes || expected_proof.signature_fingerprint != package.proof.signature_fingerprint @@ -129,7 +129,7 @@ impl AxonRuntime { .state .streaming .payloads - .get(package.proof.payload_uri.as_str()) + .get(package.proof.payload_ura.as_str()) .map(|p| p.clone()) else { return Ok(install_error(Self::axon_error( @@ -208,7 +208,7 @@ impl AxonRuntime { package_ref.package_id.as_str(), package.descriptor.version.as_str(), package.proof.payload_digest.as_str(), - package.proof.payload_uri.as_str(), + package.proof.payload_ura.as_str(), package.proof.payload_size_bytes, signature_fingerprint.as_str(), ); diff --git a/core/runtime-rs/src/services/capability/rpc_package.rs b/core/runtime-rs/src/services/capability/rpc_package.rs index 1036205b..b63b3016 100644 --- a/core/runtime-rs/src/services/capability/rpc_package.rs +++ b/core/runtime-rs/src/services/capability/rpc_package.rs @@ -82,18 +82,18 @@ impl AxonRuntime { false, ))); } - let payload_uri = req.payload_uri.trim().to_string(); - if payload_uri.is_empty() { + let payload_ura = req.payload_ura.trim().to_string(); + if payload_ura.is_empty() { return Ok(publish_error(Self::axon_error( ERR_CAPABILITY_PAYLOAD_URI_REQUIRED, - "payload_uri is required", + "payload_ura is required", false, ))); } - if !payload_uri.starts_with("axon://payloads/") { + if !Self::is_payload_resource_ura(&payload_ura) { return Ok(publish_error(Self::axon_error( ERR_CAPABILITY_PAYLOAD_URI_INVALID, - "payload_uri must use axon://payloads/ scheme", + "payload_ura must be a canonical EasyNet payload resource URA", false, ))); } @@ -101,12 +101,12 @@ impl AxonRuntime { .state .streaming .payloads - .get(payload_uri.as_str()) + .get(payload_ura.as_str()) .map(|p| p.clone()) else { return Ok(publish_error(Self::axon_error( ERR_CAPABILITY_PAYLOAD_NOT_FOUND, - "payload referenced by payload_uri was not uploaded", + "payload referenced by payload_ura was not uploaded", false, ))); }; @@ -137,26 +137,26 @@ impl AxonRuntime { req.package_id.as_str(), version.as_str(), digest.as_str(), - payload_uri.as_str(), + payload_ura.as_str(), payload.reference.size_bytes, signature_fingerprint.as_str(), ); let normalized_proof = pb::CapabilityPackageProof { - payload_uri: payload_uri.clone(), + payload_ura: payload_ura.clone(), payload_digest: digest.clone(), payload_size_bytes: payload.reference.size_bytes, signature_fingerprint: signature_fingerprint.clone(), package_fingerprint: package_fingerprint.clone(), }; if let Some(proof) = req.proof.clone() { - if proof.payload_uri.trim().is_empty() + if proof.payload_ura.trim().is_empty() || proof.payload_digest.trim().is_empty() || proof.signature_fingerprint.trim().is_empty() || proof.package_fingerprint.trim().is_empty() { return Ok(publish_error(Self::axon_error( ERR_CAPABILITY_PROOF_INVALID, - "proof fields payload_uri/payload_digest/signature_fingerprint/package_fingerprint are required", + "proof fields payload_ura/payload_digest/signature_fingerprint/package_fingerprint are required", false, ))); } @@ -167,7 +167,7 @@ impl AxonRuntime { false, ))); } - if proof.payload_uri != normalized_proof.payload_uri + if proof.payload_ura != normalized_proof.payload_ura || proof.payload_digest != normalized_proof.payload_digest || proof.payload_size_bytes != normalized_proof.payload_size_bytes || proof.signature_fingerprint != normalized_proof.signature_fingerprint @@ -236,7 +236,7 @@ impl AxonRuntime { entry.insert(PackageRecord { owner_tenant_id: caller_tenant_id.clone(), descriptor: descriptor.clone(), - payload_uri: payload_uri.clone(), + payload_ura: payload_ura.clone(), digest: digest.clone(), proof: normalized_proof.clone(), metadata: req.metadata.clone(), @@ -283,7 +283,7 @@ impl AxonRuntime { GetPackageResponse { header: Some(header.clone()), descriptor: None, - payload_uri: String::new(), + payload_ura: String::new(), proof: None, } ); @@ -315,7 +315,7 @@ impl AxonRuntime { return Ok(Response::new(pb::GetPackageResponse { header: Some(header), descriptor: Some(pkg.descriptor), - payload_uri: pkg.payload_uri, + payload_ura: pkg.payload_ura, proof: Some(pkg.proof), error: None, })); @@ -323,7 +323,7 @@ impl AxonRuntime { Ok(Response::new(pb::GetPackageResponse { header: Some(header), descriptor: None, - payload_uri: String::new(), + payload_ura: String::new(), proof: None, error: Some(Self::axon_error( ERR_PACKAGE_NOT_FOUND, diff --git a/core/runtime-rs/src/services/invocation/admission_gate.rs b/core/runtime-rs/src/services/invocation/admission_gate.rs index 6789ba75..c6655f87 100644 --- a/core/runtime-rs/src/services/invocation/admission_gate.rs +++ b/core/runtime-rs/src/services/invocation/admission_gate.rs @@ -104,7 +104,7 @@ pub(crate) const REASON_CALLER_SIGNATURE_REQUIRED: &str = "AXON_CALLER_SIGNATURE /// default. Returns `AXON_CALLER_SIGNATURE_REQUIRED`. /// /// This gate runs BEFORE the membership and delegation gates: an -/// unsigned envelope's `caller.uri` is an unsigned string the +/// unsigned envelope's `caller.ura` is an unsigned string the /// caller can set freely, so spending CPU on membership lookup /// against such a URA would be wasted work and would muddle the /// audit story. The signature gate's negative path returns before @@ -207,15 +207,15 @@ fn to_client_envelope(env: &pb::Envelope) -> client_pb::Envelope { priority: env.priority, easynet: None, // EasyNetContext is not in the signed region caller: env.caller.as_ref().map(|c| client_pb::AgentIdentity { - uri: c.uri.clone(), + ura: c.ura.clone(), profile: c.profile.clone(), }), callee: env.callee.as_ref().map(|c| client_pb::AgentIdentity { - uri: c.uri.clone(), + ura: c.ura.clone(), profile: c.profile.clone(), }), subject: env.subject.as_ref().map(|s| client_pb::SubjectIdentity { - uri: s.uri.clone(), + ura: s.ura.clone(), profile: s.profile.clone(), }), invocation_nonce: env.invocation_nonce.clone(), @@ -238,7 +238,7 @@ fn to_client_causal_context(c: &pb::CausalContext) -> client_pb::CausalContext { ServerForm::None(_) => ClientForm::None(client_pb::Empty {}), ServerForm::Scalar(s) => ClientForm::Scalar(client_pb::ReceiptRef { receipt_hash: s.receipt_hash.clone(), - receipt_uri: s.receipt_uri.clone(), + receipt_ura: s.receipt_ura.clone(), }), ServerForm::List(l) => ClientForm::List(client_pb::ReceiptList { prior: l @@ -246,13 +246,13 @@ fn to_client_causal_context(c: &pb::CausalContext) -> client_pb::CausalContext { .iter() .map(|r| client_pb::ReceiptRef { receipt_hash: r.receipt_hash.clone(), - receipt_uri: r.receipt_uri.clone(), + receipt_ura: r.receipt_ura.clone(), }) .collect(), }), ServerForm::Merkle(m) => ClientForm::Merkle(client_pb::MerkleRoot { root: m.root.clone(), - proof_uri: m.proof_uri.clone(), + proof_ura: m.proof_ura.clone(), }), }); client_pb::CausalContext { form } @@ -365,7 +365,7 @@ impl AxonRuntime { .as_ref() .expect("subject set post-admission"); let callee_binding_client = client_pb::AgentIdentity { - uri: signer.identity.uri.clone(), + ura: signer.identity.ura.clone(), profile: signer.identity.profile.clone(), }; let state_str = "admitted"; @@ -481,7 +481,7 @@ impl AxonRuntime { .as_ref() .expect("subject set post-admission"); let callee_binding_client = client_pb::AgentIdentity { - uri: signer.identity.uri.clone(), + ura: signer.identity.ura.clone(), profile: signer.identity.profile.clone(), }; let zero_prev = [0u8; 32]; @@ -649,7 +649,7 @@ mod tests { let env = envelope_with_signature(vec![0u8; 64]); let res = enforce_signature_policy( Some(&env), - "fleet.list_agents", + "device.agent.list", crate::state::SignaturePolicy::RequireSigned, ); assert!(res.is_ok(), "signed envelope must pass under strict policy"); @@ -660,7 +660,7 @@ mod tests { let env = envelope_without_signature(); let err = enforce_signature_policy( Some(&env), - "fleet.list_agents", + "device.agent.list", crate::state::SignaturePolicy::RequireSigned, ) .expect_err("unsigned envelope must reject under strict policy"); @@ -697,7 +697,7 @@ mod tests { let env = envelope_without_signature(); let res = enforce_signature_policy( Some(&env), - "fleet.list_agents", + "device.agent.list", crate::state::SignaturePolicy::LegacyAllowUnsigned, ); assert!( @@ -714,7 +714,7 @@ mod tests { let env = envelope_with_signature(vec![0u8; 64]); let res = enforce_signature_policy( Some(&env), - "fleet.list_agents", + "device.agent.list", crate::state::SignaturePolicy::LegacyAllowUnsigned, ); assert!(res.is_ok()); @@ -726,7 +726,7 @@ mod tests { // is treated as unsigned + non-genesis: rejected. let err = enforce_signature_policy( None, - "fleet.list_agents", + "device.agent.list", crate::state::SignaturePolicy::RequireSigned, ) .expect_err("missing envelope must reject under strict policy"); @@ -808,15 +808,15 @@ mod tests { priority: 3, easynet: None, caller: Some(pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer@1.0".to_string(), + ura: "easynet:///r/openai/agent/openai.reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0x22u8; 16], @@ -847,15 +847,15 @@ mod tests { priority: 3, easynet: None, caller: Some(client_pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(client_pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer@1.0".to_string(), + ura: "easynet:///r/openai/agent/openai.reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(client_pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0x22u8; 16], @@ -903,22 +903,22 @@ mod tests { priority: 3, easynet: None, caller: Some(pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer@1.0".to_string(), + ura: "easynet:///r/openai/agent/openai.reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0x33u8; 16], causal_context: Some(pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: vec![0x44u8; 32], - receipt_uri: "easynet:///r/silan/receipts/abc".to_string(), + receipt_ura: "easynet:///r/silan/receipts/abc".to_string(), })), }), caller_signature: Some(pb::CallerSignature { @@ -939,15 +939,15 @@ mod tests { priority: 3, easynet: None, caller: Some(client_pb::AgentIdentity { - uri: "easynet:///r/silan/agents/alice".to_string(), + ura: "easynet:///r/silan/agent/silan.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), callee: Some(client_pb::AgentIdentity { - uri: "easynet:///r/openai/agents/reviewer@1.0".to_string(), + ura: "easynet:///r/openai/agent/openai.reviewer".to_string(), profile: "easynet-strict-v2".to_string(), }), subject: Some(client_pb::SubjectIdentity { - uri: "easynet:///r/silan/papers/paper@draft-1".to_string(), + ura: "easynet:///r/silan/resource/silan.papers/paper".to_string(), profile: "easynet-strict-v2".to_string(), }), invocation_nonce: vec![0x33u8; 16], @@ -955,7 +955,7 @@ mod tests { form: Some(client_pb::causal_context::Form::Scalar( client_pb::ReceiptRef { receipt_hash: vec![0x44u8; 32], - receipt_uri: "easynet:///r/silan/receipts/abc".to_string(), + receipt_ura: "easynet:///r/silan/receipts/abc".to_string(), }, )), }), diff --git a/core/runtime-rs/src/services/invocation/bidi_handler.rs b/core/runtime-rs/src/services/invocation/bidi_handler.rs index 44ca0b1e..943bb67d 100644 --- a/core/runtime-rs/src/services/invocation/bidi_handler.rs +++ b/core/runtime-rs/src/services/invocation/bidi_handler.rs @@ -253,7 +253,7 @@ pub const DOWN_SEND_STALL_THRESHOLD: std::time::Duration = std::time::Duration:: /// wshandler.go`. Internal protocol detail — not an /// operator-visible surface — so it lives next to its single /// reader rather than a freestanding module. -pub(crate) const ABILITY_SESSION_ATTACH: &str = "fleet.session_attach"; +pub(crate) const ABILITY_SESSION_ATTACH: &str = "device.terminal.attach"; // ─── gRPC entry point ──────────────────────────────────────────── @@ -558,7 +558,7 @@ async fn run_frame_loop( // ─── Optional session bind ─────────────────────────────── // - // For `fleet.session_attach` envelopes, hand the BidiStream + // For `device.terminal.attach` envelopes, hand the BidiStream // pipe to the SessionRegistry, which routes to the // kind-matching SessionProvider. The provider spawns its // own pump; we keep the counterpart channel halves and @@ -935,7 +935,7 @@ impl SessionAttachment { } } -/// Initial-args payload for `fleet.session_attach` envelopes. +/// Initial-args payload for `device.terminal.attach` envelopes. /// Today's PTY caller and legacy code paths predating RFC-002 /// both send `{"session_id":"..."}`. Module-level so the schema /// has one canonical declaration; the dispatch helper deserialises @@ -1260,6 +1260,7 @@ mod tests { }), initial_args: Vec::new(), args_content_type: String::new(), + content_envelope: None, streams: Vec::new(), metadata: std::collections::HashMap::new(), }) diff --git a/core/runtime-rs/src/services/invocation/delegation_gate.rs b/core/runtime-rs/src/services/invocation/delegation_gate.rs index 05c0cac2..23125179 100644 --- a/core/runtime-rs/src/services/invocation/delegation_gate.rs +++ b/core/runtime-rs/src/services/invocation/delegation_gate.rs @@ -8,11 +8,11 @@ //! backend call), the envelope MUST carry a DelegationProof. The //! admission gate verifies six things before dispatching: //! -//! 1. Signature integrity against issuer_uri's public key. +//! 1. Signature integrity against issuer_ura's public key. //! 2. Issuer trust — issuer == subject (self-delegation), or //! issuer is in the realm's trusted-delegation-issuers list. -//! 3. Caller match — proof.caller_uri == envelope.caller.uri. -//! 4. Audience match — envelope.callee.uri satisfies proof.audience. +//! 3. Caller match — proof.caller_ura == envelope.caller.ura. +//! 4. Audience match — envelope.callee.ura satisfies proof.audience. //! 5. Scope match — envelope.ability satisfies one of proof.scopes. //! 6. Expiry — now < proof.expires_at_ms. //! @@ -26,14 +26,14 @@ //! `delegation.go::DelegationProofRaw`. We re-derive the same //! canonical bytes here and verify the Ed25519 signature //! against the issuer's public key. -//! - Issuer trust today is permissive: any non-empty issuer URI +//! - Issuer trust today is permissive: any non-empty issuer URA //! is accepted. The realm's "trusted issuers" registry lives //! in `state.agents` (post-P5.0); a future hardening pass //! adds a `trust_role: "delegation_issuer"` flag to //! AgentRecord and rejects issuers whose record lacks it. //! - Result: when verification succeeds, the gate returns the //! parsed `VerifiedDelegation` so downstream code can read -//! `subject_uri` (the principal whose authority the call +//! `subject_ura` (the principal whose authority the call //! invokes). Without this, every authenticated backend call //! degrades to "caller=backend acting under its own authority" //! — exactly what plan §A14 forbids. @@ -77,9 +77,9 @@ struct DelegationProofRaw { /// derives. #[derive(Debug, Deserialize, Serialize)] struct DelegationPayload { - issuer_uri: String, - subject_uri: String, - caller_uri: String, + issuer_ura: String, + subject_ura: String, + caller_ura: String, audience: String, scopes: Vec, issued_at_ms: i64, @@ -87,13 +87,13 @@ struct DelegationPayload { } /// Parsed + verified delegation, returned by the gate. Downstream -/// dispatch reads `subject_uri` to know which principal to record +/// dispatch reads `subject_ura` to know which principal to record /// in audit + (later) admission policy decisions. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct VerifiedDelegation { - pub(crate) issuer_uri: String, - pub(crate) subject_uri: String, - pub(crate) caller_uri: String, + pub(crate) issuer_ura: String, + pub(crate) subject_ura: String, + pub(crate) caller_ura: String, pub(crate) audience: String, pub(crate) scopes: Vec, pub(crate) issued_at_ms: i64, @@ -103,7 +103,7 @@ pub(crate) struct VerifiedDelegation { /// Outcome of the delegation verification step. /// /// * `Verified(d)` — proof was present, signature valid, six -/// §1.5 rules satisfied. Dispatch proceeds with d.subject_uri +/// §1.5 rules satisfied. Dispatch proceeds with d.subject_ura /// as the principal. /// * `Absent` — no `x-easynet-delegation` header. The envelope's /// Caller acts under its own authority; downstream code SHOULD @@ -134,7 +134,7 @@ impl AxonRuntime { /// Verify the optional DelegationProof carried in the /// request's gRPC metadata. Caller passes the raw metadata /// map (already extracted from the tonic Request) plus the - /// envelope (for caller URI + callee URI + ability) and the + /// envelope (for caller URA + callee URA + ability) and the /// current time in unix ms. /// /// Returns: @@ -161,7 +161,7 @@ impl AxonRuntime { // // `federation.advertise_agent` is the chicken-and-egg moment: // the caller is registering itself, so the delegation issuer - // (== caller URI) cannot already be looked up — that's + // (== caller URA) cannot already be looked up — that's // literally the row this RPC creates. // // `federation.subscribe_directory` opens a long-lived stream @@ -177,7 +177,7 @@ impl AxonRuntime { // // The carve-out is bounded: only these three ability names, // and only when the issuer in the delegation payload equals - // the envelope's caller URI (self-issued). Third parties + // the envelope's caller URA (self-issued). Third parties // forging delegations into one of these abilities would // fail the issuer-equals-caller check below and fall // through to normal verification. @@ -205,9 +205,9 @@ impl AxonRuntime { let envelope_caller = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); - if payload.issuer_uri == envelope_caller { + if payload.issuer_ura == envelope_caller { return DelegationDecision::Absent; } } @@ -276,14 +276,14 @@ impl AxonRuntime { // Step 1 — signature integrity. Resolve the issuer's // public key from the realm directory; absent => issuer // is unknown to the realm => reject. - let issuer_pubkey = match self.state.agents.lookup(&payload.issuer_uri) { + let issuer_pubkey = match self.state.agents.lookup(&payload.issuer_ura) { Some(rec) => rec.public_key, None => { return DelegationDecision::Rejected(make_error( ERR_DELEGATION_ISSUER_UNTRUSTED, format!( "delegation issuer {} not found in realm directory", - payload.issuer_uri + payload.issuer_ura ), )); } @@ -293,7 +293,7 @@ impl AxonRuntime { ERR_DELEGATION_BAD_SIGNATURE, format!( "delegation signature does not verify against issuer {}: {e}", - payload.issuer_uri + payload.issuer_ura ), )); } @@ -303,20 +303,20 @@ impl AxonRuntime { // gates "must be a member"). A future hardening pass adds // a `trust_role: "delegation_issuer"` flag. - // Step 3 — caller match. The proof's caller_uri MUST - // equal envelope.caller.uri. Otherwise a malicious caller + // Step 3 — caller match. The proof's caller_ura MUST + // equal envelope.caller.ura. Otherwise a malicious caller // could replay another Agent's delegation. let envelope_caller = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); - if payload.caller_uri != envelope_caller { + if payload.caller_ura != envelope_caller { return DelegationDecision::Rejected(make_error( ERR_DELEGATION_CALLER_MISMATCH, format!( - "delegation.caller_uri ({}) != envelope.caller ({})", - payload.caller_uri, envelope_caller + "delegation.caller_ura ({}) != envelope.caller ({})", + payload.caller_ura, envelope_caller ), )); } @@ -325,7 +325,7 @@ impl AxonRuntime { let envelope_callee = envelope .callee .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); if !audience_admits(&payload.audience, envelope_callee) { return DelegationDecision::Rejected(make_error( @@ -350,9 +350,9 @@ impl AxonRuntime { } DelegationDecision::Verified(VerifiedDelegation { - issuer_uri: payload.issuer_uri, - subject_uri: payload.subject_uri, - caller_uri: payload.caller_uri, + issuer_ura: payload.issuer_ura, + subject_ura: payload.subject_ura, + caller_ura: payload.caller_ura, audience: payload.audience, scopes: payload.scopes, issued_at_ms: payload.issued_at_ms, @@ -439,11 +439,11 @@ mod tests { use std::collections::HashMap; use std::sync::Arc; - const ISSUER_URI: &str = "easynet:///r/acme/agent/01BAK"; - const SUBJECT_URI: &str = "easynet:///r/acme/agent/01USR-alice"; - const CALLER_URI: &str = "easynet:///r/acme/agent/01BAK"; - const CALLEE_URI: &str = "easynet:///r/acme/agent/01HUB"; - const ABILITY: &str = "federation.resolve"; + const ISSUER_URI: &str = "easynet:///r/acme/agent/acme.backend"; + const SUBJECT_URI: &str = "easynet:///r/acme/agent/alice.subject"; + const CALLER_URI: &str = "easynet:///r/acme/agent/acme.backend"; + const CALLEE_URI: &str = "easynet:///r/acme/agent/acme.hub"; + const ABILITY: &str = "alice.chat"; /// Generate a deterministic test SigningKey. ed25519-dalek 2.x /// dropped the `generate` constructor; we hand-roll a 32-byte @@ -470,11 +470,11 @@ mod tests { fn envelope() -> pb::Envelope { pb::Envelope { caller: Some(pb::AgentIdentity { - uri: CALLER_URI.into(), + ura: CALLER_URI.into(), ..Default::default() }), callee: Some(pb::AgentIdentity { - uri: CALLEE_URI.into(), + ura: CALLEE_URI.into(), ..Default::default() }), ..Default::default() @@ -493,9 +493,9 @@ mod tests { fn fresh_payload(now_ms: i64) -> DelegationPayload { DelegationPayload { - issuer_uri: ISSUER_URI.into(), - subject_uri: SUBJECT_URI.into(), - caller_uri: CALLER_URI.into(), + issuer_ura: ISSUER_URI.into(), + subject_ura: SUBJECT_URI.into(), + caller_ura: CALLER_URI.into(), audience: CALLEE_URI.into(), scopes: vec![ABILITY.into()], issued_at_ms: now_ms - 1_000, @@ -540,9 +540,9 @@ mod tests { let m = meta_with(&proof); match runtime.run_delegation_gate(&m, &envelope(), ABILITY, now) { DelegationDecision::Verified(d) => { - assert_eq!(d.subject_uri, SUBJECT_URI); - assert_eq!(d.issuer_uri, ISSUER_URI); - assert_eq!(d.caller_uri, CALLER_URI); + assert_eq!(d.subject_ura, SUBJECT_URI); + assert_eq!(d.issuer_ura, ISSUER_URI); + assert_eq!(d.caller_ura, CALLER_URI); } other => panic!("want Verified, got {other:?}"), } @@ -559,7 +559,7 @@ mod tests { .state .agents .insert(AgentRecord::new_self_signed_active( - "easynet:///r/acme/agent/01OTHER", + "easynet:///r/acme/agent/acme.other", vec![1], )); let now = 1_000_000_000; @@ -597,7 +597,7 @@ mod tests { let runtime = rt_with_issuer(&signer.verifying_key().to_bytes()); let now = 1_000_000_000; let mut payload = fresh_payload(now); - payload.caller_uri = "easynet:///r/acme/agent/01OTHER-CALLER".into(); + payload.caller_ura = "easynet:///r/acme/agent/acme.other-caller".into(); let proof = build_proof(&signer, &payload); let m = meta_with(&proof); match runtime.run_delegation_gate(&m, &envelope(), ABILITY, now) { @@ -614,7 +614,7 @@ mod tests { let runtime = rt_with_issuer(&signer.verifying_key().to_bytes()); let now = 1_000_000_000; let mut payload = fresh_payload(now); - payload.audience = "easynet:///r/acme/agent/01ELSEWHERE".into(); + payload.audience = "easynet:///r/acme/agent/acme.elsewhere".into(); let proof = build_proof(&signer, &payload); let m = meta_with(&proof); match runtime.run_delegation_gate(&m, &envelope(), ABILITY, now) { @@ -647,7 +647,7 @@ mod tests { let now = 1_000_000_000; let mut payload = fresh_payload(now); payload.audience = "easynet:///r/acme/".into(); - // envelope.callee is easynet:///r/acme/agent/01HUB which + // envelope.callee is easynet:///r/acme/agent/acme.hub which // starts with the audience prefix. let proof = build_proof(&signer, &payload); let m = meta_with(&proof); @@ -663,10 +663,10 @@ mod tests { let runtime = rt_with_issuer(&signer.verifying_key().to_bytes()); let now = 1_000_000_000; let mut payload = fresh_payload(now); - payload.scopes = vec!["fleet.list_agents".into()]; + payload.scopes = vec!["device.agent.list".into()]; let proof = build_proof(&signer, &payload); let m = meta_with(&proof); - // ABILITY is "federation.resolve" — not in scopes. + // ABILITY is "alice.chat" — not in scopes. match runtime.run_delegation_gate(&m, &envelope(), ABILITY, now) { DelegationDecision::Rejected(err) => { assert_eq!(err.code, ERR_DELEGATION_SCOPE_MISMATCH); @@ -681,7 +681,7 @@ mod tests { let runtime = rt_with_issuer(&signer.verifying_key().to_bytes()); let now = 1_000_000_000; let mut payload = fresh_payload(now); - payload.scopes = vec!["federation.*".into()]; + payload.scopes = vec!["alice.*".into()]; let proof = build_proof(&signer, &payload); let m = meta_with(&proof); match runtime.run_delegation_gate(&m, &envelope(), ABILITY, now) { @@ -739,9 +739,9 @@ mod tests { let runtime = rt_with_issuer(&[0u8; 32]); let bad = serde_json::json!({ "payload": { - "issuer_uri": ISSUER_URI, - "subject_uri": SUBJECT_URI, - "caller_uri": CALLER_URI, + "issuer_ura": ISSUER_URI, + "subject_ura": SUBJECT_URI, + "caller_ura": CALLER_URI, "audience": CALLEE_URI, "scopes": [ABILITY], "issued_at_ms": 0, @@ -761,8 +761,8 @@ mod tests { #[test] fn scope_matcher_unit() { assert!(scope_matches("*", "anything")); - assert!(scope_matches("federation.*", "federation.resolve")); - assert!(!scope_matches("federation.*", "fleet.list")); + assert!(scope_matches("alice.*", "alice.chat")); + assert!(!scope_matches("federation.*", "device.agent.list")); assert!(scope_matches("exact.name", "exact.name")); assert!(!scope_matches("exact.name", "exact.name.extra")); assert!(!scope_matches("exact.name", "exact.different")); @@ -781,7 +781,7 @@ mod tests { /// list in the same order; if either side adds a field, the /// other MUST add the same field in the same position OR the /// signature breaks for every legitimate proof in flight. - const INTEROP_FIXTURE_JSON: &str = r#"{"pubkey_hex":"79b5562e8fe654f94078b112e8a98ba7901f853ae695bed7e0e3910bad049664","wire":"{\"payload\":{\"issuer_uri\":\"easynet:///r/acme/agent/01BAK\",\"subject_uri\":\"easynet:///r/acme/agent/01USR-alice\",\"caller_uri\":\"easynet:///r/acme/agent/01BAK\",\"audience\":\"easynet:///r/acme/agent/01HUB\",\"scopes\":[\"federation.resolve\"],\"issued_at_ms\":1700000000000,\"expires_at_ms\":1700000900000},\"signature\":\"9wx8AWUZvuBcUtOtk7Nlr4BzShn7QgeGVUrvtq+fkGzsARNu4/j0GYbGm/WMU7sy/E8h3051de1sO40rJMxZDA==\"}"}"#; + const INTEROP_FIXTURE_JSON: &str = r#"{"pubkey_hex":"79b5562e8fe654f94078b112e8a98ba7901f853ae695bed7e0e3910bad049664","wire":"{\"payload\":{\"issuer_ura\":\"easynet:///r/acme/agent/acme.backend\",\"subject_ura\":\"easynet:///r/acme/agent/alice.subject\",\"caller_ura\":\"easynet:///r/acme/agent/acme.backend\",\"audience\":\"easynet:///r/acme/agent/acme.hub\",\"scopes\":[\"alice.chat\"],\"issued_at_ms\":1700000000000,\"expires_at_ms\":1700000900000},\"signature\":\"VbIenFJstF/sDIsR72crGKUY+hrSPDyLAGMz6sPTfhZlxTNtXAivv9LNV18lzeD+/uNnlAxiflR6wZPt+PQ3CQ==\"}"}"#; #[test] fn cross_language_interop_go_signed_bytes_verify_in_rust() { @@ -801,19 +801,19 @@ mod tests { .state .agents .insert(AgentRecord::new_self_signed_active( - "easynet:///r/acme/agent/01BAK", + "easynet:///r/acme/agent/acme.backend", pubkey, )); // Envelope mirrors what the backend would set on a real - // request to federation.resolve against the realm hub. + // request to alice.chat against the realm hub. let envelope = pb::Envelope { caller: Some(pb::AgentIdentity { - uri: "easynet:///r/acme/agent/01BAK".into(), + ura: "easynet:///r/acme/agent/acme.backend".into(), ..Default::default() }), callee: Some(pb::AgentIdentity { - uri: "easynet:///r/acme/agent/01HUB".into(), + ura: "easynet:///r/acme/agent/acme.hub".into(), ..Default::default() }), ..Default::default() @@ -824,11 +824,11 @@ mod tests { // The Go-side fixture has expires_at_ms = 1700000900000 // (issued + 15min). Verify at 1ms before expiry. let now_ms = 1_700_000_899_999i64; - match runtime.run_delegation_gate(&metadata, &envelope, "federation.resolve", now_ms) { + match runtime.run_delegation_gate(&metadata, &envelope, "alice.chat", now_ms) { DelegationDecision::Verified(d) => { - assert_eq!(d.subject_uri, "easynet:///r/acme/agent/01USR-alice"); - assert_eq!(d.issuer_uri, "easynet:///r/acme/agent/01BAK"); - assert_eq!(d.scopes, vec!["federation.resolve".to_string()]); + assert_eq!(d.subject_ura, "easynet:///r/acme/agent/alice.subject"); + assert_eq!(d.issuer_ura, "easynet:///r/acme/agent/acme.backend"); + assert_eq!(d.scopes, vec!["alice.chat".to_string()]); } other => panic!( "Go-signed proof MUST verify in Rust; canonical bytes drifted? Got {other:?}" diff --git a/core/runtime-rs/src/services/invocation/directory_events.rs b/core/runtime-rs/src/services/invocation/directory_events.rs index 856a37f9..cd0917f4 100644 --- a/core/runtime-rs/src/services/invocation/directory_events.rs +++ b/core/runtime-rs/src/services/invocation/directory_events.rs @@ -71,7 +71,7 @@ pub enum DirectoryEvent { /// (operators care about this for "agent identity churn" /// alerting). AgentAdvertised { - agent_uri: String, + agent_ura: String, signing_authority: SigningAuthorityWire, replaced_prior: bool, unix_ms: i64, @@ -82,7 +82,7 @@ pub enum DirectoryEvent { /// SHOULD `federation.resolve` for the agent rather than /// inflating event payloads. AbilitiesAdvertised { - agent_uri: String, + agent_ura: String, count: usize, unix_ms: i64, }, @@ -92,7 +92,7 @@ pub enum DirectoryEvent { /// agent was already revoked (idempotent re-revoke) or /// unknown to the directory. AgentRevoked { - agent_uri: String, + agent_ura: String, was_active: bool, reason: String, unix_ms: i64, @@ -115,16 +115,16 @@ pub enum DirectoryEvent { #[serde(tag = "kind", rename_all = "snake_case")] pub enum SigningAuthorityWire { SelfSigned, - HostedBy { host_uri: String }, + HostedBy { host_ura: String }, } impl From<&crate::state::SigningAuthority> for SigningAuthorityWire { fn from(src: &crate::state::SigningAuthority) -> Self { match src { crate::state::SigningAuthority::Selfsigned => SigningAuthorityWire::SelfSigned, - crate::state::SigningAuthority::HostedBy { host_uri } => { + crate::state::SigningAuthority::HostedBy { host_ura } => { SigningAuthorityWire::HostedBy { - host_uri: host_uri.clone(), + host_ura: host_ura.clone(), } } } @@ -136,7 +136,7 @@ impl From<&crate::state::SigningAuthority> for SigningAuthorityWire { /// `federation.resolve`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DirectoryAgentSummary { - pub agent_uri: String, + pub agent_ura: String, pub signing_authority: SigningAuthorityWire, /// "active" | "revoked" | "suspended" — matches the string /// `federation.heartbeat` returns so subscribers can reuse one @@ -153,7 +153,7 @@ impl DirectoryAgentSummary { crate::state::AgentStatus::Suspended { .. } => "suspended", }; Self { - agent_uri: rec.uri.clone(), + agent_ura: rec.ura.clone(), signing_authority: SigningAuthorityWire::from(&rec.signing_authority), status: status.to_string(), ability_count: rec.advertised_abilities.len(), @@ -277,7 +277,7 @@ mod tests { #[test] fn agent_advertised_round_trips_with_self_signed_authority() { let evt = DirectoryEvent::AgentAdvertised { - agent_uri: "easynet:///r/test/agent/01HUB".into(), + agent_ura: "easynet:///r/test/agent/01HUB".into(), signing_authority: SigningAuthorityWire::SelfSigned, replaced_prior: false, unix_ms: 1, @@ -296,9 +296,9 @@ mod tests { #[test] fn agent_advertised_round_trips_with_hosted_authority() { let evt = DirectoryEvent::AgentAdvertised { - agent_uri: "easynet:///r/test/agent/01CON".into(), + agent_ura: "easynet:///r/test/agent/01CON".into(), signing_authority: SigningAuthorityWire::HostedBy { - host_uri: "easynet:///r/test/agent/01DEV".into(), + host_ura: "easynet:///r/test/agent/01DEV".into(), }, replaced_prior: true, unix_ms: 1, @@ -307,10 +307,10 @@ mod tests { let parsed: DirectoryEvent = serde_json::from_str(&json).unwrap(); match parsed { DirectoryEvent::AgentAdvertised { - signing_authority: SigningAuthorityWire::HostedBy { host_uri }, + signing_authority: SigningAuthorityWire::HostedBy { host_ura }, replaced_prior: true, .. - } => assert_eq!(host_uri, "easynet:///r/test/agent/01DEV"), + } => assert_eq!(host_ura, "easynet:///r/test/agent/01DEV"), _ => panic!("round-trip must preserve hosted_by variant; got {json}"), } } @@ -318,7 +318,7 @@ mod tests { #[test] fn revoke_event_carries_was_active_flag() { let evt = DirectoryEvent::AgentRevoked { - agent_uri: "easynet:///r/test/agent/01DEV-x".into(), + agent_ura: "easynet:///r/test/agent/01DEV-x".into(), was_active: true, reason: "operator request".into(), unix_ms: 1, diff --git a/core/runtime-rs/src/services/invocation/hub_forward.rs b/core/runtime-rs/src/services/invocation/hub_forward.rs index e68f70dd..269fb3ea 100644 --- a/core/runtime-rs/src/services/invocation/hub_forward.rs +++ b/core/runtime-rs/src/services/invocation/hub_forward.rs @@ -36,8 +36,8 @@ pub(crate) struct ForwardRequest { /// dispatcher MUST forward without decoding caller_signature /// or rebuilding canonical bytes. pub(crate) envelope: pb::Envelope, - /// `target_uri` for the remote `federation.forward_invoke` call. - pub(crate) target_uri: String, + /// `target_ura` for the remote `federation.forward_invoke` call. + pub(crate) target_ura: String, /// Ability name being invoked on the target. pub(crate) ability_name: String, /// Function name on the target ability (rare — defaults to @@ -150,7 +150,7 @@ impl HubForwardDispatcher for InProcessHubForwardDispatcher { // Build the args for the remote forward_invoke. Same shape // as `ForwardInvokeArgs` in hub_profile. let args = serde_json::json!({ - "target_uri": request.target_uri, + "target_ura": request.target_ura, "ability_name": request.ability_name, "function_name": request.function_name, "arguments_b64": request.arguments_b64, @@ -328,7 +328,7 @@ impl HubForwardDispatcher for GrpcHubForwardDispatcher { // in-process path so the remote `hub_forward_invoke` // handler reads them identically. let args = serde_json::json!({ - "target_uri": request.target_uri, + "target_ura": request.target_ura, "ability_name": request.ability_name, "function_name": request.function_name, "arguments_b64": request.arguments_b64, diff --git a/core/runtime-rs/src/services/invocation/hub_profile.rs b/core/runtime-rs/src/services/invocation/hub_profile.rs index f34b6d79..a42c9e31 100644 --- a/core/runtime-rs/src/services/invocation/hub_profile.rs +++ b/core/runtime-rs/src/services/invocation/hub_profile.rs @@ -67,6 +67,11 @@ pub(crate) const HUB_ERR_UNKNOWN_ABILITY: &str = "AXON_HUB_UNKNOWN_ABILITY"; #[derive(Debug, Deserialize)] struct JoinArgs { realm: String, + /// Explicit membership URA for the joining runtime. Devices join + /// with `device/`; agent runtimes may join with + /// `agent/.`. + #[serde(default)] + membership_ura: String, /// Caller's freshly-generated public key (Ed25519). /// We accept hex or base64; tests use hex for readability. #[serde(default)] @@ -85,7 +90,7 @@ struct JoinArgs { /// Wire shape for `federation.join` receipt body (§3 Step D). #[derive(Debug, Serialize)] struct JoinReceiptBody { - canonical_agent_uri: String, + membership_ura: String, realm: String, /// Hash of this receipt envelope serves as the device's /// membership lineage root (§A8 [P3]). We surface it here so @@ -154,7 +159,7 @@ impl Default for AdvertiseContract { #[derive(Debug, Deserialize)] struct AdvertiseAgentArgs { - agent_uri: String, + agent_ura: String, #[serde(default)] public_key_hex: String, #[serde(default)] @@ -173,7 +178,7 @@ enum AdvertisedSigningAuthority { #[default] SelfSigned, HostedBy { - host_uri: String, + host_ura: String, }, } @@ -185,7 +190,7 @@ struct AdvertiseAgentReceiptBody { #[derive(Debug, Deserialize)] struct AdvertiseAbilitiesArgs { - agent_uri: String, + agent_ura: String, /// Opaque ability descriptors (RFC §1.6 shape, but we store /// them as `Value` here so the kernel doesn't pin a single /// schema version). The publisher and consumer must agree on @@ -202,7 +207,7 @@ struct AdvertiseAbilitiesReceiptBody { #[derive(Debug, Deserialize)] struct RevokeArgs { - agent_uri: String, + agent_ura: String, /// Free-form operator-supplied reason. Empty falls back to a /// canonical default so audit logs always have something /// non-empty to render. @@ -252,9 +257,9 @@ struct ResolveArgs { #[derive(Debug, Deserialize, Default)] struct ResolveFilter { - /// Prefix match on agent_uri. `None` means "no filter". + /// Prefix match on agent_ura. `None` means "no filter". #[serde(default)] - agent_uri_prefix: Option, + agent_ura_prefix: Option, /// When true, the resolve receipt embeds each Agent's /// advertised ability descriptors. Off by default to keep /// catalog-listing calls cheap; the Skills page sets it. @@ -274,7 +279,7 @@ struct ResolveFilter { #[derive(Debug, Serialize, Deserialize)] struct ResolvedAgent { - uri: String, + ura: String, /// "active" | "revoked" | "suspended". Owned String (not /// &'static) so the type round-trips through serde for the /// RFC-002.2 fan-out merge path. @@ -530,12 +535,13 @@ impl AxonRuntime { // Reject if this public key is already bound to a different // canonical URA (§3 Step D). The hub never rotates a device's // key; the joining device must regenerate. - if self - .state - .agents - .snapshot() - .iter() - .any(|rec| rec.public_key == public_key) + if !public_key.is_empty() + && self + .state + .agents + .snapshot() + .iter() + .any(|rec| rec.public_key == public_key) { return Err(pb::Error { code: HUB_ERR_PUBKEY_BOUND.into(), @@ -550,24 +556,25 @@ impl AxonRuntime { // error — the membership gate already lets it through under // PRE_MEMBERSHIP_ABILITY, but a clean request shape should // still self-identify as provisional. + let requested_uri = args.membership_ura.trim(); if let Some(caller) = envelope.caller.as_ref() { - if !caller.uri.is_empty() - && !caller - .uri - .starts_with(super::membership_gate::PROVISIONAL_URA_PREFIX) - { + let caller_ura = caller.ura.as_str(); + let caller_is_provisional = + caller_ura.starts_with(super::membership_gate::PROVISIONAL_URA_PREFIX); + let caller_matches_requested = !requested_uri.is_empty() && caller_ura == requested_uri; + if !caller_ura.is_empty() && !caller_is_provisional && !caller_matches_requested { return Err(invalid_args(format!( "federation.join caller must be provisional URA, got {}", - caller.uri + caller_ura ))); } } - let canonical_uri = format!( - "easynet:///r/{realm}/agent/{id}", - realm = args.realm, - id = new_id("a") - ); + let canonical_uri = if requested_uri.is_empty() { + easynet_run_axon_client::ura::agent_ura(&args.realm, "hub", &new_id("a")) + } else { + requested_uri.to_string() + }; let record = AgentRecord::new_self_signed_active(canonical_uri.clone(), public_key.clone()); self.state.agents.insert(record); @@ -579,7 +586,7 @@ impl AxonRuntime { // flow through the heartbeat diff path. let hub_snapshot = self.state.federation.hub_published_abilities.snapshot(); let body = JoinReceiptBody { - canonical_agent_uri: canonical_uri, + membership_ura: canonical_uri, realm: args.realm, join_receipt_hash, hub_published_abilities: hub_snapshot.abilities, @@ -602,25 +609,25 @@ impl AxonRuntime { ) -> Result { let args: AdvertiseAgentArgs = serde_json::from_slice(arguments) .map_err(|e| invalid_args(format!("federation.advertise_agent args parse: {e}")))?; - if args.agent_uri.is_empty() { - return Err(invalid_args("agent_uri required")); + if args.agent_ura.is_empty() { + return Err(invalid_args("agent_ura required")); } // Per §1.4, hosted Agents may only be advertised by their // declared host. Self-signed Agents may advertise themselves. - let caller_uri = envelope + let caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); let signing_authority = match args.signing_authority { AdvertisedSigningAuthority::SelfSigned => { - if caller_uri != args.agent_uri { + if caller_ura != args.agent_ura { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "self-signed Agent {} can only be advertised by itself; caller={}", - args.agent_uri, caller_uri + args.agent_ura, caller_ura ), retryable: false, ..Default::default() @@ -628,19 +635,19 @@ impl AxonRuntime { } SigningAuthority::Selfsigned } - AdvertisedSigningAuthority::HostedBy { host_uri } => { - if caller_uri != host_uri { + AdvertisedSigningAuthority::HostedBy { host_ura } => { + if caller_ura != host_ura { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "hosted Agent {} must be advertised by its host {}; caller={}", - args.agent_uri, host_uri, caller_uri + args.agent_ura, host_ura, caller_ura ), retryable: false, ..Default::default() }); } - SigningAuthority::HostedBy { host_uri } + SigningAuthority::HostedBy { host_ura } } }; @@ -652,12 +659,12 @@ impl AxonRuntime { let prior_abilities = self .state .agents - .lookup(&args.agent_uri) + .lookup(&args.agent_ura) .map(|r| r.advertised_abilities) .unwrap_or_default(); let envelope_tenant = Self::envelope_tenant_id(Some(envelope)); let record = AgentRecord { - uri: args.agent_uri.clone(), + ura: args.agent_ura.clone(), public_key, signing_authority, status: AgentStatus::Active, @@ -666,7 +673,7 @@ impl AxonRuntime { // would sit at None until the next device heartbeat tick. last_heartbeat_unix_ms: Some(self.now_unix_ms()), // RFC-002 forward_invoke routing key. Optional; fall back - // to existing host_uri parsing on miss when forward_invoke + // to existing host_ura parsing on miss when forward_invoke // is invoked. host_node_id: args.host_node_id.clone(), // Tenant ownership for resolve's tenant-scoping. Empty @@ -692,7 +699,7 @@ impl AxonRuntime { // fail with no receivers; that's expected and ignored. let _ = self.state.federation.directory_events_tx.send( super::directory_events::DirectoryEvent::AgentAdvertised { - agent_uri: args.agent_uri.clone(), + agent_ura: args.agent_ura.clone(), signing_authority: event_authority, replaced_prior: prior.is_some(), unix_ms: self.now_unix_ms(), @@ -717,8 +724,8 @@ impl AxonRuntime { /// Authorisation rule (mirrors hub_advertise_agent): /// - When the catalog records the target Agent as Selfsigned, /// the caller MUST be the same URA. - /// - When the catalog records HostedBy(host_uri), the caller - /// MUST equal host_uri. + /// - When the catalog records HostedBy(host_ura), the caller + /// MUST equal host_ura. /// - The target Agent MUST already be registered (a prior /// advertise_agent succeeded). Otherwise we'd accumulate /// ability rows for Agents the directory doesn't know. @@ -729,24 +736,24 @@ impl AxonRuntime { ) -> Result { let args: AdvertiseAbilitiesArgs = serde_json::from_slice(arguments) .map_err(|e| invalid_args(format!("federation.advertise_abilities args parse: {e}")))?; - if args.agent_uri.is_empty() { - return Err(invalid_args("agent_uri required")); + if args.agent_ura.is_empty() { + return Err(invalid_args("agent_ura required")); } - let caller_uri = envelope + let caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); // Target must already be in the catalog. - let target = match self.state.agents.lookup(&args.agent_uri) { + let target = match self.state.agents.lookup(&args.agent_ura) { Some(rec) => rec, None => { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "agent {} not registered; call federation.advertise_agent first", - args.agent_uri + args.agent_ura ), retryable: false, ..Default::default() @@ -757,27 +764,27 @@ impl AxonRuntime { // Caller must own the right to publish for this Agent. match &target.signing_authority { crate::state::SigningAuthority::Selfsigned => { - if caller_uri != args.agent_uri { + if caller_ura != args.agent_ura { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "self-signed Agent {} can only advertise abilities for itself; \ caller={}", - args.agent_uri, caller_uri + args.agent_ura, caller_ura ), retryable: false, ..Default::default() }); } } - crate::state::SigningAuthority::HostedBy { host_uri } => { - if caller_uri != host_uri { + crate::state::SigningAuthority::HostedBy { host_ura } => { + if caller_ura != host_ura { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "hosted Agent {} abilities must be published by host {}; \ caller={}", - args.agent_uri, host_uri, caller_uri + args.agent_ura, host_ura, caller_ura ), retryable: false, ..Default::default() @@ -794,13 +801,13 @@ impl AxonRuntime { if !self .state .agents - .set_advertised_abilities(&args.agent_uri, args.abilities.clone()) + .set_advertised_abilities(&args.agent_ura, args.abilities.clone()) { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "agent {} disappeared from directory mid-advertise", - args.agent_uri + args.agent_ura ), retryable: true, ..Default::default() @@ -810,7 +817,7 @@ impl AxonRuntime { let count = args.abilities.len(); let _ = self.state.federation.directory_events_tx.send( super::directory_events::DirectoryEvent::AbilitiesAdvertised { - agent_uri: args.agent_uri.clone(), + agent_ura: args.agent_ura.clone(), count, unix_ms: self.now_unix_ms(), }, @@ -843,16 +850,16 @@ impl AxonRuntime { ) -> Result { let args: RevokeArgs = serde_json::from_slice(arguments) .map_err(|e| invalid_args(format!("federation.revoke args parse: {e}")))?; - if args.agent_uri.is_empty() { - return Err(invalid_args("agent_uri required")); + if args.agent_ura.is_empty() { + return Err(invalid_args("agent_ura required")); } - let caller_uri = envelope + let caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); - let target = match self.state.agents.lookup(&args.agent_uri) { + let target = match self.state.agents.lookup(&args.agent_ura) { Some(rec) => rec, None => { // Unknown Agent — treat as already-revoked (no-op @@ -873,25 +880,25 @@ impl AxonRuntime { match &target.signing_authority { crate::state::SigningAuthority::Selfsigned => { - if caller_uri != args.agent_uri { + if caller_ura != args.agent_ura { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "self-signed Agent {} can only be revoked by itself; caller={}", - args.agent_uri, caller_uri + args.agent_ura, caller_ura ), retryable: false, ..Default::default() }); } } - crate::state::SigningAuthority::HostedBy { host_uri } => { - if caller_uri != host_uri { + crate::state::SigningAuthority::HostedBy { host_ura } => { + if caller_ura != host_ura { return Err(pb::Error { code: HUB_ERR_NOT_HOST.into(), message: format!( "hosted Agent {} must be revoked by host {}; caller={}", - args.agent_uri, host_uri, caller_uri + args.agent_ura, host_ura, caller_ura ), retryable: false, ..Default::default() @@ -910,10 +917,10 @@ impl AxonRuntime { // unknown — we already looked above, so a false here // signals concurrent-removal which we treat as success // (the postcondition is the same). - let _ = self.state.agents.revoke(&args.agent_uri, reason.clone()); + let _ = self.state.agents.revoke(&args.agent_ura, reason.clone()); let _ = self.state.federation.directory_events_tx.send( super::directory_events::DirectoryEvent::AgentRevoked { - agent_uri: args.agent_uri.clone(), + agent_ura: args.agent_ura.clone(), was_active, reason, unix_ms: self.now_unix_ms(), @@ -946,10 +953,10 @@ impl AxonRuntime { serde_json::from_slice(arguments) .map_err(|e| invalid_args(format!("federation.heartbeat args parse: {e}")))? }; - let caller_uri = envelope + let caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); // Heartbeat is device-scoped: the caller is a device-profile // Agent and one tick refreshes liveness for the device row AND @@ -961,12 +968,12 @@ impl AxonRuntime { let _ = self .state .agents - .refresh_heartbeat_for_device(caller_uri, now_ms); + .refresh_heartbeat_for_device(caller_ura, now_ms); // The membership gate already ran. If we got here the caller // is in the directory or the catalog is empty (P3.2 fallback). // We surface their current status verbatim so the daemon can // act on a `revoked` response. - let status = match self.state.agents.lookup(caller_uri) { + let status = match self.state.agents.lookup(caller_ura) { Some(rec) => match rec.status { AgentStatus::Active => "active", AgentStatus::Revoked { .. } => "revoked", @@ -1004,7 +1011,7 @@ impl AxonRuntime { serde_json::from_slice(arguments) .map_err(|e| invalid_args(format!("federation.resolve args parse: {e}")))? }; - let prefix = args.filter.agent_uri_prefix.unwrap_or_default(); + let prefix = args.filter.agent_ura_prefix.unwrap_or_default(); let include_abilities = args.filter.include_abilities; // Tenant filter resolution rule (RFC-002 §5 update): // * `None` or `Some("")` → auto-fill with caller's tenant. @@ -1052,9 +1059,9 @@ impl AxonRuntime { }; let agents: Vec = candidates .into_iter() - .filter(|rec| prefix.is_empty() || rec.uri.starts_with(&prefix)) + .filter(|rec| prefix.is_empty() || rec.ura.starts_with(&prefix)) .map(|rec| ResolvedAgent { - uri: rec.uri.clone(), + ura: rec.ura.clone(), abilities: if include_abilities { rec.advertised_abilities.clone() } else { @@ -1082,7 +1089,7 @@ impl AxonRuntime { /// shard endpoint in parallel and merges the results before /// returning. Each remote shard's local agents come back in the /// same `ResolvedAgent` shape, so the merge is just a - /// dedup-by-URI concat. + /// dedup-by-URA concat. async fn hub_resolve_async( &self, envelope: &pb::Envelope, @@ -1152,7 +1159,7 @@ impl AxonRuntime { .map(|r| r.agents) .unwrap_or_default(); let mut seen_uris: std::collections::HashSet = - merged.iter().map(|a| a.uri.clone()).collect(); + merged.iter().map(|a| a.ura.clone()).collect(); for task in tasks { let body = match task.await { @@ -1163,7 +1170,7 @@ impl AxonRuntime { // we called federation.resolve, not forward_invoke. if let Ok(remote) = serde_json::from_value::(body) { for ag in remote.agents { - if seen_uris.insert(ag.uri.clone()) { + if seen_uris.insert(ag.ura.clone()) { merged.push(ag); } } @@ -1185,21 +1192,21 @@ impl AxonRuntime { fn hub_resolve_key(&self, arguments: &[u8]) -> Result { let args: ResolveKeyArgs = serde_json::from_slice(arguments) .map_err(|e| invalid_args(format!("federation.resolve_key args parse: {e}")))?; - if args.agent_uri.is_empty() { - return Err(invalid_args("agent_uri required")); + if args.agent_ura.is_empty() { + return Err(invalid_args("agent_ura required")); } let rec = self .state .agents - .lookup(&args.agent_uri) + .lookup(&args.agent_ura) .ok_or_else(|| pb::Error { code: "AXON_AGENT_NOT_IN_DIRECTORY".into(), - message: format!("no directory entry for {}", args.agent_uri), + message: format!("no directory entry for {}", args.agent_ura), retryable: false, ..Default::default() })?; let body = ResolveKeyReceiptBody { - agent_uri: rec.uri.clone(), + agent_ura: rec.ura.clone(), public_key_hex: hex_encode(&rec.public_key), status: match rec.status { AgentStatus::Active => "active", @@ -1283,10 +1290,10 @@ impl AxonRuntime { /// `federation.forward_invoke` (RFC-002 §5.2): hub-side router /// for cross-device + cross-tenant Invokes. The caller submits a - /// `{target_uri, ability_name, function_name, arguments_b64}` + /// `{target_ura, ability_name, function_name, arguments_b64}` /// payload; the hub: /// - /// 1. Looks up `target_uri` in the directory. + /// 1. Looks up `target_ura` in the directory. /// 2. Routes to the host node_id stored on that AgentRecord /// (populated at advertise time). /// 3. Dispatches synchronously to the host's runtime-local-tool @@ -1303,8 +1310,8 @@ impl AxonRuntime { ) -> Result { let args: ForwardInvokeArgs = serde_json::from_slice(arguments) .map_err(|e| invalid_args(format!("federation.forward_invoke args parse: {e}")))?; - if args.target_uri.is_empty() { - return Err(invalid_args("target_uri required")); + if args.target_ura.is_empty() { + return Err(invalid_args("target_ura required")); } if args.ability_name.is_empty() { return Err(invalid_args("ability_name required")); @@ -1318,7 +1325,7 @@ impl AxonRuntime { // produced. The signed envelope is forwarded byte-for-byte — // RFC-001 INV-2 (caller-signed bytes integrity) holds across // arbitrary hop counts. - let target = match self.state.agents.lookup(&args.target_uri) { + let target = match self.state.agents.lookup(&args.target_ura) { Some(t) => t, None => { if let Some(remote_outcome) = self.try_cross_shard_forward(envelope, &args).await { @@ -1326,7 +1333,7 @@ impl AxonRuntime { } return Err(pb::Error { code: "AXON_TARGET_NOT_IN_DIRECTORY".into(), - message: format!("no directory entry for target {}", args.target_uri), + message: format!("no directory entry for target {}", args.target_ura), retryable: false, ..Default::default() }); @@ -1337,7 +1344,7 @@ impl AxonRuntime { message: format!( "target {} is in directory but advertised no host_node_id; \ advertiser must re-advertise with RFC-002 host_node_id field", - args.target_uri + args.target_ura ), retryable: false, ..Default::default() @@ -1361,12 +1368,12 @@ impl AxonRuntime { args.function_name.clone() }; - // Caller URI (carried by envelope) is also informational here; + // Caller URA (carried by envelope) is also informational here; // the target's local handler decides permission. - let _caller_uri = envelope + let _caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); let target_tenant = match find_local_tool_tenant( @@ -1380,7 +1387,7 @@ impl AxonRuntime { code: "AXON_TARGET_ABILITY_NOT_REGISTERED".into(), message: format!( "target {} (node {}) has no local-tool registration for {}", - args.target_uri, host_node_id, args.ability_name + args.target_ura, host_node_id, args.ability_name ), retryable: false, ..Default::default() @@ -1446,8 +1453,8 @@ impl AxonRuntime { args: &ForwardInvokeArgs, ) -> Option> { let lrt = self.shard_resolver()?; - let realm = crate::services::invocation::shard_resolver::parse_realm_from_target_uri( - &args.target_uri, + let realm = crate::services::invocation::shard_resolver::parse_realm_from_target_ura( + &args.target_ura, )?; let location = match lrt.resolve(&realm) { Ok(loc) => loc, @@ -1486,7 +1493,7 @@ impl AxonRuntime { let req = crate::services::invocation::hub_forward::ForwardRequest { endpoint: endpoint.clone(), envelope: envelope.clone(), - target_uri: args.target_uri.clone(), + target_ura: args.target_ura.clone(), ability_name: args.ability_name.clone(), function_name: args.function_name.clone(), arguments_b64: args.arguments_b64.clone(), @@ -1528,12 +1535,12 @@ impl AxonRuntime { #[derive(Debug, Deserialize)] struct ResolveKeyArgs { - agent_uri: String, + agent_ura: String, } #[derive(Debug, Serialize)] struct ResolveKeyReceiptBody { - agent_uri: String, + agent_ura: String, public_key_hex: String, status: &'static str, key_id: String, @@ -1566,7 +1573,7 @@ struct ResolveShardReceiptBody { #[derive(Debug, Deserialize)] struct ForwardInvokeArgs { - target_uri: String, + target_ura: String, ability_name: String, #[serde(default)] function_name: String, @@ -1644,10 +1651,10 @@ fn decode_pubkey_hex(hex: &str) -> Result, pb::Error> { bytes.map_err(|e| invalid_args(format!("public_key_hex decode: {e}"))) } -fn compute_join_receipt_hash(uri: &str, public_key: &[u8]) -> String { +fn compute_join_receipt_hash(ura: &str, public_key: &[u8]) -> String { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); - hasher.update(uri.as_bytes()); + hasher.update(ura.as_bytes()); hasher.update(public_key); let digest = hasher.finalize(); hex::encode(digest) @@ -1656,6 +1663,7 @@ fn compute_join_receipt_hash(uri: &str, public_key: &[u8]) -> String { #[cfg(test)] mod tests { use super::*; + use crate::services::invocation::membership_gate::MembershipDecision; use crate::state::{AxonState, RuntimeConfig}; use std::sync::Arc; @@ -1666,17 +1674,17 @@ mod tests { fn provisional_envelope(fp: &str) -> pb::Envelope { pb::Envelope { caller: Some(pb::AgentIdentity { - uri: format!("provisional:{fp}"), + ura: format!("provisional:{fp}"), ..Default::default() }), ..Default::default() } } - fn canonical_envelope(uri: &str) -> pb::Envelope { + fn canonical_envelope(ura: &str) -> pb::Envelope { pb::Envelope { caller: Some(pb::AgentIdentity { - uri: uri.into(), + ura: ura.into(), ..Default::default() }), ..Default::default() @@ -1687,7 +1695,7 @@ mod tests { fn is_hub_ability_matches_federation_namespace() { assert!(AxonRuntime::is_hub_ability("federation.join")); assert!(AxonRuntime::is_hub_ability("federation.resolve")); - assert!(!AxonRuntime::is_hub_ability("fleet.list_agents")); + assert!(!AxonRuntime::is_hub_ability("device.agent.list")); assert!(!AxonRuntime::is_hub_ability("federationxjoin")); } @@ -1704,16 +1712,42 @@ mod tests { .dispatch_hub_ability(&env, "federation.join", args.as_bytes()) .expect("join must succeed"); let body: serde_json::Value = serde_json::from_str(&outcome.body_json).unwrap(); - let uri = body["canonical_agent_uri"].as_str().unwrap(); - assert!(uri.starts_with("easynet:///r/acme/agent/")); + let ura = body["membership_ura"].as_str().unwrap(); + assert!(ura.starts_with("easynet:///r/acme/agent/hub.a-")); assert!(!body["join_receipt_hash"].as_str().unwrap().is_empty()); // Catalog now has exactly one Active record. assert_eq!(runtime.state.agents.len(), 1); - let rec = runtime.state.agents.lookup(uri).unwrap(); + let rec = runtime.state.agents.lookup(ura).unwrap(); assert_eq!(rec.status, AgentStatus::Active); assert_eq!(rec.public_key, vec![1, 2, 3, 4, 5]); } + #[test] + fn join_accepts_explicit_canonical_device_uri_for_session_membership() { + let runtime = rt(); + let ura = "easynet:///r/acme/device/dev-1"; + let env = canonical_envelope(ura); + let args = serde_json::json!({ + "realm": "acme", + "membership_ura": ura, + "public_key_hex": "010203", + }) + .to_string(); + + let outcome = runtime + .dispatch_hub_ability(&env, "federation.join", args.as_bytes()) + .expect("device-session join must register explicit URA"); + let body: serde_json::Value = serde_json::from_str(&outcome.body_json).unwrap(); + assert_eq!(body["membership_ura"], ura); + + let rec = runtime.state.agents.lookup(ura).unwrap(); + assert_eq!(rec.status, AgentStatus::Active); + assert_eq!( + runtime.run_membership_gate(&canonical_envelope(ura), ".session"), + MembershipDecision::Allowed + ); + } + #[test] fn join_rejects_canonical_caller() { let runtime = rt(); @@ -1817,7 +1851,7 @@ mod tests { // Caller advertises itself: ok. let env = canonical_envelope("easynet:///r/acme/agent/01DEV"); let args = serde_json::json!({ - "agent_uri": "easynet:///r/acme/agent/01DEV", + "agent_ura": "easynet:///r/acme/agent/01DEV", "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -1828,7 +1862,7 @@ mod tests { // Caller advertises someone else as self-signed: rejected. let bad_args = serde_json::json!({ - "agent_uri": "easynet:///r/acme/agent/01OTHER", + "agent_ura": "easynet:///r/acme/agent/01OTHER", "public_key_hex": "bb", "signing_authority": {"kind": "self_signed"}, }) @@ -1846,9 +1880,9 @@ mod tests { // Correct host advertises hosted Agent: ok. let env = canonical_envelope(host); let args = serde_json::json!({ - "agent_uri": "easynet:///r/acme/agent/01LLM", + "agent_ura": "easynet:///r/acme/agent/01LLM", "public_key_hex": "", - "signing_authority": {"kind": "hosted_by", "host_uri": host}, + "signing_authority": {"kind": "hosted_by", "host_ura": host}, }) .to_string(); let outcome = runtime @@ -1861,9 +1895,9 @@ mod tests { // Wrong caller advertising same hosted Agent: rejected. let other_env = canonical_envelope("easynet:///r/acme/agent/01ATTACKER"); let bad_args = serde_json::json!({ - "agent_uri": "easynet:///r/acme/agent/01LLM2", + "agent_ura": "easynet:///r/acme/agent/01LLM2", "public_key_hex": "", - "signing_authority": {"kind": "hosted_by", "host_uri": host}, + "signing_authority": {"kind": "hosted_by", "host_ura": host}, }) .to_string(); let err = runtime @@ -1881,7 +1915,7 @@ mod tests { let runtime = rt(); let env = canonical_envelope("easynet:///r/acme/agent/01DEV"); let args = serde_json::json!({ - "agent_uri": "easynet:///r/acme/agent/01DEV", + "agent_ura": "easynet:///r/acme/agent/01DEV", "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2092,7 +2126,7 @@ mod tests { } #[test] - fn resolve_applies_uri_prefix_filter() { + fn resolve_applies_ura_prefix_filter() { let runtime = rt(); runtime .state @@ -2103,14 +2137,14 @@ mod tests { .agents .insert(AgentRecord::new_self_signed_active("b/2", vec![])); let env = canonical_envelope("a/1"); - let args = r#"{"filter":{"agent_uri_prefix":"a/"}}"#; + let args = r#"{"filter":{"agent_ura_prefix":"a/"}}"#; let outcome = runtime .dispatch_hub_ability(&env, "federation.resolve", args.as_bytes()) .unwrap(); let body: serde_json::Value = serde_json::from_str(&outcome.body_json).unwrap(); let agents = body["agents"].as_array().unwrap(); assert_eq!(agents.len(), 1); - assert_eq!(agents[0]["uri"], "a/1"); + assert_eq!(agents[0]["ura"], "a/1"); } #[test] @@ -2129,10 +2163,10 @@ mod tests { fn advertise_abilities_self_signed_round_trip_persists_descriptors() { let runtime = rt(); // Step 1: register the Agent. - let agent_uri = "easynet:///r/acme/agent/01HUB"; - let env = canonical_envelope(agent_uri); + let agent_ura = "easynet:///r/acme/agent/01HUB"; + let env = canonical_envelope(agent_ura); let agent_args = serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2143,9 +2177,9 @@ mod tests { // Step 2: advertise abilities. let abilities_args = serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "abilities": [ - {"name": "fleet.list_agents", "visibility": "SCOPED"}, + {"name": "device.agent.list", "visibility": "SCOPED"}, {"name": "observe.health", "visibility": "PUBLIC"}, ], }) @@ -2162,9 +2196,9 @@ mod tests { assert_eq!(body["count"], 2); // Catalog now carries the descriptors. - let stored = runtime.state.agents.abilities_for(agent_uri); + let stored = runtime.state.agents.abilities_for(agent_ura); assert_eq!(stored.len(), 2); - assert_eq!(stored[0]["name"], "fleet.list_agents"); + assert_eq!(stored[0]["name"], "device.agent.list"); } #[test] @@ -2172,7 +2206,7 @@ mod tests { let runtime = rt(); let env = canonical_envelope("easynet:///r/acme/agent/01STRANGER"); let args = serde_json::json!({ - "agent_uri": "easynet:///r/acme/agent/01STRANGER", + "agent_ura": "easynet:///r/acme/agent/01STRANGER", "abilities": [], }) .to_string(); @@ -2186,14 +2220,14 @@ mod tests { #[test] fn advertise_abilities_rejects_caller_not_self_signed_agent() { let runtime = rt(); - let agent_uri = "easynet:///r/acme/agent/01HUB"; - let env_self = canonical_envelope(agent_uri); + let agent_ura = "easynet:///r/acme/agent/01HUB"; + let env_self = canonical_envelope(agent_ura); runtime .dispatch_hub_ability( &env_self, "federation.advertise_agent", serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2206,7 +2240,7 @@ mod tests { // self-signed Agent — must be rejected. let env_attacker = canonical_envelope("easynet:///r/acme/agent/01ATTACKER"); let args = serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "abilities": [{"name": "rogue.ability"}], }) .to_string(); @@ -2224,16 +2258,16 @@ mod tests { fn advertise_abilities_rejects_caller_not_host_for_hosted_agent() { let runtime = rt(); // Set up a hosted Agent. - let host_uri = "easynet:///r/acme/agent/01DEV"; + let host_ura = "easynet:///r/acme/agent/01DEV"; let hosted_uri = "easynet:///r/acme/agent/01LLM"; runtime .dispatch_hub_ability( - &canonical_envelope(host_uri), + &canonical_envelope(host_ura), "federation.advertise_agent", serde_json::json!({ - "agent_uri": hosted_uri, + "agent_ura": hosted_uri, "public_key_hex": "", - "signing_authority": {"kind": "hosted_by", "host_uri": host_uri}, + "signing_authority": {"kind": "hosted_by", "host_ura": host_ura}, }) .to_string() .as_bytes(), @@ -2244,7 +2278,7 @@ mod tests { // hosted Agent — must be rejected. let env_other = canonical_envelope("easynet:///r/acme/agent/01OTHER"); let args = serde_json::json!({ - "agent_uri": hosted_uri, + "agent_ura": hosted_uri, "abilities": [{"name": "x.y"}], }) .to_string(); @@ -2258,7 +2292,7 @@ mod tests { assert_eq!(err.code, HUB_ERR_NOT_HOST); // Correct host CAN publish. - let env_host = canonical_envelope(host_uri); + let env_host = canonical_envelope(host_ura); let outcome = runtime .dispatch_hub_ability(&env_host, "federation.advertise_abilities", args.as_bytes()) .expect("host must be allowed to advertise hosted Agent's abilities"); @@ -2269,8 +2303,8 @@ mod tests { #[test] fn re_advertise_agent_preserves_previously_published_abilities() { let runtime = rt(); - let uri = "easynet:///r/acme/agent/01HUB"; - let env = canonical_envelope(uri); + let ura = "easynet:///r/acme/agent/01HUB"; + let env = canonical_envelope(ura); // First advertise: register + abilities. runtime @@ -2278,7 +2312,7 @@ mod tests { &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2291,8 +2325,8 @@ mod tests { &env, "federation.advertise_abilities", serde_json::json!({ - "agent_uri": uri, - "abilities": [{"name": "fleet.list_agents"}], + "agent_ura": ura, + "abilities": [{"name": "device.agent.list"}], }) .to_string() .as_bytes(), @@ -2308,7 +2342,7 @@ mod tests { &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2317,26 +2351,26 @@ mod tests { ) .unwrap(); - let stored = runtime.state.agents.abilities_for(uri); + let stored = runtime.state.agents.abilities_for(ura); assert_eq!( stored.len(), 1, "re-advertise_agent must preserve the descriptor list" ); - assert_eq!(stored[0]["name"], "fleet.list_agents"); + assert_eq!(stored[0]["name"], "device.agent.list"); } #[test] fn resolve_with_include_abilities_returns_full_descriptors() { let runtime = rt(); - let uri = "easynet:///r/acme/agent/01HUB"; - let env = canonical_envelope(uri); + let ura = "easynet:///r/acme/agent/01HUB"; + let env = canonical_envelope(ura); runtime .dispatch_hub_ability( &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2349,7 +2383,7 @@ mod tests { &env, "federation.advertise_abilities", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "abilities": [ {"name": "skill.alive-video", "visibility": "PRIVATE"}, ], @@ -2384,14 +2418,14 @@ mod tests { #[test] fn advertise_abilities_replaces_full_list_on_re_advertise() { let runtime = rt(); - let uri = "easynet:///r/acme/agent/01HUB"; - let env = canonical_envelope(uri); + let ura = "easynet:///r/acme/agent/01HUB"; + let env = canonical_envelope(ura); runtime .dispatch_hub_ability( &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2403,7 +2437,7 @@ mod tests { .dispatch_hub_ability( &env, "federation.advertise_abilities", - serde_json::json!({"agent_uri": uri, "abilities": [{"name":"a"}]}) + serde_json::json!({"agent_ura": ura, "abilities": [{"name":"a"}]}) .to_string() .as_bytes(), ) @@ -2412,12 +2446,12 @@ mod tests { .dispatch_hub_ability( &env, "federation.advertise_abilities", - serde_json::json!({"agent_uri": uri, "abilities": [{"name":"b"},{"name":"c"}]}) + serde_json::json!({"agent_ura": ura, "abilities": [{"name":"b"},{"name":"c"}]}) .to_string() .as_bytes(), ) .unwrap(); - let stored = runtime.state.agents.abilities_for(uri); + let stored = runtime.state.agents.abilities_for(ura); assert_eq!(stored.len(), 2); assert_eq!(stored[0]["name"], "b"); } @@ -2428,14 +2462,14 @@ mod tests { fn revoke_self_signed_marks_agent_revoked() { use crate::state::AgentStatus; let runtime = rt(); - let uri = "easynet:///r/acme/agent/01HUB"; - let env = canonical_envelope(uri); + let ura = "easynet:///r/acme/agent/01HUB"; + let env = canonical_envelope(ura); runtime .dispatch_hub_ability( &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2448,7 +2482,7 @@ mod tests { &env, "federation.revoke", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "reason": "key compromise", }) .to_string() @@ -2458,7 +2492,7 @@ mod tests { let body: serde_json::Value = serde_json::from_str(&outcome.body_json).unwrap(); assert_eq!(body["ack"], serde_json::Value::Bool(true)); assert_eq!(body["was_active"], serde_json::Value::Bool(true)); - let rec = runtime.state.agents.lookup(uri).unwrap(); + let rec = runtime.state.agents.lookup(ura).unwrap(); match rec.status { AgentStatus::Revoked { reason } => assert_eq!(reason, "key compromise"), other => panic!("expected Revoked, got {other:?}"), @@ -2468,14 +2502,14 @@ mod tests { #[test] fn revoke_idempotent_on_already_revoked_agent() { let runtime = rt(); - let uri = "easynet:///r/acme/agent/01HUB"; - let env = canonical_envelope(uri); + let ura = "easynet:///r/acme/agent/01HUB"; + let env = canonical_envelope(ura); runtime .dispatch_hub_ability( &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2483,7 +2517,7 @@ mod tests { .as_bytes(), ) .unwrap(); - let args = serde_json::json!({"agent_uri": uri}).to_string(); + let args = serde_json::json!({"agent_ura": ura}).to_string(); runtime .dispatch_hub_ability(&env, "federation.revoke", args.as_bytes()) .unwrap(); @@ -2504,7 +2538,7 @@ mod tests { let runtime = rt(); let env = canonical_envelope("easynet:///r/acme/agent/01CALLER"); let args = serde_json::json!({ - "agent_uri": "easynet:///r/acme/agent/01PHANTOM", + "agent_ura": "easynet:///r/acme/agent/01PHANTOM", }) .to_string(); let outcome = runtime @@ -2518,13 +2552,13 @@ mod tests { #[test] fn revoke_self_signed_rejects_other_caller() { let runtime = rt(); - let uri = "easynet:///r/acme/agent/01HUB"; + let ura = "easynet:///r/acme/agent/01HUB"; runtime .dispatch_hub_ability( - &canonical_envelope(uri), + &canonical_envelope(ura), "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2538,7 +2572,7 @@ mod tests { .dispatch_hub_ability( &attacker, "federation.revoke", - serde_json::json!({"agent_uri": uri}).to_string().as_bytes(), + serde_json::json!({"agent_ura": ura}).to_string().as_bytes(), ) .unwrap_err(); assert_eq!(err.code, HUB_ERR_NOT_HOST); @@ -2554,9 +2588,9 @@ mod tests { &canonical_envelope(host), "federation.advertise_agent", serde_json::json!({ - "agent_uri": hosted, + "agent_ura": hosted, "public_key_hex": "", - "signing_authority": {"kind": "hosted_by", "host_uri": host}, + "signing_authority": {"kind": "hosted_by", "host_ura": host}, }) .to_string() .as_bytes(), @@ -2569,7 +2603,7 @@ mod tests { .dispatch_hub_ability( &other, "federation.revoke", - serde_json::json!({"agent_uri": hosted}) + serde_json::json!({"agent_ura": hosted}) .to_string() .as_bytes(), ) @@ -2581,7 +2615,7 @@ mod tests { .dispatch_hub_ability( &canonical_envelope(host), "federation.revoke", - serde_json::json!({"agent_uri": hosted}) + serde_json::json!({"agent_ura": hosted}) .to_string() .as_bytes(), ) @@ -2594,14 +2628,14 @@ mod tests { fn revoke_default_reason_when_caller_omits_field() { use crate::state::AgentStatus; let runtime = rt(); - let uri = "easynet:///r/acme/agent/01HUB"; - let env = canonical_envelope(uri); + let ura = "easynet:///r/acme/agent/01HUB"; + let env = canonical_envelope(ura); runtime .dispatch_hub_ability( &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": uri, + "agent_ura": ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -2613,10 +2647,10 @@ mod tests { .dispatch_hub_ability( &env, "federation.revoke", - serde_json::json!({"agent_uri": uri}).to_string().as_bytes(), + serde_json::json!({"agent_ura": ura}).to_string().as_bytes(), ) .unwrap(); - let rec = runtime.state.agents.lookup(uri).unwrap(); + let rec = runtime.state.agents.lookup(ura).unwrap(); match rec.status { AgentStatus::Revoked { reason } => assert!(!reason.is_empty()), other => panic!("expected Revoked, got {other:?}"), @@ -2624,14 +2658,14 @@ mod tests { } #[test] - fn revoke_rejects_empty_agent_uri() { + fn revoke_rejects_empty_agent_ura() { let runtime = rt(); let env = canonical_envelope("easynet:///r/acme/agent/01CALLER"); let err = runtime .dispatch_hub_ability( &env, "federation.revoke", - serde_json::json!({"agent_uri": ""}).to_string().as_bytes(), + serde_json::json!({"agent_ura": ""}).to_string().as_bytes(), ) .unwrap_err(); assert_eq!(err.code, HUB_ERR_INVALID_ARGS); @@ -2645,7 +2679,7 @@ mod tests { "federation.subscribe_directory" )); assert!(!AxonRuntime::is_hub_streaming_ability("federation.resolve")); - assert!(!AxonRuntime::is_hub_streaming_ability("fleet.list_agents")); + assert!(!AxonRuntime::is_hub_streaming_ability("device.agent.list")); } #[test] @@ -2660,10 +2694,10 @@ mod tests { let mut sub = runtime.state.federation.directory_events_tx.subscribe(); // Genesis-style advertise: caller URA == agent URA so the // self-signed authority check passes. - let agent_uri = "easynet:///r/acme/agent/01CALLER"; - let env = canonical_envelope(agent_uri); + let agent_ura = "easynet:///r/acme/agent/01CALLER"; + let env = canonical_envelope(agent_ura); let args = serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "public_key_hex": "01", "signing_authority": { "kind": "self_signed" }, }) @@ -2674,11 +2708,11 @@ mod tests { let evt = sub.recv().await.expect("subscriber sees the event"); match evt { super::super::directory_events::DirectoryEvent::AgentAdvertised { - agent_uri: emitted_uri, + agent_ura: emitted_uri, replaced_prior, .. } => { - assert_eq!(emitted_uri, agent_uri); + assert_eq!(emitted_uri, agent_ura); assert!( !replaced_prior, "first advertise must NOT report replacement" @@ -2691,10 +2725,10 @@ mod tests { #[tokio::test] async fn revoke_publishes_event_with_was_active_true() { let runtime = rt(); - let agent_uri = "easynet:///r/acme/agent/01CALLER"; - let env = canonical_envelope(agent_uri); + let agent_ura = "easynet:///r/acme/agent/01CALLER"; + let env = canonical_envelope(agent_ura); let advertise_args = serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "public_key_hex": "01", "signing_authority": { "kind": "self_signed" }, }) @@ -2712,7 +2746,7 @@ mod tests { // subscription). let mut sub = runtime.state.federation.directory_events_tx.subscribe(); let revoke_args = serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "reason": "test cleanup", }) .to_string(); @@ -2740,14 +2774,14 @@ mod tests { async fn pump_subscriber_emits_snapshot_first_then_event() { let runtime = rt(); // Pre-populate one agent so the snapshot has something. - let agent_uri = "easynet:///r/acme/agent/01CALLER"; - let env = canonical_envelope(agent_uri); + let agent_ura = "easynet:///r/acme/agent/01CALLER"; + let env = canonical_envelope(agent_ura); runtime .dispatch_hub_ability( &env, "federation.advertise_agent", serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "public_key_hex": "01", "signing_authority": { "kind": "self_signed" }, }) @@ -2772,7 +2806,7 @@ mod tests { match first { super::super::directory_events::DirectoryEvent::Snapshot { agents, .. } => { assert_eq!(agents.len(), 1); - assert_eq!(agents[0].agent_uri, agent_uri); + assert_eq!(agents[0].agent_ura, agent_ura); } other => panic!("first frame must be Snapshot, got {other:?}"), } @@ -2784,7 +2818,7 @@ mod tests { &canonical_envelope(other_uri), "federation.advertise_agent", serde_json::json!({ - "agent_uri": other_uri, + "agent_ura": other_uri, "public_key_hex": "02", "signing_authority": { "kind": "self_signed" }, }) @@ -2796,7 +2830,7 @@ mod tests { let second = chunk_rx.recv().await.expect("event frame"); match second { super::super::directory_events::DirectoryEvent::AgentAdvertised { - agent_uri: emitted, + agent_ura: emitted, .. } => assert_eq!(emitted, other_uri), other => panic!("expected AgentAdvertised, got {other:?}"), diff --git a/core/runtime-rs/src/services/invocation/idempotency.rs b/core/runtime-rs/src/services/invocation/idempotency.rs index 99c418f6..7b3ab51b 100644 --- a/core/runtime-rs/src/services/invocation/idempotency.rs +++ b/core/runtime-rs/src/services/invocation/idempotency.rs @@ -202,7 +202,7 @@ impl AxonRuntime { "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", content.content_type, content.encoding, - content.schema_uri, + content.schema_ura, content.encryption, content.key_id, meta.width, @@ -221,7 +221,7 @@ impl AxonRuntime { }; format!( "{}|{}|{}|{}|{}|{}", - payload_ref.uri, + payload_ref.ura, payload_ref.digest, payload_ref.size_bytes, payload_ref.expires_at_unix_ms, diff --git a/core/runtime-rs/src/services/invocation/membership_gate.rs b/core/runtime-rs/src/services/invocation/membership_gate.rs index 2a334999..af6e2e65 100644 --- a/core/runtime-rs/src/services/invocation/membership_gate.rs +++ b/core/runtime-rs/src/services/invocation/membership_gate.rs @@ -47,9 +47,9 @@ pub(crate) enum MembershipDecision { /// federation.join exception). Proceed. Allowed, /// Caller is unknown / not yet a member. - NotMember { caller_uri: String }, + NotMember { caller_ura: String }, /// Caller exists but has been revoked. - Revoked { caller_uri: String, reason: String }, + Revoked { caller_ura: String, reason: String }, } impl MembershipDecision { @@ -58,18 +58,18 @@ impl MembershipDecision { pub(crate) fn into_pb_error(self) -> Option { match self { MembershipDecision::Allowed => None, - MembershipDecision::NotMember { caller_uri } => Some(pb::Error { + MembershipDecision::NotMember { caller_ura } => Some(pb::Error { code: ERR_MEMBERSHIP_REQUIRED.into(), message: format!( - "caller {caller_uri} is not a member of this realm; \ + "caller {caller_ura} is not a member of this realm; \ use federation.join to acquire membership before invoking" ), retryable: false, ..Default::default() }), - MembershipDecision::Revoked { caller_uri, reason } => Some(pb::Error { + MembershipDecision::Revoked { caller_ura, reason } => Some(pb::Error { code: ERR_MEMBERSHIP_REVOKED.into(), - message: format!("caller {caller_uri} membership revoked: {reason}"), + message: format!("caller {caller_ura} membership revoked: {reason}"), retryable: false, ..Default::default() }), @@ -136,38 +136,38 @@ impl AxonRuntime { // already passed the Base layer (signature verification), so // an absent caller is a programming error — we treat it as // NotMember rather than panicking. - let caller_uri = envelope + let caller_ura = envelope .caller .as_ref() - .map(|c| c.uri.as_str()) + .map(|c| c.ura.as_str()) .unwrap_or(""); - if caller_uri.is_empty() { + if caller_ura.is_empty() { return MembershipDecision::NotMember { - caller_uri: String::from(""), + caller_ura: String::from(""), }; } // Provisional URAs MUST NOT pass membership for any ability // other than federation.join (handled above). This is the // teeth of §A5: pre-membership identity is single-use. - if caller_uri.starts_with(PROVISIONAL_URA_PREFIX) { + if caller_ura.starts_with(PROVISIONAL_URA_PREFIX) { return MembershipDecision::NotMember { - caller_uri: caller_uri.into(), + caller_ura: caller_ura.into(), }; } // Realm directory lookup. The agents catalog // (state.topology.agents — landed in P3.2) is the // authoritative membership source. - match self.lookup_agent_membership(caller_uri) { + match self.lookup_agent_membership(caller_ura) { AgentMembership::Active => MembershipDecision::Allowed, AgentMembership::Revoked { reason } => MembershipDecision::Revoked { - caller_uri: caller_uri.into(), + caller_ura: caller_ura.into(), reason, }, AgentMembership::Unknown => MembershipDecision::NotMember { - caller_uri: caller_uri.into(), + caller_ura: caller_ura.into(), }, } } @@ -195,14 +195,14 @@ impl AxonRuntime { /// states without any joined agents continue to function. This /// fallback is removed in P3.3 once the hub-profile populates /// itself + the device-profile at startup. - pub(crate) fn lookup_agent_membership(&self, caller_uri: &str) -> AgentMembership { + pub(crate) fn lookup_agent_membership(&self, caller_ura: &str) -> AgentMembership { // Empty-catalog fallback. After P3.3 every running daemon // will have at least its own device-profile in the catalog, // and this branch becomes effectively dead. if self.state.agents.len() == 0 { return AgentMembership::Active; } - match self.state.agents.lookup(caller_uri) { + match self.state.agents.lookup(caller_ura) { None => AgentMembership::Unknown, Some(record) => match record.status { crate::state::AgentStatus::Active => AgentMembership::Active, @@ -259,10 +259,10 @@ mod tests { AxonRuntime::new(Arc::new(AxonState::new(RuntimeConfig::default()))) } - fn envelope_with_caller(uri: &str) -> pb::Envelope { + fn envelope_with_caller(ura: &str) -> pb::Envelope { pb::Envelope { caller: Some(pb::AgentIdentity { - uri: uri.to_string(), + ura: ura.to_string(), ..Default::default() }), ..Default::default() @@ -287,9 +287,9 @@ mod tests { // anything other than the genesis exception. let runtime = rt(); let env = envelope_with_caller("provisional:abc123"); - match runtime.run_membership_gate(&env, "fleet.list_agents") { - MembershipDecision::NotMember { caller_uri } => { - assert_eq!(caller_uri, "provisional:abc123"); + match runtime.run_membership_gate(&env, "device.agent.list") { + MembershipDecision::NotMember { caller_ura } => { + assert_eq!(caller_ura, "provisional:abc123"); } other => panic!("expected NotMember, got {other:?}"), } @@ -299,9 +299,9 @@ mod tests { fn missing_caller_rejected() { let runtime = rt(); let env = pb::Envelope::default(); - match runtime.run_membership_gate(&env, "fleet.list_agents") { - MembershipDecision::NotMember { caller_uri } => { - assert_eq!(caller_uri, ""); + match runtime.run_membership_gate(&env, "device.agent.list") { + MembershipDecision::NotMember { caller_ura } => { + assert_eq!(caller_ura, ""); } other => panic!("expected NotMember, got {other:?}"), } @@ -316,7 +316,7 @@ mod tests { let runtime = rt(); let env = envelope_with_caller("easynet:///r/acme/agent/01DEV-ulid"); assert_eq!( - runtime.run_membership_gate(&env, "fleet.list_agents"), + runtime.run_membership_gate(&env, "device.agent.list"), MembershipDecision::Allowed, ); } @@ -333,7 +333,7 @@ mod tests { )); let env = envelope_with_caller("easynet:///r/acme/agent/01DEV"); assert_eq!( - runtime.run_membership_gate(&env, "fleet.list_agents"), + runtime.run_membership_gate(&env, "device.agent.list"), MembershipDecision::Allowed, ); } @@ -351,9 +351,9 @@ mod tests { vec![], )); let env = envelope_with_caller("easynet:///r/acme/agent/01STRANGER"); - match runtime.run_membership_gate(&env, "fleet.list_agents") { - MembershipDecision::NotMember { caller_uri } => { - assert_eq!(caller_uri, "easynet:///r/acme/agent/01STRANGER"); + match runtime.run_membership_gate(&env, "device.agent.list") { + MembershipDecision::NotMember { caller_ura } => { + assert_eq!(caller_ura, "easynet:///r/acme/agent/01STRANGER"); } other => panic!("expected NotMember, got {other:?}"), } @@ -374,9 +374,9 @@ mod tests { .agents .revoke("easynet:///r/acme/agent/01DEV", "key compromise"); let env = envelope_with_caller("easynet:///r/acme/agent/01DEV"); - match runtime.run_membership_gate(&env, "fleet.list_agents") { - MembershipDecision::Revoked { caller_uri, reason } => { - assert_eq!(caller_uri, "easynet:///r/acme/agent/01DEV"); + match runtime.run_membership_gate(&env, "device.agent.list") { + MembershipDecision::Revoked { caller_ura, reason } => { + assert_eq!(caller_ura, "easynet:///r/acme/agent/01DEV"); assert_eq!(reason, "key compromise"); } other => panic!("expected Revoked, got {other:?}"), @@ -386,7 +386,7 @@ mod tests { #[test] fn not_member_decision_maps_to_canonical_error_code() { let decision = MembershipDecision::NotMember { - caller_uri: "provisional:xyz".into(), + caller_ura: "provisional:xyz".into(), }; let err = decision.into_pb_error().expect("error expected"); assert_eq!(err.code, ERR_MEMBERSHIP_REQUIRED); @@ -398,7 +398,7 @@ mod tests { #[test] fn revoked_decision_maps_to_canonical_error_code() { let decision = MembershipDecision::Revoked { - caller_uri: "easynet:///r/acme/agent/01X".into(), + caller_ura: "easynet:///r/acme/agent/01X".into(), reason: "key compromise".into(), }; let err = decision.into_pb_error().expect("error expected"); diff --git a/core/runtime-rs/src/services/invocation/rpc_handlers.rs b/core/runtime-rs/src/services/invocation/rpc_handlers.rs index d4aadad3..c8150c46 100644 --- a/core/runtime-rs/src/services/invocation/rpc_handlers.rs +++ b/core/runtime-rs/src/services/invocation/rpc_handlers.rs @@ -25,6 +25,8 @@ use tracing::warn; +use easynet_run_axon_client::ura; + use crate::interop_native::{DispatchResult, ExecutionLayer}; use crate::*; @@ -63,7 +65,7 @@ impl pb::invocation_server::Invocation for AxonRuntime { // builds. Always present on signed federation envelopes. // 2. `function_name` — the legacy unsigned shape some // callers still set (RFC-001 §A2 transitional path). - // 3. resource_uri's `abilities/@` segment — + // 3. resource_ura's `abilities/@` segment — // what the EasyNet-CLI's bridge.ability_call_raw fills. // The bridge does NOT set `target.ability_name` for // raw calls, so without this fallback every @@ -87,8 +89,8 @@ impl pb::invocation_server::Invocation for AxonRuntime { }) .unwrap_or_else(|| { req.metadata - .get("easynet.resource_uri") - .map(|u| extract_ability_name_from_resource_uri(u)) + .get("easynet.resource_ura") + .map(|u| extract_ability_name_from_resource_ura(u)) .unwrap_or("") }) .to_string(); @@ -125,7 +127,7 @@ impl pb::invocation_server::Invocation for AxonRuntime { // ── RFC 001 / AXIOM signature-policy gate (P5-rewrite §4) ─ // // Runs BEFORE the membership and delegation gates: an - // unsigned envelope's `caller.uri` is an unsigned string the + // unsigned envelope's `caller.ura` is an unsigned string the // caller can set freely, so spending CPU on membership // lookup against such a URA would be wasted work and would // muddle the audit story. @@ -205,7 +207,7 @@ impl pb::invocation_server::Invocation for AxonRuntime { } // ── RFC 001 §A6 membership + §1 hub-profile dispatch ────── // - // Membership runs whenever a caller URI is present, not only + // Membership runs whenever a caller URA is present, not only // when the envelope is signed. The §A6 invariant — "no // non-member may invoke anything but federation.join" — is a // protocol-layer rule independent of cryptographic admission. @@ -337,8 +339,8 @@ impl pb::invocation_server::Invocation for AxonRuntime { // a typed receipt — all in-process, no remote dispatch. if Self::is_runtime_admin_ability(ability_name) { let caller_tenant_id = Self::envelope_tenant_id(Some(envelope_ref)); - if let Err(err) = validate_runtime_admin_resource_uri( - req.metadata.get("easynet.resource_uri").map(String::as_str), + if let Err(err) = validate_runtime_admin_resource_ura( + req.metadata.get("easynet.resource_ura").map(String::as_str), &caller_tenant_id, ability_name, ) { @@ -1087,7 +1089,7 @@ impl pb::invocation_server::Invocation for AxonRuntime { // the tenant id lets dispatch_capability fall through to // the runtime_local_tools registry (RFC-001 Step 3) for // daemon-registered handlers like .chat / - // fleet.skill_install / fleet.file_transfer. + // device.skill.install / device.fs.transfer. let dispatch = execution .dispatch_capability_with_tenant( &selected_node_id, @@ -1520,11 +1522,11 @@ impl AxonRuntime { } /// Lightweight ability-name extractor for the `runtime.*` skip -/// check at the top of `invoke`. Returns "" when the URI shape is +/// check at the top of `invoke`. Returns "" when the URA shape is /// not the expected canonical `…/ability/hub.` form. /// /// Why a dedicated helper rather than running -/// `canonicalize_easynet_resource_uri`: the canonicalizer enforces +/// `canonicalize_easynet_resource_ura`: the canonicalizer enforces /// a long list of structural invariants (visibility, tenant_id /// query, signature-bound segments) and ALL of those are exactly /// what we want to defer until AFTER the `runtime.*` skip @@ -1534,16 +1536,16 @@ impl AxonRuntime { /// canonicalize-then-skip is circular. Extracting just the name /// is parser-only, can never fail-with-error, and never reads any /// state that bootstrap is supposed to populate. -fn extract_ability_name_from_resource_uri(uri: &str) -> &str { +fn extract_ability_name_from_resource_ura(ura: &str) -> &str { // Canonical hub-owned abilities look like: // `easynet:///r//ability/hub..`. // Return `.`. let needle = "/ability/"; - let start = match uri.find(needle) { + let start = match ura.find(needle) { Some(i) => i + needle.len(), None => return "", }; - let tail = &uri[start..]; + let tail = &ura[start..]; let end = tail.find(['?', '/']).unwrap_or(tail.len()); let ability_tail = &tail[..end]; let first_dot = match ability_tail.find('.') { @@ -1557,35 +1559,35 @@ fn extract_ability_name_from_resource_uri(uri: &str) -> &str { qualified } -fn validate_runtime_admin_resource_uri( - resource_uri: Option<&str>, +fn validate_runtime_admin_resource_ura( + resource_ura: Option<&str>, caller_tenant_id: &str, ability_name: &str, ) -> Result<(), pb::Error> { - let Some(resource_uri) = resource_uri.filter(|uri| !uri.trim().is_empty()) else { + let Some(resource_ura) = resource_ura.filter(|ura| !ura.trim().is_empty()) else { return Ok(()); }; if caller_tenant_id.trim().is_empty() { return Err(AxonRuntime::axon_error( - ERR_EASYNET_RESOURCE_URI_INVALID, - "runtime.* resource_uri requires non-empty caller tenant_id", + ERR_EASYNET_RESOURCE_URA_INVALID, + "runtime.* resource_ura requires non-empty caller tenant_id", false, )); } - let expected = format!("easynet:///r/{caller_tenant_id}/ability/hub.{ability_name}"); - if resource_uri == expected { + let expected = ura::hub_ability_ura(caller_tenant_id, ability_name); + if resource_ura == expected { return Ok(()); } Err(AxonRuntime::axon_error( - ERR_EASYNET_RESOURCE_URI_INVALID, - format!("runtime.* resource_uri must use canonical hub ability URI {expected}"), + ERR_EASYNET_RESOURCE_URA_INVALID, + format!("runtime.* resource_ura must use canonical hub ability URA {expected}"), false, )) } #[cfg(test)] mod ability_name_extractor_tests { - use super::{extract_ability_name_from_resource_uri, validate_runtime_admin_resource_uri}; + use super::{extract_ability_name_from_resource_ura, validate_runtime_admin_resource_ura}; #[test] fn extracts_name_from_canonical_runtime_admin_uri() { @@ -1596,9 +1598,9 @@ mod ability_name_extractor_tests { // bootstrap call is rejected by the easynet metadata // verifier even though the runtime would otherwise have // skipped that check for runtime.* abilities. - let uri = "easynet:///r/acme/ability/hub.runtime.bootstrap_self_identity"; + let ura = "easynet:///r/acme/ability/hub.runtime.bootstrap_self_identity"; assert_eq!( - extract_ability_name_from_resource_uri(uri), + extract_ability_name_from_resource_ura(ura), "runtime.bootstrap_self_identity" ); } @@ -1609,9 +1611,9 @@ mod ability_name_extractor_tests { // call shape, different ability — both must skip the // easynet metadata verify so the daemon can advertise its // local tool catalog without a chicken-and-egg deadlock. - let uri = "easynet:///r/acme/ability/hub.runtime.register_local_tool"; + let ura = "easynet:///r/acme/ability/hub.runtime.register_local_tool"; assert_eq!( - extract_ability_name_from_resource_uri(uri), + extract_ability_name_from_resource_ura(ura), "runtime.register_local_tool" ); } @@ -1621,54 +1623,54 @@ mod ability_name_extractor_tests { // A federation ability MUST extract too — the skip check // negates correctly only when the extractor produced the // real ability name (otherwise both `target.ability_name` - // and the resource_uri lookup return "" and the skip path + // and the resource_ura lookup return "" and the skip path // matches `"".starts_with("runtime.")` — which evaluates // to false but for the wrong reason. Pin the extractor's // output here so a future regression that returns "" for - // every non-runtime URI is caught. - let uri = "easynet:///r/acme/ability/hub.federation.advertise_agent"; + // every non-runtime URA is caught. + let ura = "easynet:///r/acme/ability/hub.federation.advertise_agent"; assert_eq!( - extract_ability_name_from_resource_uri(uri), + extract_ability_name_from_resource_ura(ura), "federation.advertise_agent" ); } #[test] fn empty_uri_returns_empty_string_not_panic() { - assert_eq!(extract_ability_name_from_resource_uri(""), ""); + assert_eq!(extract_ability_name_from_resource_ura(""), ""); } #[test] fn uri_without_ability_segment_returns_empty_string() { - // A non-canonical URI has no `/ability/` token. Returning + // A non-canonical URA has no `/ability/` token. Returning // "" so the skip check reads through to "not a runtime // ability" — same fail-closed behaviour the pre-extractor // path had. assert_eq!( - extract_ability_name_from_resource_uri("https://example.com/foo/bar"), + extract_ability_name_from_resource_ura("https://example.com/foo/bar"), "" ); } #[test] fn canonical_uri_with_query_suffix_still_extracts_name() { - let uri = "easynet:///r/acme/ability/hub.runtime.unregister_local_tool?trace=1"; + let ura = "easynet:///r/acme/ability/hub.runtime.unregister_local_tool?trace=1"; assert_eq!( - extract_ability_name_from_resource_uri(uri), + extract_ability_name_from_resource_ura(ura), "runtime.unregister_local_tool" ); } #[test] fn legacy_hub_uri_is_not_extracted_any_more() { - let uri = + let ura = "easynet:///r/prv/hub/acme/abilities/runtime.bootstrap_self_identity@1?tenant_id=t1"; - assert_eq!(extract_ability_name_from_resource_uri(uri), ""); + assert_eq!(extract_ability_name_from_resource_ura(ura), ""); } #[test] fn runtime_admin_validator_accepts_exact_canonical_uri() { - let result = validate_runtime_admin_resource_uri( + let result = validate_runtime_admin_resource_ura( Some("easynet:///r/acme/ability/hub.runtime.register_local_tool"), "acme", "runtime.register_local_tool", @@ -1678,16 +1680,16 @@ mod ability_name_extractor_tests { #[test] fn runtime_admin_validator_rejects_legacy_hub_uri() { - let err = validate_runtime_admin_resource_uri( + let err = validate_runtime_admin_resource_ura( Some( "easynet:///r/prv/hub/acme/abilities/runtime.register_local_tool@1?tenant_id=acme", ), "acme", "runtime.register_local_tool", ) - .expect_err("legacy hub URI must be rejected"); + .expect_err("noncanonical hub URA must be rejected"); assert!( - err.message.contains("canonical hub ability URI"), + err.message.contains("canonical hub ability URA"), "unexpected error: {err:?}" ); } diff --git a/core/runtime-rs/src/services/invocation/runtime_admin.rs b/core/runtime-rs/src/services/invocation/runtime_admin.rs index fbbae73e..33a3faa6 100644 --- a/core/runtime-rs/src/services/invocation/runtime_admin.rs +++ b/core/runtime-rs/src/services/invocation/runtime_admin.rs @@ -63,7 +63,7 @@ struct RegisterLocalToolArgs { /// for an offline node) would relax this; out of scope in v1. node_id: String, /// Wire-level ability name (e.g. `claude.chat`, - /// `fleet.skill_install`). MUST be non-empty. Conflict policy: + /// `device.skill.install`). MUST be non-empty. Conflict policy: /// last-writer-wins on the same `(tenant, node, tool)` triple /// — re-registration is "I'm still here, maybe with a refreshed /// spec," matching the upstream registry's intent. @@ -851,7 +851,7 @@ mod tests { assert!(AxonRuntime::is_runtime_admin_ability("runtime.future")); assert!(!AxonRuntime::is_runtime_admin_ability("federation.join")); assert!(!AxonRuntime::is_runtime_admin_ability( - "fleet.session_attach" + "device.terminal.attach" )); assert!(!AxonRuntime::is_runtime_admin_ability("runtime")); } diff --git a/core/runtime-rs/src/services/invocation/session_provider.rs b/core/runtime-rs/src/services/invocation/session_provider.rs index 609dec6a..e8360af8 100644 --- a/core/runtime-rs/src/services/invocation/session_provider.rs +++ b/core/runtime-rs/src/services/invocation/session_provider.rs @@ -13,7 +13,7 @@ // - Defines the contract between axon's bidi_handler and // per-resource backend implementations. // - Provider returns SessionMeta on create() (carries display name + -// kind-prefixed extras for fleet.list_sessions). +// kind-prefixed extras for device.terminal.list). // - Provider returns AttachResult on attach() — distinguishes // provider-policy reject from kernel-level Err so the §A16 // receipt chain knows which terminal frame to emit. @@ -38,7 +38,7 @@ // // Architectural Position: // - Lives in services/invocation/ next to bidi_handler. -// - bidi_handler dispatches fleet.session_attach by looking up the +// - bidi_handler dispatches device.terminal.attach by looking up the // target session's kind in SessionRegistry, then calling the // matching provider's attach(). // - SessionRegistry owns the per-process session table and the @@ -71,7 +71,7 @@ use serde_json::Value; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; -/// Concrete-resource backend that axon dispatches `fleet.session_*` +/// Concrete-resource backend that axon dispatches `device.terminal.*` /// calls to. One impl per persistent-resource kind. Registered once /// at daemon boot via [`SessionRegistry::register_provider`]. /// @@ -162,7 +162,7 @@ pub trait SessionProvider: Send + Sync + 'static { /// /// Returns [`SessionMeta`] carrying provider-side metadata that /// axon attaches to the session record (visible in - /// `fleet.list_sessions` and as receipt headers on attach). + /// `device.terminal.list` and as receipt headers on attach). /// Failure aborts session creation; axon will not have /// persisted any state for `session_id`. fn create( @@ -204,7 +204,7 @@ pub trait SessionProvider: Send + Sync + 'static { /// Per-session metadata the provider returns from `create`. Axon /// stores this on the session record; consumers read it via -/// `fleet.list_sessions` and as receipt headers on attach. +/// `device.terminal.list` and as receipt headers on attach. /// /// `extras` is a kind-namespaced metadata bag. Axon does NOT /// validate the contents at the type level — the convention is @@ -219,7 +219,7 @@ pub struct SessionMeta { /// /// Why duplicate it (SessionRecord already has kind): the /// SessionMeta is what gets serialised in attach-receipt - /// headers and in the `meta` field of a `fleet.list_sessions` + /// headers and in the `meta` field of a `device.terminal.list` /// response row. A consumer that only sees the meta blob /// (e.g. a backend that caches headers) needs to disambiguate /// kinds without joining back to the registry. The redundancy @@ -250,7 +250,7 @@ pub struct SessionMeta { /// impls is cheaper and catches the same bugs at PR time. /// /// `BTreeMap` (not HashMap) so JSON serialisation is - /// deterministic — operators reading `fleet.list_sessions` see + /// deterministic — operators reading `device.terminal.list` see /// stable key ordering, which makes diff-based monitoring /// possible. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] @@ -805,7 +805,7 @@ mod tests { fn session_meta_serialises_with_sorted_extras() { // BTreeMap-backed extras → JSON output is sorted. This // matters for operator tooling that diffs - // fleet.list_sessions output between polls. + // device.terminal.list output between polls. let mut meta = SessionMeta::new("stub", "x"); meta.extras.insert("stub_z".into(), Value::from(1)); meta.extras.insert("stub_a".into(), Value::from(2)); @@ -826,7 +826,7 @@ mod tests { fn session_meta_skips_empty_extras() { // `skip_serializing_if = BTreeMap::is_empty` means a // fresh SessionMeta serialises without an extras key at - // all. Operators reading `fleet.list_sessions` see no + // all. Operators reading `device.terminal.list` see no // clutter from providers that don't emit metadata. let meta = SessionMeta::new("stub", "x"); let json = serde_json::to_string(&meta).unwrap(); diff --git a/core/runtime-rs/src/services/invocation/session_registry.rs b/core/runtime-rs/src/services/invocation/session_registry.rs index 195b8cb3..2c5c857e 100644 --- a/core/runtime-rs/src/services/invocation/session_registry.rs +++ b/core/runtime-rs/src/services/invocation/session_registry.rs @@ -84,7 +84,7 @@ pub struct SessionRecord { pub session_id: String, /// Returned from `provider.create()`. Carries display name + - /// kind-prefixed extras for `fleet.list_sessions`. + /// kind-prefixed extras for `device.terminal.list`. pub meta: SessionMeta, /// Wall-clock timestamp at which the session record was @@ -92,12 +92,12 @@ pub struct SessionRecord { /// synthesis at first attach). pub created_at: DateTime, - /// Envelope's caller URI at create time. Audit-trail field; + /// Envelope's caller URA at create time. Audit-trail field; /// not used for routing post-create. - pub caller_uri: String, + pub caller_ura: String, - /// Envelope's subject URI at create time. Same audit role. - pub subject_uri: String, + /// Envelope's subject URA at create time. Same audit role. + pub subject_ura: String, /// Lifecycle phase. See [`SessionStatus`] for transitions. pub status: SessionStatus, @@ -110,7 +110,7 @@ pub struct SessionRecord { /// Kernel provenance — how this record came into existence. /// First-class field (not `meta.extras`) because it's an /// AXON-level fact, not provider metadata. Operator tooling - /// reads `record.source` directly; CLI's `fleet.list_sessions` + /// reads `record.source` directly; CLI's `device.terminal.list` /// surface MUST distinguish the two for audit / migration /// progress dashboards. pub source: SessionSource, @@ -147,7 +147,7 @@ pub enum SessionSource { /// Attached ──handle drops cleanly─────────────────► Closed /// Running ──handle drops cleanly─────────────────► Closed /// Running ──handle drops with failure_reason set─► Failed -/// Closed ──fleet.session_close──────────────────► Closed (idempotent) +/// Closed ──device.terminal.close──────────────────► Closed (idempotent) /// ``` /// /// Currently implemented: Created / Attached / Failed transitions @@ -165,7 +165,7 @@ pub enum SessionStatus { Attached, /// Bytes have flowed in at least one direction since attach. Running, - /// Backend exited cleanly OR explicit `fleet.session_close` + /// Backend exited cleanly OR explicit `device.terminal.close` /// landed. Terminal state. Closed, /// `attach` returned Rejected OR pump task observed a @@ -182,8 +182,8 @@ pub struct SessionFilter { pub kind: Option, /// Restrict to records whose status matches. pub status: Option, - /// Restrict to records created by a specific caller URI. - pub caller_uri: Option, + /// Restrict to records created by a specific caller URA. + pub caller_ura: Option, } /// Process-wide session registry. Cloneable handle around the @@ -355,8 +355,8 @@ impl SessionRegistry { /// provider's `create`, persist a SessionRecord. Returns the /// new session_id (URA tail). /// - /// `caller_uri` and `subject_uri` come from the InvokeBidi - /// envelope (or unary `fleet.session_create` envelope, when + /// `caller_ura` and `subject_ura` come from the InvokeBidi + /// envelope (or unary `device.terminal.create` envelope, when /// that lands as a separate ability). Stored on the record /// for audit; not used for routing. pub fn create_session( @@ -364,8 +364,8 @@ impl SessionRegistry { kind: &str, args: Bytes, content_type: &str, - caller_uri: String, - subject_uri: String, + caller_ura: String, + subject_ura: String, ) -> anyhow::Result { // Look up the provider under a read lock first — most // create calls succeed and we don't need to hold the @@ -418,8 +418,8 @@ impl SessionRegistry { session_id: session_id.clone(), meta, created_at: Utc::now(), - caller_uri, - subject_uri, + caller_ura, + subject_ura, status: SessionStatus::Created, attach_count: 0, source: SessionSource::CreatedViaRegistry, @@ -448,7 +448,7 @@ impl SessionRegistry { /// Look up the provider for an existing session and dispatch /// `attach`. Used by the InvokeBidi handler when a - /// `fleet.session_attach` arrives. Returns the + /// `device.terminal.attach` arrives. Returns the /// [`AttachResult`] verbatim from the provider so the caller /// (bidi_handler) can decide how to surface it on the wire. /// @@ -485,7 +485,7 @@ impl SessionRegistry { /// The synthesised record carries /// [`SessionSource::SynthesisedFromLegacy`] in its `source` /// field so operator tooling can surface "this session - /// predates the registry" in fleet.list_sessions output. + /// predates the registry" in device.terminal.list output. /// /// Once all session creates flow through `create_session`, /// every call site can pass `None` for `synthesise_kind` and @@ -530,8 +530,8 @@ impl SessionRegistry { // create path doesn't surface them. Empty // strings are an honest "not recorded" // signal that operator tooling can spot. - caller_uri: String::new(), - subject_uri: String::new(), + caller_ura: String::new(), + subject_ura: String::new(), status: SessionStatus::Created, attach_count: 0, source: SessionSource::SynthesisedFromLegacy, @@ -588,7 +588,7 @@ impl SessionRegistry { } /// Snapshot of live sessions matching `filter`. Backs the - /// `fleet.list_sessions` ability handler. + /// `device.terminal.list` ability handler. /// /// Returns owned records (Cloning is cheap; SessionMeta's /// extras BTreeMap clones in O(n) entries but lists are @@ -604,9 +604,9 @@ impl SessionRegistry { filter.kind.as_deref().map_or(true, |k| r.kind == k) && filter.status.map_or(true, |s| r.status == s) && filter - .caller_uri + .caller_ura .as_deref() - .map_or(true, |c| r.caller_uri == c) + .map_or(true, |c| r.caller_ura == c) }) .cloned() .collect() @@ -852,8 +852,8 @@ mod tests { let rec = reg.get_session(&id).expect("record persisted"); assert_eq!(rec.kind, "pty"); assert_eq!(rec.session_id, id); - assert_eq!(rec.caller_uri, "c"); - assert_eq!(rec.subject_uri, "s"); + assert_eq!(rec.caller_ura, "c"); + assert_eq!(rec.subject_ura, "s"); assert_eq!(rec.status, SessionStatus::Created); assert_eq!(rec.attach_count, 0); } diff --git a/core/runtime-rs/src/services/invocation/shard_resolver.rs b/core/runtime-rs/src/services/invocation/shard_resolver.rs index b478263e..f209e89c 100644 --- a/core/runtime-rs/src/services/invocation/shard_resolver.rs +++ b/core/runtime-rs/src/services/invocation/shard_resolver.rs @@ -264,17 +264,17 @@ impl LocalRoutingTable { } } -/// Helper: extract the realm segment from a target URI of the +/// Helper: extract the realm segment from a target URA of the /// shape `easynet:///r//agent/`. Returns None when the -/// URI does not match. Used by `forward_invoke` before consulting +/// URA does not match. Used by `forward_invoke` before consulting /// the resolver. /// /// Accepts both the legacy 3-segment (`r//agent/`) and /// URA-conformant 4-segment (`r//reg/agent.`) forms. /// In the URA form the realm is carried by `?tenant_id=...`; we /// pull from there when present. -pub(crate) fn parse_realm_from_target_uri(uri: &str) -> Option { - let after_scheme = uri.strip_prefix("easynet:///r/")?; +pub(crate) fn parse_realm_from_target_ura(ura: &str) -> Option { + let after_scheme = ura.strip_prefix("easynet:///r/")?; // URA-conformant: "/reg/agent.?tenant_id=" if let Some((_, query)) = after_scheme.split_once('?') { for kv in query.split('&') { @@ -372,7 +372,7 @@ mod tests { #[test] fn parse_realm_from_legacy_form() { assert_eq!( - parse_realm_from_target_uri("easynet:///r/silan.localhost/agent/01XYZ"), + parse_realm_from_target_ura("easynet:///r/silan.localhost/agent/01XYZ"), Some("silan.localhost".into()) ); } @@ -380,24 +380,24 @@ mod tests { #[test] fn parse_realm_from_ura_v2_query_form() { assert_eq!( - parse_realm_from_target_uri("easynet:///r/org/reg/agent.01XYZ?tenant_id=alice.easynet"), + parse_realm_from_target_ura("easynet:///r/org/reg/agent.01XYZ?tenant_id=alice.easynet"), Some("alice.easynet".into()) ); } #[test] fn parse_realm_returns_none_for_garbage() { - assert_eq!(parse_realm_from_target_uri(""), None); - assert_eq!(parse_realm_from_target_uri("not-a-uri"), None); + assert_eq!(parse_realm_from_target_ura(""), None); + assert_eq!(parse_realm_from_target_ura("not-a-ura"), None); // Hub-profile abilities are NOT realm-shaped under the legacy // or canonical forms (their second segment is `hub` or // `ability`, never `agent`): assert_eq!( - parse_realm_from_target_uri( + parse_realm_from_target_ura( "easynet:///r/silan.localhost/ability/hub.federation.resolve" ), None, - "hub-profile URIs must not be misclassified as agent realms" + "hub-profile URAs must not be misclassified as agent realms" ); } } diff --git a/core/runtime-rs/src/services/payload_transfer.rs b/core/runtime-rs/src/services/payload_transfer.rs index 35b6f96b..6ded7375 100644 --- a/core/runtime-rs/src/services/payload_transfer.rs +++ b/core/runtime-rs/src/services/payload_transfer.rs @@ -46,6 +46,7 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { let mut expected_size: Option = None; let mut protocol_error: Option = None; let mut owner_tenant_id = String::new(); + let mut owner_resource_id = String::new(); let store_dir = self.state.payload_store_dir.clone(); std::fs::create_dir_all(&store_dir).map_err(|e| { @@ -83,6 +84,14 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { break; } }; + owner_resource_id = + match Self::envelope_resource_owner_id(init.envelope.as_ref()) { + Ok(v) => v, + Err(err) => { + protocol_error = Some(err); + break; + } + }; let file = std::fs::File::create(&tmp_path).map_err(|e| { Status::internal(format!( "failed to create temp payload file {}: {e}", @@ -181,6 +190,18 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { )), })); } + if owner_resource_id.is_empty() { + cleanup_tmp(); + return Ok(Response::new(pb::UploadPayloadResponse { + header: Some(header), + r#ref: None, + error: Some(Self::axon_error( + ERR_UNAUTHENTICATED, + "caller resource owner is required in envelope", + false, + )), + })); + } // Flush the writer if let Some(mut writer) = tmp_file.take() { @@ -234,7 +255,11 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { } let payload_id = new_id("payload"); - let uri = format!("axon://payloads/{payload_id}"); + let ura = easynet_run_axon_client::ura::payload_resource_ura( + &owner_tenant_id, + &owner_resource_id, + &payload_id, + ); let final_path = store_dir.join(format!("{payload_id}.bin")); std::fs::rename(&tmp_path, &final_path).map_err(|e| { Status::internal(format!( @@ -245,7 +270,7 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { })?; let reference = pb::PayloadRef { - uri: uri.clone(), + ura: ura.clone(), digest, size_bytes: written_bytes, content, @@ -253,7 +278,7 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { labels, }; self.state.streaming.payloads.insert( - uri, + ura, PayloadRecord { owner_tenant_id, reference: reference.clone(), @@ -277,7 +302,7 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { .state .streaming .payloads - .get(&req.uri) + .get(&req.ura) .map(|p| p.clone()) else { return Err(Status::not_found("payload not found")); @@ -356,7 +381,7 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { ) -> Result, Status> { let req = request.into_inner(); let header = Self::header_from_envelope(req.envelope.as_ref(), "completed"); - if let Some(payload) = self.state.streaming.payloads.get(&req.uri) { + if let Some(payload) = self.state.streaming.payloads.get(&req.ura) { if let Err(err) = Self::ensure_tenant_scope(&payload.owner_tenant_id, req.envelope.as_ref()) { @@ -389,7 +414,7 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { ) -> Result, Status> { let req = request.into_inner(); let header = Self::header_from_envelope(req.envelope.as_ref(), "completed"); - if let Some(payload) = self.state.streaming.payloads.get(&req.uri) { + if let Some(payload) = self.state.streaming.payloads.get(&req.ura) { if let Err(err) = Self::ensure_tenant_scope(&payload.owner_tenant_id, req.envelope.as_ref()) { @@ -401,7 +426,7 @@ impl pb::payload_transfer_server::PayloadTransfer for AxonRuntime { } // Tenant check passed — drop the read guard before removing. drop(payload); - let removed = self.state.streaming.payloads.remove(&req.uri); + let removed = self.state.streaming.payloads.remove(&req.ura); if let Some((_, record)) = removed.as_ref() { let _ = std::fs::remove_file(&record.data_path); } diff --git a/core/runtime-rs/src/services/stream/terminal_proxy.rs b/core/runtime-rs/src/services/stream/terminal_proxy.rs index fa5fe6c5..f346b0ef 100644 --- a/core/runtime-rs/src/services/stream/terminal_proxy.rs +++ b/core/runtime-rs/src/services/stream/terminal_proxy.rs @@ -5,7 +5,7 @@ //! (`CallMCPTool` against the `session_bridge` tool). Both the //! federation MCP path and the `session_bridge` built-in tool are //! deleted by RFC-001 — terminal sessions are now invocations of -//! `fleet.session_*` abilities advertised by the device-profile Agent. +//! `device.terminal.*` abilities advertised by the device-profile Agent. //! //! P1.2.a: stub keeps the module compilable so services/stream/lifecycle //! can still call into it without breaking the build. @@ -27,7 +27,7 @@ pub(crate) async fn handle_terminal_proxy( ) { // RFC-001 P1.2.a: federation MCP terminal proxy removed. // P1.2.f will replace this with InvokeStream against - // device-agent's fleet.session_read / session_input / session_resize / session_close. + // device-agent's device.terminal.read / session_input / session_resize / session_close. let _ = (runtime, open_body, session_id, inbound); let _ = tx .send(Err(Status::unimplemented( diff --git a/core/runtime-rs/src/state/agents.rs b/core/runtime-rs/src/state/agents.rs index a2da14af..53ef4c55 100644 --- a/core/runtime-rs/src/state/agents.rs +++ b/core/runtime-rs/src/state/agents.rs @@ -23,7 +23,7 @@ //! responses into its local copy. //! //! Lookup contract: -//! `lookup(uri) -> Option`. The membership gate maps: +//! `lookup(ura) -> Option`. The membership gate maps: //! None → AgentMembership::Unknown (NotMember) //! Some(active) → AgentMembership::Active //! Some(revoked{reason, ..}) → AgentMembership::Revoked{reason} @@ -59,8 +59,8 @@ pub(crate) enum SigningAuthority { /// Agent owns and uses its own keypair. Selfsigned, /// Agent's receipts are signed by the named hosting Agent's key. - /// `host_uri` is the canonical URA of the hosting Agent. - HostedBy { host_uri: String }, + /// `host_ura` is the canonical URA of the hosting Agent. + HostedBy { host_ura: String }, } /// One row in the realm directory. The on-wire `DirectoryEntry` @@ -72,7 +72,7 @@ pub(crate) struct AgentRecord { /// URAs (`provisional:`) MUST NOT be inserted into /// the catalog; the §A5 transition through `federation.join` is /// what mints a canonical URA. - pub(crate) uri: String, + pub(crate) ura: String, /// Ed25519 public key bytes. Used by the Base admission layer's /// signature verifier when the catalog backs the resolver. pub(crate) public_key: Vec, @@ -113,9 +113,9 @@ pub(crate) struct AgentRecord { impl AgentRecord { /// Construct a minimal Active record for the canonical happy path. /// Callers wire the public_key from `federation.join`'s envelope. - pub(crate) fn new_self_signed_active(uri: impl Into, public_key: Vec) -> Self { + pub(crate) fn new_self_signed_active(ura: impl Into, public_key: Vec) -> Self { Self { - uri: uri.into(), + ura: ura.into(), public_key, signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -141,11 +141,11 @@ impl AgentRecord { /// /// Indexes /// ------- -/// `by_uri` is the canonical store; every record lives here. The +/// `by_ura` is the canonical store; every record lives here. The /// secondary indexes are derived projections kept in sync inside /// `insert` / `revoke`: /// -/// * `by_tenant` — `tenant_id → set`. The hot path for +/// * `by_tenant` — `tenant_id → set`. The hot path for /// `federation.resolve(tenant_filter)` and for the device-scoped /// heartbeat fan-out's tenant-scoped variant. Without this /// resolve was an O(N_total) scan of the whole hub directory; @@ -153,7 +153,7 @@ impl AgentRecord { /// a multi-tenant hub serving millions of agents across thousands /// of small tenants. (RFC-002 §5.1, "tenant index" follow-up.) /// -/// * `by_host_node` — `host_node_id → set`. Used by the +/// * `by_host_node` — `host_node_id → set`. Used by the /// device-scoped heartbeat fan-out (`refresh_heartbeat_for_device`) /// so a single device's hosted-agent refresh is O(N_my_hosted) /// instead of O(N_total). @@ -167,12 +167,12 @@ impl AgentRecord { /// record, which we use to compute the diff). #[derive(Default)] pub(crate) struct AgentsCatalog { - by_uri: DashMap, - /// `tenant_id → {agent_uri, ...}`. Maintained by `insert` and + by_ura: DashMap, + /// `tenant_id → {agent_ura, ...}`. Maintained by `insert` and /// `revoke`. Tenants with no records have no entry. Read by /// `snapshot_for_tenant` and `len_for_tenant`. by_tenant: DashMap>, - /// `host_node_id → {agent_uri, ...}`. Maintained by `insert` and + /// `host_node_id → {agent_ura, ...}`. Maintained by `insert` and /// `revoke`. Read by `refresh_heartbeat_for_device`. by_host_node: DashMap>, } @@ -189,15 +189,15 @@ impl AgentsCatalog { /// Maintains the secondary indexes (`by_tenant`, `by_host_node`) /// in lockstep: a re-insert that changes either field removes /// the URA from the prior index slot before adding it to the - /// new one. Race-free because the primary `by_uri.insert` is + /// new one. Race-free because the primary `by_ura.insert` is /// the linearisation point; readers of secondary indexes that /// momentarily see the URA in both slots will resolve through - /// `by_uri` and observe the post-insert record either way. + /// `by_ura` and observe the post-insert record either way. pub(crate) fn insert(&self, record: AgentRecord) -> Option { - let uri = record.uri.clone(); + let ura = record.ura.clone(); let new_tenant = record.tenant_id.clone(); let new_host = record.host_node_id.clone(); - let prior = self.by_uri.insert(uri.clone(), record); + let prior = self.by_ura.insert(ura.clone(), record); if let Some(p) = &prior { // Diff: drop URA from prior tenant/host index when it @@ -205,12 +205,12 @@ impl AgentsCatalog { // no-op below because we re-insert into the same slot. if p.tenant_id != new_tenant { if let Some(t) = &p.tenant_id { - self.remove_from_index(&self.by_tenant, t, &uri); + self.remove_from_index(&self.by_tenant, t, &ura); } } if p.host_node_id != new_host { if let Some(h) = &p.host_node_id { - self.remove_from_index(&self.by_host_node, h, &uri); + self.remove_from_index(&self.by_host_node, h, &ura); } } } @@ -218,13 +218,13 @@ impl AgentsCatalog { self.by_tenant .entry(t.clone()) .or_default() - .insert(uri.clone()); + .insert(ura.clone()); } if let Some(h) = &new_host { self.by_host_node .entry(h.clone()) .or_default() - .insert(uri.clone()); + .insert(ura.clone()); } prior } @@ -233,7 +233,7 @@ impl AgentsCatalog { &self, index: &DashMap>, key: &str, - uri: &str, + ura: &str, ) { // Remove URA from the set; if the set is now empty, // remove the bucket entirely so iteration over the index @@ -241,7 +241,7 @@ impl AgentsCatalog { // is racy by construction but the cost is at most one // empty-set bucket — acceptable. let now_empty = if let Some(set) = index.get(key) { - set.remove(uri); + set.remove(ura); set.is_empty() } else { false @@ -254,22 +254,22 @@ impl AgentsCatalog { /// O(1) lookup by canonical URA. Cloned because `DashMap`'s /// `Ref<'_, _, _>` would borrow the shard guard across the /// admission gate's call boundary. - pub(crate) fn lookup(&self, uri: &str) -> Option { - self.by_uri.get(uri).map(|entry| entry.value().clone()) + pub(crate) fn lookup(&self, ura: &str) -> Option { + self.by_ura.get(ura).map(|entry| entry.value().clone()) } /// Soft revoke. Used by `federation.revoke` and by the hub when /// its key-rotation flow tombstones an old key. /// - /// The record stays in `by_uri` (it's a tombstone, not a + /// The record stays in `by_ura` (it's a tombstone, not a /// deletion) but is removed from the secondary indexes — a /// revoked agent is not a candidate for tenant-scoped resolve /// or for heartbeat refresh, so the indexes drop the URA. A /// subsequent `insert` (re-advertise after key rotation, say) /// re-populates the indexes through the standard insert path. - pub(crate) fn revoke(&self, uri: &str, reason: impl Into) -> bool { + pub(crate) fn revoke(&self, ura: &str, reason: impl Into) -> bool { let (had_record, prior_tenant, prior_host) = - if let Some(mut entry) = self.by_uri.get_mut(uri) { + if let Some(mut entry) = self.by_ura.get_mut(ura) { entry.status = AgentStatus::Revoked { reason: reason.into(), }; @@ -281,10 +281,10 @@ impl AgentsCatalog { return false; } if let Some(t) = &prior_tenant { - self.remove_from_index(&self.by_tenant, t, uri); + self.remove_from_index(&self.by_tenant, t, ura); } if let Some(h) = &prior_host { - self.remove_from_index(&self.by_host_node, h, uri); + self.remove_from_index(&self.by_host_node, h, ura); } true } @@ -292,7 +292,7 @@ impl AgentsCatalog { /// Sweep Active records whose `last_heartbeat_unix_ms` is older /// than `now_ms - stale_threshold_ms` and demote them to /// `Suspended { reason: "heartbeat stale" }`. Returns the - /// `(uri, elapsed_ms)` of every record that was demoted on this + /// `(ura, elapsed_ms)` of every record that was demoted on this /// pass. /// /// Why this exists @@ -330,7 +330,7 @@ impl AgentsCatalog { pub(crate) fn sweep_stale(&self, now_ms: i64, stale_threshold_ms: i64) -> Vec<(String, i64)> { let mut demoted = Vec::new(); // DashMap's iter() returns refs we cannot mutate through; - // collect the URI list first, then fetch get_mut per + // collect the URA list first, then fetch get_mut per // candidate. The two-pass shape also means a concurrent // re-advertise of the same URA between the two passes // wins — the get_mut sees the fresh Active record with a @@ -339,7 +339,7 @@ impl AgentsCatalog { // record that just got refreshed is by definition not // stale. let candidates: Vec = self - .by_uri + .by_ura .iter() .filter_map(|entry| { let rec = entry.value(); @@ -356,8 +356,8 @@ impl AgentsCatalog { }) .collect(); - for uri in candidates { - if let Some(mut entry) = self.by_uri.get_mut(&uri) { + for ura in candidates { + if let Some(mut entry) = self.by_ura.get_mut(&ura) { if !matches!(entry.status, AgentStatus::Active) { continue; } @@ -374,7 +374,7 @@ impl AgentsCatalog { entry.status = AgentStatus::Suspended { reason: "heartbeat stale".to_string(), }; - demoted.push((uri, elapsed)); + demoted.push((ura, elapsed)); } } demoted @@ -387,10 +387,10 @@ impl AgentsCatalog { /// MUST be preceded by a successful `federation.advertise_agent`. pub(crate) fn set_advertised_abilities( &self, - uri: &str, + ura: &str, abilities: Vec, ) -> bool { - if let Some(mut entry) = self.by_uri.get_mut(uri) { + if let Some(mut entry) = self.by_ura.get_mut(ura) { entry.advertised_abilities = abilities; true } else { @@ -399,11 +399,11 @@ impl AgentsCatalog { } /// Read-only snapshot of one Agent's advertised abilities. - /// Returns an empty vec for unknown URIs or Agents that have + /// Returns an empty vec for unknown URAs or Agents that have /// not yet advertised. - pub(crate) fn abilities_for(&self, uri: &str) -> Vec { - self.by_uri - .get(uri) + pub(crate) fn abilities_for(&self, ura: &str) -> Vec { + self.by_ura + .get(ura) .map(|entry| entry.value().advertised_abilities.clone()) .unwrap_or_default() } @@ -411,11 +411,11 @@ impl AgentsCatalog { /// Total Agent count (active + revoked + suspended). Useful for /// observability and the `federation.resolve` empty-filter path. pub(crate) fn len(&self) -> usize { - self.by_uri.len() + self.by_ura.len() } /// Refresh the liveness timestamp for a device-profile Agent and - /// every hosted Agent whose `SigningAuthority::HostedBy { host_uri }` + /// every hosted Agent whose `SigningAuthority::HostedBy { host_ura }` /// names that device. Returns `(self_refreshed, hosted_refreshed)`. /// /// This is the device-scoped heartbeat model: a single @@ -440,11 +440,11 @@ impl AgentsCatalog { /// zero as the migration window closes. pub(crate) fn refresh_heartbeat_for_device( &self, - device_uri: &str, + device_ura: &str, unix_ms: i64, ) -> (bool, usize) { let mut self_refreshed = false; - if let Some(mut entry) = self.by_uri.get_mut(device_uri) { + if let Some(mut entry) = self.by_ura.get_mut(device_ura) { entry.last_heartbeat_unix_ms = Some(unix_ms); self_refreshed = true; } @@ -454,8 +454,8 @@ impl AgentsCatalog { // host_node_id == the URA's last segment; if neither field // exists we fall through to the SigningAuthority scan below. let host_node_id_opt = self - .by_uri - .get(device_uri) + .by_ura + .get(device_ura) .and_then(|entry| entry.value().host_node_id.clone()); let mut hosted = 0usize; @@ -464,13 +464,13 @@ impl AgentsCatalog { if let Some(host_node_id) = host_node_id_opt.as_ref() { if let Some(uris) = self.by_host_node.get(host_node_id) { - for uri in uris.iter() { - if uri.key() == device_uri { + for ura in uris.iter() { + if ura.key() == device_ura { continue; } - if let Some(mut entry) = self.by_uri.get_mut(uri.key()) { + if let Some(mut entry) = self.by_ura.get_mut(ura.key()) { entry.last_heartbeat_unix_ms = Some(unix_ms); - already_refreshed.insert(uri.key().clone()); + already_refreshed.insert(ura.key().clone()); hosted += 1; } } @@ -480,12 +480,12 @@ impl AgentsCatalog { // Fallback for records that advertised pre-host_node_id and // therefore are not in the index. Bounded by index miss set; // trends to zero as old records are re-advertised. - for mut entry in self.by_uri.iter_mut() { + for mut entry in self.by_ura.iter_mut() { if already_refreshed.contains(entry.key()) { continue; } - if let SigningAuthority::HostedBy { host_uri } = &entry.signing_authority { - if host_uri == device_uri && entry.host_node_id.is_none() { + if let SigningAuthority::HostedBy { host_ura } = &entry.signing_authority { + if host_ura == device_ura && entry.host_node_id.is_none() { entry.last_heartbeat_unix_ms = Some(unix_ms); hosted += 1; } @@ -504,7 +504,7 @@ impl AgentsCatalog { return Vec::new(); }; set.iter() - .filter_map(|uri| self.by_uri.get(uri.key()).map(|e| e.value().clone())) + .filter_map(|ura| self.by_ura.get(ura.key()).map(|e| e.value().clone())) .collect() } @@ -520,7 +520,7 @@ impl AgentsCatalog { /// migration-period directory. O(N_total) — but the result set /// shrinks to zero as old records re-advertise. pub(crate) fn snapshot_legacy_no_tenant(&self) -> Vec { - self.by_uri + self.by_ura .iter() .filter(|e| e.value().tenant_id.is_none()) .map(|e| e.value().clone()) @@ -531,7 +531,7 @@ impl AgentsCatalog { /// `federation.resolve` is not on a hot Invoke path; admission /// uses `lookup` directly. pub(crate) fn snapshot(&self) -> Vec { - self.by_uri + self.by_ura .iter() .map(|entry| entry.value().clone()) .collect() @@ -609,14 +609,14 @@ mod tests { let cat = AgentsCatalog::new(); for i in 0..3 { cat.insert(AgentRecord::new_self_signed_active( - format!("easynet:///r/acme/agent/01X{i}"), + easynet_run_axon_client::ura::agent_ura("acme", &format!("u{i}"), "runtime"), vec![i as u8], )); } let mut snap = cat.snapshot(); - snap.sort_by(|a, b| a.uri.cmp(&b.uri)); + snap.sort_by(|a, b| a.ura.cmp(&b.ura)); assert_eq!(snap.len(), 3); - assert_eq!(snap[0].uri, "easynet:///r/acme/agent/01X0"); + assert_eq!(snap[0].ura, "easynet:///r/acme/agent/u0.runtime"); } #[test] @@ -672,10 +672,10 @@ mod tests { cat.insert(AgentRecord::new_self_signed_active(device, vec![1])); cat.insert(AgentRecord { - uri: hosted_a.into(), + ura: hosted_a.into(), public_key: vec![], signing_authority: SigningAuthority::HostedBy { - host_uri: device.into(), + host_ura: device.into(), }, status: AgentStatus::Active, advertised_abilities: vec![], @@ -684,10 +684,10 @@ mod tests { tenant_id: None, }); cat.insert(AgentRecord { - uri: hosted_b.into(), + ura: hosted_b.into(), public_key: vec![], signing_authority: SigningAuthority::HostedBy { - host_uri: device.into(), + host_ura: device.into(), }, status: AgentStatus::Active, advertised_abilities: vec![], @@ -697,10 +697,10 @@ mod tests { }); // Hosted by a different device — must not be touched. cat.insert(AgentRecord { - uri: stranger.into(), + ura: stranger.into(), public_key: vec![], signing_authority: SigningAuthority::HostedBy { - host_uri: "easynet:///r/acme/agent/01OTHER".into(), + host_ura: "easynet:///r/acme/agent/01OTHER".into(), }, status: AgentStatus::Active, advertised_abilities: vec![], @@ -733,7 +733,7 @@ mod tests { fn by_tenant_index_returns_only_tenant_members() { let cat = AgentsCatalog::new(); cat.insert(AgentRecord { - uri: "easynet:///r/x/agent/silan-1".into(), + ura: "easynet:///r/x/agent/silan-1".into(), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -743,7 +743,7 @@ mod tests { tenant_id: Some("silan.localhost".into()), }); cat.insert(AgentRecord { - uri: "easynet:///r/x/agent/silan-2".into(), + ura: "easynet:///r/x/agent/silan-2".into(), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -753,7 +753,7 @@ mod tests { tenant_id: Some("silan.localhost".into()), }); cat.insert(AgentRecord { - uri: "easynet:///r/x/agent/alice-1".into(), + ura: "easynet:///r/x/agent/alice-1".into(), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -773,9 +773,9 @@ mod tests { #[test] fn revoke_drops_agent_from_secondary_indexes() { let cat = AgentsCatalog::new(); - let uri = "easynet:///r/x/agent/silan-1"; + let ura = "easynet:///r/x/agent/silan-1"; cat.insert(AgentRecord { - uri: uri.into(), + ura: ura.into(), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -785,18 +785,18 @@ mod tests { tenant_id: Some("silan.localhost".into()), }); assert_eq!(cat.snapshot_for_tenant("silan.localhost").len(), 1); - cat.revoke(uri, "test"); - // Tombstone stays in by_uri but is excluded from the index. - assert!(cat.lookup(uri).is_some()); + cat.revoke(ura, "test"); + // Tombstone stays in by_ura but is excluded from the index. + assert!(cat.lookup(ura).is_some()); assert!(cat.snapshot_for_tenant("silan.localhost").is_empty()); } #[test] fn re_advertise_with_changed_tenant_updates_secondary_index() { let cat = AgentsCatalog::new(); - let uri = "easynet:///r/x/agent/migrating"; + let ura = "easynet:///r/x/agent/migrating"; cat.insert(AgentRecord { - uri: uri.into(), + ura: ura.into(), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -807,7 +807,7 @@ mod tests { }); // Re-advertise with new tenant. cat.insert(AgentRecord { - uri: uri.into(), + ura: ura.into(), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -823,10 +823,10 @@ mod tests { #[test] fn host_node_index_drives_heartbeat_fan_out() { let cat = AgentsCatalog::new(); - let device_uri = "easynet:///r/x/agent/dev-1"; + let device_ura = "easynet:///r/x/agent/dev-1"; let hosted_uri = "easynet:///r/x/agent/hosted-1"; cat.insert(AgentRecord { - uri: device_uri.into(), + ura: device_ura.into(), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -836,10 +836,10 @@ mod tests { tenant_id: None, }); cat.insert(AgentRecord { - uri: hosted_uri.into(), + ura: hosted_uri.into(), public_key: vec![], signing_authority: SigningAuthority::HostedBy { - host_uri: device_uri.into(), + host_ura: device_ura.into(), }, status: AgentStatus::Active, advertised_abilities: vec![], @@ -848,7 +848,7 @@ mod tests { tenant_id: None, }); let (refreshed_device, refreshed_hosted) = - cat.refresh_heartbeat_for_device(device_uri, 1234); + cat.refresh_heartbeat_for_device(device_ura, 1234); assert!(refreshed_device); assert_eq!(refreshed_hosted, 1); assert_eq!( @@ -875,7 +875,7 @@ mod tests { const TENANTS: usize = 1_000; for i in 0..N { cat.insert(AgentRecord { - uri: format!("easynet:///r/x/agent/n-{i}"), + ura: easynet_run_axon_client::ura::agent_ura("x", &format!("n-{i}"), "runtime"), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -924,7 +924,7 @@ mod tests { let t_insert = std::time::Instant::now(); for i in 0..N { cat.insert(AgentRecord { - uri: format!("easynet:///r/x/agent/n-{i}"), + ura: easynet_run_axon_client::ura::agent_ura("x", &format!("n-{i}"), "runtime"), public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -970,9 +970,9 @@ mod tests { const TENANTS: usize = 1_000; for i in 0..N { let tenant = format!("t{}.localhost", i % TENANTS); - let uri = format!("easynet:///r/x/agent/n-{i}"); + let ura = easynet_run_axon_client::ura::agent_ura("x", &format!("n-{i}"), "runtime"); cat.insert(AgentRecord { - uri, + ura, public_key: vec![], signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -998,10 +998,10 @@ mod tests { let device = "easynet:///r/acme/agent/01DEV"; let hosted = "easynet:///r/acme/agent/01HOST"; cat.insert(AgentRecord { - uri: hosted.into(), + ura: hosted.into(), public_key: vec![], signing_authority: SigningAuthority::HostedBy { - host_uri: device.into(), + host_ura: device.into(), }, status: AgentStatus::Active, advertised_abilities: vec![], diff --git a/core/runtime-rs/src/state/capability.rs b/core/runtime-rs/src/state/capability.rs index 9efa6b48..d7f95460 100644 --- a/core/runtime-rs/src/state/capability.rs +++ b/core/runtime-rs/src/state/capability.rs @@ -31,7 +31,7 @@ use crate::pb; pub(crate) struct PackageRecord { pub(crate) owner_tenant_id: String, pub(crate) descriptor: pb::CapabilityDescriptor, - pub(crate) payload_uri: String, + pub(crate) payload_ura: String, pub(crate) digest: String, pub(crate) proof: pb::CapabilityPackageProof, pub(crate) metadata: HashMap, diff --git a/core/runtime-rs/src/state/mod.rs b/core/runtime-rs/src/state/mod.rs index 3e585fe2..3999505b 100644 --- a/core/runtime-rs/src/state/mod.rs +++ b/core/runtime-rs/src/state/mod.rs @@ -592,7 +592,7 @@ impl std::fmt::Debug for CalleeSigner { // Defence in depth: never let `{:?}` print the signing // material. Identity URI is fine to show. f.debug_struct("CalleeSigner") - .field("identity", &self.identity.uri) + .field("identity", &self.identity.ura) .field("key", &"") .finish() } @@ -681,7 +681,7 @@ pub(crate) struct AxonState { // ── AXON-RFC-002 Session kernel ──────────────────────────────────── /// Process-wide registry of [`SessionProvider`] impls + live /// [`SessionRecord`] rows. Allocates session URAs, dispatches - /// `fleet.session_create` / `fleet.session_attach` to the + /// `device.terminal.create` / `device.terminal.attach` to the /// registered backend for each kind. /// /// `bidi_handler::run_frame_loop` reads through this to @@ -833,7 +833,7 @@ impl AxonState { // Local-fast mode by default (resolver: None) — every // server starts this way until a registry-backed resolver // is explicitly installed. The replay store is process- - // lifetime-owned so the (caller.uri, ability, nonce) + // lifetime-owned so the (caller.ura, ability, nonce) // dedup window persists across RPC calls. admission: AdmissionState { replay_store: easynet_run_axon_client::admission::NonceReplayStore::new(), diff --git a/core/runtime-rs/src/tests/admission.rs b/core/runtime-rs/src/tests/admission.rs index d03a428b..e260a73d 100644 --- a/core/runtime-rs/src/tests/admission.rs +++ b/core/runtime-rs/src/tests/admission.rs @@ -21,7 +21,7 @@ //! §1 anchor; tamper after signing so the admission pipeline //! rejects with `AXON_CALLER_SIGNATURE_INVALID`. //! - For replay tests, two sequential `Invoke` calls share the same -//! `(caller.uri, ability, nonce)` tuple; admission rejects the +//! `(caller.ura, ability, nonce)` tuple; admission rejects the //! second with `AXON_NONCE_REPLAY`. //! - Row 07' (same nonce, different ability) proves the dedup key //! includes `ability` — a legitimate cross-ability reuse is NOT @@ -49,7 +49,7 @@ use std::collections::HashMap; use std::sync::Arc; /// Resolver used by Federated-mode rows 01–05: always returns the -/// single configured pubkey regardless of `caller_uri`. Row 05 +/// single configured pubkey regardless of `caller_ura`. Row 05 /// installs an *imposter* pubkey so valid signatures under the /// worked seed still fail verification — that's the identity-spoof /// scenario. @@ -83,22 +83,22 @@ fn federated_runtime_imposter() -> AxonRuntime { // ── Worked-example anchors (PR2 §1) ───────────────────────────────── const WORKED_SEED: [u8; 32] = [0x01; 32]; -const WORKED_CALLER_URI: &str = "easynet:///r/silan/agents/alice"; -const WORKED_CALLEE_URI: &str = "easynet:///r/openai/agents/reviewer@1.0"; -const WORKED_SUBJECT_URI: &str = "easynet:///r/silan/papers/paper@draft-1"; +const WORKED_CALLER_URI: &str = "easynet:///r/silan/agent/silan.alice"; +const WORKED_CALLEE_URI: &str = "easynet:///r/openai/agent/openai.reviewer"; +const WORKED_SUBJECT_URI: &str = "easynet:///r/silan/resource/silan.papers/paper"; const WORKED_ABILITY: &str = "review"; const WORKED_PAYLOAD: &[u8] = b"{}"; const WORKED_NONCE: [u8; 16] = [0x22; 16]; -fn agent(uri: &str) -> pb::AgentIdentity { +fn agent(ura: &str) -> pb::AgentIdentity { pb::AgentIdentity { - uri: uri.to_string(), + ura: ura.to_string(), profile: "easynet-strict-v2".to_string(), } } -fn subject(uri: &str) -> pb::SubjectIdentity { +fn subject(ura: &str) -> pb::SubjectIdentity { pb::SubjectIdentity { - uri: uri.to_string(), + ura: ura.to_string(), profile: "easynet-strict-v2".to_string(), } } @@ -151,11 +151,11 @@ fn sign_envelope_in_place(env: &mut pb::Envelope) { out.extend_from_slice(&(b.len() as u32).to_be_bytes()); out.extend_from_slice(b); }; - put_str(&mut bytes, &caller.uri); + put_str(&mut bytes, &caller.ura); put_str(&mut bytes, &caller.profile); - put_str(&mut bytes, &callee.uri); + put_str(&mut bytes, &callee.ura); put_str(&mut bytes, &callee.profile); - put_str(&mut bytes, &subject.uri); + put_str(&mut bytes, &subject.ura); put_str(&mut bytes, &subject.profile); put_str(&mut bytes, WORKED_ABILITY); bytes.extend_from_slice(&digest); @@ -166,8 +166,8 @@ fn sign_envelope_in_place(env: &mut pb::Envelope) { Some(pb::causal_context::Form::Scalar(s)) => { let mut v = vec![0x01u8]; v.extend_from_slice(&s.receipt_hash); - v.extend_from_slice(&(s.receipt_uri.len() as u32).to_be_bytes()); - v.extend_from_slice(s.receipt_uri.as_bytes()); + v.extend_from_slice(&(s.receipt_ura.len() as u32).to_be_bytes()); + v.extend_from_slice(s.receipt_ura.as_bytes()); v } _ => panic!("test only exercises None/Scalar causal forms"), @@ -217,17 +217,17 @@ async fn invoke(runtime: &AxonRuntime, env: pb::Envelope) -> pb::InvokeResponse } // ═══════════════════════════════════════════════════════════════════════ -// Row 01 — tamper caller.uri after sign +// Row 01 — tamper caller.ura after sign // expected: AXON_CALLER_SIGNATURE_INVALID // layer: server admission step 3 // ═══════════════════════════════════════════════════════════════════════ #[tokio::test] -async fn row01_tampered_caller_uri_is_caller_signature_invalid() { +async fn row01_tampered_caller_ura_is_caller_signature_invalid() { let runtime = federated_runtime_worked(); let mut env = worked_signed_envelope("r01", WORKED_NONCE); // Minimal tamper: caller URI only. - env.caller.as_mut().unwrap().uri = "easynet:///r/mallory/agents/imposter".to_string(); + env.caller.as_mut().unwrap().ura = "easynet:///r/mallory/agent/mallory.imposter".to_string(); let resp = invoke(&runtime, env).await; let err = resp.error.expect("admission must reject tampered caller"); assert_eq!(err.code, "AXON_CALLER_SIGNATURE_INVALID"); @@ -271,7 +271,8 @@ async fn row02_tampered_payload_is_caller_signature_invalid() { async fn row03_tampered_subject_is_caller_signature_invalid() { let runtime = federated_runtime_worked(); let mut env = worked_signed_envelope("r03", WORKED_NONCE); - env.subject.as_mut().unwrap().uri = "easynet:///r/mallory/papers/evil@1".to_string(); + env.subject.as_mut().unwrap().ura = + "easynet:///r/mallory/resource/mallory.papers/evil".to_string(); let resp = invoke(&runtime, env).await; let err = resp.error.expect("admission must reject tampered subject"); assert_eq!(err.code, "AXON_CALLER_SIGNATURE_INVALID"); @@ -290,7 +291,7 @@ async fn row04_tampered_causal_context_is_caller_signature_invalid() { env.causal_context = Some(pb::CausalContext { form: Some(pb::causal_context::Form::Scalar(pb::ReceiptRef { receipt_hash: vec![0xEEu8; 32], - receipt_uri: "easynet:///r/mallory/receipts/fake".to_string(), + receipt_ura: "easynet:///r/mallory/receipts/fake".to_string(), })), }); let resp = invoke(&runtime, env).await; @@ -431,11 +432,11 @@ async fn row07prime_same_nonce_different_ability_is_not_replay() { let caller = env_b.caller.as_ref().unwrap(); let callee = env_b.callee.as_ref().unwrap(); let subj = env_b.subject.as_ref().unwrap(); - put_str(&mut bytes, &caller.uri); + put_str(&mut bytes, &caller.ura); put_str(&mut bytes, &caller.profile); - put_str(&mut bytes, &callee.uri); + put_str(&mut bytes, &callee.ura); put_str(&mut bytes, &callee.profile); - put_str(&mut bytes, &subj.uri); + put_str(&mut bytes, &subj.ura); put_str(&mut bytes, &subj.profile); put_str(&mut bytes, "publish"); bytes.extend_from_slice(&digest); @@ -501,7 +502,7 @@ async fn row07prime_same_nonce_different_ability_is_not_replay() { // ═══════════════════════════════════════════════════════════════════════ const CALLEE_SEED: [u8; 32] = [0x42; 32]; -const CALLEE_URI: &str = "easynet:///r/openai/agents/reviewer@1.0"; +const CALLEE_URI: &str = "easynet:///r/openai/agent/openai.reviewer"; /// Hex-encoded form of `CALLEE_SEED`. Kept in lock-step with the byte /// constant so the externalised axiom-vectors fixture /// (`testdata/axiom-vectors/v1.0/`, extracted in PR2.5 step 1c) can @@ -547,7 +548,7 @@ async fn signed_admit_emits_signed_receipt_with_callee_binding() { .callee_binding .as_ref() .expect("receipt must carry callee_binding"); - assert_eq!(cb.uri, CALLEE_URI); + assert_eq!(cb.ura, CALLEE_URI); assert_eq!(cb.profile, "easynet-strict-v2"); // 2. caller_binding echoes the envelope. @@ -555,7 +556,7 @@ async fn signed_admit_emits_signed_receipt_with_callee_binding() { .caller_binding .as_ref() .expect("receipt must carry caller_binding"); - assert_eq!(caller_binding.uri, WORKED_CALLER_URI); + assert_eq!(caller_binding.ura, WORKED_CALLER_URI); // 3. invocation_nonce echoes the envelope. assert_eq!(receipt.invocation_nonce.as_slice(), &WORKED_NONCE); @@ -594,15 +595,15 @@ async fn signed_admit_receipt_verifies_offline_against_callee_pubkey() { let callee_binding = receipt.callee_binding.as_ref().unwrap(); let subject_binding = receipt.subject_binding.as_ref().unwrap(); let client_caller = client_pb::AgentIdentity { - uri: caller_binding.uri.clone(), + ura: caller_binding.ura.clone(), profile: caller_binding.profile.clone(), }; let client_callee = client_pb::AgentIdentity { - uri: callee_binding.uri.clone(), + ura: callee_binding.ura.clone(), profile: callee_binding.profile.clone(), }; let client_subject = client_pb::SubjectIdentity { - uri: subject_binding.uri.clone(), + ura: subject_binding.ura.clone(), profile: subject_binding.profile.clone(), }; // Causal: runtime-rs → client-sdk pb conversion. For the worked @@ -674,15 +675,15 @@ async fn signed_admit_receipt_rejects_wrong_pubkey() { let callee_binding = receipt.callee_binding.as_ref().unwrap(); let subject_binding = receipt.subject_binding.as_ref().unwrap(); let client_caller = client_pb::AgentIdentity { - uri: caller_binding.uri.clone(), + ura: caller_binding.ura.clone(), profile: caller_binding.profile.clone(), }; let client_callee = client_pb::AgentIdentity { - uri: callee_binding.uri.clone(), + ura: callee_binding.ura.clone(), profile: callee_binding.profile.clone(), }; let client_subject = client_pb::SubjectIdentity { - uri: subject_binding.uri.clone(), + ura: subject_binding.ura.clone(), profile: subject_binding.profile.clone(), }; let client_causal = receipt @@ -763,19 +764,19 @@ fn receipt_to_verifier_json( Some(pb::causal_context::Form::Scalar(s)) => serde_json::json!({ "form": "scalar", "receipt_hash_hex": hex::encode(&s.receipt_hash), - "receipt_uri": s.receipt_uri, + "receipt_ura": s.receipt_ura, }), Some(pb::causal_context::Form::List(l)) => serde_json::json!({ "form": "list", "prior": l.prior.iter().map(|p| serde_json::json!({ "receipt_hash_hex": hex::encode(&p.receipt_hash), - "receipt_uri": p.receipt_uri, + "receipt_ura": p.receipt_ura, })).collect::>(), }), Some(pb::causal_context::Form::Merkle(m)) => serde_json::json!({ "form": "merkle", "root_hex": hex::encode(&m.root), - "proof_uri": m.proof_uri, + "proof_ura": m.proof_ura, }), }); let sig = r @@ -789,9 +790,9 @@ fn receipt_to_verifier_json( "state": state_ascii, "timestamp_unix_ms": r.timestamp_unix_ms, "prev_receipt_hash_hex": hex::encode(&r.prev_receipt_hash), - "caller_binding": { "uri": caller.uri, "profile": caller.profile }, - "callee_binding": { "uri": callee.uri, "profile": callee.profile }, - "subject_binding": { "uri": subject.uri, "profile": subject.profile }, + "caller_binding": { "uri": caller.ura, "profile": caller.profile }, + "callee_binding": { "uri": callee.ura, "profile": callee.profile }, + "subject_binding": { "uri": subject.ura, "profile": subject.profile }, "invocation_nonce_base64": BASE64_STANDARD.encode(&r.invocation_nonce), "causal_binding": causal, "payload_digest_hex": hex::encode(payload_digest), @@ -933,7 +934,7 @@ async fn cross_boundary_tampered_receipt_rejected_by_external_binary() { // which the signature was produced no longer match what the // verifier reconstructs. json["caller_binding"]["uri"] = - serde_json::Value::String("easynet:///r/mallory/agents/imposter".to_string()); + serde_json::Value::String("easynet:///r/mallory/agent/mallory.imposter".to_string()); let dir = tempdir_for("cross-tamper"); let path = dir.join("receipt.json"); @@ -965,7 +966,7 @@ async fn unsigned_admit_does_not_emit_receipt() { let runtime = test_runtime_with_callee_signer_and_resolver(); let env = pb::Envelope { request_id: "unsigned-receipt".to_string(), - caller: Some(agent("easynet:///r/tenant-test/agents/tester")), + caller: Some(agent("easynet:///r/tenant-test/agent/tenant-test.tester")), ..Default::default() }; let req = pb::InvokeRequest { @@ -1024,7 +1025,7 @@ async fn unsigned_caller_bypasses_admission_completely() { // legacy unsigned path that every pre-RFC-001 caller uses. let env = pb::Envelope { request_id: "unsigned".to_string(), - caller: Some(agent("easynet:///r/tenant-test/agents/tester")), + caller: Some(agent("easynet:///r/tenant-test/agent/tenant-test.tester")), ..Default::default() }; let req = pb::InvokeRequest { @@ -1089,7 +1090,7 @@ async fn strict_policy_rejects_unsigned_non_genesis_call() { let runtime = strict_runtime(); let env = pb::Envelope { request_id: "strict-unsigned-1".to_string(), - caller: Some(agent("easynet:///r/tenant-test/agents/tester")), + caller: Some(agent("easynet:///r/tenant-test/agent/tenant-test.tester")), ..Default::default() }; let req = pb::InvokeRequest { @@ -1097,18 +1098,18 @@ async fn strict_policy_rejects_unsigned_non_genesis_call() { target: Some(pb::InvocationTarget { strategy: 1, node_id: String::new(), - ability_name: "fleet.list_agents".to_string(), + ability_name: "device.agent.list".to_string(), function_name: String::new(), required_tags: Vec::new(), min_trust_level: 0, typed_target: Some(pb::invocation_target::TypedTarget::Ability( pb::AbilityTarget { - ability_name: "fleet.list_agents".to_string(), + ability_name: "device.agent.list".to_string(), function_name: String::new(), }, )), }), - function_name: "fleet.list_agents".to_string(), + function_name: "device.agent.list".to_string(), arguments: b"{}".to_vec(), content_type: "application/json".to_string(), timeout_seconds: 5, @@ -1142,7 +1143,7 @@ async fn strict_policy_admits_unsigned_federation_join() { let env = pb::Envelope { request_id: "strict-genesis-1".to_string(), caller: Some(pb::AgentIdentity { - uri: "provisional:0123456789abcdef".to_string(), + ura: "provisional:0123456789abcdef".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1204,7 +1205,7 @@ async fn strict_policy_rejects_unsigned_invoke_stream() { let runtime = strict_runtime(); let env = pb::Envelope { request_id: "strict-stream-unsigned-1".to_string(), - caller: Some(agent("easynet:///r/tenant-test/agents/tester")), + caller: Some(agent("easynet:///r/tenant-test/agent/tenant-test.tester")), ..Default::default() }; let req = pb::InvokeServerStreamRequest { @@ -1212,18 +1213,18 @@ async fn strict_policy_rejects_unsigned_invoke_stream() { target: Some(pb::InvocationTarget { strategy: 1, node_id: String::new(), - ability_name: "fleet.session_read".to_string(), + ability_name: "device.terminal.read".to_string(), function_name: String::new(), required_tags: Vec::new(), min_trust_level: 0, typed_target: Some(pb::invocation_target::TypedTarget::Ability( pb::AbilityTarget { - ability_name: "fleet.session_read".to_string(), + ability_name: "device.terminal.read".to_string(), function_name: String::new(), }, )), }), - function_name: "fleet.session_read".to_string(), + function_name: "device.terminal.read".to_string(), arguments: b"{}".to_vec(), content_type: "application/json".to_string(), timeout_seconds: 5, @@ -1261,7 +1262,7 @@ async fn strict_policy_admits_signed_invoke_stream_through_gates() { // assert that the rejection — when it comes — is NOT from any // of the four gates. The actual rejection at this layer is // resource_exhausted ("no node for server stream") because no - // device is registered for fleet.session_read in this test + // device is registered for device.terminal.read in this test // fixture. That's the right negative-of-negative shape. let runtime = federated_runtime_worked(); let env = worked_signed_envelope("strict-stream-signed-1", WORKED_NONCE); diff --git a/core/runtime-rs/src/tests/capability.rs b/core/runtime-rs/src/tests/capability.rs index 1abb9281..742ab5af 100644 --- a/core/runtime-rs/src/tests/capability.rs +++ b/core/runtime-rs/src/tests/capability.rs @@ -188,7 +188,7 @@ async fn publish_package_same_version_is_idempotent_for_identical_content() { tags: vec!["a2a".to_string()], requirements: HashMap::new(), metadata: HashMap::from([("a2a.skill_id".to_string(), "idempotent".to_string())]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -219,7 +219,7 @@ async fn publish_package_same_version_is_idempotent_for_identical_content() { tags: vec!["a2a".to_string()], requirements: HashMap::new(), metadata: HashMap::from([("a2a.skill_id".to_string(), "idempotent".to_string())]), - payload_uri: payload_ref.uri, + payload_ura: payload_ref.ura, publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -273,7 +273,7 @@ async fn publish_package_rejects_same_version_content_mutation() { tags: vec!["mcp".to_string()], requirements: HashMap::new(), metadata: HashMap::from([("mcp.tool_name".to_string(), "immutable_a".to_string())]), - payload_uri: payload_ref_v1.uri.clone(), + payload_ura: payload_ref_v1.ura.clone(), publisher_key_version: 1, proof: Some(proof_v1), }), @@ -301,7 +301,7 @@ async fn publish_package_rejects_same_version_content_mutation() { tags: vec!["mcp".to_string()], requirements: HashMap::new(), metadata: HashMap::from([("mcp.tool_name".to_string(), "immutable_b".to_string())]), - payload_uri: payload_ref_v2.uri, + payload_ura: payload_ref_v2.ura, publisher_key_version: 1, proof: Some(proof_v2), }), @@ -351,7 +351,7 @@ async fn capability_paths_reject_cross_tenant_scope() { tags: vec!["mcp".to_string()], requirements: HashMap::new(), metadata: HashMap::from([("mcp.tool_name".to_string(), "tenant_a_search".to_string())]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -427,7 +427,7 @@ async fn capability_paths_reject_cross_tenant_scope() { } #[tokio::test] -async fn publish_package_rejects_non_transferred_payload_uri() { +async fn publish_package_rejects_non_transferred_payload_ura() { let runtime = test_runtime(); let package_id = "pkg.invalid.payload-uri"; let version = "1.0.0"; @@ -448,17 +448,17 @@ async fn publish_package_rejects_non_transferred_payload_uri() { Request::new(pb::PublishPackageRequest { envelope: envelope("pub-invalid-payload-uri"), package_id: package_id.to_string(), - name: "invalid_payload_uri".to_string(), + name: "invalid_payload_ura".to_string(), version: version.to_string(), digest, signature, tags: Vec::new(), requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: "oss://pkg.invalid.payload-uri/1.0.0".to_string(), + payload_ura: "oss://pkg.invalid.payload-uri/1.0.0".to_string(), publisher_key_version: 1, proof: Some(pb::CapabilityPackageProof { - payload_uri: "oss://pkg.invalid.payload-uri/1.0.0".to_string(), + payload_ura: "oss://pkg.invalid.payload-uri/1.0.0".to_string(), payload_digest: format!("sha256:{}", AxonRuntime::sha256_hex(b"payload")), payload_size_bytes: 7, signature_fingerprint, @@ -503,7 +503,7 @@ async fn publish_package_accepts_legacy_call_without_proof() { tags: Vec::new(), requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: None, }), @@ -519,7 +519,7 @@ async fn publish_package_accepts_legacy_call_without_proof() { let proof = resp .proof .expect("runtime should return canonical proof for legacy publish"); - assert_eq!(proof.payload_uri, expected_proof.payload_uri); + assert_eq!(proof.payload_ura, expected_proof.payload_ura); assert_eq!(proof.payload_digest, expected_proof.payload_digest); assert_eq!(proof.payload_size_bytes, expected_proof.payload_size_bytes); assert_eq!( @@ -565,7 +565,7 @@ async fn install_capability_accepts_legacy_call_without_expected_proof() { tags: Vec::new(), requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -598,7 +598,7 @@ async fn install_capability_accepts_legacy_call_without_expected_proof() { let verified = install .verified_proof .expect("runtime should return verified proof for legacy install"); - assert_eq!(verified.payload_uri, proof.payload_uri); + assert_eq!(verified.payload_ura, proof.payload_ura); assert_eq!(verified.payload_digest, proof.payload_digest); assert_eq!(verified.payload_size_bytes, proof.payload_size_bytes); assert_eq!(verified.signature_fingerprint, proof.signature_fingerprint); @@ -638,7 +638,7 @@ async fn install_capability_rejects_tampered_expected_proof() { tags: Vec::new(), requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri, + payload_ura: payload_ref.ura, publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -707,7 +707,7 @@ async fn package_by_install_rejects_digest_mismatch_without_capability_fallback( tags: vec!["a2a".to_string()], requirements: HashMap::new(), metadata: HashMap::from([("a2a.skill_id".to_string(), "take_photo".to_string())]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -784,7 +784,7 @@ async fn install_capability_rejects_payload_bytes_digest_mismatch() { tags: Vec::new(), requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -796,7 +796,7 @@ async fn install_capability_rejects_payload_bytes_digest_mismatch() { .state .streaming .payloads - .get_mut(payload_ref.uri.as_str()) + .get_mut(payload_ref.ura.as_str()) { let original = std::fs::read(&payload.data_path).expect("read payload for tamper"); let mut tampered = original.clone(); @@ -872,7 +872,7 @@ async fn install_capability_rejects_archive_with_symlink_entry() { "axon.exec.command".to_string(), "sh {ability_package_root}/scripts/run.sh photo {node_id}".to_string(), )]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -947,7 +947,7 @@ async fn install_capability_rebuilds_stale_materialized_layout() { "axon.exec.command".to_string(), "sh {ability_package_root}/scripts/run.sh photo {node_id}".to_string(), )]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -1065,7 +1065,7 @@ async fn install_capability_materialized_layout_is_node_scoped() { "axon.exec.command".to_string(), "sh {ability_package_root}/scripts/run.sh photo {node_id}".to_string(), )]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -1178,7 +1178,7 @@ async fn install_capability_accepts_archive_with_appledouble_entries() { "axon.exec.command".to_string(), "sh {ability_package_root}/scripts/run.sh photo {node_id}".to_string(), )]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -1247,7 +1247,7 @@ async fn install_capability_accepts_archive_without_docs_usage() { "axon.exec.command".to_string(), "sh {ability_package_root}/scripts/run.sh photo {node_id}".to_string(), )]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -1637,7 +1637,7 @@ async fn publish_package_rejects_zero_size_payload() { package_id, version, digest.as_str(), - payload_ref.uri.as_str(), + payload_ref.ura.as_str(), payload_ref.size_bytes, signature_fingerprint.as_str(), ); @@ -1654,10 +1654,10 @@ async fn publish_package_rejects_zero_size_payload() { tags: Vec::new(), requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(pb::CapabilityPackageProof { - payload_uri: payload_ref.uri, + payload_ura: payload_ref.ura, payload_digest: payload_ref.digest, payload_size_bytes: payload_ref.size_bytes, signature_fingerprint, @@ -1700,7 +1700,7 @@ async fn install_capability_bootstrap_failure_cleans_up_materialized_layout() { package_id, version, digest.as_str(), - payload_ref.uri.as_str(), + payload_ref.ura.as_str(), payload_ref.size_bytes, signature_fingerprint.as_str(), ); @@ -1713,7 +1713,7 @@ async fn install_capability_bootstrap_failure_cleans_up_materialized_layout() { ); let proof = pb::CapabilityPackageProof { - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), payload_digest: digest.clone(), payload_size_bytes: payload_ref.size_bytes, signature_fingerprint: signature_fingerprint.clone(), @@ -1733,7 +1733,7 @@ async fn install_capability_bootstrap_failure_cleans_up_materialized_layout() { tags: Vec::new(), requirements: HashMap::new(), metadata, - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -1821,7 +1821,7 @@ fn streaming_digest_matches_in_memory_digest() { } } -/// format: `"{package_id}\n{version}\n{payload_digest}\n{payload_uri}\n{payload_size_bytes}\n{signature_fingerprint}"`. +/// format: `"{package_id}\n{version}\n{payload_digest}\n{payload_ura}\n{payload_size_bytes}\n{signature_fingerprint}"`. #[test] fn test_fingerprint_consistency_server_sdk() { use sha2::{Digest, Sha256}; @@ -1843,12 +1843,12 @@ fn test_fingerprint_consistency_server_sdk() { package_id: &str, version: &str, payload_digest: &str, - payload_uri: &str, + payload_ura: &str, payload_size_bytes: i64, signature_fingerprint: &str, ) -> String { let canonical = format!( - "{package_id}\n{version}\n{payload_digest}\n{payload_uri}\n{payload_size_bytes}\n{signature_fingerprint}" + "{package_id}\n{version}\n{payload_digest}\n{payload_ura}\n{payload_size_bytes}\n{signature_fingerprint}" ); sdk_sha256_prefixed(canonical.as_bytes()) } @@ -1858,7 +1858,7 @@ fn test_fingerprint_consistency_server_sdk() { "pkg-a", "1.0.0", "sha256:abcd", - "axon://payloads/p1", + "easynet:///r/tenant-test/resource/user.tenant-test/payload/p1", 1024i64, "sha256:sig1", ), @@ -1866,7 +1866,7 @@ fn test_fingerprint_consistency_server_sdk() { "pkg-b", "0.0.1", "sha256:0000", - "axon://payloads/p2", + "easynet:///r/tenant-test/resource/user.tenant-test/payload/p2", 0i64, "sha256:0000", ), @@ -1874,17 +1874,17 @@ fn test_fingerprint_consistency_server_sdk() { "pkg-c", "99.99.99", "sha256:ffff", - "axon://payloads/large", + "easynet:///r/tenant-test/resource/user.tenant-test/payload/large", 999999999i64, "sha256:ffff", ), ]; - for (package_id, version, payload_digest, payload_uri, payload_size_bytes, sig_fp) in cases { + for (package_id, version, payload_digest, payload_ura, payload_size_bytes, sig_fp) in cases { let server_result = capability_package_fingerprint( package_id, version, payload_digest, - payload_uri, + payload_ura, payload_size_bytes, sig_fp, ); @@ -1892,7 +1892,7 @@ fn test_fingerprint_consistency_server_sdk() { package_id, version, payload_digest, - payload_uri, + payload_ura, payload_size_bytes, sig_fp, ); @@ -1958,7 +1958,7 @@ async fn install_full( tags: vec!["test".to_string()], requirements: HashMap::new(), metadata, - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2087,7 +2087,7 @@ async fn concurrent_publish_same_package_version_identical_content() { tags: vec!["test".to_string()], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: pr.uri.clone(), + payload_ura: pr.ura.clone(), publisher_key_version: 1, proof: Some(prf), }), @@ -2165,7 +2165,7 @@ async fn concurrent_publish_same_package_version_different_content() { tags: vec!["test".to_string()], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof), }), @@ -2228,7 +2228,7 @@ async fn concurrent_install_same_package_to_different_nodes() { tags: vec!["test".to_string()], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2328,7 +2328,7 @@ async fn concurrent_install_same_package_same_node() { tags: vec!["test".to_string()], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2530,7 +2530,7 @@ async fn install_rejects_when_payload_file_corrupted_on_disk() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2591,7 +2591,7 @@ async fn install_rejects_when_payload_file_deleted_from_disk() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2654,7 +2654,7 @@ async fn install_fails_when_install_root_is_blocked() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2738,7 +2738,7 @@ async fn install_rejects_when_payload_file_truncated_on_disk() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2806,7 +2806,7 @@ async fn install_rebuilds_after_corrupted_install_json() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2901,7 +2901,7 @@ async fn install_rebuilds_after_missing_source_directory() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -2997,7 +2997,7 @@ async fn install_rebuilds_after_source_content_tampered() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -3098,7 +3098,7 @@ async fn install_cleans_up_stale_ability_root_before_rebuild() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -3217,7 +3217,7 @@ async fn concurrent_install_and_uninstall_same_node() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref_b.uri.clone(), + payload_ura: payload_ref_b.ura.clone(), publisher_key_version: 1, proof: Some(proof_b.clone()), }), @@ -3358,7 +3358,7 @@ async fn concurrent_upload_and_delete_same_payload() { let upload_resp = upload_fut.await.unwrap().into_inner(); assert!(upload_resp.error.is_none()); let payload_ref = upload_resp.r#ref.expect("ref must exist"); - let uri = payload_ref.uri.clone(); + let uri = payload_ref.ura.clone(); // Now concurrently: download + delete let barrier = Arc::new(tokio::sync::Barrier::new(3)); @@ -3373,7 +3373,7 @@ async fn concurrent_upload_and_delete_same_payload() { client .download_payload(grpc_pb::DownloadPayloadRequest { envelope: grpc_envelope("download-during-delete"), - uri: uri_dl, + ura: uri_dl, offset: 0, limit: 0, }) @@ -3390,7 +3390,7 @@ async fn concurrent_upload_and_delete_same_payload() { client .delete_payload(grpc_pb::DeletePayloadRequest { envelope: grpc_envelope("delete-during-download"), - uri: uri_del, + ura: uri_del, }) .await }); @@ -3447,7 +3447,7 @@ async fn concurrent_sweep_during_install() { tags: vec![], requirements: HashMap::new(), metadata: HashMap::new(), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), diff --git a/core/runtime-rs/src/tests/federation.rs b/core/runtime-rs/src/tests/federation.rs index 17bd499d..a53d1d73 100644 --- a/core/runtime-rs/src/tests/federation.rs +++ b/core/runtime-rs/src/tests/federation.rs @@ -2403,7 +2403,7 @@ fn federation_heartbeat_emits_tier1_mcp_summaries() { }], ..Default::default() }, - payload_uri: String::new(), + payload_ura: String::new(), digest: String::new(), proof: pb::CapabilityPackageProof::default(), metadata: HashMap::new(), diff --git a/core/runtime-rs/src/tests/federation_e2e.rs b/core/runtime-rs/src/tests/federation_e2e.rs index 799a302c..d50b8144 100644 --- a/core/runtime-rs/src/tests/federation_e2e.rs +++ b/core/runtime-rs/src/tests/federation_e2e.rs @@ -36,7 +36,7 @@ use pb::invocation_server::Invocation; use std::sync::Arc; use tonic::Request; -const PROVISIONAL_URI: &str = "provisional:0123456789abcdef"; +const PROVISIONAL_URA: &str = "provisional:0123456789abcdef"; const REALM: &str = "acme"; fn fresh_runtime() -> AxonRuntime { @@ -59,18 +59,18 @@ fn provisional_envelope(request_id: &str) -> Option { Some(pb::Envelope { request_id: request_id.into(), caller: Some(pb::AgentIdentity { - uri: PROVISIONAL_URI.into(), + ura: PROVISIONAL_URA.into(), ..Default::default() }), ..Default::default() }) } -fn canonical_envelope(request_id: &str, agent_uri: &str) -> Option { +fn canonical_envelope(request_id: &str, agent_ura: &str) -> Option { Some(pb::Envelope { request_id: request_id.into(), caller: Some(pb::AgentIdentity { - uri: agent_uri.into(), + ura: agent_ura.into(), ..Default::default() }), ..Default::default() @@ -121,8 +121,8 @@ async fn invoke( #[tokio::test] async fn join_round_trip_inserts_canonical_record_and_returns_uri() { // §3 Step D: federation.join from a provisional caller produces - // a Receipt carrying the canonical agent URI and the - // join_receipt_hash, AND the catalog has the new Active record. + // a Receipt carrying the membership URA and the join_receipt_hash, + // AND the catalog has the new Active record. let runtime = fresh_runtime(); let args = serde_json::json!({ "realm": REALM, @@ -143,14 +143,14 @@ async fn join_round_trip_inserts_canonical_record_and_returns_uri() { "federation.join from provisional caller must succeed" ); let body: serde_json::Value = serde_json::from_slice(&resp.result).unwrap(); - let canonical_uri = body["canonical_agent_uri"].as_str().unwrap(); - assert!(canonical_uri.starts_with(&format!("easynet:///r/{REALM}/agent/"))); + let membership_ura = body["membership_ura"].as_str().unwrap(); + assert!(membership_ura.starts_with(&format!("easynet:///r/{REALM}/agent/hub.a-"))); assert_eq!(body["realm"], REALM); assert!(!body["join_receipt_hash"].as_str().unwrap().is_empty()); // Catalog now has exactly one Active record with the published key. assert_eq!(runtime.state.agents.len(), 1); - let rec = runtime.state.agents.lookup(canonical_uri).unwrap(); + let rec = runtime.state.agents.lookup(membership_ura).unwrap(); assert_eq!(rec.public_key, vec![1, 2, 3, 4, 5]); } @@ -165,7 +165,7 @@ async fn join_with_canonical_caller_is_rejected_with_invalid_args() { let resp = invoke( &runtime, "join-bad", - canonical_envelope("join-bad", "easynet:///r/acme/agent/01CANON"), + canonical_envelope("join-bad", "easynet:///r/acme/agent/01CANON.runtime"), "federation.join", args.as_bytes(), ) @@ -203,24 +203,24 @@ async fn duplicate_public_key_is_rejected_with_specific_code() { #[tokio::test] async fn non_federation_ability_does_not_reach_hub_profile_dispatch() { // The hub-profile dispatcher must not see anything outside the - // federation.* namespace. We send a `fleet.*` ability and assert + // federation.* namespace. We send a `device.*` ability and assert // the response was NOT produced by hub-profile. let runtime = fresh_runtime(); let resp = invoke( &runtime, "non-fed-1", - canonical_envelope("non-fed-1", "easynet:///r/acme/agent/01DEV"), - "fleet.list_agents", + canonical_envelope("non-fed-1", "easynet:///r/acme/agent/01DEV.runtime"), + "device.agent.list", b"{}", ) .await; assert_ne!( resp.scheduling_reason, "hub_profile_inprocess", - "fleet.* must not route through hub-profile", + "device.* must not route through hub-profile", ); assert_ne!( resp.scheduling_reason, "hub_profile_rejected", - "fleet.* must not be rejected by hub-profile", + "device.* must not be rejected by hub-profile", ); } @@ -230,9 +230,9 @@ async fn advertise_agent_self_signed_round_trip_persists_in_catalog() { // itself as self-signed. The catalog should accept and report // replaced_prior=false for the first call, true for the second. let runtime = fresh_runtime(); - let hub_uri = "easynet:///r/acme/agent/01HUB"; + let hub_ura = "easynet:///r/acme/agent/01HUB.runtime"; let args = serde_json::json!({ - "agent_uri": hub_uri, + "agent_ura": hub_ura, "public_key_hex": "aa", "signing_authority": {"kind": "self_signed"}, }) @@ -240,7 +240,7 @@ async fn advertise_agent_self_signed_round_trip_persists_in_catalog() { let first = invoke( &runtime, "adv-1", - canonical_envelope("adv-1", hub_uri), + canonical_envelope("adv-1", hub_ura), "federation.advertise_agent", args.as_bytes(), ) @@ -252,7 +252,7 @@ async fn advertise_agent_self_signed_round_trip_persists_in_catalog() { let second = invoke( &runtime, "adv-2", - canonical_envelope("adv-2", hub_uri), + canonical_envelope("adv-2", hub_ura), "federation.advertise_agent", args.as_bytes(), ) @@ -269,21 +269,21 @@ async fn resolve_returns_only_agents_matching_prefix_filter() { .state .agents .insert(AgentRecord::new_self_signed_active( - "easynet:///r/acme/agent/01HUB", + "easynet:///r/acme/agent/01HUB.runtime", vec![], )); runtime .state .agents .insert(AgentRecord::new_self_signed_active( - "easynet:///r/other/agent/01XYZ", + "easynet:///r/other/agent/01XYZ.runtime", vec![], )); - let args = r#"{"filter":{"agent_uri_prefix":"easynet:///r/acme/"}}"#; + let args = r#"{"filter":{"agent_ura_prefix":"easynet:///r/acme/"}}"#; let resp = invoke( &runtime, "res-1", - canonical_envelope("res-1", "easynet:///r/acme/agent/01HUB"), + canonical_envelope("res-1", "easynet:///r/acme/agent/01HUB.runtime"), "federation.resolve", args.as_bytes(), ) @@ -292,7 +292,7 @@ async fn resolve_returns_only_agents_matching_prefix_filter() { let body: serde_json::Value = serde_json::from_slice(&resp.result).unwrap(); let agents = body["agents"].as_array().unwrap(); assert_eq!(agents.len(), 1); - assert_eq!(agents[0]["uri"], "easynet:///r/acme/agent/01HUB"); + assert_eq!(agents[0]["ura"], "easynet:///r/acme/agent/01HUB.runtime"); } #[tokio::test] @@ -303,7 +303,7 @@ async fn revoked_caller_is_rejected_at_membership_gate_before_dispatch() { // AXON_MEMBERSHIP_REVOKED with the revoke reason verbatim, and // scheduling_reason = "membership_rejected". let runtime = fresh_runtime(); - let dev = "easynet:///r/acme/agent/01DEV"; + let dev = "easynet:///r/acme/agent/01DEV.runtime"; runtime .state .agents @@ -330,7 +330,7 @@ async fn revoked_caller_is_rejected_at_membership_gate_before_dispatch() { #[tokio::test] async fn heartbeat_round_trip_for_active_member_returns_status() { let runtime = fresh_runtime(); - let dev = "easynet:///r/acme/agent/01DEV"; + let dev = "easynet:///r/acme/agent/01DEV.runtime"; runtime .state .agents diff --git a/core/runtime-rs/src/tests/forward_invoke_e2e.rs b/core/runtime-rs/src/tests/forward_invoke_e2e.rs index 2117b090..875f8756 100644 --- a/core/runtime-rs/src/tests/forward_invoke_e2e.rs +++ b/core/runtime-rs/src/tests/forward_invoke_e2e.rs @@ -15,7 +15,7 @@ //! instance. Caller in tenant `silan` invokes an ability //! hosted by a node in tenant `alice` through the same hub. //! The forward path is tenant-blind by construction (the -//! hub lookup keys on agent URI + host_node_id). +//! hub lookup keys on agent URA + host_node_id). //! //! Both experiments stand up real UnixListeners on /tmp to emulate //! daemon-side dispatch_endpoints; the hub's @@ -45,11 +45,11 @@ fn fresh_runtime() -> AxonRuntime { AxonRuntime::new(Arc::new(state)) } -fn caller_envelope(request_id: &str, caller_uri: &str) -> Option { +fn caller_envelope(request_id: &str, caller_ura: &str) -> Option { Some(pb::Envelope { request_id: request_id.into(), caller: Some(pb::AgentIdentity { - uri: caller_uri.into(), + ura: caller_ura.into(), ..Default::default() }), ..Default::default() @@ -151,7 +151,7 @@ async fn register_local_tool( tool_name: &str, dispatch_endpoint: &str, ) { - let resource_uri = format!("easynet:///r/{REALM}/ability/hub.runtime.register_local_tool"); + let resource_ura = format!("easynet:///r/{REALM}/ability/hub.runtime.register_local_tool"); let args = serde_json::json!({ "tenant_id": tenant, "node_id": node_id, @@ -160,7 +160,10 @@ async fn register_local_tool( "spec_proto_b64": "", }) .to_string(); - let env = caller_envelope("reg", &format!("easynet:///r/{REALM}/agent/{node_id}")); + let env = caller_envelope( + "reg", + &format!("easynet:///r/{REALM}/agent/{node_id}.runtime"), + ); let req = pb::InvokeRequest { envelope: env, target: Some(pb::InvocationTarget { @@ -183,7 +186,7 @@ async fn register_local_tool( timeout_seconds: 5, metadata: { let mut m = std::collections::HashMap::new(); - m.insert("easynet.resource_uri".into(), resource_uri); + m.insert("easynet.resource_ura".into(), resource_ura); m }, payload_ref: None, @@ -205,19 +208,19 @@ async fn register_local_tool( /// test pre-seeding. Production paths advertise through the wire /// API; tests prefer this fast path so each test is independent and /// does not need to bootstrap a full federation.join sequence. -fn seed_directory_agent(runtime: &AxonRuntime, agent_uri: &str, host_node_id: &str) { - seed_directory_agent_with_tenant(runtime, agent_uri, host_node_id, None); +fn seed_directory_agent(runtime: &AxonRuntime, agent_ura: &str, host_node_id: &str) { + seed_directory_agent_with_tenant(runtime, agent_ura, host_node_id, None); } fn seed_directory_agent_with_tenant( runtime: &AxonRuntime, - agent_uri: &str, + agent_ura: &str, host_node_id: &str, tenant_id: Option<&str>, ) { use crate::state::{AgentRecord, AgentStatus, SigningAuthority}; runtime.state.agents.insert(AgentRecord { - uri: agent_uri.to_string(), + ura: agent_ura.to_string(), public_key: Vec::new(), signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -234,23 +237,23 @@ fn seed_directory_agent_with_tenant( async fn advertise_self_signed( runtime: &AxonRuntime, tenant: &str, - agent_uri: &str, + agent_ura: &str, host_node_id: &str, public_key_hex: &str, ) { let args = serde_json::json!({ - "agent_uri": agent_uri, + "agent_ura": agent_ura, "public_key_hex": public_key_hex, "signing_authority": { "kind": "self_signed" }, "host_node_id": host_node_id, }) .to_string(); let _ = tenant; - let env = caller_envelope("adv", agent_uri); + let env = caller_envelope("adv", agent_ura); let resp = invoke(runtime, env, "federation.advertise_agent", args.as_bytes()).await; assert_eq!( resp.error, None, - "advertise_agent({agent_uri}) failed: {:?}", + "advertise_agent({agent_ura}) failed: {:?}", resp.error ); } @@ -264,8 +267,8 @@ async fn exp1_single_user_two_devices_forward_invoke_round_trip() { let device_a = "node-A"; let device_b = "node-B"; - let agent_a = format!("easynet:///r/{REALM}/agent/{device_a}"); - let agent_b = format!("easynet:///r/{REALM}/agent/{device_b}"); + let agent_a = format!("easynet:///r/{REALM}/agent/{device_a}.runtime"); + let agent_b = format!("easynet:///r/{REALM}/agent/{device_b}.runtime"); // Stand up device B's fake dispatch endpoint. The ability // `weather.fetch` returns a fixed JSON payload. @@ -297,7 +300,7 @@ async fn exp1_single_user_two_devices_forward_invoke_round_trip() { let target_args = serde_json::json!({"city": "Singapore"}); let target_args_bytes = serde_json::to_vec(&target_args).unwrap(); let forward_args = serde_json::json!({ - "target_uri": agent_b, + "target_ura": agent_b, "ability_name": "weather.fetch", "function_name": "", "arguments_b64": B64.encode(&target_args_bytes), @@ -330,13 +333,13 @@ async fn exp1_single_user_two_devices_forward_invoke_round_trip() { async fn exp1_forward_invoke_unknown_target_returns_typed_error() { let runtime = fresh_runtime(); let tenant = "silan.localhost"; - let agent_a = format!("easynet:///r/{REALM}/agent/node-A"); + let agent_a = format!("easynet:///r/{REALM}/agent/node-A.runtime"); seed_directory_agent(&runtime, &agent_a, "node-A"); let _ = tenant; let forward_args = serde_json::json!({ - "target_uri": "easynet:///r/exp-realm/agent/ghost", + "target_ura": "easynet:///r/exp-realm/agent/ghost.runtime", "ability_name": "any.ability", "arguments_b64": "", }) @@ -357,8 +360,8 @@ async fn exp1_forward_invoke_unknown_target_returns_typed_error() { async fn exp1_forward_invoke_target_without_host_node_returns_typed_error() { let runtime = fresh_runtime(); let tenant = "silan.localhost"; - let agent_a = format!("easynet:///r/{REALM}/agent/node-A"); - let agent_b = format!("easynet:///r/{REALM}/agent/node-B"); + let agent_a = format!("easynet:///r/{REALM}/agent/node-A.runtime"); + let agent_b = format!("easynet:///r/{REALM}/agent/node-B.runtime"); seed_directory_agent(&runtime, &agent_a, "node-A"); let _ = tenant; @@ -367,7 +370,7 @@ async fn exp1_forward_invoke_target_without_host_node_returns_typed_error() { { use crate::state::{AgentRecord, AgentStatus, SigningAuthority}; runtime.state.agents.insert(AgentRecord { - uri: agent_b.clone(), + ura: agent_b.clone(), public_key: Vec::new(), signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -379,7 +382,7 @@ async fn exp1_forward_invoke_target_without_host_node_returns_typed_error() { } let forward_args = serde_json::json!({ - "target_uri": agent_b, + "target_ura": agent_b, "ability_name": "any.ability", "arguments_b64": "", }) @@ -404,8 +407,8 @@ async fn exp2_cross_tenant_forward_invoke_round_trip() { let tenant_silan = "silan.localhost"; let tenant_alice = "alice.localhost"; - let agent_silan = format!("easynet:///r/{REALM}/agent/silan-node"); - let agent_alice = format!("easynet:///r/{REALM}/agent/alice-node"); + let agent_silan = format!("easynet:///r/{REALM}/agent/silan-node.runtime"); + let agent_alice = format!("easynet:///r/{REALM}/agent/alice-node.runtime"); // Alice's daemon hosts ability `ping.greet` with a fixed reply. let endpoint_alice = spawn_fake_daemon_endpoint( @@ -432,12 +435,12 @@ async fn exp2_cross_tenant_forward_invoke_round_trip() { // Silan invokes alice's ping.greet via forward_invoke. Note the // caller envelope is silan's; the hub looks up alice via - // target_uri and discovers tenant_alice through the + // target_ura and discovers tenant_alice through the // runtime_local_tools scan. let target_args = serde_json::json!({"from": "silan"}); let target_args_bytes = serde_json::to_vec(&target_args).unwrap(); let forward_args = serde_json::json!({ - "target_uri": agent_alice, + "target_ura": agent_alice, "ability_name": "ping.greet", "arguments_b64": B64.encode(&target_args_bytes), }) @@ -470,7 +473,7 @@ async fn exp2_cross_tenant_forward_invoke_round_trip() { async fn resolve_key_returns_directory_public_key_for_advertised_agent() { let runtime = fresh_runtime(); let tenant = "silan.localhost"; - let agent = format!("easynet:///r/{REALM}/agent/whoami"); + let agent = format!("easynet:///r/{REALM}/agent/whoami.runtime"); // Advertise with a non-empty public_key_hex so resolve_key can // echo it back. First call seeds membership for the caller. @@ -479,12 +482,12 @@ async fn resolve_key_returns_directory_public_key_for_advertised_agent() { advertise_self_signed(&runtime, tenant, &agent, "whoami", "deadbeefcafe").await; // Now query resolve_key. - let q = serde_json::json!({ "agent_uri": agent }).to_string(); + let q = serde_json::json!({ "agent_ura": agent }).to_string(); let env = caller_envelope("rk", &agent); let resp = invoke(&runtime, env, "federation.resolve_key", q.as_bytes()).await; assert_eq!(resp.error, None, "resolve_key: {:?}", resp.error); let body: serde_json::Value = serde_json::from_slice(&resp.result).unwrap(); - assert_eq!(body["agent_uri"], agent); + assert_eq!(body["agent_ura"], agent); assert_eq!(body["public_key_hex"], "deadbeefcafe"); assert_eq!(body["status"], "active"); } @@ -498,8 +501,8 @@ async fn resolve_default_scope_filters_to_callers_tenant() { // tenant_filter MUST return only silan's agent — the auto-fill // rule scopes the query to the caller's tenant. let runtime = fresh_runtime(); - let agent_silan = "easynet:///r/silan.localhost/agent/silan-node".to_string(); - let agent_alice = "easynet:///r/alice.localhost/agent/alice-node".to_string(); + let agent_silan = "easynet:///r/silan.localhost/agent/silan-node.runtime".to_string(); + let agent_alice = "easynet:///r/alice.localhost/agent/alice-node.runtime".to_string(); seed_directory_agent_with_tenant( &runtime, &agent_silan, @@ -517,7 +520,7 @@ async fn resolve_default_scope_filters_to_callers_tenant() { // we use a URA whose scope segment equals the desired tenant. let caller_env = caller_envelope( "res-scoped", - "easynet:///r/silan.localhost/agent/silan-node", + "easynet:///r/silan.localhost/agent/silan-node.runtime", ); // Empty filter → auto-fill with caller tenant. let resp = invoke(&runtime, caller_env, "federation.resolve", b"{}").await; @@ -527,7 +530,7 @@ async fn resolve_default_scope_filters_to_callers_tenant() { .as_array() .unwrap() .iter() - .map(|v| v["uri"].as_str().unwrap().to_string()) + .map(|v| v["ura"].as_str().unwrap().to_string()) .collect(); assert_eq!(uris.len(), 1, "expected only silan's agent, got {uris:?}"); assert_eq!(uris[0], agent_silan); @@ -539,8 +542,8 @@ async fn resolve_with_wildcard_filter_returns_all_tenants() { // to opt into a cross-tenant catalog listing. Both records // come back. let runtime = fresh_runtime(); - let agent_silan = "easynet:///r/silan.localhost/agent/silan-node".to_string(); - let agent_alice = "easynet:///r/alice.localhost/agent/alice-node".to_string(); + let agent_silan = "easynet:///r/silan.localhost/agent/silan-node.runtime".to_string(); + let agent_alice = "easynet:///r/alice.localhost/agent/alice-node.runtime".to_string(); seed_directory_agent_with_tenant( &runtime, &agent_silan, @@ -553,7 +556,10 @@ async fn resolve_with_wildcard_filter_returns_all_tenants() { "alice-node", Some("alice.localhost"), ); - let caller_env = caller_envelope("res-wild", "easynet:///r/silan.localhost/agent/silan-node"); + let caller_env = caller_envelope( + "res-wild", + "easynet:///r/silan.localhost/agent/silan-node.runtime", + ); let args = r#"{"filter":{"tenant_filter":"*"}}"#; let resp = invoke(&runtime, caller_env, "federation.resolve", args.as_bytes()).await; assert_eq!(resp.error, None); @@ -562,7 +568,7 @@ async fn resolve_with_wildcard_filter_returns_all_tenants() { .as_array() .unwrap() .iter() - .map(|v| v["uri"].as_str().unwrap().to_string()) + .map(|v| v["ura"].as_str().unwrap().to_string()) .collect(); assert_eq!( uris.len(), @@ -574,8 +580,8 @@ async fn resolve_with_wildcard_filter_returns_all_tenants() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn resolve_with_explicit_tenant_filter_returns_only_that_tenant() { let runtime = fresh_runtime(); - let agent_silan = "easynet:///r/silan.localhost/agent/silan-node".to_string(); - let agent_alice = "easynet:///r/alice.localhost/agent/alice-node".to_string(); + let agent_silan = "easynet:///r/silan.localhost/agent/silan-node.runtime".to_string(); + let agent_alice = "easynet:///r/alice.localhost/agent/alice-node.runtime".to_string(); seed_directory_agent_with_tenant( &runtime, &agent_silan, @@ -591,7 +597,7 @@ async fn resolve_with_explicit_tenant_filter_returns_only_that_tenant() { // Silan asks for alice's catalog explicitly. let caller_env = caller_envelope( "res-explicit", - "easynet:///r/silan.localhost/agent/silan-node", + "easynet:///r/silan.localhost/agent/silan-node.runtime", ); let args = r#"{"filter":{"tenant_filter":"alice.localhost"}}"#; let resp = invoke(&runtime, caller_env, "federation.resolve", args.as_bytes()).await; @@ -601,7 +607,7 @@ async fn resolve_with_explicit_tenant_filter_returns_only_that_tenant() { .as_array() .unwrap() .iter() - .map(|v| v["uri"].as_str().unwrap().to_string()) + .map(|v| v["ura"].as_str().unwrap().to_string()) .collect(); assert_eq!(uris.len(), 1); assert_eq!(uris[0], agent_alice); @@ -610,8 +616,9 @@ async fn resolve_with_explicit_tenant_filter_returns_only_that_tenant() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn resolve_key_returns_typed_error_for_unknown_agent() { let runtime = fresh_runtime(); - let q = serde_json::json!({ "agent_uri": "easynet:///r/exp-realm/agent/ghost" }).to_string(); - let env = caller_envelope("rk-ghost", "easynet:///r/exp-realm/agent/seeker"); + let q = serde_json::json!({ "agent_ura": "easynet:///r/exp-realm/agent/ghost.runtime" }) + .to_string(); + let env = caller_envelope("rk-ghost", "easynet:///r/exp-realm/agent/seeker.runtime"); let resp = invoke(&runtime, env, "federation.resolve_key", q.as_bytes()).await; let err = resp.error.expect("must fail"); assert_eq!(err.code, "AXON_AGENT_NOT_IN_DIRECTORY"); diff --git a/core/runtime-rs/src/tests/grpc_multi_shard_e2e.rs b/core/runtime-rs/src/tests/grpc_multi_shard_e2e.rs index a3e9d986..edf3710d 100644 --- a/core/runtime-rs/src/tests/grpc_multi_shard_e2e.rs +++ b/core/runtime-rs/src/tests/grpc_multi_shard_e2e.rs @@ -44,11 +44,11 @@ fn fresh_runtime() -> AxonRuntime { AxonRuntime::new(Arc::new(state)) } -fn caller_envelope(uri: &str) -> Option { +fn caller_envelope(ura: &str) -> Option { Some(pb::Envelope { request_id: "grpc-cluster".into(), caller: Some(pb::AgentIdentity { - uri: uri.into(), + ura: ura.into(), ..Default::default() }), ..Default::default() @@ -150,7 +150,7 @@ async fn register_local_tool_for( "spec_proto_b64": "", }) .to_string(); - let env = caller_envelope(&format!("easynet:///r/{tenant}/agent/{node_id}")); + let env = caller_envelope(&format!("easynet:///r/{tenant}/agent/{node_id}.runtime")); let req = pb::InvokeRequest { envelope: env, target: Some(pb::InvocationTarget { @@ -174,7 +174,7 @@ async fn register_local_tool_for( metadata: { let mut m = std::collections::HashMap::new(); m.insert( - "easynet.resource_uri".into(), + "easynet.resource_ura".into(), format!("easynet:///r/{tenant}/ability/hub.runtime.register_local_tool"), ); m @@ -189,9 +189,9 @@ async fn register_local_tool_for( assert_eq!(resp.error, None, "register_local_tool: {:?}", resp.error); } -fn seed_agent(runtime: &AxonRuntime, uri: &str, host_node_id: &str, tenant: Option<&str>) { +fn seed_agent(runtime: &AxonRuntime, ura: &str, host_node_id: &str, tenant: Option<&str>) { runtime.state.agents.insert(AgentRecord { - uri: uri.to_string(), + ura: ura.to_string(), public_key: Vec::new(), signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -224,13 +224,13 @@ async fn cross_shard_chat_round_trip_over_real_grpc() { }) .await; - let target_uri = "easynet:///r/silan.pi/agent/pi-rasp"; + let target_ura = "easynet:///r/silan.pi/agent/pi-rasp.runtime"; register_local_tool_for(&s_a, "silan.pi", "pi-rasp", "chat.echo", &endpoint).await; - seed_agent(&s_a, target_uri, "pi-rasp", Some("silan.pi")); + seed_agent(&s_a, target_ura, "pi-rasp", Some("silan.pi")); // Shard-B: caller agent seeded so the local membership gate passes. - let caller_uri = "easynet:///r/silan.laptop/agent/laptop-mac"; - seed_agent(&s_b, caller_uri, "laptop-mac", Some("silan.laptop")); + let caller_ura = "easynet:///r/silan.laptop/agent/laptop-mac.runtime"; + seed_agent(&s_b, caller_ura, "laptop-mac", Some("silan.laptop")); // Shard-A also needs to know the caller exists, otherwise its // membership gate rejects the inbound forward_invoke before it @@ -238,7 +238,7 @@ async fn cross_shard_chat_round_trip_over_real_grpc() { // bootstraps this by replicating directory snapshots between // shards (federation.subscribe_directory) — for the test we // pre-seed the same caller record on both sides. - seed_agent(&s_a, caller_uri, "laptop-mac", Some("silan.laptop")); + seed_agent(&s_a, caller_ura, "laptop-mac", Some("silan.laptop")); // Wire shard-B's resolver: silan.pi lives on addr_a (shard-A's // gRPC URL). silan.laptop is local to shard-B. @@ -258,13 +258,13 @@ async fn cross_shard_chat_round_trip_over_real_grpc() { // real HTTP/2, gets back the wrapped receipt, returns it. let chat_args = serde_json::json!({"message": "hello-cross-network"}); let forward_args = serde_json::json!({ - "target_uri": target_uri, + "target_ura": target_ura, "ability_name": "chat.echo", "function_name": "", "arguments_b64": B64.encode(&serde_json::to_vec(&chat_args).unwrap()), }) .to_string(); - let env = caller_envelope(caller_uri); + let env = caller_envelope(caller_ura); let req = pb::InvokeRequest { envelope: env, target: Some(pb::InvocationTarget { @@ -323,7 +323,7 @@ async fn grpc_dispatcher_returns_typed_error_on_unknown_endpoint() { let req = ForwardRequest { endpoint: "http://127.0.0.1:1".into(), envelope: pb::Envelope::default(), - target_uri: "x".into(), + target_ura: "x".into(), ability_name: "y".into(), function_name: String::new(), arguments_b64: String::new(), diff --git a/core/runtime-rs/src/tests/identity.rs b/core/runtime-rs/src/tests/identity.rs index d7d15709..8432b445 100644 --- a/core/runtime-rs/src/tests/identity.rs +++ b/core/runtime-rs/src/tests/identity.rs @@ -1366,13 +1366,13 @@ async fn invoke_accepts_valid_easynet_signed_metadata() { let request_id = "invoke-easynet-ok"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test"; let metadata = easynet_metadata_signed( request_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-easynet-ok", ); @@ -1383,7 +1383,7 @@ async fn invoke_accepts_valid_easynet_signed_metadata() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1416,12 +1416,12 @@ async fn invoke_accepts_valid_easynet_signed_metadata() { } #[tokio::test] -async fn invoke_rejects_legacy_authority_resource_uri_forms() { +async fn invoke_rejects_legacy_authority_resource_ura_forms() { let runtime = test_runtime(); let _ = setup_node_and_tool(&runtime).await; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - for (request_id, resource_uri, nonce_seed) in [ + for (request_id, resource_ura, nonce_seed) in [ ( "invoke-easynet-legacy-r-authority", "easynet://r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test", @@ -1433,14 +1433,14 @@ async fn invoke_rejects_legacy_authority_resource_uri_forms() { b"nonce-legacy-agent-authority".as_slice(), ), ] { - // Use raw URI helper: these are intentionally malformed legacy URIs that + // Use raw URI helper: these are intentionally malformed noncanonical URIs that // the canonicalizer rejects; we need uncanonicalized metadata to test // that the runtime properly rejects them. let metadata = easynet_metadata_signed_raw_uri( request_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), nonce_seed, ); @@ -1450,7 +1450,7 @@ async fn invoke_rejects_legacy_authority_resource_uri_forms() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1481,9 +1481,9 @@ async fn invoke_rejects_legacy_authority_resource_uri_forms() { assert_eq!( resp.error .as_ref() - .expect("legacy authority forms must be rejected") + .expect("noncanonical authority forms must be rejected") .code, - ERR_EASYNET_RESOURCE_URI_INVALID + ERR_EASYNET_RESOURCE_URA_INVALID ); } } @@ -1495,12 +1495,12 @@ async fn invoke_accepts_pub_resource_with_non_empty_tenant() { let request_id = "invoke-easynet-pub-tenant"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = "easynet:///r/pub/reg/agent.alice/abilities/web_search@1.0.0"; + let resource_ura = "easynet:///r/pub/reg/agent.alice/abilities/web_search@1.0.0"; let metadata = easynet_metadata_signed( request_id, "tenant-test", "easynet:pub:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-easynet-pub-tenant", ); @@ -1511,7 +1511,7 @@ async fn invoke_accepts_pub_resource_with_non_empty_tenant() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1550,7 +1550,7 @@ async fn invoke_rejects_pub_resource_with_empty_tenant() { let request_id = "invoke-easynet-pub-empty-tenant"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = "easynet:///r/pub/reg/agent.alice/abilities/web_search@1.0.0"; + let resource_ura = "easynet:///r/pub/reg/agent.alice/abilities/web_search@1.0.0"; // Use raw URI helper: empty tenant_id is intentionally invalid for pub URIs, // so the canonicalizer rejects it. We construct uncanonicalized metadata to // test that the runtime properly rejects this at verification time. @@ -1558,7 +1558,7 @@ async fn invoke_rejects_pub_resource_with_empty_tenant() { request_id, "", "easynet:pub:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-easynet-pub-empty-tenant", ); @@ -1569,7 +1569,7 @@ async fn invoke_rejects_pub_resource_with_empty_tenant() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r//agents/alice".to_string(), + ura: "easynet:///r//agent/alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1613,13 +1613,13 @@ async fn invoke_rejects_easynet_subject_namespace_spoof_for_agent_authority() { let request_id = "invoke-easynet-subject-spoof"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test"; let metadata = easynet_metadata_signed( request_id, "tenant-test", "spoof:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-easynet-spoof", ); @@ -1630,7 +1630,7 @@ async fn invoke_rejects_easynet_subject_namespace_spoof_for_agent_authority() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1702,13 +1702,13 @@ async fn invoke_rejects_derived_subject_key_after_owner_rotates_to_registered_ke let request_id = "invoke-easynet-derived-untrusted"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test"; let metadata = easynet_metadata_signed( request_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-derived-untrusted", ); @@ -1719,7 +1719,7 @@ async fn invoke_rejects_derived_subject_key_after_owner_rotates_to_registered_ke envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1762,13 +1762,13 @@ async fn invoke_rejects_subject_when_owner_key_not_registered() { let request_id = "invoke-easynet-owner-key-unregistered"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.legacy-owner/abilities/web_search@1.0.0?tenant_id=tenant-test"; let metadata = easynet_metadata_signed( request_id, "tenant-test", "easynet:org:reg:agent.legacy-owner", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-owner-key-unregistered", ); @@ -1779,7 +1779,7 @@ async fn invoke_rejects_subject_when_owner_key_not_registered() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/legacy-owner".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.legacy-owner".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1839,13 +1839,13 @@ async fn invoke_rejects_ed25519_key_when_no_active_ed25519_version_exists() { let request_id = "invoke-easynet-no-active-ed25519"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test"; let metadata = easynet_metadata_signed( request_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-no-active-ed25519", ); @@ -1856,7 +1856,7 @@ async fn invoke_rejects_ed25519_key_when_no_active_ed25519_version_exists() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1901,13 +1901,13 @@ async fn invoke_rejects_ed25519_key_when_node_key_history_is_missing() { let request_id = "invoke-easynet-missing-node-key-history"; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test"; let metadata = easynet_metadata_signed( request_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-missing-node-key-history", ); @@ -1918,7 +1918,7 @@ async fn invoke_rejects_ed25519_key_when_node_key_history_is_missing() { envelope: Some(pb::Envelope { request_id: request_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1961,7 +1961,7 @@ async fn invoke_rejects_easynet_nonce_replay() { let _ = setup_node_and_tool(&runtime).await; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test"; let req1_id = "invoke-easynet-replay-1"; @@ -1969,7 +1969,7 @@ async fn invoke_rejects_easynet_nonce_replay() { req1_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-replay", ); @@ -1979,7 +1979,7 @@ async fn invoke_rejects_easynet_nonce_replay() { envelope: Some(pb::Envelope { request_id: req1_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2012,7 +2012,7 @@ async fn invoke_rejects_easynet_nonce_replay() { req2_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-replay", ); @@ -2022,7 +2022,7 @@ async fn invoke_rejects_easynet_nonce_replay() { envelope: Some(pb::Envelope { request_id: req2_id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() diff --git a/core/runtime-rs/src/tests/invocation.rs b/core/runtime-rs/src/tests/invocation.rs index 8b8c294b..71609819 100644 --- a/core/runtime-rs/src/tests/invocation.rs +++ b/core/runtime-rs/src/tests/invocation.rs @@ -338,7 +338,7 @@ async fn invoke_replays_completed_result_for_same_idempotency_key() { request_id: req_id.to_string(), idempotency_key: "idem-key-1".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -407,7 +407,7 @@ async fn invoke_rejects_idempotency_key_reuse_for_different_request() { request_id: req_id.to_string(), idempotency_key: "idem-mismatch-key".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -492,7 +492,7 @@ async fn invoke_idempotency_key_is_scoped_by_tenant_and_principal() { request_id: req_id.to_string(), idempotency_key: "idem-scope-key".to_string(), caller: Some(pb::AgentIdentity { - uri: format!("easynet:///r/{tenant_id}/agents/{principal_id}"), + ura: format!("easynet:///r/{tenant_id}/agent/{principal_id}.runtime"), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -601,7 +601,7 @@ async fn invoke_idempotent_rate_limited_failure_is_replayed() { request_id: req_id.to_string(), idempotency_key: "idem-rate-limit-key".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -658,7 +658,7 @@ async fn invoke_async_rejects_idempotency_key_reuse_for_different_request() { request_id: req_id.to_string(), idempotency_key: "async-idem-mismatch-key".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -745,7 +745,7 @@ async fn invoke_concurrent_idempotency_mismatch_rejects_one_request() { request_id: req_id.to_string(), idempotency_key: "idem-concurrent-key".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -843,7 +843,7 @@ async fn invoke_allows_reuse_after_idempotency_window_expires() { request_id: req_id.to_string(), idempotency_key: "idem-window-key".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -899,7 +899,7 @@ async fn invoke_idempotent_replay_waits_for_terminal_state() { request_id: "invoke-idem-wait".to_string(), idempotency_key: idempotency_key.clone(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -994,7 +994,7 @@ async fn replay_result_reports_expired_window_reason_and_cleans_stale_index() { Some(&pb::Envelope { request_id: "replay-expired-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1074,7 +1074,7 @@ async fn replay_result_reports_in_progress_reason() { Some(&pb::Envelope { request_id: "replay-pending-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1160,7 +1160,7 @@ async fn replay_result_expired_cleanup_does_not_delete_newer_fingerprint_owner() Some(&pb::Envelope { request_id: "replay-expired-owner-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1234,7 +1234,7 @@ async fn replay_result_without_index_recovers_from_fingerprint_and_repairs_index Some(&pb::Envelope { request_id: "replay-missing-index-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1308,7 +1308,7 @@ async fn replay_result_without_authoritative_mappings_returns_not_found() { Some(&pb::Envelope { request_id: "replay-fallback-scan-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1367,7 +1367,7 @@ async fn replay_result_cleans_stale_fingerprint_owner_without_invocation() { Some(&pb::Envelope { request_id: "replay-stale-fingerprint-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1421,7 +1421,7 @@ async fn compare_delete_idempotency_index_does_not_remove_new_mapping_when_expec Some(&pb::Envelope { request_id: "compare-delete-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1463,7 +1463,7 @@ async fn sweep_terminal_invocations_removes_expired_records_aliases_and_indexes( Some(&pb::Envelope { request_id: "inv-sweep-expired-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1573,7 +1573,7 @@ async fn sweep_terminal_invocations_preserves_newer_idempotency_mapping() { Some(&pb::Envelope { request_id: "inv-sweep-preserve-envelope".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1782,7 +1782,7 @@ async fn invoke_async_populates_idempotency_replay_index() { request_id: "invoke-async-idem-1".to_string(), idempotency_key: "async-idem-key-1".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1869,7 +1869,7 @@ async fn invoke_async_idempotent_rate_limited_failure_is_replayed() { request_id: req_id.to_string(), idempotency_key: "async-idem-rate-key".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -1935,7 +1935,7 @@ async fn invoke_async_reuses_inflight_idempotent_invocation_once_visible() { request_id: "invoke-async-reuse".to_string(), idempotency_key: idempotency_key.clone(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2020,7 +2020,7 @@ async fn invoke_async_reuses_inflight_idempotent_invocation_with_delayed_visibil request_id: "invoke-async-reuse-delayed".to_string(), idempotency_key: idempotency_key.clone(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2106,7 +2106,7 @@ async fn invoke_async_inflight_pending_publication_returns_auditable_failure() { request_id: "invoke-async-pending-publication".to_string(), idempotency_key: idempotency_key.clone(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2175,7 +2175,7 @@ async fn invoke_inflight_pending_publication_returns_auditable_failure() { request_id: "invoke-sync-pending-publication".to_string(), idempotency_key: idempotency_key.clone(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2343,7 +2343,7 @@ async fn invoke_supports_encrypted_payload_round_trip() { .unwrap() .into_inner(); assert!(!kex.session_key_id.is_empty()); - let key_ref = format!("axon://keys/session/{}", kex.session_key_id); + let key_ref = format!("easynet:///r/local/resource/session-key/{}", kex.session_key_id); let encrypted_args = runtime .encrypt_bytes_with_session_key( EncryptionAlgorithm::Aes256Gcm as i32, @@ -2375,7 +2375,7 @@ async fn invoke_supports_encrypted_payload_round_trip() { content_envelope: Some(pb::ContentEnvelope { content_type: "application/json".to_string(), encoding: "identity".to_string(), - schema_uri: String::new(), + schema_ura: String::new(), meta: None, encryption: EncryptionAlgorithm::Aes256Gcm as i32, key_id: key_ref.clone(), @@ -2411,7 +2411,7 @@ async fn invoke_async_encrypted_payload_requires_request_id() { envelope: Some(pb::Envelope { request_id: String::new(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2436,10 +2436,10 @@ async fn invoke_async_encrypted_payload_requires_request_id() { content_envelope: Some(pb::ContentEnvelope { content_type: "application/json".to_string(), encoding: "identity".to_string(), - schema_uri: String::new(), + schema_ura: String::new(), meta: None, encryption: EncryptionAlgorithm::Aes256Gcm as i32, - key_id: "axon://keys/session/key-test".to_string(), + key_id: "easynet:///r/local/resource/session-key/key-test".to_string(), }), }), ) @@ -2465,7 +2465,7 @@ async fn invoke_server_stream_encrypted_payload_requires_request_id() { envelope: Some(pb::Envelope { request_id: String::new(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2488,10 +2488,10 @@ async fn invoke_server_stream_encrypted_payload_requires_request_id() { content_envelope: Some(pb::ContentEnvelope { content_type: "application/json".to_string(), encoding: "identity".to_string(), - schema_uri: String::new(), + schema_ura: String::new(), meta: None, encryption: EncryptionAlgorithm::Aes256Gcm as i32, - key_id: "axon://keys/session/key-test".to_string(), + key_id: "easynet:///r/local/resource/session-key/key-test".to_string(), }), }), ) @@ -2517,7 +2517,7 @@ async fn invoke_idempotent_easynet_retry_with_fresh_nonce_is_accepted() { let _ = setup_node_and_tool(&runtime).await; let payload = br#"{"sku":"A1","qty":2}"#.to_vec(); - let resource_uri = + let resource_ura = "easynet:///r/org/reg/agent.alice/abilities/web_search@1.0.0?tenant_id=tenant-test"; let idempotency_key = "idem-easynet-fresh-nonce"; @@ -2526,7 +2526,7 @@ async fn invoke_idempotent_easynet_retry_with_fresh_nonce_is_accepted() { req1_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-idem-1", ); @@ -2537,7 +2537,7 @@ async fn invoke_idempotent_easynet_retry_with_fresh_nonce_is_accepted() { request_id: req1_id.to_string(), idempotency_key: idempotency_key.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2571,7 +2571,7 @@ async fn invoke_idempotent_easynet_retry_with_fresh_nonce_is_accepted() { req2_id, "tenant-test", "easynet:org:reg:agent.alice", - resource_uri, + resource_ura, payload.as_slice(), b"nonce-idem-2", ); @@ -2582,7 +2582,7 @@ async fn invoke_idempotent_easynet_retry_with_fresh_nonce_is_accepted() { request_id: req2_id.to_string(), idempotency_key: idempotency_key.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/alice".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.alice".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2624,7 +2624,7 @@ async fn stress_idempotency_index_eviction_under_load() { request_id: req_id.to_string(), idempotency_key: idem_key.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2681,7 +2681,7 @@ async fn idempotency_fingerprint_remains_authoritative_after_hot_index_eviction( request_id: req_id.to_string(), idempotency_key: idem_key.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2733,7 +2733,7 @@ async fn idempotency_fingerprint_remains_authoritative_after_hot_index_eviction( Some(&pb::Envelope { request_id: "idem-authoritative-replay".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -2935,7 +2935,7 @@ async fn idempotency_metrics_snapshot_uses_named_fields() { Some(&pb::Envelope { request_id: "field-test".to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() diff --git a/core/runtime-rs/src/tests/mod.rs b/core/runtime-rs/src/tests/mod.rs index 21311efc..1444b80d 100644 --- a/core/runtime-rs/src/tests/mod.rs +++ b/core/runtime-rs/src/tests/mod.rs @@ -171,7 +171,7 @@ fn envelope(id: &str) -> Option { Some(pb::Envelope { request_id: id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -182,7 +182,7 @@ fn envelope_with_principal(id: &str, principal_id: &str) -> Option Some(pb::Envelope { request_id: id.to_string(), caller: Some(pb::AgentIdentity { - uri: format!("easynet:///r/tenant-test/agents/{principal_id}"), + ura: format!("easynet:///r/tenant-test/agent/{principal_id}.runtime"), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -193,7 +193,7 @@ fn envelope_with_priority(id: &str, priority: i32) -> Option { Some(pb::Envelope { request_id: id.to_string(), caller: Some(pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), priority, @@ -205,7 +205,7 @@ fn envelope_for_tenant(id: &str, tenant_id: &str, principal_id: &str) -> Option< Some(pb::Envelope { request_id: id.to_string(), caller: Some(pb::AgentIdentity { - uri: format!("easynet:///r/{tenant_id}/agents/{principal_id}"), + ura: format!("easynet:///r/{tenant_id}/agent/{principal_id}.runtime"), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -258,7 +258,7 @@ fn grpc_envelope(id: &str) -> Option { Some(grpc_pb::Envelope { request_id: id.to_string(), caller: Some(grpc_pb::AgentIdentity { - uri: "easynet:///r/tenant-test/agents/tester".to_string(), + ura: "easynet:///r/tenant-test/agent/tenant-test.tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -275,10 +275,14 @@ fn seed_capability_payload( std::fs::create_dir_all(&store_dir).expect("create test payload store"); let file_path = store_dir.join(format!("{payload_id}.bin")); std::fs::write(&file_path, bytes).expect("write test payload file"); - let uri = format!("axon://payloads/{payload_id}"); + let uri = easynet_run_axon_client::ura::payload_resource_ura( + tenant_id, + &format!("user.{tenant_id}"), + payload_id, + ); let digest = format!("sha256:{}", AxonRuntime::sha256_hex(bytes)); let payload_ref = pb::PayloadRef { - uri: uri.clone(), + ura: uri.clone(), digest, size_bytes: bytes.len() as i64, content: None, @@ -304,12 +308,12 @@ fn capability_package_fingerprint( package_id: &str, version: &str, payload_digest: &str, - payload_uri: &str, + payload_ura: &str, payload_size_bytes: i64, signature_fingerprint: &str, ) -> String { let canonical = format!( - "{package_id}\n{version}\n{payload_digest}\n{payload_uri}\n{payload_size_bytes}\n{signature_fingerprint}" + "{package_id}\n{version}\n{payload_digest}\n{payload_ura}\n{payload_size_bytes}\n{signature_fingerprint}" ); format!("sha256:{}", AxonRuntime::sha256_hex(canonical.as_bytes())) } @@ -325,12 +329,12 @@ fn capability_package_proof( package_id, version, payload_ref.digest.as_str(), - payload_ref.uri.as_str(), + payload_ref.ura.as_str(), payload_ref.size_bytes, signature_fingerprint.as_str(), ); pb::CapabilityPackageProof { - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), payload_digest: payload_ref.digest.clone(), payload_size_bytes: payload_ref.size_bytes, signature_fingerprint, @@ -442,7 +446,7 @@ fn easynet_metadata_signed( request_id: &str, tenant_id: &str, subject_id: &str, - resource_uri: &str, + resource_ura: &str, payload: &[u8], nonce_seed: &[u8], ) -> std::collections::HashMap { @@ -451,7 +455,7 @@ fn easynet_metadata_signed( request_id, tenant_id, subject_id, - resource_uri, + resource_ura, payload, nonce_seed, &auth, @@ -462,7 +466,7 @@ fn easynet_metadata_signed_raw_uri( request_id: &str, tenant_id: &str, subject_id: &str, - resource_uri: &str, + resource_ura: &str, payload: &[u8], nonce_seed: &[u8], ) -> std::collections::HashMap { @@ -471,7 +475,7 @@ fn easynet_metadata_signed_raw_uri( request_id, tenant_id, subject_id, - resource_uri, + resource_ura, payload, nonce_seed, &auth, @@ -482,7 +486,7 @@ fn easynet_metadata_signed_with_auth( request_id: &str, tenant_id: &str, subject_id: &str, - resource_uri: &str, + resource_ura: &str, payload: &[u8], nonce_seed: &[u8], auth: &EasyNetUserAuth, @@ -497,8 +501,8 @@ fn easynet_metadata_signed_with_auth( let nonce_b64 = URL_SAFE_NO_PAD.encode(nonce); let payload_sha = AxonRuntime::sha256_hex(payload); let issued_at = now_unix_ms(); - let canonical_uri = SdkClient::canonicalize_easynet_resource_uri(resource_uri, tenant_id) - .expect("resource URI should canonicalize in test helper"); + let canonical_uri = SdkClient::canonicalize_easynet_resource_ura(resource_ura, tenant_id) + .expect("resource URA should canonicalize in test helper"); let issued_at_text = issued_at.to_string(); let signing_key = SigningKey::from_bytes(&auth.private_key); @@ -517,7 +521,7 @@ fn easynet_metadata_signed_with_auth( std::collections::HashMap::from([ ("easynet.envelope_version".to_string(), "1".to_string()), ("easynet.subject_id".to_string(), subject_id.to_string()), - ("easynet.resource_uri".to_string(), canonical_uri), + ("easynet.resource_ura".to_string(), canonical_uri), ( "easynet.issued_at_unix_ms".to_string(), issued_at.to_string(), @@ -539,7 +543,7 @@ fn easynet_metadata_signed_raw_uri_with_auth( request_id: &str, tenant_id: &str, subject_id: &str, - resource_uri: &str, + resource_ura: &str, payload: &[u8], nonce_seed: &[u8], auth: &EasyNetUserAuth, @@ -562,7 +566,7 @@ fn easynet_metadata_signed_raw_uri_with_auth( request_id, subject_id, tenant_id, - resource_uri, + resource_ura, &issued_at_text, &nonce_b64, &payload_sha, @@ -572,7 +576,7 @@ fn easynet_metadata_signed_raw_uri_with_auth( std::collections::HashMap::from([ ("easynet.envelope_version".to_string(), "1".to_string()), ("easynet.subject_id".to_string(), subject_id.to_string()), - ("easynet.resource_uri".to_string(), resource_uri.to_string()), + ("easynet.resource_ura".to_string(), resource_ura.to_string()), ( "easynet.issued_at_unix_ms".to_string(), issued_at.to_string(), diff --git a/core/runtime-rs/src/tests/multi_shard_e2e.rs b/core/runtime-rs/src/tests/multi_shard_e2e.rs index 1e9b97e3..af9effe7 100644 --- a/core/runtime-rs/src/tests/multi_shard_e2e.rs +++ b/core/runtime-rs/src/tests/multi_shard_e2e.rs @@ -52,11 +52,11 @@ fn spawn_runtime() -> AxonRuntime { AxonRuntime::new(Arc::new(state)) } -fn caller_envelope(uri: &str) -> Option { +fn caller_envelope(ura: &str) -> Option { Some(pb::Envelope { request_id: "fwd-cluster".into(), caller: Some(pb::AgentIdentity { - uri: uri.into(), + ura: ura.into(), ..Default::default() }), ..Default::default() @@ -102,9 +102,9 @@ async fn invoke( .into_inner() } -fn seed_agent(runtime: &AxonRuntime, uri: &str, host_node_id: &str, tenant: Option<&str>) { +fn seed_agent(runtime: &AxonRuntime, ura: &str, host_node_id: &str, tenant: Option<&str>) { runtime.state.agents.insert(AgentRecord { - uri: uri.to_string(), + ura: ura.to_string(), public_key: Vec::new(), signing_authority: SigningAuthority::Selfsigned, status: AgentStatus::Active, @@ -277,7 +277,7 @@ async fn register_local_tool_for( "spec_proto_b64": "", }) .to_string(); - let env = caller_envelope(&format!("easynet:///r/{tenant}/agent/{node_id}")); + let env = caller_envelope(&format!("easynet:///r/{tenant}/agent/{node_id}.runtime")); let req = pb::InvokeRequest { envelope: env, target: Some(pb::InvocationTarget { @@ -301,7 +301,7 @@ async fn register_local_tool_for( metadata: { let mut m = std::collections::HashMap::new(); m.insert( - "easynet.resource_uri".into(), + "easynet.resource_ura".into(), format!("easynet:///r/{tenant}/ability/hub.runtime.register_local_tool"), ); m @@ -336,11 +336,11 @@ fn single_tenant_two_shard_cluster( // live on shard-pi. Realm-to-shard mapping uses a synthetic // sub-realm (`silan.localhost/laptop` vs // `silan.localhost/pi`) so the shard resolver can disambiguate - // by URI prefix when a cross-device target is invoked. + // by URA prefix when a cross-device target is invoked. // // Production deployments would use a different sharding key // (consistent hash on node_id, etc.); for the test the static - // map is enough — `parse_realm_from_target_uri` reads the URA + // map is enough — `parse_realm_from_target_ura` reads the URA // realm segment which we set to the sub-realm form. let r_laptop = Arc::new(StaticShardResolver::new("shard-laptop")); r_laptop.map_realm("silan.laptop", vec!["shard-laptop".into()]); @@ -390,13 +390,13 @@ async fn single_tenant_cross_shard_chat_round_trip() { }) .await; - let pi_target = "easynet:///r/silan.pi/agent/pi-rasp"; + let pi_target = "easynet:///r/silan.pi/agent/pi-rasp.runtime"; register_local_tool_for(&s_pi, "silan.pi", "pi-rasp", "chat.echo", &endpoint).await; seed_agent(&s_pi, pi_target, "pi-rasp", Some("silan.pi")); // laptop is also a member so its caller URA passes the // membership gate on shard-laptop. - let laptop_uri = "easynet:///r/silan.laptop/agent/laptop-mac"; + let laptop_uri = "easynet:///r/silan.laptop/agent/laptop-mac.runtime"; seed_agent(&s_laptop, laptop_uri, "laptop-mac", Some("silan.laptop")); // Build the cross-shard forward call. caller is laptop, @@ -406,7 +406,7 @@ async fn single_tenant_cross_shard_chat_round_trip() { let chat_args = serde_json::json!({"message": "hello world"}); let chat_args_bytes = serde_json::to_vec(&chat_args).unwrap(); let forward_args = serde_json::json!({ - "target_uri": pi_target, + "target_ura": pi_target, "ability_name": "chat.echo", "function_name": "", "arguments_b64": B64.encode(&chat_args_bytes), @@ -463,15 +463,15 @@ async fn single_tenant_cross_shard_chat_propagates_target_handler_error() { }) .await; - let pi_target = "easynet:///r/silan.pi/agent/pi-rasp"; + let pi_target = "easynet:///r/silan.pi/agent/pi-rasp.runtime"; register_local_tool_for(&s_pi, "silan.pi", "pi-rasp", "chat.echo", &endpoint).await; seed_agent(&s_pi, pi_target, "pi-rasp", Some("silan.pi")); - let laptop_uri = "easynet:///r/silan.laptop/agent/laptop-mac"; + let laptop_uri = "easynet:///r/silan.laptop/agent/laptop-mac.runtime"; seed_agent(&s_laptop, laptop_uri, "laptop-mac", Some("silan.laptop")); let chat_args = serde_json::json!({"message": "any"}); let forward_args = serde_json::json!({ - "target_uri": pi_target, + "target_ura": pi_target, "ability_name": "chat.echo", "arguments_b64": B64.encode(&serde_json::to_vec(&chat_args).unwrap()), }) @@ -529,10 +529,10 @@ async fn cross_shard_forward_preserves_caller_signature_unchanged() { }) .await; - let pi_target = "easynet:///r/silan.pi/agent/pi-rasp"; + let pi_target = "easynet:///r/silan.pi/agent/pi-rasp.runtime"; register_local_tool_for(&s_pi, "silan.pi", "pi-rasp", "chat.echo", &endpoint).await; seed_agent(&s_pi, pi_target, "pi-rasp", Some("silan.pi")); - let laptop_uri = "easynet:///r/silan.laptop/agent/laptop-mac"; + let laptop_uri = "easynet:///r/silan.laptop/agent/laptop-mac.runtime"; seed_agent(&s_laptop, laptop_uri, "laptop-mac", Some("silan.laptop")); // A message with leading/trailing whitespace + a 4-byte UTF-8 @@ -542,7 +542,7 @@ async fn cross_shard_forward_preserves_caller_signature_unchanged() { let local_byte_len = probe.len(); // 16 bytes (your-good = 6 bytes + space + world + 4 spaces) let chat_args = serde_json::json!({"message": probe}); let forward_args = serde_json::json!({ - "target_uri": pi_target, + "target_ura": pi_target, "ability_name": "chat.echo", "arguments_b64": B64.encode(&serde_json::to_vec(&chat_args).unwrap()), }) @@ -575,7 +575,7 @@ async fn cross_shard_forward_invoke_routes_through_hub_to_hub() { // Target lives on shard-1 (silan.localhost). // s1 also needs the local-tool registered for the dispatch // path on the other side — register a fake UDS endpoint. - let target_uri = "easynet:///r/silan.localhost/agent/silan-laptop"; + let target_ura = "easynet:///r/silan.localhost/agent/silan-laptop.runtime"; let endpoint = spawn_endpoint( "x-shard", serde_json::json!({"echo": "from-silan", "via": "shard-1"}), @@ -591,7 +591,7 @@ async fn cross_shard_forward_invoke_routes_through_hub_to_hub() { "spec_proto_b64": "", }) .to_string(); - let env_local = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop"); + let env_local = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop.runtime"); let req = pb::InvokeRequest { envelope: env_local, target: Some(pb::InvocationTarget { @@ -615,7 +615,7 @@ async fn cross_shard_forward_invoke_routes_through_hub_to_hub() { metadata: { let mut m = std::collections::HashMap::new(); m.insert( - "easynet.resource_uri".into(), + "easynet.resource_ura".into(), "easynet:///r/silan.localhost/ability/hub.runtime.register_local_tool".into(), ); m @@ -629,7 +629,7 @@ async fn cross_shard_forward_invoke_routes_through_hub_to_hub() { .into_inner(); assert_eq!(resp.error, None, "register_local_tool: {:?}", resp.error); - seed_agent(&s1, target_uri, "silan-laptop", Some("silan.localhost")); + seed_agent(&s1, target_ura, "silan-laptop", Some("silan.localhost")); // Caller homed on shard-3 issues forward_invoke. shard-3 // doesn't have the target in its local directory, so @@ -638,20 +638,20 @@ async fn cross_shard_forward_invoke_routes_through_hub_to_hub() { // locally, and the receipt comes back. seed_agent( &s3, - "easynet:///r/bob.localhost/agent/bob-pi", + "easynet:///r/bob.localhost/agent/bob-pi.runtime", "bob-pi", Some("bob.localhost"), ); let target_args = serde_json::json!({"hello": "from-bob"}); let target_args_bytes = serde_json::to_vec(&target_args).unwrap(); let forward_args = serde_json::json!({ - "target_uri": target_uri, + "target_ura": target_ura, "ability_name": "ping", "function_name": "", "arguments_b64": B64.encode(&target_args_bytes), }) .to_string(); - let env_bob = caller_envelope("easynet:///r/bob.localhost/agent/bob-pi"); + let env_bob = caller_envelope("easynet:///r/bob.localhost/agent/bob-pi.runtime"); let resp = invoke( &s3, env_bob, @@ -682,19 +682,19 @@ async fn cross_shard_resolve_public_fans_out_and_merges() { seed_agent( &s1, - "easynet:///r/silan.localhost/agent/silan-laptop", + "easynet:///r/silan.localhost/agent/silan-laptop.runtime", "silan-laptop", Some("silan.localhost"), ); seed_agent( &s2, - "easynet:///r/alice.localhost/agent/alice-phone", + "easynet:///r/alice.localhost/agent/alice-phone.runtime", "alice-phone", Some("alice.localhost"), ); seed_agent( &s3, - "easynet:///r/bob.localhost/agent/bob-pi", + "easynet:///r/bob.localhost/agent/bob-pi.runtime", "bob-pi", Some("bob.localhost"), ); @@ -703,7 +703,7 @@ async fn cross_shard_resolve_public_fans_out_and_merges() { // Each shard receives the same arguments and contributes its // local agents. let args = r#"{"filter":{"tenant_filter":"*"}}"#; - let env_silan = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop"); + let env_silan = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop.runtime"); let resp = invoke(&s1, env_silan, "federation.resolve", args.as_bytes()).await; assert_eq!(resp.error, None, "resolve fan-out: {:?}", resp.error); let body: serde_json::Value = serde_json::from_slice(&resp.result).unwrap(); @@ -711,18 +711,18 @@ async fn cross_shard_resolve_public_fans_out_and_merges() { .as_array() .unwrap() .iter() - .map(|v| v["uri"].as_str().unwrap().to_string()) + .map(|v| v["ura"].as_str().unwrap().to_string()) .collect(); assert!( - uris.contains("easynet:///r/silan.localhost/agent/silan-laptop"), + uris.contains("easynet:///r/silan.localhost/agent/silan-laptop.runtime"), "missing silan: {uris:?}" ); assert!( - uris.contains("easynet:///r/alice.localhost/agent/alice-phone"), + uris.contains("easynet:///r/alice.localhost/agent/alice-phone.runtime"), "missing alice: {uris:?}" ); assert!( - uris.contains("easynet:///r/bob.localhost/agent/bob-pi"), + uris.contains("easynet:///r/bob.localhost/agent/bob-pi.runtime"), "missing bob: {uris:?}" ); } @@ -735,13 +735,13 @@ async fn tenant_scoped_resolve_does_not_fan_out() { seed_agent( &s1, - "easynet:///r/silan.localhost/agent/silan-laptop", + "easynet:///r/silan.localhost/agent/silan-laptop.runtime", "silan-laptop", Some("silan.localhost"), ); seed_agent( &s2, - "easynet:///r/alice.localhost/agent/alice-phone", + "easynet:///r/alice.localhost/agent/alice-phone.runtime", "alice-phone", Some("alice.localhost"), ); @@ -750,7 +750,7 @@ async fn tenant_scoped_resolve_does_not_fan_out() { // Default empty filter. Caller is in silan.localhost; the hub // auto-fills the tenant filter from the envelope. No fan-out; // alice's agent must NOT appear. - let env_silan = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop"); + let env_silan = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop.runtime"); let resp = invoke(&s1, env_silan, "federation.resolve", b"{}").await; assert_eq!(resp.error, None); let body: serde_json::Value = serde_json::from_slice(&resp.result).unwrap(); @@ -758,14 +758,17 @@ async fn tenant_scoped_resolve_does_not_fan_out() { .as_array() .unwrap() .iter() - .map(|v| v["uri"].as_str().unwrap().to_string()) + .map(|v| v["ura"].as_str().unwrap().to_string()) .collect(); assert_eq!( uris.len(), 1, "tenant-scoped should be local-only: {uris:?}" ); - assert_eq!(uris[0], "easynet:///r/silan.localhost/agent/silan-laptop"); + assert_eq!( + uris[0], + "easynet:///r/silan.localhost/agent/silan-laptop.runtime" + ); } // ── EXP-D: resolve_shard reports local vs remote correctly ──────── @@ -774,7 +777,7 @@ async fn tenant_scoped_resolve_does_not_fan_out() { async fn resolve_shard_reports_local_for_owned_realm() { let (s1, _s2, _s3, _disp) = three_shard_cluster(); - let env_caller = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop"); + let env_caller = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop.runtime"); let args = r#"{"realm":"silan.localhost"}"#; let resp = invoke(&s1, env_caller, "federation.resolve_shard", args.as_bytes()).await; assert_eq!(resp.error, None); @@ -788,7 +791,7 @@ async fn resolve_shard_reports_local_for_owned_realm() { async fn resolve_shard_reports_remote_endpoints_for_off_shard_realm() { let (s1, _s2, _s3, _disp) = three_shard_cluster(); - let env_caller = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop"); + let env_caller = caller_envelope("easynet:///r/silan.localhost/agent/silan-laptop.runtime"); let args = r#"{"realm":"alice.localhost"}"#; let resp = invoke(&s1, env_caller, "federation.resolve_shard", args.as_bytes()).await; assert_eq!(resp.error, None); diff --git a/core/runtime-rs/src/tests/stream.rs b/core/runtime-rs/src/tests/stream.rs index e84a3809..5b5d8be1 100644 --- a/core/runtime-rs/src/tests/stream.rs +++ b/core/runtime-rs/src/tests/stream.rs @@ -318,7 +318,7 @@ async fn grpc_open_stream_rejects_invalid_tenant_id() { envelope: Some(grpc_pb::Envelope { request_id: "grpc-open-invalid-tenant".to_string(), caller: Some(grpc_pb::AgentIdentity { - uri: "easynet:///r/tenant:bad/agents/tester".to_string(), + ura: "easynet:///r/tenant:bad/agent/tester.runtime".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -584,7 +584,7 @@ async fn grpc_upload_payload_client_stream_round_trip_over_real_connection() { content: Some(grpc_pb::ContentEnvelope { content_type: "application/json".to_string(), encoding: "identity".to_string(), - schema_uri: String::new(), + schema_ura: String::new(), meta: None, encryption: grpc_pb::EncryptionAlgorithm::EncryptionUnspecified as i32, key_id: String::new(), @@ -630,14 +630,14 @@ async fn grpc_upload_payload_client_stream_round_trip_over_real_connection() { let upload_resp = upload_fut.await.unwrap().into_inner(); assert!(upload_resp.error.is_none()); let payload_ref = upload_resp.r#ref.expect("payload ref must exist"); - assert!(payload_ref.uri.starts_with("axon://payloads/")); + assert!(AxonRuntime::is_payload_resource_ura(&payload_ref.ura)); assert_eq!(payload_ref.size_bytes, payload.len() as i64); assert_eq!(payload_ref.digest, digest); let mut download = payload_client .download_payload(grpc_pb::DownloadPayloadRequest { envelope: grpc_envelope("grpc-upload-download"), - uri: payload_ref.uri, + ura: payload_ref.ura, offset: 0, limit: 0, }) @@ -712,7 +712,7 @@ async fn grpc_upload_payload_client_stream_rejects_missing_tenant_in_init() { // RFC 001: empty tenant scope ⇒ empty scope segment // in caller URA. Test asserts server rejects this. caller: Some(grpc_pb::AgentIdentity { - uri: "easynet:///r//agents/tester".to_string(), + ura: "easynet:///r//agent/tester".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -720,7 +720,7 @@ async fn grpc_upload_payload_client_stream_rejects_missing_tenant_in_init() { content: Some(grpc_pb::ContentEnvelope { content_type: "application/octet-stream".to_string(), encoding: "identity".to_string(), - schema_uri: String::new(), + schema_ura: String::new(), meta: None, encryption: grpc_pb::EncryptionAlgorithm::EncryptionUnspecified as i32, key_id: String::new(), @@ -779,7 +779,7 @@ async fn grpc_upload_payload_client_stream_rejects_invalid_tenant_in_init() { envelope: Some(grpc_pb::Envelope { request_id: "grpc-upload-invalid-tenant".to_string(), caller: Some(grpc_pb::AgentIdentity { - uri: "easynet:///r/tenant:bad/agents/tester".to_string(), + ura: "easynet:///r/tenant:bad/agent/tester.runtime".to_string(), profile: "easynet-strict-v2".to_string(), }), ..Default::default() @@ -787,7 +787,7 @@ async fn grpc_upload_payload_client_stream_rejects_invalid_tenant_in_init() { content: Some(grpc_pb::ContentEnvelope { content_type: "application/octet-stream".to_string(), encoding: "identity".to_string(), - schema_uri: String::new(), + schema_ura: String::new(), meta: None, encryption: grpc_pb::EncryptionAlgorithm::EncryptionUnspecified as i32, key_id: String::new(), @@ -831,13 +831,17 @@ async fn grpc_upload_payload_client_stream_rejects_invalid_tenant_in_init() { #[tokio::test] async fn payload_meta_and_delete_reject_cross_tenant_access() { let runtime = test_runtime(); - let uri = "axon://payloads/cross-tenant-check".to_string(); + let uri = easynet_run_axon_client::ura::payload_resource_ura( + "tenant-test", + "user.tenant-test", + "cross-tenant-check", + ); runtime.state.streaming.payloads.insert( uri.clone(), PayloadRecord { owner_tenant_id: "tenant-test".to_string(), reference: pb::PayloadRef { - uri: uri.clone(), + ura: uri.clone(), digest: format!("sha256:{}", AxonRuntime::sha256_hex(b"payload")), size_bytes: 7, content: None, @@ -852,7 +856,7 @@ async fn payload_meta_and_delete_reject_cross_tenant_access() { &runtime, Request::new(pb::GetPayloadMetaRequest { envelope: envelope_for_tenant("payload-meta-deny", "tenant-other", "tester"), - uri: uri.clone(), + ura: uri.clone(), }), ) .await @@ -865,7 +869,7 @@ async fn payload_meta_and_delete_reject_cross_tenant_access() { &runtime, Request::new(pb::DeletePayloadRequest { envelope: envelope_for_tenant("payload-del-deny", "tenant-other", "tester"), - uri: uri.clone(), + ura: uri.clone(), }), ) .await @@ -881,13 +885,17 @@ async fn payload_meta_and_delete_reject_cross_tenant_access() { #[tokio::test] async fn payload_download_rejects_cross_tenant_access() { let runtime = test_runtime(); - let uri = "axon://payloads/cross-tenant-download".to_string(); + let uri = easynet_run_axon_client::ura::payload_resource_ura( + "tenant-test", + "user.tenant-test", + "cross-tenant-download", + ); runtime.state.streaming.payloads.insert( uri.clone(), PayloadRecord { owner_tenant_id: "tenant-test".to_string(), reference: pb::PayloadRef { - uri: uri.clone(), + ura: uri.clone(), digest: format!("sha256:{}", AxonRuntime::sha256_hex(b"payload")), size_bytes: 7, content: None, @@ -916,7 +924,11 @@ async fn payload_download_rejects_cross_tenant_access() { #[tokio::test] async fn payload_download_reports_data_loss_when_file_truncated() { let runtime = test_runtime(); - let uri = "axon://payloads/truncated-download".to_string(); + let uri = easynet_run_axon_client::ura::payload_resource_ura( + "tenant-test", + "user.tenant-test", + "truncated-download", + ); let full_payload = b"payload-data-for-truncated-download"; let file_path = test_payload_file("truncated-download", full_payload); runtime.state.streaming.payloads.insert( @@ -924,7 +936,7 @@ async fn payload_download_reports_data_loss_when_file_truncated() { PayloadRecord { owner_tenant_id: "tenant-test".to_string(), reference: pb::PayloadRef { - uri: uri.clone(), + ura: uri.clone(), digest: format!("sha256:{}", AxonRuntime::sha256_hex(full_payload)), size_bytes: full_payload.len() as i64, content: None, @@ -954,13 +966,17 @@ async fn payload_download_reports_data_loss_when_file_truncated() { #[tokio::test] async fn payload_meta_rejects_empty_tenant_scope_even_when_owner_empty() { let runtime = test_runtime(); - let uri = "axon://payloads/empty-tenant-scope".to_string(); + let uri = easynet_run_axon_client::ura::payload_resource_ura( + "tenant-test", + "user.tenant-test", + "empty-tenant-scope", + ); runtime.state.streaming.payloads.insert( uri.clone(), PayloadRecord { owner_tenant_id: String::new(), reference: pb::PayloadRef { - uri: uri.clone(), + ura: uri.clone(), digest: format!("sha256:{}", AxonRuntime::sha256_hex(b"payload")), size_bytes: 7, content: None, @@ -1041,7 +1057,7 @@ async fn upload_stream_missing_final_frame_accepts_without_digest_check() { let mut download = dl_client .download_payload(grpc_pb::DownloadPayloadRequest { envelope: grpc_envelope("download-no-final"), - uri: payload_ref.uri, + ura: payload_ref.ura, offset: 0, limit: 0, }) @@ -1241,7 +1257,7 @@ async fn upload_stream_overlapping_chunk_offsets_correct() { let mut download = dl_client .download_payload(grpc_pb::DownloadPayloadRequest { envelope: grpc_envelope("download-overlap"), - uri: payload_ref.uri, + ura: payload_ref.ura, offset: 0, limit: 0, }) diff --git a/core/runtime-rs/src/tests/target_resolver.rs b/core/runtime-rs/src/tests/target_resolver.rs index 75c46671..fc30b00c 100644 --- a/core/runtime-rs/src/tests/target_resolver.rs +++ b/core/runtime-rs/src/tests/target_resolver.rs @@ -59,7 +59,7 @@ async fn setup_node_with_mcp_tool(runtime: &AxonRuntime, node_id: &str) -> Strin "{\"type\":\"object\"}".to_string(), ), ]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -132,7 +132,7 @@ async fn setup_node_with_a2a_skill(runtime: &AxonRuntime, node_id: &str) -> Stri ("a2a.skill_id".to_string(), "translate_text".to_string()), ("a2a.skill_name".to_string(), "Text Translation".to_string()), ]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), @@ -650,7 +650,7 @@ async fn setup_case15_session_bridge(runtime: &AxonRuntime, node_id: &str) -> St .to_string(), ), ]), - payload_uri: payload_ref.uri.clone(), + payload_ura: payload_ref.ura.clone(), publisher_key_version: 1, proof: Some(proof.clone()), }), diff --git a/docs/rfc/AXON-RFC-001-plan-v4.1.1.md b/docs/rfc/AXON-RFC-001-plan-v4.1.1.md index acdb3853..fb332c10 100644 --- a/docs/rfc/AXON-RFC-001-plan-v4.1.1.md +++ b/docs/rfc/AXON-RFC-001-plan-v4.1.1.md @@ -153,7 +153,7 @@ mcp_client = true # outgoing MCP; default Each becomes: name: skill. visibility: PRIVATE - scope: owner_agent_uri = the LLM sub-agent's URA + scope: owner_agent_ura = the LLM sub-agent's URA schema: synthesized from SKILL.md frontmatter ``` @@ -161,14 +161,14 @@ Each becomes: ``` LocalAgentCatalog (per daemon, in-memory) - Map: agent_uri → LocalDispatchBinding + Map: agent_ura → LocalDispatchBinding where LocalDispatchBinding = InProcess(handler) | LocalIPC(socket) | LocalChild(pid) Built at boot from profiles + managed sub-agents + persisted ~/.easynet/local-agents.json. Holds dispatch handles for Agents physically resident on this host. Never sent over the network. RealmDirectory (held by hub-profile Agent; cached by every daemon) - Map: agent_uri → DirectoryEntry + Map: agent_ura → DirectoryEntry where DirectoryEntry = { identity: { public_key, signing_authority, host_attestation? }, abilities: AbilityDescriptor[], // §1.6 @@ -181,8 +181,8 @@ RealmDirectory (held by hub-profile Agent; cached by every daemon) ``` A daemon dispatching an Invocation: -1. Look up callee_uri in LocalAgentCatalog. Hit → in-process / IPC / child dispatch. Done. -2. Miss → look up callee_uri in cached RealmDirectory. Get endpoints. gRPC Invoke to remote daemon. +1. Look up callee_ura in LocalAgentCatalog. Hit → in-process / IPC / child dispatch. Done. +2. Miss → look up callee_ura in cached RealmDirectory. Get endpoints. gRPC Invoke to remote daemon. 3. Cache miss → invoke `federation.resolve` on hub. Update local cache. Then retry step 2. ### §1.3 — Hosted Agent identity and signing authority [P1] @@ -203,13 +203,13 @@ is per-Agent and recorded in DirectoryEntry.identity.signing_authority. produced by hosted Agent X under host Y." - Used by: consent-profile, policy-profile, mcp-profile, llm-profile, and any sub-agent spawned by `fleet.start_agent`. -- DirectoryEntry.identity.signing_authority = "hosted_by:". +- DirectoryEntry.identity.signing_authority = "hosted_by:". - Receipt schema for hosted Agent's response includes: - - `callee_agent_uri` — the hosted Agent (the apparent callee) - - `signer_agent_uri` — the hosting device-profile Agent + - `callee_agent_ura` — the hosted Agent (the apparent callee) + - `signer_agent_ura` — the hosting device-profile Agent - `host_attestation` — signed assertion that signer hosts callee -A receipt verifier checks: signer_agent_uri's key signs the receipt; +A receipt verifier checks: signer_agent_ura's key signs the receipt; the host_attestation in DirectoryEntry confirms signer hosts callee. **Model B is the default for daemon-spawned local Agents.** It avoids @@ -225,25 +225,25 @@ Path: ~/.easynet/local-agents.json (mode 0600) Owner: the easynet-daemon process Format: { - "host_device_agent_uri": "easynet:///r/acme/agent/01DEV-...", + "host_device_agent_ura": "easynet:///r/acme/agent/01DEV-...", "hosted_agents": [ { "profile": "consent", "name": "default", - "agent_uri": "easynet:///r/acme/agent/01CON-...", + "agent_ura": "easynet:///r/acme/agent/01CON-...", "signing_authority": "hosted_by:easynet:///r/acme/agent/01DEV-...", "first_seen_at": "" }, { "profile": "mcp", "name": "default", - "agent_uri": "easynet:///r/acme/agent/01MCP-...", + "agent_ura": "easynet:///r/acme/agent/01MCP-...", "signing_authority": "hosted_by:easynet:///r/acme/agent/01DEV-..." }, { "profile": "llm", "name": "claude", - "agent_uri": "easynet:///r/acme/agent/01LLM-...-claude", + "agent_ura": "easynet:///r/acme/agent/01LLM-...-claude", "signing_authority": "hosted_by:easynet:///r/acme/agent/01DEV-..." } ] @@ -270,9 +270,9 @@ MUST carry a DelegationProof: ``` DelegationProof { - issuer_uri // who issued this delegation (e.g. backend, identity-issuer) - subject_uri // the principal being represented - caller_uri // the Agent authorized to act for subject (must equal envelope.caller) + issuer_ura // who issued this delegation (e.g. backend, identity-issuer) + subject_ura // the principal being represented + caller_ura // the Agent authorized to act for subject (must equal envelope.caller) audience // restriction: which callee(s) this delegation may target // may be specific URI, URI prefix, or "*" for unrestricted scopes[] // ability-name patterns this delegation allows @@ -285,17 +285,17 @@ DelegationProof { Verification rules at the admission gate: -1. **Signature integrity**: signature verifies against issuer_uri's +1. **Signature integrity**: signature verifies against issuer_ura's public key (looked up in RealmDirectory). 2. **Issuer trust**: - - If `issuer_uri == subject_uri`: any subject may issue delegation + - If `issuer_ura == subject_ura`: any subject may issue delegation for themselves. Verify against subject's public key (recorded at federation.join or during key rotation). - - Else: issuer_uri must be in the realm's "trusted delegation + - Else: issuer_ura must be in the realm's "trusted delegation issuers" list (configured at hub; e.g. backend-profile may be trusted to issue delegations for human operators it has authenticated via JWT). -3. **Caller match**: caller_uri MUST equal envelope.caller. Otherwise +3. **Caller match**: caller_ura MUST equal envelope.caller. Otherwise reject — caller cannot reuse another Agent's delegation. 4. **Audience match**: envelope.callee MUST satisfy audience pattern. 5. **Scope match**: envelope.ability MUST satisfy at least one scope @@ -309,8 +309,8 @@ to envelope.caller). JWTs from web auth flows can be wrapped in DelegationProof: backend authenticates a user via JWT, then constructs a DelegationProof with -issuer_uri = backend-profile's URA, subject_uri = the user's URA, -caller_uri = backend-profile's URA, audience = whichever hub or device +issuer_ura = backend-profile's URA, subject_ura = the user's URA, +caller_ura = backend-profile's URA, audience = whichever hub or device the call targets, scopes = the JWT's scope claims, signed by the backend's key. @@ -321,7 +321,7 @@ Every advertised Ability is described by: ``` AbilityDescriptor { name // e.g. "fleet.list_abilities", "skill.alive-video" - owner_agent_uri // the Agent that hosts this Ability (always callee in invoke) + owner_agent_ura // the Agent that hosts this Ability (always callee in invoke) visibility // PRIVATE | SCOPED | PUBLIC scope_subjects[] // when SCOPED: list of subject URAs (or URA prefixes) allowed to invoke scope_agents[] // when SCOPED: list of caller URAs allowed (in addition to scope_subjects check) @@ -350,7 +350,7 @@ PUBLIC → always returned SCOPED → returned iff (subject ∈ scope_subjects OR scope_subjects empty) AND (caller ∈ scope_agents OR scope_agents empty) with empty meaning "no restriction on that axis" -PRIVATE → returned iff caller is the owner_agent_uri's signing authority +PRIVATE → returned iff caller is the owner_agent_ura's signing authority (i.e. the device-profile that hosts the owning Agent) OR subject is the operator who owns the host Otherwise omitted from response @@ -369,7 +369,7 @@ PRIVATE Abilities are functionally a degenerate SCOPED case: scope = Step 1. Daemon process starts. Reads ~/.easynet/config.toml. Sees profiles.device = true. Reads ~/.easynet/credentials.json. MUST exist for this mode. - credentials = { realm, canonical_agent_uri, public_key, + credentials = { realm, canonical_agent_ura, public_key, membership_token, hub_endpoints, join_receipt_hash } If missing AND profiles.hub = false: daemon prints "run @@ -425,7 +425,7 @@ Step 6. Advertise local Agents to hub. For each hosted Agent in attests authority) callee = hub-profile Agent ability = federation.advertise_agent - args = { agent_uri, + args = { agent_ura, identity: { public_key, signing_authority: "hosted_by:", @@ -524,7 +524,7 @@ Step C. Hub admission gate: reason: "invalid_token"}. Step D. Hub federation.join handler: - Allocate canonical_agent_uri = easynet:///r//agent/. + Allocate canonical_agent_ura = easynet:///r//agent/. If public_key already bound to a different URI: Receipt {Failed, reason: "public_key_already_bound", hint: "regenerate keypair and retry"}. Hub does NOT rotate the @@ -532,15 +532,15 @@ Step D. Hub federation.join handler: Bind public_key to URA in RealmDirectory. Persist membership. Sign Receipt: - { Ok, body: { canonical_agent_uri, membership_token, + { Ok, body: { canonical_agent_ura, membership_token, hub_endpoints, heartbeat_ms, realm_trust_root_pubkey, join_receipt_hash } } Publish receipt hash to realm transparency log. Step E. CLI receives Receipt. - Writes ~/.easynet/credentials.json with canonical_agent_uri. + Writes ~/.easynet/credentials.json with canonical_agent_ura. Writes ~/.easynet/local-agents.json with this URA as - host_device_agent_uri. + host_device_agent_ura. join_receipt_hash is THIS DEVICE'S MEMBERSHIP LINEAGE ROOT [P3]. Future invocations SHOULD reference it directly or transitively @@ -550,7 +550,7 @@ Step E. CLI receives Receipt. operator-initiated commands and periodic activity may use Null with reason per §A8. -Step F. CLI prints: "Joined realm as ." +Step F. CLI prints: "Joined realm as ." ``` --- @@ -604,7 +604,7 @@ Step B. device-profile fleet.start_agent handler: (caller = device-profile, subject = new llm Agent). 6. federation.advertise_abilities for its abilities. -Step C. Receipt to CLI: { canonical_agent_uri, advertised_abilities_count }. +Step C. Receipt to CLI: { canonical_agent_ura, advertised_abilities_count }. Step D. CLI prints: "Added agent claude () with N abilities." ``` @@ -675,8 +675,8 @@ Step D. Dispatch via LocalAgentCatalog → claude Agent's skill.alive-video handler (in-process). Step E. Handler returns. Daemon constructs Receipt: - callee_agent_uri = claude Agent URA - signer_agent_uri = device-profile Agent URA [P1, hosted Model B] + callee_agent_ura = claude Agent URA + signer_agent_ura = device-profile Agent URA [P1, hosted Model B] host_attestation = signed by device-profile body = handler result causal_context = (carried from envelope) @@ -708,9 +708,9 @@ unless `meta.publish` has changed visibility to PUBLIC. [Backend] (NODE) Validates JWT → operator URA. Constructs DelegationProof: - issuer_uri = backend-profile Agent URA - subject_uri = operator URA - caller_uri = backend-profile Agent URA + issuer_ura = backend-profile Agent URA + subject_ura = operator URA + caller_ura = backend-profile Agent URA audience = hub-profile URA scopes = ["federation.resolve", "meta.list_abilities"] issued_at, expires_at = JWT validity window @@ -747,7 +747,7 @@ unless `meta.publish` has changed visibility to PUBLIC. InstalledSkill[] } HTTP response. [Browser] - Renders. Each row carries owner_agent_uri. + Renders. Each row carries owner_agent_ura. ``` No node-to-node MCP. Backend signs as backend-profile. Operator's @@ -766,7 +766,7 @@ Same as §9 with empty filter. Returns federation-wide ability catalog. ``` [Browser] POST /api/v1/abilities/invoke - body = { callee_agent_uri, ability: "conversation.send", + body = { callee_agent_ura, ability: "conversation.send", args: { prompt } } [Backend] @@ -815,7 +815,7 @@ Same as §9 with empty filter. Returns federation-wide ability catalog. ability = federation.resolve args = { filter: { visibility: ["PUBLIC"], - scope_includes: subject_uri // includes SCOPED matching this operator + scope_includes: subject_ura // includes SCOPED matching this operator } } // PRIVATE NOT included by default @@ -1041,23 +1041,23 @@ Visibility column reflects [P8] correction for conversation.*.) | Namespace | Ability | Owner profile | Default Visibility | Input | Receipt body | |---|---|---|---|---|---| -| federation | join | hub | PUBLIC (pre-membership exception) | `{realm, pairing_secret, public_key, host_descriptor, profiles_summary}` | `{canonical_agent_uri, membership_token, hub_endpoints[], heartbeat_ms, realm_trust_root_pubkey, join_receipt_hash}` | +| federation | join | hub | PUBLIC (pre-membership exception) | `{realm, pairing_secret, public_key, host_descriptor, profiles_summary}` | `{canonical_agent_ura, membership_token, hub_endpoints[], heartbeat_ms, realm_trust_root_pubkey, join_receipt_hash}` | | federation | leave | hub | SCOPED to caller agent | `{reason}` | `{ack}` | -| federation | resolve | hub | PUBLIC callable, policy-filtered result | `{filter: {has_ability_prefix?, visibility?, scope_includes?, agent_uri?}}` | `{agents: [{uri, identity, abilities[], endpoints[], metadata, status}]}` | -| federation | advertise_agent | hub | SCOPED to caller agent | `{agent_uri, identity, metadata}` | `{ack, replaced_prior}` | -| federation | advertise_abilities | hub | SCOPED to caller agent | `{agent_uri, abilities[]}` | `{ack, replaced_prior}` | +| federation | resolve | hub | PUBLIC callable, policy-filtered result | `{filter: {has_ability_prefix?, visibility?, scope_includes?, agent_ura?}}` | `{agents: [{uri, identity, abilities[], endpoints[], metadata, status}]}` | +| federation | advertise_agent | hub | SCOPED to caller agent | `{agent_ura, identity, metadata}` | `{ack, replaced_prior}` | +| federation | advertise_abilities | hub | SCOPED to caller agent | `{agent_ura, abilities[]}` | `{ack, replaced_prior}` | | federation | heartbeat | hub | SCOPED to caller agent | `{observed_load, advertised_abilities_hash, initial?}` | `{membership_status, realm_directory_delta, policy_updates}` | -| federation | revoke | hub | SCOPED (admin) | `{agent_uri, reason}` | `{ack}` | +| federation | revoke | hub | SCOPED (admin) | `{agent_ura, reason}` | `{ack}` | | federation | federate | hub | SCOPED (admin) | `{other_hub_uri, trust_root}` | `{federation_link_id}` | | transport | relay.invoke | hub (opt-in) | SCOPED | `{target_invoke_envelope}` | passthrough Receipt | | transport | relay.stream | hub (opt-in) | SCOPED | same | streamed Receipt chunks | -| identity | rotate_key | hub | SCOPED (subject auth required) | `{agent_uri, new_pubkey, attestation}` | `{rotated_at, prior_key_id}` | +| identity | rotate_key | hub | SCOPED (subject auth required) | `{agent_ura, new_pubkey, attestation}` | `{rotated_at, prior_key_id}` | | identity | revoke_key | hub | SCOPED | `{key_id, reason}` | `{ack}` | | identity | issue_token | hub | SCOPED | `{purpose, ttl}` | `{token}` | | fleet | list_agents | device | SCOPED to local operator | `{}` | `{agents[]}` | | fleet | list_abilities | device | SCOPED | `{visibility_filter?, name_prefix?}` | `{abilities[]}` | -| fleet | list_sessions | device | SCOPED | `{agent_uri?}` | `{sessions[]}` | -| fleet | start_agent | device | SCOPED | `{name, agent_type, model?}` | `{canonical_agent_uri}` | +| fleet | list_sessions | device | SCOPED | `{agent_ura?}` | `{sessions[]}` | +| fleet | start_agent | device | SCOPED | `{name, agent_type, model?}` | `{canonical_agent_ura}` | | fleet | stop_agent | device | SCOPED | `{name_or_uri}` | `{ack}` | | fleet | attach_session | device | SCOPED | `{session_id}` | streaming chunks | | fleet | session_input | device | SCOPED | `{session_id, data}` | `{ack}` | @@ -1168,7 +1168,7 @@ This table, combined with §18, is the binding contract. | Caller spoofing (Frontend writing `caller=human-agent`) | Backend SDK signs envelopes with backend key automatically; subject is set from JWT; SDK does not allow caller override | | Subject delegation forged | DelegationProof signature verified at admission gate per §1.5 | | PRIVATE skill leaks via MCP | Conformance test: MCP tools/list with fake remote operator; PRIVATE never appears unless project_local_private_for_owner AND local connection | -| Hosted Agent receipt signing confusion | Receipt schema must include `signer_agent_uri` distinct from `callee_agent_uri` for hosted Agents; verified by smoke test | +| Hosted Agent receipt signing confusion | Receipt schema must include `signer_agent_ura` distinct from `callee_agent_ura` for hosted Agents; verified by smoke test | | Hosted Agent URI churn across restarts | Smoke test: stop daemon → start daemon → `easynet ability list` shows same URAs | | `admission_internal=true` from network | Transport layer rejects inbound envelopes with this flag set; verified by negative test | | Old client silent success | Cross-version negative test | @@ -1192,10 +1192,10 @@ Future revisions MUST satisfy every item below. | A9 | Old RPC negative behavior requires UNIMPLEMENTED / unknown method / parse error. Custom migration message text best-effort. | §17 | | A10 | Every ability referenced anywhere in this document appears in the §18 Standard Ability Registry. | §18 | | A11 | "Hub down → cross-device invocation works" requires prior cache warmup. Without cached RealmDirectory entry for the target, hub is required for resolve. | §16 | -| A12 | **Hosted child Agents (Model B) sign receipts via the hosting device-profile, with `signer_agent_uri` distinct from `callee_agent_uri` and a `host_attestation` field. Self-signing Agents (Model A) sign their own receipts. The choice is recorded in DirectoryEntry.identity.signing_authority.** [P1] | §1.3, §7 Step E | +| A12 | **Hosted child Agents (Model B) sign receipts via the hosting device-profile, with `signer_agent_ura` distinct from `callee_agent_ura` and a `host_attestation` field. Self-signing Agents (Model A) sign their own receipts. The choice is recorded in DirectoryEntry.identity.signing_authority.** [P1] | §1.3, §7 Step E | | A13 | **Hosted Agent URIs are minted by the hosting device-profile, persisted to ~/.easynet/local-agents.json, and reused across daemon restarts. Hub accepts them only via `federation.advertise_agent` from the hosting device-profile.** [P2] | §1.4 | | A14 | **DelegationProof schema (issuer, subject, caller, audience, scopes, issued_at, expires_at, signature). Verification at admission gate per §1.5 rules. JWT verification is not hardcoded against operator public key — it goes through the DelegationProof model.** [P5] | §1.5, §9, §11 | -| A15 | **AbilityDescriptor includes owner_agent_uri, visibility, scope_subjects[], scope_agents[], source, schema_summary, hints. PRIVATE is a degenerate SCOPED case: scope = {host operator}.** [P9] | §1.6, §6, §18 | +| A15 | **AbilityDescriptor includes owner_agent_ura, visibility, scope_subjects[], scope_agents[], source, schema_summary, hints. PRIVATE is a degenerate SCOPED case: scope = {host operator}.** [P9] | §1.6, §6, §18 | --- diff --git a/docs/rfc/AXON-RFC-001-restatement-mapping.md b/docs/rfc/AXON-RFC-001-restatement-mapping.md index 7c41a1b2..2d773b43 100644 --- a/docs/rfc/AXON-RFC-001-restatement-mapping.md +++ b/docs/rfc/AXON-RFC-001-restatement-mapping.md @@ -99,8 +99,8 @@ Grouped by source proto file. Every row maps `old_rpc → owner profile → new | `GetMCPToolDetail` | mcp (CLI-side) | `mcp.bridge.list_tools` returns full schema in single call; OR `meta.describe` against the underlying Agent | — | SCOPED | `{tool_name}` | tool spec | | `CallMCPTool` | mcp (CLI-side) | `mcp.bridge.call_tool` | mcp-profile | SCOPED to local MCP clients | `{tool_name, args, timeout_ms}` | `{result, content_type, is_error}` | | `CallMCPToolStream` | mcp (CLI-side) | `mcp.bridge.call_tool` invoked through `InvokeStream` | mcp-profile | SCOPED | same | streaming MCP chunks | -| `RegisterMCPTool` | hub | `federation.advertise_abilities` | self | SCOPED to caller | `{agent_uri, abilities[]}` | `{ack, replaced_prior}` | -| `UnregisterMCPTool` | hub | `federation.advertise_abilities` (with updated set) | self | SCOPED to caller | `{agent_uri, abilities[]}` | `{ack, replaced_prior}` | +| `RegisterMCPTool` | hub | `federation.advertise_abilities` | self | SCOPED to caller | `{agent_ura, abilities[]}` | `{ack, replaced_prior}` | +| `UnregisterMCPTool` | hub | `federation.advertise_abilities` (with updated set) | self | SCOPED to caller | `{agent_ura, abilities[]}` | `{ack, replaced_prior}` | | `GetA2AAgentCard` | a2a-bridge profile | `bridge.a2a.get_card` | a2a-bridge | SCOPED | `{target_agent_id}` | `{card}` | | `ListA2AAgents` | a2a-bridge profile | `bridge.a2a.list` | a2a-bridge | SCOPED | `{filter}` | `{agents[]}` | | `SendA2ATask` | a2a-bridge profile | `bridge.a2a.send` | a2a-bridge | SCOPED | `{target_agent, skill_id, input}` | `{result}` | @@ -117,16 +117,16 @@ Grouped by source proto file. Every row maps `old_rpc → owner profile → new | Old RPC | Owner profile | New ability | Caller / Subject | Visibility | Args mapping | Receipt body mapping | |---|---|---|---|---|---|---| -| `RegisterNode` | hub | `federation.join` | provisional Agent | PUBLIC (pre-membership exception) | `{realm, pairing_secret, public_key, host_descriptor, profiles_summary}` | `{canonical_agent_uri, membership_token, hub_endpoints[], heartbeat_ms, realm_trust_root_pubkey, join_receipt_hash}` | +| `RegisterNode` | hub | `federation.join` | provisional Agent | PUBLIC (pre-membership exception) | `{realm, pairing_secret, public_key, host_descriptor, profiles_summary}` | `{canonical_agent_ura, membership_token, hub_endpoints[], heartbeat_ms, realm_trust_root_pubkey, join_receipt_hash}` | | `Heartbeat` | hub | `federation.heartbeat` | self | SCOPED to caller | `{observed_load, advertised_abilities_hash, initial?}` | `{membership_status, realm_directory_delta, policy_updates}` | -| `DrainNode` | hub | `admin.drain_node` (admin namespace; new) | operator | SCOPED (admin) | `{agent_uri, drain_options}` | `{ack, status}` | -| `UndrainNode` | hub | `admin.undrain_node` | operator | SCOPED (admin) | `{agent_uri}` | `{ack}` | -| `QuarantineNode` | hub | `admin.quarantine_node` | operator | SCOPED (admin) | `{agent_uri, reason}` | `{ack, status}` | -| `DeregisterNode` | hub | `federation.leave` invoked on behalf of the target Agent (admin override) OR `federation.revoke` for involuntary | operator | SCOPED (admin) | `{agent_uri, reason}` | `{ack}` | -| `GetNodeTrust` | hub | `identity.get_trust` | any (read-only) | PUBLIC | `{agent_uri}` | `{trust_level, claims}` | -| `SetNodeTrust` | hub | `identity.set_trust` | operator | SCOPED (admin) | `{agent_uri, new_trust_level}` | `{ack, prior_level}` | +| `DrainNode` | hub | `admin.drain_node` (admin namespace; new) | operator | SCOPED (admin) | `{agent_ura, drain_options}` | `{ack, status}` | +| `UndrainNode` | hub | `admin.undrain_node` | operator | SCOPED (admin) | `{agent_ura}` | `{ack}` | +| `QuarantineNode` | hub | `admin.quarantine_node` | operator | SCOPED (admin) | `{agent_ura, reason}` | `{ack, status}` | +| `DeregisterNode` | hub | `federation.leave` invoked on behalf of the target Agent (admin override) OR `federation.revoke` for involuntary | operator | SCOPED (admin) | `{agent_ura, reason}` | `{ack}` | +| `GetNodeTrust` | hub | `identity.get_trust` | any (read-only) | PUBLIC | `{agent_ura}` | `{trust_level, claims}` | +| `SetNodeTrust` | hub | `identity.set_trust` | operator | SCOPED (admin) | `{agent_ura, new_trust_level}` | `{ack, prior_level}` | | `ListNodes` | hub | `federation.resolve` (with empty filter or filter by has_ability_prefix) | any | PUBLIC callable, policy-filtered | `{filter}` | `{agents[]}` | -| `GetNode` | hub | `federation.resolve` (filter `agent_uri`) | any | PUBLIC callable, policy-filtered | `{filter:{agent_uri}}` | `{agents:[1 entry]}` | +| `GetNode` | hub | `federation.resolve` (filter `agent_ura`) | any | PUBLIC callable, policy-filtered | `{filter:{agent_ura}}` | `{agents:[1 entry]}` | | `ResolveNode` | hub | `federation.resolve` (alias→canonical) | any | PUBLIC | `{filter:{alias}}` | `{agents:[1 entry]}` | | `GetDeviceOverview` | device-profile | `meta.describe` (extended to return overview) on the target device-profile | operator | SCOPED | `{}` | `{device_overview}` | | `ListDeviceOverviews` | hub | `aggregate.list_device_overviews` (backend-profile aggregator) | backend-profile | SCOPED to operator | `{filter}` | `{overviews[]}` | @@ -138,16 +138,16 @@ Grouped by source proto file. Every row maps `old_rpc → owner profile → new | Old RPC | Owner profile | New ability | Caller / Subject | Visibility | Args mapping | Receipt body mapping | |---|---|---|---|---|---|---| -| `RotateNodeKey` | hub | `identity.rotate_key` | self (or admin via delegation) | SCOPED (subject auth required) | `{agent_uri, new_pubkey, attestation}` | `{rotated_at, prior_key_id}` | +| `RotateNodeKey` | hub | `identity.rotate_key` | self (or admin via delegation) | SCOPED (subject auth required) | `{agent_ura, new_pubkey, attestation}` | `{rotated_at, prior_key_id}` | | `RevokeNodeKey` | hub | `identity.revoke_key` | self / admin | SCOPED | `{key_id, reason}` | `{ack}` | | `GetTrustRoot` | hub | `identity.get_trust_root` | any | PUBLIC | `{}` | `{realm_trust_root_pubkey}` | | `RotateTrustRoot` | hub | `identity.rotate_trust_root` | hub-admin | SCOPED (admin) | `{new_pubkey, attestation}` | `{rotated_at, prior_id}` | -| `VerifySignature` | hub | `identity.verify_signature` | any | PUBLIC | `{signed_blob, signer_uri}` | `{valid, signer_key_id}` | -| `ListNodeKeys` | hub | `identity.list_keys` | self / admin | SCOPED | `{agent_uri}` | `{keys[]}` | +| `VerifySignature` | hub | `identity.verify_signature` | any | PUBLIC | `{signed_blob, signer_ura}` | `{valid, signer_key_id}` | +| `ListNodeKeys` | hub | `identity.list_keys` | self / admin | SCOPED | `{agent_ura}` | `{keys[]}` | | `IssueToken` | hub | `identity.issue_token` | hub-admin / authz issuer | SCOPED | `{purpose, ttl, scopes}` | `{token}` | | `RotateToken` | hub | `identity.rotate_token` | issuer | SCOPED | `{token_id}` | `{new_token}` | | `RevokeToken` | hub | `identity.revoke_token` | issuer | SCOPED | `{token_id, reason}` | `{ack}` | -| `WhoAmI` | hub | `identity.whoami` | any | PUBLIC | `{}` (caller identity from envelope) | `{agent_uri, claims, trust_level}` | +| `WhoAmI` | hub | `identity.whoami` | any | PUBLIC | `{}` (caller identity from envelope) | `{agent_ura, claims, trust_level}` | | `CreateTenant` | hub | `identity.create_tenant` | hub-admin | SCOPED (admin) | `{tenant_id, descriptor}` | `{ack}` | | `GetTenant` | hub | `identity.get_tenant` | any | PUBLIC | `{tenant_id}` | `{tenant_descriptor}` | | `UpdateTenant` | hub | `identity.update_tenant` | hub-admin | SCOPED (admin) | `{tenant_id, updates}` | `{ack}` | @@ -229,12 +229,12 @@ operations become AAL meta-abilities. | `ActivateCapability` | target Agent | `meta.publish` (set visibility=PUBLIC or SCOPED) | self | SCOPED | `{ability_name, visibility, scope?}` | `{ack}` | | `DeactivateCapability` | target Agent | `meta.publish` (set visibility=PRIVATE) | self | SCOPED | `{ability_name, visibility:PRIVATE}` | `{ack}` | | `RollbackCapability` | target Agent | `meta.rollback` | self / admin | SCOPED | `{ability_name, to_version}` | `{ack, current_version}` | -| `RevokeCapability` | hub | `capability.revoke` | hub-admin | SCOPED (admin) | `{ability_id, agent_uri, reason}` | `{ack}` | +| `RevokeCapability` | hub | `capability.revoke` | hub-admin | SCOPED (admin) | `{ability_id, agent_ura, reason}` | `{ack}` | | `UninstallCapability` | target Agent | `meta.forget` (per AAL §3.4) | self | SCOPED | `{ability_name}` | `{ack}` | | `ListNodeCapabilities` | target Agent | `meta.list_abilities` | any | callable PUBLIC, policy-filtered | `{visibility_filter?, name_prefix?}` | `{abilities[]}` | | `QueryCapabilities` | hub | `capability.query` (federation-wide search across packages, not per-Agent advertisement) | any | PUBLIC | `{filter}` | `{packages[]}` | | `ResolveCapability` | hub | `capability.resolve` (package_id → install location / availability) | any | PUBLIC | `{capability_ref}` | `{availability[]}` | -| `GrantConsent` | consent | `consent.grant` (long-lived consent grant) | operator | SCOPED to UI | `{ability_name, agent_uri, ttl, scopes}` | `{consent_id}` | +| `GrantConsent` | consent | `consent.grant` (long-lived consent grant) | operator | SCOPED to UI | `{ability_name, agent_ura, ttl, scopes}` | `{consent_id}` | | `RevokeConsent` | consent | `consent.revoke` | operator | SCOPED to UI | `{consent_id}` | `{ack}` | | `ListConsents` | consent | `consent.list_grants` | operator | SCOPED to UI | `{filter}` | `{consents[]}` | | `WatchCapabilityEvents` | hub | `capability.watch_events` (InvokeStream) | any / operator | SCOPED | `{filter}` | streaming events | @@ -342,7 +342,7 @@ duplicates them. ### transfer.proto (4) — all kept PayloadTransfer carries large opaque binary blobs (megabytes to gigabytes) -referenced by `axon://payloads/` URIs. This is **not** Agent-level +referenced by `easynet:///r//resource//payload/` URAs. This is **not** Agent-level semantics; it is the byte substrate that Agent abilities reference when their args or receipt bodies exceed inline gRPC limits. @@ -350,7 +350,7 @@ their args or receipt bodies exceed inline gRPC limits. |---|---|---| | **`UploadPayload`** | Three-phase client-streaming upload (init → data chunks → final verification) for large binary payloads. Cannot be expressed as a single Invoke without packing chunks into args (defeats the point of streaming for memory bounds). | Capability package distribution, large mission inputs/outputs, voice recording archives, model weights. | | **`DownloadPayload`** | Server-streaming download with offset-based resume. Same justification as upload — chunked binary substrate. | Same as upload. | -| **`GetPayloadMeta`** | Metadata query for a payload (size, digest, content-type). Could be expressed as `Invoke` against a `payload.get_meta` ability, but doing so would require **the ability to itself reference a payload URI** — circular if the ability lives on the payload service. Cleanest to keep as a transport-layer query. | Used by anything that needs to verify a payload before consuming it. | +| **`GetPayloadMeta`** | Metadata query for a payload (size, digest, content-type). Could be expressed as `Invoke` against a `payload.get_meta` ability, but doing so would require **the ability to itself reference a payload URA** — circular if the ability lives on the payload service. Cleanest to keep as a transport-layer query. | Used by anything that needs to verify a payload before consuming it. | | **`DeletePayload`** | Garbage collection. Could be a `payload.delete` ability, but again, the natural caller is the payload service itself or a GC scheduler — not really an Agent-level action. | Storage GC. | **Argument for keeping all four together:** they form one cohesive diff --git a/document/brand/02-six-guarantees-evidence-matrix.md b/document/brand/02-six-guarantees-evidence-matrix.md index e6741e23..690bcac2 100644 --- a/document/brand/02-six-guarantees-evidence-matrix.md +++ b/document/brand/02-six-guarantees-evidence-matrix.md @@ -11,14 +11,14 @@ | Aspect | Status | Evidence | |--------|--------|---------| -| **Claim** | Every network object has a canonical URI (`axon://...`) | `types.proto:63-70` | -| **URI scheme defined** | Implemented | `axon://nodes/`, `axon://capabilities/`, `axon://invocations/`, etc. | -| **EasyNet URI** | Implemented | `easynet:///r/org/reg/agent/abilities/name@version` — full ability addressing | -| **SDK support** | Implemented | All 6 SDKs support URI-first invocation via fluent API | -| **Resolution** | Implemented | Runtime resolves URI → node + capability + tenant scope | -| **Gap** | Minor | No URI discovery/registry protocol (clients must know URIs in advance) | - -**Evidence strength: Strong.** URI addressing is pervasive and functional. +| **Claim** | Every network object has a canonical URA (`axon://...`) | `types.proto:63-70` | +| **URA scheme defined** | Implemented | `easynet:///r//device/`, `easynet:///r//ability/`, `easynet:///r//resource/invocation/`, etc. | +| **EasyNet URA** | Implemented | `easynet:///r/org/reg/agent/abilities/name@version` — full ability addressing | +| **SDK support** | Implemented | All 6 SDKs support URA-first invocation via fluent API | +| **Resolution** | Implemented | Runtime resolves URA → node + capability + tenant scope | +| **Gap** | Minor | No URA discovery/registry protocol (clients must know URAs in advance) | + +**Evidence strength: Strong.** URA addressing is pervasive and functional. --- diff --git a/document/concepts/ONTOLOGY_AGENT_ABILITY.md b/document/concepts/ONTOLOGY_AGENT_ABILITY.md index c09ddac8..5f7db9e5 100644 --- a/document/concepts/ONTOLOGY_AGENT_ABILITY.md +++ b/document/concepts/ONTOLOGY_AGENT_ABILITY.md @@ -414,7 +414,7 @@ RFC. ```proto message Agent { - string agent_uri = 1; // globally unique identity + string agent_ura = 1; // globally unique identity AgentKind kind = 2; // human | machine | hub | orchestrator Identity identity = 3; // keys + reputation + claims repeated AbilityRef abilities = 4; @@ -429,7 +429,7 @@ message Agent { ```proto message InvokeRequest { Agent caller = 1; // first-class field, not metadata - AbilityRef callee = 2; // (callee_agent_uri, ability_name) + AbilityRef callee = 2; // (callee_agent_ura, ability_name) bytes args = 3; InvokeOptions options = 4; } diff --git a/document/plans/ecosystem/02-capability-delivery-and-usage-interface-plan.md b/document/plans/ecosystem/02-capability-delivery-and-usage-interface-plan.md index 997d8852..446eb58a 100644 --- a/document/plans/ecosystem/02-capability-delivery-and-usage-interface-plan.md +++ b/document/plans/ecosystem/02-capability-delivery-and-usage-interface-plan.md @@ -94,7 +94,7 @@ Protocol mapping: Use `PublishPackageRequest.metadata` keys as transition contract: -- `easynet.resource_uri` = `easynet:///r/org/reg/agent./abilities/@` +- `easynet.resource_ura` = `easynet:///r/org/reg/agent./abilities/@` - `easynet.subject_id` = `agent.` - `easynet.visibility` = `pub|org|prv` - `easynet.tenant_required` = `true|false` diff --git a/document/plans/ecosystem/03-identity-routing-and-tenant-rules.md b/document/plans/ecosystem/03-identity-routing-and-tenant-rules.md index b0b0c931..d6e328ac 100644 --- a/document/plans/ecosystem/03-identity-routing-and-tenant-rules.md +++ b/document/plans/ecosystem/03-identity-routing-and-tenant-rules.md @@ -44,7 +44,7 @@ Hard checks: Resolver input: - `tenant_id` -- `resource_uri` +- `resource_ura` - optional constraints (`required_tags`, `min_trust_level`, timeout hints) Resolver output: @@ -78,7 +78,7 @@ Invocation envelope should include at least: - `invocation_id` - `subject_id` - `tenant_id` -- `resource_uri` +- `resource_ura` - `issued_at` - `deadline` - `nonce` diff --git a/document/plans/ecosystem/04-user-node-and-capability-registration.md b/document/plans/ecosystem/04-user-node-and-capability-registration.md index 7f6733e9..78275232 100644 --- a/document/plans/ecosystem/04-user-node-and-capability-registration.md +++ b/document/plans/ecosystem/04-user-node-and-capability-registration.md @@ -123,7 +123,7 @@ Key input fields: | `tags` | `repeated string` | capability tags | | `requirements` | `map` | runtime constraints | | `metadata` | `map` | execution and ecosystem metadata | -| `payload_uri` | `string` | external payload location | +| `payload_ura` | `string` | external payload location | Response message: `PublishPackageResponse` @@ -173,7 +173,7 @@ Response message: `ActivateCapabilityResponse` For `easynet:///...` style capability UX, carry metadata at publish time: -- `easynet.resource_uri` = `easynet:///r/org/reg/agent./abilities/@` +- `easynet.resource_ura` = `easynet:///r/org/reg/agent./abilities/@` - `easynet.subject_id` = `agent.` - `easynet.visibility` = `pub|org|prv` - `easynet.tenant_required` = `true` diff --git a/document/plans/ecosystem/05-rust-native-support-plan.md b/document/plans/ecosystem/05-rust-native-support-plan.md index 45e95d20..2a933644 100644 --- a/document/plans/ecosystem/05-rust-native-support-plan.md +++ b/document/plans/ecosystem/05-rust-native-support-plan.md @@ -87,11 +87,11 @@ async fn main() -> anyhow::Result<()> { ("mcp.output_schema".into(), r#"{"type":"object"}"#.into()), ("axon.exec.command".into(), "/opt/easynet/bin/order_quote_rs".into()), ( - "easynet.resource_uri".into(), + "easynet.resource_ura".into(), "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1".into(), ), ]), - payload_uri: "oss://pkg.order_quote_rust/1.0.0".into(), + payload_ura: "oss://pkg.order_quote_rust/1.0.0".into(), publisher_key_version: 1, }; @@ -183,8 +183,8 @@ For parity with target ecosystem APIs (`ability(...).expose()`, `.tenant(...).ab - `publish_ability` - `install_ability` - `activate_ability` -2. URI-first invocation wrapper: - - `call_ability_uri(tenant, resource_uri, input)` +2. URA-first invocation wrapper: + - `call_ability_ura(tenant, resource_ura, input)` 3. Async + stream wrappers: - `call_ability_async` - `stream_ability` @@ -195,5 +195,5 @@ For parity with target ecosystem APIs (`ability(...).expose()`, `.tenant(...).ab 1. Keep existing `easynet-run-axon-client` APIs as stable base. 2. Add new builder facade layer without breaking old methods. -3. Add URI resolver helper that maps `easynet:///...` to current `ResolveCapability` + `Invoke` flow. +3. Add URA resolver helper that maps `easynet:///...` to current `ResolveCapability` + `Invoke` flow. 4. Add conformance tests for Rust <-> Python/TS cross-language invocation payload compatibility. diff --git a/document/plans/ecosystem/06-mcp-native-support-deploy-and-reference.md b/document/plans/ecosystem/06-mcp-native-support-deploy-and-reference.md index 5504f045..88d94392 100644 --- a/document/plans/ecosystem/06-mcp-native-support-deploy-and-reference.md +++ b/document/plans/ecosystem/06-mcp-native-support-deploy-and-reference.md @@ -178,13 +178,13 @@ This allows traceability from tool call back to Axon capability execution. ## 3.3 Suggested ecosystem reference convention -During transition to URI-first UX, add metadata: +Durang transition to URA-first UX, add metadata: -- `easynet.resource_uri = easynet:///r/org/reg/agent./abilities/@` +- `easynet.resource_ura = easynet:///r/org/reg/agent./abilities/@` Then maintain a resolver mapping: -- `resource_uri` -> `mcp.tool_name` -> `capability_name` +- `resource_ura` -> `mcp.tool_name` -> `capability_name` ## 4. Rust Client Usage @@ -231,4 +231,4 @@ The request/response types are fully defined in `core/proto/axon/v1/interop.prot 1. Replace placeholder `CallMCPToolStream` payload with real execution streaming path. 2. Add high-level SDK wrappers for publish/install/activate in `easynet-run-axon-client`. -3. Add URI-first helper: `call_ability_uri(...)` resolving to native MCP/Invoke path. +3. Add URA-first helper: `call_ability_ura(...)` resolving to native MCP/Invoke path. diff --git a/document/plans/ecosystem/08-packaging-and-release-plan.md b/document/plans/ecosystem/08-packaging-and-release-plan.md index adc3d253..e6812f0d 100644 --- a/document/plans/ecosystem/08-packaging-and-release-plan.md +++ b/document/plans/ecosystem/08-packaging-and-release-plan.md @@ -78,7 +78,7 @@ Each SDK pack must depend on the same Protocol Pack version family. - client-stream: `path + list(base64(protobuf request chunk)) -> base64(protobuf response)` - bidi-stream: `path + list(base64(protobuf request chunk)) -> list(base64(protobuf response chunk))` 3. Coverage target: all Axon gRPC methods addressable by canonical method path (`/package.Service/Method`) for all four gRPC rpc shapes. -4. Native helper call contract is also exposed for EasyNet fluent ability invoke path (`tenant_id + resource_uri + payload_json`). +4. Native helper call contract is also exposed for EasyNet fluent ability invoke path (`tenant_id + resource_ura + payload_json`). 5. Sidecar remains as compatibility channel, but protocol-complete coverage is anchored at native bridge layer. ## 4. Sidecar-first strategy for non-Rust diff --git a/document/releases/2026-03-30-review-remediation-upgrade-notes.md b/document/releases/2026-03-30-review-remediation-upgrade-notes.md index c355e549..1d47d714 100644 --- a/document/releases/2026-03-30-review-remediation-upgrade-notes.md +++ b/document/releases/2026-03-30-review-remediation-upgrade-notes.md @@ -74,7 +74,7 @@ Recommended rollout posture: ### Shell sanitization in invoke script generation (Node, Python, Swift) -- `generateInvokeScript` / `_generate_invoke_script` / `generateInvokeScript` now validate `endpoint` and `resource_uri` against a shell-unsafe character set before interpolation. +- `generateInvokeScript` / `_generate_invoke_script` / `generateInvokeScript` now validate `endpoint` and `resource_ura` against a shell-unsafe character set before interpolation. - Characters rejected: `` ` $ \ " ' \n \r ; | & < > ( ) { } ! # `` and control characters. - Matches the existing Go and Rust SDK behaviour. Callers passing shell metacharacters in endpoint or resource URI values will receive a config error instead of generating an injectable script. diff --git a/document/rfcs/001-envelope-axiom-alignment.md b/document/rfcs/001-envelope-axiom-alignment.md index e68914a7..bc44883e 100644 --- a/document/rfcs/001-envelope-axiom-alignment.md +++ b/document/rfcs/001-envelope-axiom-alignment.md @@ -191,7 +191,7 @@ message Empty {} message ReceiptRef { bytes receipt_hash = 1; // 32-byte SHA-256 - string receipt_uri = 2; // URA locator for auditor fetch + string receipt_ura = 2; // URA locator for auditor fetch } message ReceiptList { @@ -202,7 +202,7 @@ message ReceiptList { message MerkleRoot { bytes root = 1; // 32-byte Merkle root - string proof_uri = 2; // URA of the published proof artefact + string proof_ura = 2; // URA of the published proof artefact } ``` @@ -292,7 +292,7 @@ One-byte discriminator followed by form-specific bytes: - `0x02` (list) — `count as u32be || scalar_bytes × count` where each entry is `receipt_hash(32) || len(uri) as u32be || uri`. Order is caller-asserted; runtime MUST NOT reorder. -- `0x03` (merkle) — `root(32) || len(proof_uri) as u32be || proof_uri`. +- `0x03` (merkle) — `root(32) || len(proof_ura) as u32be || proof_ura`. ### 4.3 Callee signature input @@ -444,10 +444,10 @@ On every state transition the runtime: - Caller key resolution is a pluggable interface, `KeyResolver`: ``` - resolve(agent_uri: str) → VerifyingKey + resolve(agent_ura: str) → VerifyingKey ``` -- RFC 001 ships a file-based resolver: `FileKeyResolver` maps `agent_uri +- RFC 001 ships a file-based resolver: `FileKeyResolver` maps `agent_ura → file path containing the 32-byte Ed25519 public key`. - `easynet-verify` binary uses the file-based resolver. No network diff --git a/document/rfcs/001-pr2-acceptance-checklist.md b/document/rfcs/001-pr2-acceptance-checklist.md index 86e1bbcc..d4a37b32 100644 --- a/document/rfcs/001-pr2-acceptance-checklist.md +++ b/document/rfcs/001-pr2-acceptance-checklist.md @@ -210,7 +210,7 @@ and §2.4 complete in commit 2b when admission is in place. - [ ] Missing `signing` ⇒ session is unsigned (legacy path). - [ ] `signing.algorithm != "ed25519"` ⇒ `BRIDGE_SIGNING_INTERNAL`. - [ ] `seed_base64` decodes to ≠ 32 bytes ⇒ `BRIDGE_SIGNING_INTERNAL`. - - [ ] `caller_uri` or `caller_profile` empty ⇒ `BRIDGE_BAD_REQUEST`. + - [ ] `caller_ura` or `caller_profile` empty ⇒ `BRIDGE_BAD_REQUEST`. - [ ] Session struct stores seed in a zeroize-on-drop wrapper; seed never appears in logs, trace, or read-back FFI. - [ ] `core/runtime-rs/dendrite-bridge/src/ability.rs`: new FFI @@ -255,7 +255,7 @@ otherwise the test is skipped for them but not removed. > dependency. They will be un-ignored and filled in by commit 2b. > Rows 08–12 are bridge-local and land in commit 2a. -- [ ] **Tampered caller_uri after sign** — bridge mutates `caller.uri` +- [ ] **Tampered caller_ura after sign** — bridge mutates `caller.uri` after signing (test-only hook); callee returns `AXON_CALLER_SIGNATURE_INVALID` with `source: "callee"`. - [ ] **Tampered payload after sign** — mutate payload bytes; same @@ -263,11 +263,11 @@ otherwise the test is skipped for them but not removed. - [ ] **Tampered subject after sign** — same expected error. - [ ] **Tampered causal_context after sign** — same expected error. - [ ] **Wrong session seed (identity spoof)** — session seed is - `[0x01; 32]` but `caller_uri` resolves server-side to a + `[0x01; 32]` but `caller_ura` resolves server-side to a different pubkey; runtime returns `AXON_CALLER_SIGNATURE_INVALID` with `source: "callee"`. - [ ] **Replay — same nonce twice** — two calls with identical - `(caller_uri, ability, nonce)` within the replay window; second + `(caller_ura, ability, nonce)` within the replay window; second call returns `AXON_NONCE_REPLAY` with `source: "callee"`. - [ ] **Replay does not consume quota** — same scenario, but also assert: caller's rate-limit counter did not increment on the @@ -289,7 +289,7 @@ otherwise the test is skipped for them but not removed. the signed path) > **Blocks on §2.0.** The receipt-chain assertion -> (`caller_binding.uri` matches session `caller_uri`, +> (`caller_binding.uri` matches session `caller_ura`, > `invocation_nonce` matches sent nonce) requires the server to > emit receipts bound to the admitted envelope. Until §5.2 > admission is plumbed on the server, the canonical-bytes and @@ -341,7 +341,7 @@ canonical_receipt_bytes` (pinned by offline (independent of the runtime). - [ ] Receipt chain retrieved via `get_invocation_receipts` includes a receipt whose `caller_binding.uri` matches the session's - `caller_uri` and whose `invocation_nonce` matches the sent + `caller_ura` and whose `invocation_nonce` matches the sent nonce. ### 2.5 Seed zeroization diff --git a/document/rfcs/002-1-distributed-realm-routing.md b/document/rfcs/002-1-distributed-realm-routing.md index 53690fd5..573f2958 100644 --- a/document/rfcs/002-1-distributed-realm-routing.md +++ b/document/rfcs/002-1-distributed-realm-routing.md @@ -78,8 +78,8 @@ Endpoints are RFCed-out URAs: `easynet:///r/sys/shard//abilities/...` LRT (Local Routing Table): realm_fqdn → (shard_endpoint, ttl_unix_ms, key_pin?) -resolve_target(target_uri): - realm = parse_realm(target_uri) +resolve_target(target_ura): + realm = parse_realm(target_ura) if LRT[realm] is fresh: return LRT[realm].endpoint if realm == self.realm: return "local" # Walk up the namespace @@ -97,18 +97,18 @@ inherits the delegation without re-querying the root. ### 2.3 Cross-shard forward_invoke -Today's `federation.forward_invoke` looks up `target_uri` in the +Today's `federation.forward_invoke` looks up `target_ura` in the local catalog and dispatches to the host's `runtime_local_tools`. Distributed extension: when the lookup misses, check if the target's realm belongs to a different shard, and if so, recurse: ``` -hub_forward_invoke(target_uri, signed_envelope): - if let Some(rec) = self.agents.lookup(target_uri): +hub_forward_invoke(target_ura, signed_envelope): + if let Some(rec) = self.agents.lookup(target_ura): # local — dispatch via runtime_local_tools (today's path) dispatch_local(rec.host_node_id, signed_envelope) else: - realm = parse_realm(target_uri) + realm = parse_realm(target_ura) target_shard = self.shard_resolver.resolve(realm) if target_shard == self.shard_id: return AXON_TARGET_NOT_IN_DIRECTORY diff --git a/document/rfcs/002-keyring-and-keyresolver.md b/document/rfcs/002-keyring-and-keyresolver.md index 8ad8b870..90568a57 100644 --- a/document/rfcs/002-keyring-and-keyresolver.md +++ b/document/rfcs/002-keyring-and-keyresolver.md @@ -76,7 +76,7 @@ message AgentIdentity { ``` **Verifier rule (admission Federated mode):** -1. Resolve `agent_uri` → list of `(key_id, public_key, rotation_epoch, status)`. +1. Resolve `agent_ura` → list of `(key_id, public_key, rotation_epoch, status)`. 2. Pick the entry where `key_id == envelope.caller.key_id`. 3. If `entry.rotation_epoch < latest_active_epoch` and grace_window has elapsed, reject `AXON_KEY_ROTATED`. @@ -202,9 +202,9 @@ pub struct LocalKeyringResolver { } impl KeyResolver for LocalKeyringResolver { - fn resolve(&self, agent_uri: &str) -> Result { + fn resolve(&self, agent_ura: &str) -> Result { self.keyring - .find_active_by_bound_subject(agent_uri) + .find_active_by_bound_subject(agent_ura) .map(|entry| VerifyingKey::from_bytes(&entry.public_key)) .ok_or(ResolveError::Unknown) } @@ -219,9 +219,9 @@ pub struct PeerKeyringResolver { } impl KeyResolver for PeerKeyringResolver { - fn resolve(&self, agent_uri: &str) -> Result { + fn resolve(&self, agent_ura: &str) -> Result { self.keyring - .find_peer_by_uri(agent_uri) + .find_peer_by_uri(agent_ura) .filter(|p| p.status == PeerStatus::Trusted) .map(|p| VerifyingKey::from_bytes(&p.public_key)) .ok_or(ResolveError::Unknown) @@ -235,9 +235,9 @@ impl KeyResolver for PeerKeyringResolver { pub struct ChainResolver(Vec>); impl KeyResolver for ChainResolver { - fn resolve(&self, agent_uri: &str) -> Result { + fn resolve(&self, agent_ura: &str) -> Result { for r in &self.0 { - match r.resolve(agent_uri) { + match r.resolve(agent_ura) { Ok(k) => return Ok(k), Err(ResolveError::Unknown) => continue, Err(e) => return Err(e), @@ -262,7 +262,7 @@ request to a not-yet-known peer fails closed rather than hanging. ### 5.1 `federation.resolve_key` ``` -Args: { agent_uri: string } +Args: { agent_ura: string } Returns: { public_key: bytes, key_id: string, rotation_epoch: u64, status: "active"|"retired"|"revoked" } ``` @@ -273,14 +273,14 @@ Returns `AXON_AGENT_NOT_IN_DIRECTORY` if the URA is unknown. ### 5.2 `federation.forward_invoke` ``` -Args: { target_uri: string, signed_envelope: bytes } +Args: { target_ura: string, signed_envelope: bytes } Returns: { receipt: bytes } ``` Hub algorithm: 1. Verify caller exists in directory and signature is valid. -2. Lookup `target_uri` in directory; if `signing_authority = HostedBy{host_uri}`, - route to that device daemon. Otherwise route to target_uri itself +2. Lookup `target_ura` in directory; if `signing_authority = HostedBy{host_ura}`, + route to that device daemon. Otherwise route to target_ura itself (self-signed agent on its own daemon). 3. Stream the signed envelope to the target daemon over the existing hub-to-daemon push channel (re-using the directory_events transport). @@ -289,7 +289,7 @@ Hub algorithm: the target ability's `[access]` block on the target daemon. Failure modes: -- `AXON_TARGET_NOT_IN_DIRECTORY` — unknown target_uri. +- `AXON_TARGET_NOT_IN_DIRECTORY` — unknown target_ura. - `AXON_TARGET_OFFLINE` — target's heartbeat is stale. - `AXON_FORWARD_TIMEOUT` — target accepted but did not return receipt within the configured forward window (default 30s). diff --git a/examples/00-entrance/hello-ability/README.md b/examples/00-entrance/hello-ability/README.md index 66a7d24b..a5b5d359 100644 --- a/examples/00-entrance/hello-ability/README.md +++ b/examples/00-entrance/hello-ability/README.md @@ -12,7 +12,7 @@ A single `greet(name) -> greeting` ability: - has a **declared schema** (input/output types, schema version); - is **bound to this process** (runs where it's hosted; cannot be equivalent-copied to another host at runtime); -- is **network-addressable** via `axon://capabilities/`; +- is **network-addressable** via `easynet:///r//ability/`; - produces an **auditable invocation record** after the call. A reader who runs this understands the difference between an diff --git a/examples/apps/multi-user-ability-control-tui-rs/src/app.rs b/examples/apps/multi-user-ability-control-tui-rs/src/app.rs index 674224da..a80eaa2f 100644 --- a/examples/apps/multi-user-ability-control-tui-rs/src/app.rs +++ b/examples/apps/multi-user-ability-control-tui-rs/src/app.rs @@ -137,7 +137,7 @@ impl App { *seq += 1; self.log(&format!( "RegisterNode owner={owner} node={node_id} subject={} url={}", - profile.subject_id, profile.base_resource_uri + profile.subject_id, profile.base_resource_ura )); } } @@ -329,12 +329,12 @@ impl App { self.refresh_snapshot(); } - fn ability_resource_uri(&self, owner_id: &str, ability_name: &str) -> Option { + fn ability_resource_ura(&self, owner_id: &str, ability_name: &str) -> Option { let profile = self.profiles.get(owner_id)?; let spec = self.ability_catalog.get(ability_name)?; Some(format!( "{}/abilities/{}@{}?tenant_id={}", - profile.base_resource_uri, ability_name, spec.version, self.tenant_id + profile.base_resource_ura, ability_name, spec.version, self.tenant_id )) } @@ -502,7 +502,7 @@ impl App { return; }; - let Some(resource_uri) = self.ability_resource_uri(owner_id, ability_name) else { + let Some(resource_ura) = self.ability_resource_ura(owner_id, ability_name) else { self.log(&format!( "Invoke blocked owner={owner_id} ability={ability_name} reason=URI_NOT_AVAILABLE" )); @@ -512,7 +512,7 @@ impl App { let payload = self.sample_payload(ability_name); let resp = match self.gateway.invoke_ability( &profile.subject_id, - &resource_uri, + &resource_ura, ability_name, &auth, payload.as_bytes(), @@ -593,7 +593,7 @@ impl App { let owner_id = format!("user.new{}", self.new_user_seq); let token = safe_token(&owner_id); let subject_id = format!("easynet:org:reg:agent.{token}"); - let base_resource_uri = format!("easynet:///r/org/reg/agent.{token}"); + let base_resource_ura = format!("easynet:///r/org/reg/agent.{token}"); let mut abilities = vec!["order.quote".to_string()]; let mut all: Vec = self.ability_catalog.keys().cloned().collect(); @@ -610,7 +610,7 @@ impl App { UserProfile { owner_id: owner_id.clone(), subject_id: subject_id.clone(), - base_resource_uri: base_resource_uri.clone(), + base_resource_ura: base_resource_ura.clone(), desired_abilities: abilities, }, ); @@ -623,7 +623,7 @@ impl App { self.add_node_for_owner(&owner_id); self.log(&format!( - "RegisterUserClient owner={owner_id} subject={subject_id} url={base_resource_uri}?tenant_id={}", + "RegisterUserClient owner={owner_id} subject={subject_id} url={base_resource_ura}?tenant_id={}", self.tenant_id )); @@ -879,7 +879,7 @@ impl App { lines.push(Line::styled( format!( "url_base: {}?tenant_id={}", - profile.base_resource_uri, self.tenant_id + profile.base_resource_ura, self.tenant_id ), Style::default().fg(Color::Blue), )); @@ -958,7 +958,7 @@ impl App { if let Some(selected) = abilities.get(self.ability_index) { let uri = self - .ability_resource_uri(&owner, selected) + .ability_resource_ura(&owner, selected) .unwrap_or_else(|| "-".to_string()); lines.push(Line::styled( format!("Selected URI: {uri}"), diff --git a/examples/apps/multi-user-ability-control-tui-rs/src/bin/shared/mcp_list_dir.rs b/examples/apps/multi-user-ability-control-tui-rs/src/bin/shared/mcp_list_dir.rs index 566bc015..abc14549 100644 --- a/examples/apps/multi-user-ability-control-tui-rs/src/bin/shared/mcp_list_dir.rs +++ b/examples/apps/multi-user-ability-control-tui-rs/src/bin/shared/mcp_list_dir.rs @@ -126,7 +126,7 @@ pub async fn publish_list_dir_capability( spec.signature = signature.to_vec(); spec.tags = tags.iter().map(|tag| tag.to_string()).collect(); spec.metadata = metadata; - spec.payload_uri = payload_ref.uri; + spec.payload_ura = payload_ref.uri; spec.payload_size_bytes = payload_ref.size_bytes; let (package_ref, _proof) = client diff --git a/examples/apps/multi-user-ability-control-tui-rs/src/gateway.rs b/examples/apps/multi-user-ability-control-tui-rs/src/gateway.rs index 33c483de..72d78a47 100644 --- a/examples/apps/multi-user-ability-control-tui-rs/src/gateway.rs +++ b/examples/apps/multi-user-ability-control-tui-rs/src/gateway.rs @@ -122,7 +122,7 @@ impl AxonGateway { labels.insert("easynet.subject_id".to_string(), profile.subject_id.clone()); labels.insert( "easynet.url_base".to_string(), - profile.base_resource_uri.clone(), + profile.base_resource_ura.clone(), ); labels.insert("easynet.tenant_id".to_string(), self.tenant_id.clone()); if let Some(auth) = auth { @@ -347,7 +347,7 @@ impl AxonGateway { spec_out.signature = vec![1, 2, 3]; spec_out.tags = vec!["gallery".to_string(), "mcp".to_string()]; spec_out.metadata = metadata; - spec_out.payload_uri = payload_ref.uri; + spec_out.payload_ura = payload_ref.uri; spec_out.payload_size_bytes = payload_ref.size_bytes; let (package_ref, _proof) = self @@ -402,7 +402,7 @@ impl AxonGateway { pub fn invoke_ability( &mut self, subject_id: &str, - resource_uri: &str, + resource_ura: &str, ability_name: &str, auth: &UserAuth, payload: &[u8], @@ -419,14 +419,14 @@ impl AxonGateway { self.runtime .block_on(async { self.client - .call_ability_uri_json( + .call_ability_ura_json( self.tenant_id.clone(), - resource_uri.to_string(), + resource_ura.to_string(), payload.to_vec(), options, ) .await }) - .context("call_ability_uri_json failed") + .context("call_ability_ura_json failed") } } diff --git a/examples/apps/multi-user-ability-control-tui-rs/src/models.rs b/examples/apps/multi-user-ability-control-tui-rs/src/models.rs index 6758b0cb..9c273ff2 100644 --- a/examples/apps/multi-user-ability-control-tui-rs/src/models.rs +++ b/examples/apps/multi-user-ability-control-tui-rs/src/models.rs @@ -62,7 +62,7 @@ impl AbilitySpec { pub struct UserProfile { pub owner_id: String, pub subject_id: String, - pub base_resource_uri: String, + pub base_resource_ura: String, pub desired_abilities: Vec, } @@ -139,7 +139,7 @@ pub fn make_profile(owner_id: &str, desired: Vec<&str>) -> UserProfile { UserProfile { owner_id: owner_id.to_string(), subject_id: format!("easynet:org:reg:agent.{token}"), - base_resource_uri: format!("easynet:///r/org/reg/agent.{token}"), + base_resource_ura: format!("easynet:///r/org/reg/agent.{token}"), desired_abilities: desired.into_iter().map(|s| s.to_string()).collect(), } } diff --git a/examples/ecosystem/04-cli-platform-bridge/15-device-client/ios/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h b/examples/ecosystem/04-cli-platform-bridge/15-device-client/ios/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h index 3fbe79b2..1576cedc 100644 --- a/examples/ecosystem/04-cli-platform-bridge/15-device-client/ios/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h +++ b/examples/ecosystem/04-cli-platform-bridge/15-device-client/ios/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h @@ -119,7 +119,7 @@ char *axon_dendrite_bidi_stream_call_json(uint64_t handle, // input JSON: // { // "tenant_id":"tenant-test", -// "resource_uri":"easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", +// "resource_ura":"easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", // "payload_json":{"sku":"A1","qty":2}, // "timeout_ms":30000 // } diff --git a/examples/ecosystem/04-cli-platform-bridge/15-device-client/macos/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h b/examples/ecosystem/04-cli-platform-bridge/15-device-client/macos/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h index 3fbe79b2..1576cedc 100644 --- a/examples/ecosystem/04-cli-platform-bridge/15-device-client/macos/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h +++ b/examples/ecosystem/04-cli-platform-bridge/15-device-client/macos/EasyNetAgent/CAxonBridge/include/axon_dendrite_bridge.h @@ -119,7 +119,7 @@ char *axon_dendrite_bidi_stream_call_json(uint64_t handle, // input JSON: // { // "tenant_id":"tenant-test", -// "resource_uri":"easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", +// "resource_ura":"easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", // "payload_json":{"sku":"A1","qty":2}, // "timeout_ms":30000 // } diff --git a/examples/reference/axiom-obligations/I1-admission-receipt/harness/src/main.rs b/examples/reference/axiom-obligations/I1-admission-receipt/harness/src/main.rs index a4a32bfa..9fa7e0c0 100644 --- a/examples/reference/axiom-obligations/I1-admission-receipt/harness/src/main.rs +++ b/examples/reference/axiom-obligations/I1-admission-receipt/harness/src/main.rs @@ -40,9 +40,9 @@ struct Args { lib: String, endpoint: String, caller_seed_hex: String, - caller_uri: String, - callee_uri: String, - subject_uri: String, + caller_ura: String, + callee_ura: String, + subject_ura: String, ability: String, nonce_hex: String, receipt_out: String, @@ -64,9 +64,9 @@ fn parse_args() -> Args { lib: get(&m, "--lib"), endpoint: get(&m, "--endpoint"), caller_seed_hex: get(&m, "--caller-seed-hex"), - caller_uri: get(&m, "--caller-uri"), - callee_uri: get(&m, "--callee-uri"), - subject_uri: get(&m, "--subject-uri"), + caller_ura: get(&m, "--caller-uri"), + callee_ura: get(&m, "--callee-uri"), + subject_ura: get(&m, "--subject-uri"), ability: get(&m, "--ability"), nonce_hex: get(&m, "--nonce-hex"), receipt_out: get(&m, "--receipt-out"), @@ -152,7 +152,7 @@ fn main() { "signing": { "algorithm": "ed25519", "seed_base64": base64_encode(&seed_bytes), - "caller_uri": args.caller_uri, + "caller_ura": args.caller_ura, "caller_profile": "easynet-strict-v2", }, }); @@ -174,11 +174,11 @@ fn main() { assert_eq!(nonce_bytes.len(), 16, "nonce must be 16 bytes"); let invoke_req = json!({ "callee": { - "uri": args.callee_uri, + "uri": args.callee_ura, "profile": "easynet-strict-v2", }, "subject": { - "uri": args.subject_uri, + "uri": args.subject_ura, "profile": "easynet-strict-v2", }, "ability": args.ability, diff --git a/examples/reference/cross-language-sdk/04-gallery/README.md b/examples/reference/cross-language-sdk/04-gallery/README.md index 0282101a..cd7d6b31 100644 --- a/examples/reference/cross-language-sdk/04-gallery/README.md +++ b/examples/reference/cross-language-sdk/04-gallery/README.md @@ -82,7 +82,7 @@ examples/cases/04-cross-language-native-sdk-gallery/run_packaged_local.sh - `AXON_TENANT`(默认 `tenant-test`) - `EASYNET_DENDRITE_BRIDGE_PLATFORM`(可选:`ios` / `android` / `linux` / `windows` / `macos`) - `EASYNET_DENDRITE_BRIDGE_HOME`(可选:解包目录,建议统一到 `dist/sdk-packs/` 或其上层目录) -- `RESOURCE_URI`(fluent 调用目标 URI) +- `RESOURCE_URA`(fluent 调用目标 URI) - `PAYLOAD_JSON`(fluent 调用 payload) - `RPC_PATH`(协议形态测试 path,默认 `/axon.v1.Invocation/Invoke`) @@ -130,7 +130,7 @@ PYTHONPATH=sdk/python \ python3 examples/cases/04-cross-language-native-sdk-gallery/clients/python/client_call.py \ --endpoint http://127.0.0.1:50051 \ --tenant tenant-test \ - --resource-uri 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ + --resource-ura 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ --payload '{"sku":"A1","qty":2}' ``` @@ -145,7 +145,7 @@ npm install npm run call -- \ --endpoint http://127.0.0.1:50051 \ --tenant tenant-test \ - --resource-uri 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ + --resource-ura 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ --payload '{"sku":"A1","qty":2}' ``` @@ -156,7 +156,7 @@ cd examples/cases/04-cross-language-native-sdk-gallery/clients/go go run . \ --endpoint http://127.0.0.1:50051 \ --tenant tenant-test \ - --resource-uri 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ + --resource-ura 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ --payload '{"sku":"A1","qty":2}' ``` @@ -167,7 +167,7 @@ cd examples/cases/04-cross-language-native-sdk-gallery/clients/java ./run.sh call \ --endpoint http://127.0.0.1:50051 \ --tenant tenant-test \ - --resource-uri 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ + --resource-ura 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ --payload '{"sku":"A1","qty":2}' ``` @@ -178,7 +178,7 @@ cd examples/cases/04-cross-language-native-sdk-gallery/clients/rust cargo run --bin client_call -- \ --endpoint http://127.0.0.1:50051 \ --tenant tenant-test \ - --resource-uri 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ + --resource-ura 'easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test' \ --payload '{"sku":"A1","qty":2}' ``` diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/go/case/shared/case_kit.go b/examples/reference/cross-language-sdk/04-gallery/clients/go/case/shared/case_kit.go index 8bceed69..095578d3 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/go/case/shared/case_kit.go +++ b/examples/reference/cross-language-sdk/04-gallery/clients/go/case/shared/case_kit.go @@ -12,7 +12,7 @@ import ( const ( defaultEndpoint = "http://127.0.0.1:50051" defaultTenant = "tenant-test" - defaultResourceURI = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test" + defaultResourceURA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test" defaultPayload = `{"sku":"A1","qty":2}` defaultPath = "/axon.v1.Invocation/Invoke" defaultTimeoutMs = 3000 @@ -23,7 +23,7 @@ const ( type CallConfig struct { Endpoint string Tenant string - ResourceURI string + ResourceURA string Payload string } @@ -44,7 +44,7 @@ func ParseCallConfig(argv []string) (CallConfig, error) { cfg := CallConfig{ Endpoint: values["endpoint"], Tenant: values["tenant"], - ResourceURI: values["resource-uri"], + ResourceURA: values["resource-ura"], Payload: values["payload"], } normalizeCallConfig(&cfg) @@ -116,8 +116,8 @@ func normalizeCallConfig(cfg *CallConfig) { if cfg.Tenant == "" { cfg.Tenant = defaultTenant } - if cfg.ResourceURI == "" { - cfg.ResourceURI = defaultResourceURI + if cfg.ResourceURA == "" { + cfg.ResourceURA = defaultResourceURA } if cfg.Payload == "" { cfg.Payload = defaultPayload diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/go/main.go b/examples/reference/cross-language-sdk/04-gallery/clients/go/main.go index 9b4a400b..7b67d256 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/go/main.go +++ b/examples/reference/cross-language-sdk/04-gallery/clients/go/main.go @@ -5,7 +5,7 @@ // Description: Cross-language native SDK fluent call sample entrypoint for tenant-scoped ability invocation and JSON output. // // Protocol Responsibility: -// - Accepts endpoint/tenant/resource-uri/payload input and executes one ability call through the language SDK. +// - Accepts endpoint/tenant/resource-ura/payload input and executes one ability call through the language SDK. // - Normalizes invocation output into deterministic JSON for gallery verification across language implementations. // // Implementation Approach: @@ -54,7 +54,7 @@ func main() { casekit.EnsureNativeLibEnv() result, err := easynet.NewClient(nil). Tenant(cfg.Tenant). - Ability(cfg.ResourceURI). + Ability(cfg.ResourceURA). Call(context.Background(), payload) if err != nil { fmt.Fprintf(os.Stderr, "gallery go call failed: %v\n", err) diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/ClientCall.java b/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/ClientCall.java index 9d1a8211..96db8bb8 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/ClientCall.java +++ b/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/ClientCall.java @@ -5,7 +5,7 @@ // Description: Cross-language native SDK fluent call sample entrypoint for tenant-scoped ability invocation and JSON output. // // Protocol Responsibility: -// - Accepts endpoint/tenant/resource-uri/payload input and executes one ability call through the language SDK. +// - Accepts endpoint/tenant/resource-ura/payload input and executes one ability call through the language SDK. // - Normalizes invocation output into deterministic JSON for gallery verification across language implementations. // // Implementation Approach: @@ -35,20 +35,20 @@ public static void main(String[] args) { CaseKit.CallArgs cfg = CaseKit.parseCallArgs(args); String bridgePath = CaseKit.requireNativeLibraryPath(); Map payload = CaseKit.parsePayloadJson(cfg.payload); - Map result = runClient(cfg.endpoint, cfg.tenant, cfg.resourceUri, bridgePath, payload); + Map result = runClient(cfg.endpoint, cfg.tenant, cfg.resourceUra, bridgePath, payload); System.out.println(GSON.toJson(result)); } private static Map runClient( String endpoint, String tenant, - String resourceUri, + String resourceUra, String bridgePath, Map payload ) { return run.easynet.axon.Client.of(new run.easynet.axon.SidecarTransport(endpoint, 5000, 30000, bridgePath)) .tenant(tenant) - .ability(resourceUri) + .ability(resourceUra) .call(payload); } diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/shared/CaseKit.java b/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/shared/CaseKit.java index 7963c41e..1294e6f4 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/shared/CaseKit.java +++ b/examples/reference/cross-language-sdk/04-gallery/clients/java/src/main/java/io/easynet/gallery/shared/CaseKit.java @@ -16,7 +16,7 @@ public final class CaseKit { }.getType(); private static final String DEFAULT_ENDPOINT = "http://127.0.0.1:50051"; private static final String DEFAULT_TENANT = "tenant-test"; - private static final String DEFAULT_RESOURCE_URI = + private static final String DEFAULT_RESOURCE_URA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; private static final String DEFAULT_PAYLOAD = "{\"sku\":\"A1\",\"qty\":2}"; private static final String DEFAULT_PATH = "/axon.v1.Invocation/Invoke"; @@ -27,13 +27,13 @@ public final class CaseKit { public static final class CallArgs { public final String endpoint; public final String tenant; - public final String resourceUri; + public final String resourceUra; public final String payload; - public CallArgs(String endpoint, String tenant, String resourceUri, String payload) { + public CallArgs(String endpoint, String tenant, String resourceUra, String payload) { this.endpoint = endpoint; this.tenant = tenant; - this.resourceUri = resourceUri; + this.resourceUra = resourceUra; this.payload = payload; } } @@ -64,7 +64,7 @@ public static CallArgs parseCallArgs(String[] args) { return new CallArgs( values.getOrDefault("endpoint", DEFAULT_ENDPOINT), values.getOrDefault("tenant", DEFAULT_TENANT), - values.getOrDefault("resource-uri", DEFAULT_RESOURCE_URI), + values.getOrDefault("resource-ura", DEFAULT_RESOURCE_URA), values.getOrDefault("payload", DEFAULT_PAYLOAD) ); } diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/node/client_call.ts b/examples/reference/cross-language-sdk/04-gallery/clients/node/client_call.ts index 8fe31c3d..5107368a 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/node/client_call.ts +++ b/examples/reference/cross-language-sdk/04-gallery/clients/node/client_call.ts @@ -5,7 +5,7 @@ // Description: Cross-language native SDK fluent call sample entrypoint for tenant-scoped ability invocation and JSON output. // // Protocol Responsibility: -// - Accepts endpoint/tenant/resource-uri/payload input and executes one ability call through the language SDK. +// - Accepts endpoint/tenant/resource-ura/payload input and executes one ability call through the language SDK. // - Normalizes invocation output into deterministic JSON for gallery verification across language implementations. // // Implementation Approach: @@ -27,7 +27,7 @@ import { client } from "@easynet-run/node"; import { ensureNativeLibEnv, parseCallArgs } from "./shared/case_kit"; function usage(): string { - return "usage: npm run call -- --endpoint --tenant --resource-uri --payload "; + return "usage: npm run call -- --endpoint --tenant --resource-ura --payload "; } function decodePayload(raw: string): Record { @@ -39,14 +39,14 @@ function decodePayload(raw: string): Record { } async function main(): Promise { - const { endpoint, tenant, resourceUri, payload } = parseCallArgs(process.argv.slice(2)); + const { endpoint, tenant, resourceUra, payload } = parseCallArgs(process.argv.slice(2)); const payloadObject = decodePayload(payload); process.env.EASYNET_AXON_ENDPOINT = endpoint; ensureNativeLibEnv(); const result = await client() .tenant(tenant) - .ability(resourceUri) + .ability(resourceUra) .call(payloadObject); process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); } diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.js b/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.js index bbfa7602..289d4505 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.js +++ b/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.js @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"; const DEFAULT_ENDPOINT = "http://127.0.0.1:50051"; const DEFAULT_TENANT = "tenant-test"; -const DEFAULT_RESOURCE_URI = +const DEFAULT_RESOURCE_URA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; const DEFAULT_PAYLOAD = '{"sku":"A1","qty":2}'; const DEFAULT_PATH = "/axon.v1.Invocation/Invoke"; @@ -31,7 +31,7 @@ export function parseCallArgs(argv) { return { endpoint: args.endpoint ?? DEFAULT_ENDPOINT, tenant: args.tenant ?? DEFAULT_TENANT, - resourceUri: args["resource-uri"] ?? DEFAULT_RESOURCE_URI, + resourceUra: args["resource-ura"] ?? DEFAULT_RESOURCE_URA, payload: args.payload ?? DEFAULT_PAYLOAD, }; } @@ -105,7 +105,7 @@ export function ensureNativeLibEnv() { export const defaults = { endpoint: DEFAULT_ENDPOINT, tenant: DEFAULT_TENANT, - resourceUri: DEFAULT_RESOURCE_URI, + resourceUra: DEFAULT_RESOURCE_URA, payload: DEFAULT_PAYLOAD, path: DEFAULT_PATH, }; diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.ts b/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.ts index da1986c8..30cd787c 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.ts +++ b/examples/reference/cross-language-sdk/04-gallery/clients/node/shared/case_kit.ts @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; export interface CallArgs { endpoint: string; tenant: string; - resourceUri: string; + resourceUra: string; payload: string; } @@ -20,7 +20,7 @@ export interface ProtocolArgs { const DEFAULT_ENDPOINT = "http://127.0.0.1:50051"; const DEFAULT_TENANT = "tenant-test"; -const DEFAULT_RESOURCE_URI = +const DEFAULT_RESOURCE_URA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; const DEFAULT_PAYLOAD = '{"sku":"A1","qty":2}'; const DEFAULT_PATH = "/axon.v1.Invocation/Invoke"; @@ -47,7 +47,7 @@ export function parseCallArgs(argv: string[]): CallArgs { return { endpoint: args.endpoint ?? DEFAULT_ENDPOINT, tenant: args.tenant ?? DEFAULT_TENANT, - resourceUri: args["resource-uri"] ?? DEFAULT_RESOURCE_URI, + resourceUra: args["resource-ura"] ?? DEFAULT_RESOURCE_URA, payload: args.payload ?? DEFAULT_PAYLOAD, }; } @@ -121,7 +121,7 @@ export function ensureNativeLibEnv(): void { export const defaults = { endpoint: DEFAULT_ENDPOINT, tenant: DEFAULT_TENANT, - resourceUri: DEFAULT_RESOURCE_URI, + resourceUra: DEFAULT_RESOURCE_URA, payload: DEFAULT_PAYLOAD, path: DEFAULT_PATH, }; diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/python/client_call.py b/examples/reference/cross-language-sdk/04-gallery/clients/python/client_call.py index 636f6235..9f518a22 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/python/client_call.py +++ b/examples/reference/cross-language-sdk/04-gallery/clients/python/client_call.py @@ -7,7 +7,7 @@ # Description: Cross-language native SDK fluent call sample entrypoint for tenant-scoped ability invocation and JSON output. # # Protocol Responsibility: -# - Accepts endpoint/tenant/resource-uri/payload input and executes one ability call through the language SDK. +# - Accepts endpoint/tenant/resource-ura/payload input and executes one ability call through the language SDK. # - Normalizes invocation output into deterministic JSON for gallery verification across language implementations. # # Implementation Approach: @@ -57,7 +57,7 @@ def main() -> int: os.environ["EASYNET_AXON_ENDPOINT"] = args.endpoint ensure_native_bridge_env() payload = parse_payload(args.payload) - result = client().tenant(args.tenant).ability(args.resource_uri).call(payload) + result = client().tenant(args.tenant).ability(args.resource_ura).call(payload) print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True)) return 0 diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/python/shared/case_kit.py b/examples/reference/cross-language-sdk/04-gallery/clients/python/shared/case_kit.py index b0c1d2bf..ca5e1bed 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/python/shared/case_kit.py +++ b/examples/reference/cross-language-sdk/04-gallery/clients/python/shared/case_kit.py @@ -11,7 +11,7 @@ def default_case_options() -> dict[str, str]: return { "endpoint": "http://127.0.0.1:50051", "tenant": "tenant-test", - "resource_uri": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", + "resource_ura": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", "payload": '{"sku":"A1","qty":2}', "path": "/axon.v1.Invocation/Invoke", } @@ -22,7 +22,7 @@ def add_base_arguments(parser: argparse.ArgumentParser, mode: str) -> None: if mode == "call": parser.add_argument("--endpoint", default=defaults["endpoint"]) parser.add_argument("--tenant", default=defaults["tenant"]) - parser.add_argument("--resource-uri", default=defaults["resource_uri"]) + parser.add_argument("--resource-ura", default=defaults["resource_ura"]) parser.add_argument("--payload", default=defaults["payload"]) elif mode == "protocol-shapes": parser.add_argument("--endpoint", default=defaults["endpoint"]) diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/rust/src/bin/client_call.rs b/examples/reference/cross-language-sdk/04-gallery/clients/rust/src/bin/client_call.rs index 4c465b32..5e7d9fd4 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/rust/src/bin/client_call.rs +++ b/examples/reference/cross-language-sdk/04-gallery/clients/rust/src/bin/client_call.rs @@ -5,7 +5,7 @@ //! Description: Cross-language native SDK fluent call sample entrypoint for tenant-scoped ability invocation and JSON output. //! //! Protocol Responsibility: -//! - Accepts endpoint/tenant/resource-uri/payload input and executes one ability call through the language SDK. +//! - Accepts endpoint/tenant/resource-ura/payload input and executes one ability call through the language SDK. //! - Normalizes invocation output into deterministic JSON for gallery verification across language implementations. //! //! Implementation Approach: @@ -37,13 +37,13 @@ use gallery_native_sdk_rust::shared::case_kit::ensure_native_bridge_library; struct CallConfig { endpoint: String, tenant: String, - resource_uri: String, + resource_ura: String, payload: String, } const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:50051"; const DEFAULT_TENANT: &str = "tenant-test"; -const DEFAULT_RESOURCE_URI: &str = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; +const DEFAULT_RESOURCE_URA: &str = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; const DEFAULT_PAYLOAD: &str = "{\"sku\":\"A1\",\"qty\":2}"; fn parse_call_config(argv: &[String]) -> Result { @@ -54,10 +54,10 @@ fn parse_call_config(argv: &[String]) -> Result { .cloned() .unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()), tenant: values.get("tenant").cloned().unwrap_or_else(|| DEFAULT_TENANT.to_string()), - resource_uri: values - .get("resource-uri") + resource_ura: values + .get("resource-ura") .cloned() - .unwrap_or_else(|| DEFAULT_RESOURCE_URI.to_string()), + .unwrap_or_else(|| DEFAULT_RESOURCE_URA.to_string()), payload: values.get("payload").cloned().unwrap_or_else(|| DEFAULT_PAYLOAD.to_string()), }) } @@ -103,7 +103,7 @@ async fn run() -> Result<(), String> { .map_err(|e| format!("failed to connect axon endpoint: {e}"))?; let resp = client .tenant(cfg.tenant.clone()) - .ability(cfg.resource_uri.clone()) + .ability(cfg.resource_ura.clone()) .call_json(payload_bytes) .await .map_err(|e| format!("ability call failed: {e}"))?; @@ -115,7 +115,7 @@ async fn run() -> Result<(), String> { "ok": true, "endpoint": cfg.endpoint, "tenant": cfg.tenant, - "resource_uri": cfg.resource_uri, + "resource_ura": cfg.resource_ura, "state": resp.state, "elapsed_ms": resp.elapsed_ms, "selected_node_id": resp.selected_node_id, diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/ClientCall/main.swift b/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/ClientCall/main.swift index 2fdca5d7..4dea52dd 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/ClientCall/main.swift +++ b/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/ClientCall/main.swift @@ -12,7 +12,7 @@ struct NativeSwiftClientCall { let payload = try parsePayloadObject(config.payload) let result = try client() .tenant(config.tenant) - .ability(config.resourceURI) + .ability(config.resourceURA) .call(payload) try printJSON(anyJSONObject(result)) } catch { diff --git a/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/Shared/NativeCaseKit.swift b/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/Shared/NativeCaseKit.swift index 394c53fe..8bfc14b3 100644 --- a/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/Shared/NativeCaseKit.swift +++ b/examples/reference/cross-language-sdk/04-gallery/clients/swift/Sources/Shared/NativeCaseKit.swift @@ -10,7 +10,7 @@ import Glibc struct NativeCallConfig { let endpoint: String let tenant: String - let resourceURI: String + let resourceURA: String let payload: String } @@ -28,7 +28,7 @@ func parseNativeCallConfig(arguments: [String]) throws -> NativeCallConfig { return NativeCallConfig( endpoint: args["endpoint"] ?? "http://127.0.0.1:50051", tenant: args["tenant"] ?? "tenant-test", - resourceURI: args["resource-uri"] ?? "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", + resourceURA: args["resource-ura"] ?? "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", payload: args["payload"] ?? #"{"sku":"A1","qty":2}"# ) } diff --git a/examples/reference/cross-language-sdk/04-gallery/run_packaged_local.sh b/examples/reference/cross-language-sdk/04-gallery/run_packaged_local.sh index 63332f26..b802ce21 100755 --- a/examples/reference/cross-language-sdk/04-gallery/run_packaged_local.sh +++ b/examples/reference/cross-language-sdk/04-gallery/run_packaged_local.sh @@ -20,7 +20,7 @@ APPS_DIR="${CASE_DIR}/clients" SDK_VERSION="${SDK_VERSION:-$(resolve_repo_version "${REPO_ROOT}" || echo "0.1.0")}" AXON_ENDPOINT="${AXON_ENDPOINT:-http://127.0.0.1:50051}" AXON_TENANT="${AXON_TENANT:-tenant-test}" -RESOURCE_URI="${RESOURCE_URI:-easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test}" +RESOURCE_URA="${RESOURCE_URA:-easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test}" PAYLOAD_JSON="${PAYLOAD_JSON:-{\"sku\":\"A1\",\"qty\":2}}" RPC_PATH="${RPC_PATH:-/axon.v1.Invocation/Invoke}" REQUEST_BASE64="${REQUEST_BASE64:-}" @@ -32,12 +32,12 @@ CASE04_AUTO_START_RUNTIME="${CASE04_AUTO_START_RUNTIME:-1}" # 1 auto-start local CASE04_RUNTIME_READY_TIMEOUT_SEC="${CASE04_RUNTIME_READY_TIMEOUT_SEC:-5}" CASE04_RUNTIME_BOOT_TIMEOUT_SEC="${CASE04_RUNTIME_BOOT_TIMEOUT_SEC:-80}" CASE04_BOOTSTRAP_SUBJECT_TRUST="${CASE04_BOOTSTRAP_SUBJECT_TRUST:-1}" # 1 pre-register owner-matched node/key before call mode -CASE04_BOOTSTRAP_OWNER_ID="${CASE04_BOOTSTRAP_OWNER_ID:-}" # optional explicit owner override; fallback derives from RESOURCE_URI subject +CASE04_BOOTSTRAP_OWNER_ID="${CASE04_BOOTSTRAP_OWNER_ID:-}" # optional explicit owner override; fallback derives from RESOURCE_URA subject CASE04_BOOTSTRAP_NODE_ID="${CASE04_BOOTSTRAP_NODE_ID:-case04-subject-bootstrap}" CASE04_BOOTSTRAP_DISPLAY_NAME="${CASE04_BOOTSTRAP_DISPLAY_NAME:-case04-subject-bootstrap}" CASE04_BOOTSTRAP_HEARTBEAT_MS="${CASE04_BOOTSTRAP_HEARTBEAT_MS:-1200}" CASE04_BOOTSTRAP_READY_TIMEOUT_SEC="${CASE04_BOOTSTRAP_READY_TIMEOUT_SEC:-45}" -CASE04_BOOTSTRAP_RESOURCE_CAPABILITY="${CASE04_BOOTSTRAP_RESOURCE_CAPABILITY:-1}" # 1 publish/install/activate RESOURCE_URI ability onto bootstrap node +CASE04_BOOTSTRAP_RESOURCE_CAPABILITY="${CASE04_BOOTSTRAP_RESOURCE_CAPABILITY:-1}" # 1 publish/install/activate RESOURCE_URA ability onto bootstrap node CASE04_BOOTSTRAP_SIGNATURE_BASE64="${CASE04_BOOTSTRAP_SIGNATURE_BASE64:-__AXON_EPHEMERAL_DO_NOT_USE_IN_PROD__}" CASE04_BOOTSTRAP_INSTALL_TIMEOUT_SEC="${CASE04_BOOTSTRAP_INSTALL_TIMEOUT_SEC:-45}" enable_placeholder_deploy_signature_for_local_demo "${CASE04_BOOTSTRAP_SIGNATURE_BASE64}" @@ -52,14 +52,14 @@ PACK_DIR="${REPO_ROOT}/dist/sdk-packs/${SDK_VERSION}" # The functions runtime_probe, wait_runtime_ready, endpoint_is_local, and # ensure_runtime_ready are provided by case_runner.sh (sourced above). -derive_owner_from_resource_uri() { - python3 - "${RESOURCE_URI}" <<'PY' +derive_owner_from_resource_ura() { + python3 - "${RESOURCE_URA}" <<'PY' import sys -resource_uri = sys.argv[1].strip() -if not resource_uri.startswith("easynet://"): +resource_ura = sys.argv[1].strip() +if not resource_ura.startswith("easynet://"): raise SystemExit(0) -rest = resource_uri[len("easynet://") :] +rest = resource_ura[len("easynet://") :] path = rest.split("?", 1)[0] parts = [p for p in path.split("/") if p] if len(parts) < 4 or parts[0].lower() != "r" or parts[2].lower() != "reg": @@ -70,14 +70,14 @@ if subject_value.startswith("agent.") and len(subject_value) > len("agent."): PY } -derive_ability_from_resource_uri() { - python3 - "${RESOURCE_URI}" <<'PY' +derive_ability_from_resource_ura() { + python3 - "${RESOURCE_URA}" <<'PY' import sys -resource_uri = sys.argv[1].strip() -if not resource_uri.startswith("easynet://"): +resource_ura = sys.argv[1].strip() +if not resource_ura.startswith("easynet://"): raise SystemExit(0) -rest = resource_uri[len("easynet://") :] +rest = resource_ura[len("easynet://") :] path = rest.split("?", 1)[0] parts = [p for p in path.split("/") if p] try: @@ -141,9 +141,9 @@ bootstrap_resource_capability() { fi local ability_spec - ability_spec="$(derive_ability_from_resource_uri)" + ability_spec="$(derive_ability_from_resource_ura)" if [[ -z "${ability_spec}" ]]; then - echo "[packaged-case04] skip resource capability bootstrap: cannot parse ability from RESOURCE_URI=${RESOURCE_URI}" >&2 + echo "[packaged-case04] skip resource capability bootstrap: cannot parse ability from RESOURCE_URA=${RESOURCE_URA}" >&2 return 0 fi local ability_name="${ability_spec%%|*}" @@ -181,7 +181,7 @@ SH "${command_template}" \ "${CASE04_BOOTSTRAP_SIGNATURE_BASE64}" \ "${CASE04_BOOTSTRAP_INSTALL_TIMEOUT_SEC}" \ - "${RESOURCE_URI}" \ + "${RESOURCE_URA}" \ >"${OUT_DIR}/bootstrap-capability.out" 2>"${LOG_DIR}/bootstrap-capability.log" <<'PY' import base64 import hashlib @@ -200,7 +200,7 @@ ability_version = sys.argv[5] command_template = sys.argv[6] signature_base64 = sys.argv[7] install_timeout_raw = sys.argv[8] -resource_uri = sys.argv[9] +resource_ura = sys.argv[9] try: install_timeout_seconds = int(float(install_timeout_raw)) @@ -287,7 +287,7 @@ with DendriteBridge(endpoint, connect_timeout_ms=2000) as bridge: activate = bridge.activate_capability(tenant, node_id, install_id) call = bridge.ability_call( tenant, - resource_uri, + resource_ura, payload_json={"case04_bootstrap_probe": True}, ) @@ -323,10 +323,10 @@ bootstrap_subject_trust_node() { local owner_id="${CASE04_BOOTSTRAP_OWNER_ID}" if [[ -z "${owner_id}" ]]; then - owner_id="$(derive_owner_from_resource_uri)" + owner_id="$(derive_owner_from_resource_ura)" fi if [[ -z "${owner_id}" ]]; then - echo "[packaged-case04] skip subject trust bootstrap: cannot derive owner from RESOURCE_URI and CASE04_BOOTSTRAP_OWNER_ID unset" >&2 + echo "[packaged-case04] skip subject trust bootstrap: cannot derive owner from RESOURCE_URA and CASE04_BOOTSTRAP_OWNER_ID unset" >&2 return 0 fi @@ -647,7 +647,7 @@ if [[ "${RUN_MODE}" == "call" || "${RUN_MODE}" == "both" ]]; then "${PY_BIN}" "${APPS_DIR}/python/client_call.py" \ --endpoint "${AXON_ENDPOINT}" \ --tenant "${AXON_TENANT}" \ - --resource-uri "${RESOURCE_URI}" \ + --resource-ura "${RESOURCE_URA}" \ --payload "${PAYLOAD_JSON}" fi @@ -658,7 +658,7 @@ if [[ "${RUN_MODE}" == "call" || "${RUN_MODE}" == "both" ]]; then "${NODE_TSX}" "${NODE_APP_DIR}/client_call.ts" \ --endpoint "${AXON_ENDPOINT}" \ --tenant "${AXON_TENANT}" \ - --resource-uri "${RESOURCE_URI}" \ + --resource-ura "${RESOURCE_URA}" \ --payload "${PAYLOAD_JSON}" fi @@ -670,7 +670,7 @@ if [[ "${RUN_MODE}" == "call" || "${RUN_MODE}" == "both" ]]; then GOSUMDB=off \ GOMODCACHE="${WORK_DIR}/gomodcache" \ _PAYLOAD="${PAYLOAD_JSON}" \ - bash -lc "cd '${GO_APP_DIR}' && go run -mod=mod . --endpoint '${AXON_ENDPOINT}' --tenant '${AXON_TENANT}' --resource-uri '${RESOURCE_URI}' --payload \"\${_PAYLOAD}\"" + bash -lc "cd '${GO_APP_DIR}' && go run -mod=mod . --endpoint '${AXON_ENDPOINT}' --tenant '${AXON_TENANT}' --resource-ura '${RESOURCE_URA}' --payload \"\${_PAYLOAD}\"" fi if case04_lang_enabled java; then @@ -679,7 +679,7 @@ if [[ "${RUN_MODE}" == "call" || "${RUN_MODE}" == "both" ]]; then java -cp "${JAVA_CP}" io.easynet.gallery.ClientCall \ --endpoint "${AXON_ENDPOINT}" \ --tenant "${AXON_TENANT}" \ - --resource-uri "${RESOURCE_URI}" \ + --resource-ura "${RESOURCE_URA}" \ --payload "${PAYLOAD_JSON}" fi @@ -687,7 +687,7 @@ if [[ "${RUN_MODE}" == "call" || "${RUN_MODE}" == "both" ]]; then run_step_logged "rust.call" \ env -u EASYNET_DENDRITE_BRIDGE_LIB \ _PAYLOAD="${PAYLOAD_JSON}" \ - bash -lc "cd '${RUST_APP_DIR}' && cargo run --quiet --bin client_call -- --endpoint '${AXON_ENDPOINT}' --tenant '${AXON_TENANT}' --resource-uri '${RESOURCE_URI}' --payload \"\${_PAYLOAD}\"" + bash -lc "cd '${RUST_APP_DIR}' && cargo run --quiet --bin client_call -- --endpoint '${AXON_ENDPOINT}' --tenant '${AXON_TENANT}' --resource-ura '${RESOURCE_URA}' --payload \"\${_PAYLOAD}\"" fi if case04_lang_enabled swift; then @@ -695,7 +695,7 @@ if [[ "${RUN_MODE}" == "call" || "${RUN_MODE}" == "both" ]]; then bash "${APPS_DIR}/swift/run.sh" call \ --endpoint "${AXON_ENDPOINT}" \ --tenant "${AXON_TENANT}" \ - --resource-uri "${RESOURCE_URI}" \ + --resource-ura "${RESOURCE_URA}" \ --payload "${PAYLOAD_JSON}" fi fi diff --git a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/go/shared/case_kit.go b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/go/shared/case_kit.go index 7510a98d..d099f476 100644 --- a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/go/shared/case_kit.go +++ b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/go/shared/case_kit.go @@ -9,7 +9,7 @@ import ( const ( defaultEndpoint = "http://127.0.0.1:50051" defaultTenant = "tenant-test" - defaultResourceURI = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test" + defaultResourceURA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test" defaultPayload = `{"sku":"A1","qty":2}` defaultPath = "/axon.v1.Invocation/Invoke" defaultTimeoutMs = 3000 @@ -20,7 +20,7 @@ const ( type CallConfig struct { Endpoint string Tenant string - ResourceURI string + ResourceURA string Payload string } @@ -41,7 +41,7 @@ func ParseCallConfig(argv []string) (CallConfig, error) { cfg := CallConfig{ Endpoint: values["endpoint"], Tenant: values["tenant"], - ResourceURI: values["resource-uri"], + ResourceURA: values["resource-ura"], Payload: values["payload"], } normalizeCallConfig(&cfg) @@ -91,8 +91,8 @@ func normalizeCallConfig(cfg *CallConfig) { if cfg.Tenant == "" { cfg.Tenant = defaultTenant } - if cfg.ResourceURI == "" { - cfg.ResourceURI = defaultResourceURI + if cfg.ResourceURA == "" { + cfg.ResourceURA = defaultResourceURA } if cfg.Payload == "" { cfg.Payload = defaultPayload diff --git a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/java/src/main/java/io/easynet/gallery/case05/shared/CaseKit.java b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/java/src/main/java/io/easynet/gallery/case05/shared/CaseKit.java index 57378992..61eec4e8 100644 --- a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/java/src/main/java/io/easynet/gallery/case05/shared/CaseKit.java +++ b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/java/src/main/java/io/easynet/gallery/case05/shared/CaseKit.java @@ -16,7 +16,7 @@ public final class CaseKit { }.getType(); private static final String DEFAULT_ENDPOINT = "http://127.0.0.1:50051"; private static final String DEFAULT_TENANT = "tenant-test"; - private static final String DEFAULT_RESOURCE_URI = + private static final String DEFAULT_RESOURCE_URA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; private static final String DEFAULT_PAYLOAD = "{\"sku\":\"A1\",\"qty\":2}"; private static final String DEFAULT_PATH = "/axon.v1.Invocation/Invoke"; @@ -27,13 +27,13 @@ public final class CaseKit { public static final class CallArgs { public final String endpoint; public final String tenant; - public final String resourceUri; + public final String resourceUra; public final String payload; - public CallArgs(String endpoint, String tenant, String resourceUri, String payload) { + public CallArgs(String endpoint, String tenant, String resourceUra, String payload) { this.endpoint = endpoint; this.tenant = tenant; - this.resourceUri = resourceUri; + this.resourceUra = resourceUra; this.payload = payload; } } @@ -64,7 +64,7 @@ public static CallArgs parseCallArgs(String[] args) { return new CallArgs( values.getOrDefault("endpoint", DEFAULT_ENDPOINT), values.getOrDefault("tenant", DEFAULT_TENANT), - values.getOrDefault("resource-uri", DEFAULT_RESOURCE_URI), + values.getOrDefault("resource-ura", DEFAULT_RESOURCE_URA), values.getOrDefault("payload", DEFAULT_PAYLOAD) ); } diff --git a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.js b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.js index bbfa7602..289d4505 100644 --- a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.js +++ b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.js @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"; const DEFAULT_ENDPOINT = "http://127.0.0.1:50051"; const DEFAULT_TENANT = "tenant-test"; -const DEFAULT_RESOURCE_URI = +const DEFAULT_RESOURCE_URA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; const DEFAULT_PAYLOAD = '{"sku":"A1","qty":2}'; const DEFAULT_PATH = "/axon.v1.Invocation/Invoke"; @@ -31,7 +31,7 @@ export function parseCallArgs(argv) { return { endpoint: args.endpoint ?? DEFAULT_ENDPOINT, tenant: args.tenant ?? DEFAULT_TENANT, - resourceUri: args["resource-uri"] ?? DEFAULT_RESOURCE_URI, + resourceUra: args["resource-ura"] ?? DEFAULT_RESOURCE_URA, payload: args.payload ?? DEFAULT_PAYLOAD, }; } @@ -105,7 +105,7 @@ export function ensureNativeLibEnv() { export const defaults = { endpoint: DEFAULT_ENDPOINT, tenant: DEFAULT_TENANT, - resourceUri: DEFAULT_RESOURCE_URI, + resourceUra: DEFAULT_RESOURCE_URA, payload: DEFAULT_PAYLOAD, path: DEFAULT_PATH, }; diff --git a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.ts b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.ts index da1986c8..30cd787c 100644 --- a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.ts +++ b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/node/shared/case_kit.ts @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; export interface CallArgs { endpoint: string; tenant: string; - resourceUri: string; + resourceUra: string; payload: string; } @@ -20,7 +20,7 @@ export interface ProtocolArgs { const DEFAULT_ENDPOINT = "http://127.0.0.1:50051"; const DEFAULT_TENANT = "tenant-test"; -const DEFAULT_RESOURCE_URI = +const DEFAULT_RESOURCE_URA = "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test"; const DEFAULT_PAYLOAD = '{"sku":"A1","qty":2}'; const DEFAULT_PATH = "/axon.v1.Invocation/Invoke"; @@ -47,7 +47,7 @@ export function parseCallArgs(argv: string[]): CallArgs { return { endpoint: args.endpoint ?? DEFAULT_ENDPOINT, tenant: args.tenant ?? DEFAULT_TENANT, - resourceUri: args["resource-uri"] ?? DEFAULT_RESOURCE_URI, + resourceUra: args["resource-ura"] ?? DEFAULT_RESOURCE_URA, payload: args.payload ?? DEFAULT_PAYLOAD, }; } @@ -121,7 +121,7 @@ export function ensureNativeLibEnv(): void { export const defaults = { endpoint: DEFAULT_ENDPOINT, tenant: DEFAULT_TENANT, - resourceUri: DEFAULT_RESOURCE_URI, + resourceUra: DEFAULT_RESOURCE_URA, payload: DEFAULT_PAYLOAD, path: DEFAULT_PATH, }; diff --git a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/python/shared/case_kit.py b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/python/shared/case_kit.py index b0c1d2bf..ca5e1bed 100644 --- a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/python/shared/case_kit.py +++ b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/python/shared/case_kit.py @@ -11,7 +11,7 @@ def default_case_options() -> dict[str, str]: return { "endpoint": "http://127.0.0.1:50051", "tenant": "tenant-test", - "resource_uri": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", + "resource_ura": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", "payload": '{"sku":"A1","qty":2}', "path": "/axon.v1.Invocation/Invoke", } @@ -22,7 +22,7 @@ def add_base_arguments(parser: argparse.ArgumentParser, mode: str) -> None: if mode == "call": parser.add_argument("--endpoint", default=defaults["endpoint"]) parser.add_argument("--tenant", default=defaults["tenant"]) - parser.add_argument("--resource-uri", default=defaults["resource_uri"]) + parser.add_argument("--resource-ura", default=defaults["resource_ura"]) parser.add_argument("--payload", default=defaults["payload"]) elif mode == "protocol-shapes": parser.add_argument("--endpoint", default=defaults["endpoint"]) diff --git a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/rust/src/lib.rs b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/rust/src/lib.rs index 0493108c..4863a3ce 100644 --- a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/rust/src/lib.rs +++ b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/rust/src/lib.rs @@ -235,7 +235,7 @@ impl DendriteBridge { signature_base64: Option<&str>, tags: &[&str], metadata: Value, - payload_uri: Option<&str>, + payload_ura: Option<&str>, payload_size_bytes: Option, package_bytes_base64: Option<&str>, signature_fingerprint: Option<&str>, @@ -250,7 +250,7 @@ impl DendriteBridge { "signature_base64": signature_base64.unwrap_or(""), "tags": tags, "metadata": metadata, - "payload_uri": payload_uri.unwrap_or(""), + "payload_ura": payload_ura.unwrap_or(""), "payload_size_bytes": payload_size_bytes, "package_bytes_base64": package_bytes_base64, "signature_fingerprint": signature_fingerprint, diff --git a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/swift/Sources/Shared/NativeCaseKit.swift b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/swift/Sources/Shared/NativeCaseKit.swift index 394c53fe..8bfc14b3 100644 --- a/examples/reference/cross-language-sdk/05-selected-dispatch/clients/swift/Sources/Shared/NativeCaseKit.swift +++ b/examples/reference/cross-language-sdk/05-selected-dispatch/clients/swift/Sources/Shared/NativeCaseKit.swift @@ -10,7 +10,7 @@ import Glibc struct NativeCallConfig { let endpoint: String let tenant: String - let resourceURI: String + let resourceURA: String let payload: String } @@ -28,7 +28,7 @@ func parseNativeCallConfig(arguments: [String]) throws -> NativeCallConfig { return NativeCallConfig( endpoint: args["endpoint"] ?? "http://127.0.0.1:50051", tenant: args["tenant"] ?? "tenant-test", - resourceURI: args["resource-uri"] ?? "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", + resourceURA: args["resource-ura"] ?? "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", payload: args["payload"] ?? #"{"sku":"A1","qty":2}"# ) } diff --git a/examples/reference/mcp-integration/10-tool-adapter/clients/python/tool_adapter_demo.py b/examples/reference/mcp-integration/10-tool-adapter/clients/python/tool_adapter_demo.py index bf24d29c..300508b1 100644 --- a/examples/reference/mcp-integration/10-tool-adapter/clients/python/tool_adapter_demo.py +++ b/examples/reference/mcp-integration/10-tool-adapter/clients/python/tool_adapter_demo.py @@ -85,7 +85,7 @@ def calculate_bmi(weight_kg: float, height_m: float) -> dict[str, object]: adapter.register_ability( "photo_capture", - resource_uri="easynet:///r/org/photo_capture", + resource_ura="easynet:///r/org/photo_capture", description="Capture a photo from a remote camera node.", parameters={ "type": "object", diff --git a/examples/reference/mcp-integration/10-tool-adapter/clients/rust/src/bin/tool_adapter_demo.rs b/examples/reference/mcp-integration/10-tool-adapter/clients/rust/src/bin/tool_adapter_demo.rs index 8ae613df..89911a8b 100644 --- a/examples/reference/mcp-integration/10-tool-adapter/clients/rust/src/bin/tool_adapter_demo.rs +++ b/examples/reference/mcp-integration/10-tool-adapter/clients/rust/src/bin/tool_adapter_demo.rs @@ -48,7 +48,7 @@ fn main() { ToolSpec { name: "get_horoscope".into(), description: "Get today's horoscope for a zodiac sign.".into(), - resource_uri: "easynet:///r/org/get_horoscope".into(), + resource_ura: "easynet:///r/org/get_horoscope".into(), parameters: json!({ "type": "object", "properties": { @@ -79,7 +79,7 @@ fn main() { ToolSpec { name: "calculate_bmi".into(), description: "Calculate BMI from weight (kg) and height (m).".into(), - resource_uri: "easynet:///r/org/calculate_bmi".into(), + resource_ura: "easynet:///r/org/calculate_bmi".into(), parameters: json!({ "type": "object", "properties": { @@ -96,7 +96,7 @@ fn main() { adapter.register_ability(ToolSpec { name: "photo_capture".into(), description: "Capture a photo from a remote camera node.".into(), - resource_uri: "easynet:///r/org/photo_capture".into(), + resource_ura: "easynet:///r/org/photo_capture".into(), parameters: json!({ "type": "object", "properties": { diff --git a/examples/reference/mcp-integration/10-tool-adapter/clients/swift/Sources/Case10Swift/main.swift b/examples/reference/mcp-integration/10-tool-adapter/clients/swift/Sources/Case10Swift/main.swift index 25cc70c6..75b6edcd 100644 --- a/examples/reference/mcp-integration/10-tool-adapter/clients/swift/Sources/Case10Swift/main.swift +++ b/examples/reference/mcp-integration/10-tool-adapter/clients/swift/Sources/Case10Swift/main.swift @@ -65,7 +65,7 @@ struct Case10Swift { _ = adapter.registerAbility( "photo_capture", - resourceURI: "easynet:///r/org/photo_capture", + resourceURA: "easynet:///r/org/photo_capture", description: "Capture a photo from a remote camera node.", parameters: [ "type": .string("object"), diff --git a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/go/main.go b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/go/main.go index 8c403592..59d7d4e8 100644 --- a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/go/main.go +++ b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/go/main.go @@ -50,7 +50,7 @@ func main() { nil, // outputSchema "1.0.0", []string{"media", "capture"}, - "", // resourceURI (auto-generated) + "", // resourceURA (auto-generated) "", // instructions nil, // inputExamples nil, // prerequisites @@ -63,7 +63,7 @@ func main() { fmt.Println("=== AbilityDescriptor ===") fmt.Printf("Name: %s\n", descriptor.Name) - fmt.Printf("Resource URI: %s\n", descriptor.ResourceURI) + fmt.Printf("Resource URA: %s\n", descriptor.ResourceURA) fmt.Printf("Version: %s\n", descriptor.Version) fmt.Println() diff --git a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/java/src/main/java/io/easynet/gallery/case11/LifecycleExportDemo.java b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/java/src/main/java/io/easynet/gallery/case11/LifecycleExportDemo.java index 809f93ba..e1565dab 100644 --- a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/java/src/main/java/io/easynet/gallery/case11/LifecycleExportDemo.java +++ b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/java/src/main/java/io/easynet/gallery/case11/LifecycleExportDemo.java @@ -67,12 +67,12 @@ public static void main(String[] args) { null, // outputSchema — use default "1.0.0", Arrays.asList("media", "capture"), - null // resourceUri — auto-generated + null // resourceUra — auto-generated ); System.out.println("=== AbilityDescriptor ==="); System.out.println("Name: " + descriptor.name); - System.out.println("Resource URI: " + descriptor.resourceUri); + System.out.println("Resource URA: " + descriptor.resourceUra); System.out.println("Version: " + descriptor.version); System.out.println(); diff --git a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/node_client.mjs b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/node_client.mjs index f7f7264f..109a4ad9 100644 --- a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/node_client.mjs +++ b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/node_client.mjs @@ -48,7 +48,7 @@ const descriptor = buildAbilityDescriptor({ console.log("=== AbilityDescriptor ==="); console.log(`Name: ${descriptor.name}`); -console.log(`Resource URI: ${descriptor.resourceUri}`); +console.log(`Resource URA: ${descriptor.resourceUra}`); console.log(`Version: ${descriptor.version}`); console.log(); diff --git a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/python_client.py b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/python_client.py index eccb7286..6ae9bf42 100644 --- a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/python_client.py +++ b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/python_client.py @@ -59,7 +59,7 @@ def main(): ) print("=== AbilityDescriptor ===") print(f"Name: {descriptor.name}") - print(f"Resource URI: {descriptor.resource_uri}") + print(f"Resource URA: {descriptor.resource_ura}") print(f"Version: {descriptor.version}") print() diff --git a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/rust/src/bin/lifecycle_export.rs b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/rust/src/bin/lifecycle_export.rs index 9c63607e..9cd34d0c 100644 --- a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/rust/src/bin/lifecycle_export.rs +++ b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/rust/src/bin/lifecycle_export.rs @@ -47,7 +47,7 @@ fn main() -> easynet_axon::AxonResult<()> { println!("=== AbilityDescriptor ==="); println!("Name: {}", descriptor.name); - println!("Resource URI: {}", descriptor.resource_uri); + println!("Resource URA: {}", descriptor.resource_ura); println!("Version: {}", descriptor.version); println!(); @@ -73,7 +73,7 @@ fn main() -> easynet_axon::AxonResult<()> { let spec_json = json!({ "name": spec.name, "description": spec.description, - "resource_uri": spec.resource_uri, + "resource_ura": spec.resource_ura, "parameters": spec.parameters, }); println!("=== ToolSpec ==="); diff --git a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/swift/Sources/Case11Swift/main.swift b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/swift/Sources/Case11Swift/main.swift index ba5445a2..c5c81bde 100644 --- a/examples/reference/skill-lifecycle/11-lifecycle-export/clients/swift/Sources/Case11Swift/main.swift +++ b/examples/reference/skill-lifecycle/11-lifecycle-export/clients/swift/Sources/Case11Swift/main.swift @@ -61,7 +61,7 @@ struct Case11Swift { "language": "swift", "descriptor": [ "name": descriptor.name, - "resource_uri": descriptor.resourceURI, + "resource_ura": descriptor.resourceURA, "version": descriptor.version, "tags": descriptor.tags, ], diff --git a/examples/reference/skill-lifecycle/12-remote-device/skill/SKILL.md b/examples/reference/skill-lifecycle/12-remote-device/skill/SKILL.md index f5112fbf..8ba3af83 100644 --- a/examples/reference/skill-lifecycle/12-remote-device/skill/SKILL.md +++ b/examples/reference/skill-lifecycle/12-remote-device/skill/SKILL.md @@ -5,7 +5,7 @@ compatibility: Requires Axon Runtime binary built and Python SDK metadata: author: easynet-axon version: "0.3.0" - axon-resource-uri: "easynet:///r/org/device-control" + axon-resource-ura: "easynet:///r/org/device-control" allowed-tools: Bash(*) --- @@ -127,5 +127,5 @@ ${CLAUDE_SKILL_DIR}/scripts/invoke.sh disconnect ## Axon Resource -- **URI**: `easynet:///r/org/device-control` +- **URA**: `easynet:///r/org/device-control` - **Version**: 0.3.0 diff --git a/examples/reference/tui-desktop-app/02-multi-user-tui/README.md b/examples/reference/tui-desktop-app/02-multi-user-tui/README.md index 4b8d2674..b4c92e9a 100644 --- a/examples/reference/tui-desktop-app/02-multi-user-tui/README.md +++ b/examples/reference/tui-desktop-app/02-multi-user-tui/README.md @@ -18,7 +18,7 @@ The TUI models protocol-aligned behavior: 3. Ability install and activate (`InstallCapability` + `ActivateCapability` semantics) 4. Server-side recognized ability set 5. Ability invocation and recent invocation history -6. Signed EasyNet invoke metadata verification (`subject_id`, `resource_uri`, nonce, payload hash, signature) +6. Signed EasyNet invoke metadata verification (`subject_id`, `resource_ura`, nonce, payload hash, signature) This case uses the real Axon runtime gRPC services in `core/runtime-rs`: @@ -27,7 +27,7 @@ This case uses the real Axon runtime gRPC services in `core/runtime-rs`: - `Invocation` for ability execution - `Interop` for MCP tool discovery -When `easynet.resource_uri` is present, runtime now enforces: +When `easynet.resource_ura` is present, runtime now enforces: - URI tenant/subject consistency checks - payload SHA-256 match diff --git a/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json b/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json index 6cbecfec..36c12e51 100644 --- a/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json +++ b/packaging/protocol-pack/conformance-vectors/easynet-uri-v1.json @@ -35,7 +35,7 @@ "tenant_id": "tenant-test", "input_uri": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=beta", "canonical_uri": null, - "expect_error": "tenant_id mismatch between envelope and resource_uri" + "expect_error": "tenant_id mismatch between envelope and resource_ura" } ] } diff --git a/packaging/protocol-pack/conformance-vectors/envelope-signing-v1.json b/packaging/protocol-pack/conformance-vectors/envelope-signing-v1.json index 31eedb10..9687d01d 100644 --- a/packaging/protocol-pack/conformance-vectors/envelope-signing-v1.json +++ b/packaging/protocol-pack/conformance-vectors/envelope-signing-v1.json @@ -6,7 +6,7 @@ "invocation_id", "subject_id", "tenant_id", - "resource_uri", + "resource_ura", "issued_at", "nonce", "payload_sha256" @@ -16,7 +16,7 @@ "invocation_id": "018f5c2d-5276-7c0b-bf39-95f954f1410c", "subject_id": "easynet:org:reg:agent.quote-bot", "tenant_id": "tenant-test", - "resource_uri": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", + "resource_ura": "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", "issued_at": "2026-02-20T00:00:00Z", "nonce": "bm9uY2UtMDEyMzQ1Njc4OWFiY2RlZg", "payload_sha256": "6a7f589a34e0f9f8f8879ff5764f359f09de41862073f52f7e7f57f9df6ec8ec" diff --git a/sdk/API_MAPPING.md b/sdk/API_MAPPING.md index 8f181123..fb8c65c4 100644 --- a/sdk/API_MAPPING.md +++ b/sdk/API_MAPPING.md @@ -87,7 +87,7 @@ translate between `Envelope.caller` (composite) and the - `AxonRuntime::envelope_tenant_id(envelope) → String` - `AxonRuntime::envelope_principal_id(envelope) → String` -- `AxonRuntime::build_caller_uri(tenant, principal) → String` +- `AxonRuntime::build_caller_ura(tenant, principal) → String` - `AxonRuntime::build_caller_identity(tenant, principal) → Option` See `core/runtime-rs/src/runtime/mod.rs` for their contract, test diff --git a/sdk/FEDERATION_INVOKE_SCHEMAS.md b/sdk/FEDERATION_INVOKE_SCHEMAS.md index 2eed5a43..5c7d156f 100644 --- a/sdk/FEDERATION_INVOKE_SCHEMAS.md +++ b/sdk/FEDERATION_INVOKE_SCHEMAS.md @@ -28,13 +28,13 @@ This is the post-§A1 replacement for the legacy `RegisterNode` RPC. ```json { - "agent_uri": "axon://realm/", + "agent_ura": "easynet:///r//agent/", "public_key_hex": "<64 hex chars>", "signing_authority": {"kind": "self_signed"} } ``` -`signing_authority` may also be `{"kind": "hosted_by", "host_uri": "..."}` +`signing_authority` may also be `{"kind": "hosted_by", "host_ura": "..."}` when the Agent is hosted by another. `public_key_hex` and `signing_authority` may be omitted on re-advertisement (the prior record is reused). @@ -54,7 +54,7 @@ Replaces the per-RPC ability publish path. ```json { - "agent_uri": "axon://realm/", + "agent_ura": "easynet:///r//agent/", "abilities": [ /* opaque RFC §1.6 ability descriptor objects */ ] } ``` @@ -96,7 +96,7 @@ collapses into a single revoke). ```json { - "agent_uri": "axon://realm/", + "agent_ura": "easynet:///r//agent/", "reason": "operator: maintenance" } ``` @@ -119,7 +119,7 @@ RPCs. ```json { "filter": { - "agent_uri_prefix": "axon://realm/edge-", + "agent_ura_prefix": "easynet:///r/realm/agent/edge-", "include_abilities": false } } @@ -134,7 +134,7 @@ without ability descriptors. { "agents": [ { - "uri": "axon://realm/foo", + "uri": "easynet:///r/realm/agent/foo", "status": "active", "abilities": [ /* present only when include_abilities=true */ ] } @@ -164,7 +164,7 @@ legacy realm-bind RPC. ```json { - "canonical_agent_uri": "axon://easynet/", + "canonical_agent_ura": "easynet:///r/easynet/agent/", "realm": "easynet", "join_receipt_hash": "" } @@ -213,22 +213,22 @@ test that asserts the helper produces this payload. ### V1 — `federation.advertise_agent`, minimal -Inputs: `agent_uri = "axon://realm/foo"`, all other fields omitted. +Inputs: `agent_ura = "easynet:///r/realm/agent/foo"`, all other fields omitted. Payload: ```json -{"agent_uri": "axon://realm/foo"} +{"agent_ura": "easynet:///r/realm/agent/foo"} ``` ### V2 — `federation.advertise_agent`, full -Inputs: `agent_uri = "axon://realm/foo"`, `public_key_hex = "deadbeef"`, +Inputs: `agent_ura = "easynet:///r/realm/agent/foo"`, `public_key_hex = "deadbeef"`, `signing_authority = {"kind": "self_signed"}`. Payload: ```json { - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "public_key_hex": "deadbeef", "signing_authority": {"kind": "self_signed"} } @@ -236,12 +236,12 @@ Payload: ### V3 — `federation.advertise_agent`, omit empty/blank fields -Inputs: `agent_uri = "axon://realm/foo"`, `public_key_hex = ""`, +Inputs: `agent_ura = "easynet:///r/realm/agent/foo"`, `public_key_hex = ""`, `signing_authority = {}` (empty dict). Payload: ```json -{"agent_uri": "axon://realm/foo"} +{"agent_ura": "easynet:///r/realm/agent/foo"} ``` (Empty `public_key_hex` and empty `signing_authority` are omitted — @@ -258,21 +258,21 @@ Payload: ### V5 — `federation.revoke`, no reason -Inputs: `agent_uri = "axon://realm/foo"`, `reason = null` (or empty). +Inputs: `agent_ura = "easynet:///r/realm/agent/foo"`, `reason = null` (or empty). Payload: ```json -{"agent_uri": "axon://realm/foo"} +{"agent_ura": "easynet:///r/realm/agent/foo"} ``` ### V6 — `federation.revoke`, with reason -Inputs: `agent_uri = "axon://realm/foo"`, `reason = "operator: maintenance"`. +Inputs: `agent_ura = "easynet:///r/realm/agent/foo"`, `reason = "operator: maintenance"`. Payload: ```json { - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "reason": "operator: maintenance" } ``` @@ -288,13 +288,13 @@ Payload: ### V8 — `federation.resolve`, with filter -Inputs: `agent_uri_prefix = "axon://realm/edge-"`, `include_abilities = true`. +Inputs: `agent_ura_prefix = "easynet:///r/realm/agent/edge-"`, `include_abilities = true`. Payload: ```json { "filter": { - "agent_uri_prefix": "axon://realm/edge-", + "agent_ura_prefix": "easynet:///r/realm/agent/edge-", "include_abilities": true } } @@ -302,12 +302,12 @@ Payload: ### V9 — `federation.advertise_abilities` -Inputs: `agent_uri = "axon://realm/foo"`, `abilities = [{"name": "echo"}]`. +Inputs: `agent_ura = "easynet:///r/realm/agent/foo"`, `abilities = [{"name": "echo"}]`. Payload: ```json { - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "abilities": [{"name": "echo"}] } ``` diff --git a/sdk/SDK_INTERFACE_SPEC.md b/sdk/SDK_INTERFACE_SPEC.md index 60b403ec..cb85c42b 100644 --- a/sdk/SDK_INTERFACE_SPEC.md +++ b/sdk/SDK_INTERFACE_SPEC.md @@ -100,7 +100,7 @@ elsewhere (`federationHeartbeat`). parameters (Rust, Go) accept `0` to mean "use the default". 3. The `federation.heartbeat` body is `{}` — the runtime reads the caller identity from the envelope. -4. `federation.revoke` carries a single `agent_uri` and an optional +4. `federation.revoke` carries a single `agent_ura` and an optional `reason`; drain-then-deregister is no longer expressible as two distinct verbs. 5. `federation.resolve` returns `{"agents": [...]}` where each agent diff --git a/sdk/conformance/cases/axiom/README.md b/sdk/conformance/cases/axiom/README.md index 2ca1d9e8..af65aa09 100644 --- a/sdk/conformance/cases/axiom/README.md +++ b/sdk/conformance/cases/axiom/README.md @@ -71,15 +71,15 @@ Where `canonical_causal_bytes` is: form == "none" → 0x00 form == "scalar" → 0x01 || receipt_hash (32 bytes) - || len_prefixed(receipt_uri) + || len_prefixed(receipt_ura) form == "list" → 0x02 || u32be(count(prior)) || for each ref in prior: receipt_hash (32 bytes) - || len_prefixed(receipt_uri) + || len_prefixed(receipt_ura) form == "merkle" → 0x03 || root (32 bytes) - || len_prefixed(proof_uri) + || len_prefixed(proof_ura) ``` **Primitives.** @@ -115,9 +115,9 @@ out per-vector; see the specific JSON file for the fields it uses. "description": "human-readable narrative — safe to ignore for test logic", "inputs": { - "caller": { "uri": "...", "profile": "easynet-strict-v2" }, - "callee": { "uri": "...", "profile": "easynet-strict-v2" }, - "subject": { "uri": "...", "profile": "easynet-strict-v2" }, + "caller": { "ura": "...", "profile": "easynet-strict-v2" }, + "callee": { "ura": "...", "profile": "easynet-strict-v2" }, + "subject": { "ura": "...", "profile": "easynet-strict-v2" }, "ability": "review", // Either `payload_base64` + `payload_hex_reference` OR `args_digest_hex` diff --git a/sdk/conformance/cases/axiom/axiom-e1-envelope-7tuple.json b/sdk/conformance/cases/axiom/axiom-e1-envelope-7tuple.json index 71074615..1e84df1e 100644 --- a/sdk/conformance/cases/axiom/axiom-e1-envelope-7tuple.json +++ b/sdk/conformance/cases/axiom/axiom-e1-envelope-7tuple.json @@ -6,15 +6,15 @@ "title": "envelope carries all seven axiom parameters", "inputs": { "caller": { - "uri": "easynet:///r/silan/agents/researcher@1.0", + "ura": "easynet:///r/silan/agents/researcher@1.0", "profile": "easynet-strict-v2" }, "callee": { - "uri": "easynet:///r/openai/agents/reviewer@1.0", + "ura": "easynet:///r/openai/agents/reviewer@1.0", "profile": "easynet-strict-v2" }, "subject": { - "uri": "easynet:///r/silan/papers/paper@draft-1", + "ura": "easynet:///r/silan/papers/paper@draft-1", "profile": "easynet-strict-v2" }, "ability": "review", diff --git a/sdk/conformance/cases/axiom/axiom-e2-caller-sig-required.json b/sdk/conformance/cases/axiom/axiom-e2-caller-sig-required.json index 7a53f1e0..d571f736 100644 --- a/sdk/conformance/cases/axiom/axiom-e2-caller-sig-required.json +++ b/sdk/conformance/cases/axiom/axiom-e2-caller-sig-required.json @@ -6,9 +6,9 @@ "title": "signature produced under one envelope must not verify for another", "description": "Signing bytes cover the full seven-tuple. If a verifier is given a mismatched envelope but a valid-looking signature, verification fails. This is the test that demonstrates the caller's signature cannot be stripped or replayed against a different envelope.", "inputs": { - "caller": { "uri": "easynet:///r/silan/x@1", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/openai/y@1", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/s@1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/x@1", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/openai/y@1", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/s@1", "profile": "easynet-strict-v2" }, "ability": "echo", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "22222222222222222222222222222222", diff --git a/sdk/conformance/cases/axiom/axiom-e3-nonce-replay-discriminated.json b/sdk/conformance/cases/axiom/axiom-e3-nonce-replay-discriminated.json index 63d9c2be..35968149 100644 --- a/sdk/conformance/cases/axiom/axiom-e3-nonce-replay-discriminated.json +++ b/sdk/conformance/cases/axiom/axiom-e3-nonce-replay-discriminated.json @@ -6,18 +6,18 @@ "title": "nonce is inside signed bytes; two envelopes differing only in nonce have distinct canonical bytes", "description": "RFC 001 §5.2 step 4 uses (caller.uri, invocation_nonce) as the admission dedup key. This vector proves that a replay attacker cannot change just the nonce and keep the signature — canonical bytes would differ and verification would fail.", "inputs_a": { - "caller": { "uri": "easynet:///r/silan/x@1", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/openai/y@1", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/s@1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/x@1", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/openai/y@1", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/s@1", "profile": "easynet-strict-v2" }, "ability": "echo", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "causal_context": { "form": "none" } }, "inputs_b": { - "caller": { "uri": "easynet:///r/silan/x@1", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/openai/y@1", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/s@1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/x@1", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/openai/y@1", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/s@1", "profile": "easynet-strict-v2" }, "ability": "echo", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", diff --git a/sdk/conformance/cases/axiom/axiom-e4-subject-distinct-from-callee.json b/sdk/conformance/cases/axiom/axiom-e4-subject-distinct-from-callee.json index dd2e858f..075003fe 100644 --- a/sdk/conformance/cases/axiom/axiom-e4-subject-distinct-from-callee.json +++ b/sdk/conformance/cases/axiom/axiom-e4-subject-distinct-from-callee.json @@ -6,9 +6,9 @@ "title": "subject URI can differ in namespace/scope/type from callee URI", "description": "Under RFC 001, a callee agent can act on a subject that lives in a different namespace. A receipt records both URIs independently. This test pins that the runtime MUST accept a subject whose namespace/scope/subject-type differs from the callee.", "inputs": { - "caller": { "uri": "easynet:///r/silan/agents/writer@1.0", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/openai/agents/reviewer@1.0", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/papers/paper@draft-1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/agents/writer@1.0", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/openai/agents/reviewer@1.0", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/papers/paper@draft-1", "profile": "easynet-strict-v2" }, "ability": "review", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "cccccccccccccccccccccccccccccccc", diff --git a/sdk/conformance/cases/axiom/axiom-e6-causal-scalar.json b/sdk/conformance/cases/axiom/axiom-e6-causal-scalar.json index 1ed8cba6..fa3efc93 100644 --- a/sdk/conformance/cases/axiom/axiom-e6-causal-scalar.json +++ b/sdk/conformance/cases/axiom/axiom-e6-causal-scalar.json @@ -9,7 +9,7 @@ "causal_context": { "form": "scalar", "receipt_hash_hex": "abababababababababababababababababababababababababababababababab", - "receipt_uri": "easynet:///r/silan/receipts/r1" + "receipt_ura": "easynet:///r/silan/receipts/r1" } }, "expect": { diff --git a/sdk/conformance/cases/axiom/axiom-e7-causal-list-fanin.json b/sdk/conformance/cases/axiom/axiom-e7-causal-list-fanin.json index 7c765149..3b9639af 100644 --- a/sdk/conformance/cases/axiom/axiom-e7-causal-list-fanin.json +++ b/sdk/conformance/cases/axiom/axiom-e7-causal-list-fanin.json @@ -9,8 +9,8 @@ "causal_context": { "form": "list", "prior": [ - { "receipt_hash_hex": "1111111111111111111111111111111111111111111111111111111111111111", "receipt_uri": "u1" }, - { "receipt_hash_hex": "2222222222222222222222222222222222222222222222222222222222222222", "receipt_uri": "u2" } + { "receipt_hash_hex": "1111111111111111111111111111111111111111111111111111111111111111", "receipt_ura": "u1" }, + { "receipt_hash_hex": "2222222222222222222222222222222222222222222222222222222222222222", "receipt_ura": "u2" } ] } }, @@ -18,8 +18,8 @@ "causal_context": { "form": "list", "prior": [ - { "receipt_hash_hex": "2222222222222222222222222222222222222222222222222222222222222222", "receipt_uri": "u2" }, - { "receipt_hash_hex": "1111111111111111111111111111111111111111111111111111111111111111", "receipt_uri": "u1" } + { "receipt_hash_hex": "2222222222222222222222222222222222222222222222222222222222222222", "receipt_ura": "u2" }, + { "receipt_hash_hex": "1111111111111111111111111111111111111111111111111111111111111111", "receipt_ura": "u1" } ] } }, diff --git a/sdk/conformance/cases/axiom/axiom-identity-composite-required.json b/sdk/conformance/cases/axiom/axiom-identity-composite-required.json index f7dd2d4b..e2651b60 100644 --- a/sdk/conformance/cases/axiom/axiom-identity-composite-required.json +++ b/sdk/conformance/cases/axiom/axiom-identity-composite-required.json @@ -6,18 +6,18 @@ "title": "identity fields are composite (URI + profile), not raw strings", "description": "Two envelopes with byte-identical URIs but different profiles must produce different canonical bytes — the profile is part of the identity block per §4.1. This is the anti-profile-confusion vector called out in §11 D-series: an implementation that strips the profile when hashing is non-conformant.", "inputs_strict": { - "caller": { "uri": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/openai/agents/q@1", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/openai/agents/q@1", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, "ability": "echo", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "dddddddddddddddddddddddddddddddd", "causal_context": { "form": "none" } }, "inputs_websafe": { - "caller": { "uri": "easynet:///r/silan/agents/q@1", "profile": "web-safe-v2" }, - "callee": { "uri": "easynet:///r/openai/agents/q@1", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/agents/q@1", "profile": "web-safe-v2" }, + "callee": { "ura": "easynet:///r/openai/agents/q@1", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, "ability": "echo", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "dddddddddddddddddddddddddddddddd", diff --git a/sdk/conformance/cases/axiom/axiom-profile-binding.json b/sdk/conformance/cases/axiom/axiom-profile-binding.json index 6581fc94..6c1e6c37 100644 --- a/sdk/conformance/cases/axiom/axiom-profile-binding.json +++ b/sdk/conformance/cases/axiom/axiom-profile-binding.json @@ -6,9 +6,9 @@ "title": "profile substitution produces different signing bytes (anti-profile-confusion)", "description": "A signature produced under profile A MUST NOT verify against the same URI under profile B, even if a re-hash of the URI alone would collide. This vector signs once under easynet-strict-v2 and attempts verification under web-safe-v2 — must fail.", "inputs": { - "caller": { "uri": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/openai/agents/q@1", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/openai/agents/q@1", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/agents/q@1", "profile": "easynet-strict-v2" }, "ability": "echo", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", diff --git a/sdk/conformance/cases/axiom/axiom-subject-survives-callee-swap.json b/sdk/conformance/cases/axiom/axiom-subject-survives-callee-swap.json index 6a314713..50c3af76 100644 --- a/sdk/conformance/cases/axiom/axiom-subject-survives-callee-swap.json +++ b/sdk/conformance/cases/axiom/axiom-subject-survives-callee-swap.json @@ -6,25 +6,25 @@ "title": "two invocations on the same subject with structurally different callees both verify; subject_binding is byte-identical across them", "description": "The §1.3 aha-demo vector: invocation A on subject paper@draft-1 is dispatched to pool-a/writer; pool-a dies; invocation B on the SAME subject URI is dispatched to pool-b/writer. Both receipts carry byte-identical subject_binding and legitimately different callee_binding. HTTP would require a 3xx redirect; Axon does not. This vector pins that the axiom encoder does not reorder or collapse these fields.", "inputs_a": { - "caller": { "uri": "easynet:///r/silan/agents/dispatcher@1.0", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/silan/pool-a/workers/writer@1.0", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/papers/paper@draft-1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/agents/dispatcher@1.0", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/silan/pool-a/workers/writer@1.0", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/papers/paper@draft-1", "profile": "easynet-strict-v2" }, "ability": "draft", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1", "causal_context": { "form": "none" } }, "inputs_b": { - "caller": { "uri": "easynet:///r/silan/agents/dispatcher@1.0", "profile": "easynet-strict-v2" }, - "callee": { "uri": "easynet:///r/silan/pool-b/workers/writer@1.0", "profile": "easynet-strict-v2" }, - "subject": { "uri": "easynet:///r/silan/papers/paper@draft-1", "profile": "easynet-strict-v2" }, + "caller": { "ura": "easynet:///r/silan/agents/dispatcher@1.0", "profile": "easynet-strict-v2" }, + "callee": { "ura": "easynet:///r/silan/pool-b/workers/writer@1.0", "profile": "easynet-strict-v2" }, + "subject": { "ura": "easynet:///r/silan/papers/paper@draft-1", "profile": "easynet-strict-v2" }, "ability": "draft", "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "invocation_nonce_hex": "b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2", "causal_context": { "form": "scalar", "receipt_hash_hex": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", - "receipt_uri": "easynet:///r/silan/receipts/partial-from-pool-a" + "receipt_ura": "easynet:///r/silan/receipts/partial-from-pool-a" } }, "expect": { diff --git a/sdk/conformance/cases/axiom/axiom-worked-example-authenticated.json b/sdk/conformance/cases/axiom/axiom-worked-example-authenticated.json index 484522db..724bc3a0 100644 --- a/sdk/conformance/cases/axiom/axiom-worked-example-authenticated.json +++ b/sdk/conformance/cases/axiom/axiom-worked-example-authenticated.json @@ -11,15 +11,15 @@ "inputs": { "signing_seed_hex": "0101010101010101010101010101010101010101010101010101010101010101", "caller": { - "uri": "easynet:///r/silan/agents/alice", + "ura": "easynet:///r/silan/agent/silan.alice", "profile": "easynet-strict-v2" }, "callee": { - "uri": "easynet:///r/openai/agents/reviewer@1.0", + "ura": "easynet:///r/openai/agent/openai.reviewer", "profile": "easynet-strict-v2" }, "subject": { - "uri": "easynet:///r/silan/papers/paper@draft-1", + "ura": "easynet:///r/silan/resource/silan.papers/paper", "profile": "easynet-strict-v2" }, "ability": "review", @@ -34,8 +34,8 @@ "expected": { "args_digest_hex": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", "caller_pubkey_hex": "8a88e3dd7409f195fd52db2d3cba5d72ca6709bf1d94121bf3748801b40f6f5c", - "canonical_invocation_sha256": "132aacb0e21a0159a187fc7d71f204f58ecf12feab06eec9f61d3769321820f7", - "caller_signature_base64": "onZ3dvtXDf66nw+I5xe1QPDH5Vm8uqxzELiuX79mNV5uPvvnoddClhFiDemXlF4gS5zWPXhZ4QGQ45FVuhdjBQ==" + "canonical_invocation_sha256": "68464c0da3500e842ece4d3e6e539ec74d12b741160bd5174b13234b02b1eb28", + "caller_signature_base64": "N78HErlFC7s7NiUumMf7s7mpaBiH+yV8rYo0m0YDxIzZf0d9i/7lMb0mTxMNVwHpP61mN5swqnPH/2WQUsO/AQ==" }, "invariants": { diff --git a/sdk/go/easynet/ability_lifecycle.go b/sdk/go/easynet/ability_lifecycle.go index d03e2ad0..08d9e36f 100644 --- a/sdk/go/easynet/ability_lifecycle.go +++ b/sdk/go/easynet/ability_lifecycle.go @@ -6,7 +6,7 @@ // // Protocol Responsibility: // - Defines typed ability descriptors, export targets, and deployment helpers exposed to SDK users. -// - Keeps cross-language ability naming, resource-uri, and tool-spec semantics aligned. +// - Keeps cross-language ability naming, resource-ura, and tool-spec semantics aligned. // // Implementation Approach: // - Separates pure descriptor/export helpers from bridge-backed deployment and invocation flows. @@ -84,7 +84,7 @@ type AbilityDescriptor struct { OutputSchema map[string]any `json:"output_schema"` Version string `json:"version"` Tags []string `json:"tags"` - ResourceURI string `json:"resource_uri"` + ResourceURA string `json:"resource_ura"` // Agent ecosystem extensions (SKILL.md / MCP / CLI) Instructions string `json:"instructions,omitempty"` InputExamples []any `json:"input_examples,omitempty"` @@ -94,10 +94,10 @@ type AbilityDescriptor struct { // MCP safety hints — fail-closed defaults per protocol convention. // Map to MCPToolSpec.{read_only_hint, destructive_hint, idempotent_hint, // open_world_hint} in types.proto:766-769. - ReadOnly bool `json:"read_only"` // ability does NOT modify state (default: false — assume writes) - Destructive bool `json:"destructive"` // ability MAY cause irreversible changes (default: true — assume destructive) - Idempotent bool `json:"idempotent"` // repeated calls produce same result (default: false — assume non-idempotent) - OpenWorld bool `json:"open_world"` // ability interacts with external entities (default: true — assume open-world) + ReadOnly bool `json:"read_only"` // ability does NOT modify state (default: false — assume writes) + Destructive bool `json:"destructive"` // ability MAY cause irreversible changes (default: true — assume destructive) + Idempotent bool `json:"idempotent"` // repeated calls produce same result (default: false — assume non-idempotent) + OpenWorld bool `json:"open_world"` // ability interacts with external entities (default: true — assume open-world) // Execution policy hints — advisory, enforced by runtime when supported. TimeoutSeconds int `json:"timeout_seconds,omitempty"` MaxRetries int `json:"max_retries,omitempty"` @@ -139,7 +139,7 @@ func BuildAbilityDescriptor( inputSchema, outputSchema map[string]any, version string, tags []string, - resourceURI string, + resourceURA string, instructions string, inputExamples []any, prerequisites []string, @@ -165,8 +165,8 @@ func BuildAbilityDescriptor( if tags == nil { tags = []string{} } - if resourceURI == "" { - resourceURI = fmt.Sprintf("easynet:///r/org/%s", token) + if resourceURA == "" { + resourceURA = ResourceDotURA("org", token, "") } return &AbilityDescriptor{ Name: name, @@ -177,7 +177,7 @@ func BuildAbilityDescriptor( OutputSchema: outputSchema, Version: version, Tags: tags, - ResourceURI: resourceURI, + ResourceURA: resourceURA, Instructions: instructions, InputExamples: inputExamples, Prerequisites: prerequisites, @@ -197,10 +197,10 @@ func BuildAbilityDescriptor( // ToToolSpec converts the descriptor to a ToolSpec for use with AbilityToolAdapter. func (d *AbilityDescriptor) ToToolSpec() ToolSpec { return ToolSpec{ - Name: d.ToolName, - Description: d.Description, - ResourceURI: d.ResourceURI, - Parameters: d.InputSchema, + Name: d.ToolName, + Description: d.Description, + ResourceURA: d.ResourceURA, + Parameters: d.InputSchema, ReadOnlyHint: d.ReadOnly, DestructiveHint: d.Destructive, IdempotentHint: d.Idempotent, @@ -214,7 +214,7 @@ func ExportAbility(descriptor *AbilityDescriptor, target AbilityTarget, axonEndp if axonEndpoint == "" { axonEndpoint = fmt.Sprintf("http://127.0.0.1:%d", DefaultAxonPort) } - invokeScript, err := generateInvokeScript(descriptor.ResourceURI, axonEndpoint) + invokeScript, err := generateInvokeScript(descriptor.ResourceURA, axonEndpoint) if err != nil { return nil, err } @@ -817,12 +817,12 @@ func federationSpawnEnv(hub, hubTenant, hubRuntimeID, hubLabel, hubJoinToken str // StartServerOptions configures local runtime bootstrap and federation join behavior. type StartServerOptions struct { - Endpoint string - LogFile string - Insecure *bool - Timeout time.Duration - Hub string - HubTenant string + Endpoint string + LogFile string + Insecure *bool + Timeout time.Duration + Hub string + HubTenant string // HubRuntimeID is a stable identifier for federation membership (JoinFederation.runtime_id). // If empty, the runtime falls back to its internally generated instance id. // Device clients should set this to their pairing node_id so Hub membership @@ -961,12 +961,12 @@ func sanitizeShellValue(value, label string) (string, error) { return value, nil } -func generateInvokeScript(resourceURI, endpoint string) (string, error) { +func generateInvokeScript(resourceURA, endpoint string) (string, error) { safeEP, err := sanitizeShellValue(endpoint, "endpoint") if err != nil { return "", err } - safeURI, err := sanitizeShellValue(resourceURI, "resource_uri") + safeURA, err := sanitizeShellValue(resourceURA, "resource_ura") if err != nil { return "", err } @@ -974,19 +974,19 @@ func generateInvokeScript(resourceURI, endpoint string) (string, error) { set -euo pipefail AXON_ENDPOINT="${AXON_ENDPOINT:-%s}" TENANT="${AXON_TENANT:-default}" -RESOURCE_URI="%s" +RESOURCE_URA="%s" ARGS="${1:-{}}" curl -sS -X POST "${AXON_ENDPOINT}/v1/invoke" \ -H "Content-Type: application/json" \ - -d "{\"tenant_id\":\"${TENANT}\",\"resource_uri\":\"${RESOURCE_URI}\",\"payload\":${ARGS}}" -`, safeEP, safeURI), nil + -d "{\"tenant_id\":\"${TENANT}\",\"resource_ura\":\"${RESOURCE_URA}\",\"payload\":${ARGS}}" +`, safeEP, safeURA), nil } -func pushMetadata(b *strings.Builder, version, resourceURI string) { +func pushMetadata(b *strings.Builder, version, resourceURA string) { b.WriteString("metadata:\n") b.WriteString(" author: easynet-axon\n") fmt.Fprintf(b, " version: \"%s\"\n", version) - fmt.Fprintf(b, " axon-resource-uri: \"%s\"\n", resourceURI) + fmt.Fprintf(b, " axon-resource-ura: \"%s\"\n", resourceURA) } func generateAbilityMd(descriptor *AbilityDescriptor, target AbilityTarget, token string) string { @@ -996,7 +996,7 @@ func generateAbilityMd(descriptor *AbilityDescriptor, target AbilityTarget, toke fmt.Fprintf(&b, "description: %s\n", descriptor.Description) b.WriteString("compatibility: Requires network access to Axon runtime\n") - pushMetadata(&b, descriptor.Version, descriptor.ResourceURI) + pushMetadata(&b, descriptor.Version, descriptor.ResourceURA) switch target { case AbilityTargetClaude: b.WriteString("allowed-tools: Bash(*)\n") @@ -1089,7 +1089,7 @@ func generateAbilityMd(descriptor *AbilityDescriptor, target AbilityTarget, toke fmt.Fprintf(&b, "${%s}/scripts/invoke.sh '{\"param\": \"value\"}'\n", skillDirVar) b.WriteString("```\n\n") b.WriteString("## Axon Resource\n\n") - fmt.Fprintf(&b, "- **URI**: `%s`\n", descriptor.ResourceURI) + fmt.Fprintf(&b, "- **URA**: `%s`\n", descriptor.ResourceURA) fmt.Fprintf(&b, "- **Version**: %s\n", descriptor.Version) if descriptor.Category != "" { fmt.Fprintf(&b, "- **Category**: %s\n", descriptor.Category) diff --git a/sdk/go/easynet/audio.go b/sdk/go/easynet/audio.go index a8b35396..bc84cb70 100644 --- a/sdk/go/easynet/audio.go +++ b/sdk/go/easynet/audio.go @@ -57,10 +57,10 @@ func DefaultMicConfig() MicConfig { type VadAggressiveness int const ( - VadQuality VadAggressiveness = 0 - VadLowBitrate VadAggressiveness = 1 - VadAggressive VadAggressiveness = 2 - VadVeryAggressive VadAggressiveness = 3 + VadQuality VadAggressiveness = 0 + VadLowBitrate VadAggressiveness = 1 + VadAggressive VadAggressiveness = 2 + VadVeryAggressive VadAggressiveness = 3 ) // VoiceActivityDetector: pure-Go energy+zero-crossing VAD. @@ -122,8 +122,8 @@ var ErrAudioUnavailable = errors.New("native audio backend not compiled in; buil // MicHandle is returned by OpenMic. Close stops capture. type MicHandle struct { - Sink *StreamSink - closeFn func() + Sink *StreamSink + closeFn func() } // Close stops the underlying input device and emits a terminal frame. diff --git a/sdk/go/easynet/client.go b/sdk/go/easynet/client.go index 737b525a..de9244c9 100644 --- a/sdk/go/easynet/client.go +++ b/sdk/go/easynet/client.go @@ -38,7 +38,7 @@ import ( type Payload map[string]any type Transport interface { - Call(ctx context.Context, tenantID string, resourceURI string, payload Payload) (Payload, error) + Call(ctx context.Context, tenantID string, resourceURA string, payload Payload) (Payload, error) } type CallOptions struct { @@ -47,11 +47,11 @@ type CallOptions struct { type PrincipalAwareTransport interface { Transport - CallWithOptions(ctx context.Context, tenantID string, resourceURI string, payload Payload, options CallOptions) (Payload, error) + CallWithOptions(ctx context.Context, tenantID string, resourceURA string, payload Payload, options CallOptions) (Payload, error) } type RawTransport interface { - CallRaw(ctx context.Context, tenantID string, resourceURI string, payload Payload, options CallOptions) (Payload, error) + CallRaw(ctx context.Context, tenantID string, resourceURA string, payload Payload, options CallOptions) (Payload, error) } type SidecarTransport struct { @@ -80,8 +80,8 @@ func defaultAxonEndpoint() string { return "http://127.0.0.1:50051" } -func subjectVisibilityFromResourceURI(resourceURI string) string { - normalized := strings.ToLower(strings.TrimSpace(resourceURI)) +func subjectVisibilityFromResourceURA(resourceURA string) string { + normalized := strings.ToLower(strings.TrimSpace(resourceURA)) if strings.HasPrefix(normalized, "easynet:///r/pub/") { return "pub" } @@ -91,7 +91,7 @@ func subjectVisibilityFromResourceURI(resourceURI string) string { return "org" } -func principalToSubjectID(principalID string, resourceURI string) string { +func principalToSubjectID(principalID string, resourceURA string) string { normalized := strings.TrimSpace(principalID) if normalized == "" { return "" @@ -99,7 +99,7 @@ func principalToSubjectID(principalID string, resourceURI string) string { if strings.HasPrefix(normalized, "easynet:") { return normalized } - return "easynet:" + subjectVisibilityFromResourceURI(resourceURI) + ":reg:agent." + normalized + return "easynet:" + subjectVisibilityFromResourceURA(resourceURA) + ":reg:agent." + normalized } func (s *SidecarTransport) ensureClient() error { @@ -173,16 +173,16 @@ func (s *SidecarTransport) Close() error { return outErr } -func (s *SidecarTransport) Call(ctx context.Context, tenantID string, resourceURI string, payload Payload) (Payload, error) { - return s.CallWithOptions(ctx, tenantID, resourceURI, payload, CallOptions{}) +func (s *SidecarTransport) Call(ctx context.Context, tenantID string, resourceURA string, payload Payload) (Payload, error) { + return s.CallWithOptions(ctx, tenantID, resourceURA, payload, CallOptions{}) } -type bridgeInvoker func(bridge *DendriteBridge, handle uint64, tenantID, resourceURI string, payload Payload, subjectID string, metadata map[string]string, timeoutMs int) (map[string]any, error) +type bridgeInvoker func(bridge *DendriteBridge, handle uint64, tenantID, resourceURA string, payload Payload, subjectID string, metadata map[string]string, timeoutMs int) (map[string]any, error) func (s *SidecarTransport) callInternal( ctx context.Context, tenantID string, - resourceURI string, + resourceURA string, payload Payload, options CallOptions, invoke bridgeInvoker, @@ -216,8 +216,8 @@ func (s *SidecarTransport) callInternal( } } - subjectID := principalToSubjectID(options.PrincipalID, resourceURI) - result, err := invoke(bridge, handle, tenantID, resourceURI, payload, subjectID, nil, timeoutMs) + subjectID := principalToSubjectID(options.PrincipalID, resourceURA) + result, err := invoke(bridge, handle, tenantID, resourceURA, payload, subjectID, nil, timeoutMs) if err != nil { // Flag the transport as disconnected when the error smells like a // dropped connection so the background worker can drive a reconnect @@ -240,11 +240,11 @@ func (s *SidecarTransport) callInternal( func (s *SidecarTransport) CallWithOptions( ctx context.Context, tenantID string, - resourceURI string, + resourceURA string, payload Payload, options CallOptions, ) (Payload, error) { - return s.callInternal(ctx, tenantID, resourceURI, payload, options, func(b *DendriteBridge, handle uint64, tid, ruri string, p Payload, sid string, md map[string]string, tms int) (map[string]any, error) { + return s.callInternal(ctx, tenantID, resourceURA, payload, options, func(b *DendriteBridge, handle uint64, tid, ruri string, p Payload, sid string, md map[string]string, tms int) (map[string]any, error) { return b.InvokeAbilityWithSubject(handle, tid, ruri, p, sid, md, tms) }) } @@ -252,11 +252,11 @@ func (s *SidecarTransport) CallWithOptions( func (s *SidecarTransport) CallRaw( ctx context.Context, tenantID string, - resourceURI string, + resourceURA string, payload Payload, options CallOptions, ) (Payload, error) { - return s.callInternal(ctx, tenantID, resourceURI, payload, options, func(b *DendriteBridge, handle uint64, tid, ruri string, p Payload, sid string, md map[string]string, tms int) (map[string]any, error) { + return s.callInternal(ctx, tenantID, resourceURA, payload, options, func(b *DendriteBridge, handle uint64, tid, ruri string, p Payload, sid string, md map[string]string, tms int) (map[string]any, error) { return b.InvokeAbilityRawWithSubject(handle, tid, ruri, p, sid, md, tms) }) } @@ -264,7 +264,7 @@ func (s *SidecarTransport) CallRaw( type Client struct { transport Transport tenantID string - resourceURI string + resourceURA string principalID string } @@ -285,9 +285,9 @@ func (c *Client) Tenant(tenantID string) *Client { return &next } -func (c *Client) Ability(resourceURI string) *Client { +func (c *Client) Ability(resourceURA string) *Client { next := *c - next.resourceURI = resourceURI + next.resourceURA = resourceURA return &next } @@ -301,7 +301,7 @@ func (c *Client) Call(ctx context.Context, payload Payload) (Payload, error) { if c.tenantID == "" { return nil, errors.New("tenant(...) is required before call(...)") } - if c.resourceURI == "" { + if c.resourceURA == "" { return nil, errors.New("ability(...) is required before call(...)") } if c.principalID != "" { @@ -309,20 +309,20 @@ func (c *Client) Call(ctx context.Context, payload Payload) (Payload, error) { return nil, errors.New("principal(...) cannot be blank") } if aware, ok := c.transport.(PrincipalAwareTransport); ok { - return aware.CallWithOptions(ctx, c.tenantID, c.resourceURI, payload, CallOptions{ + return aware.CallWithOptions(ctx, c.tenantID, c.resourceURA, payload, CallOptions{ PrincipalID: c.principalID, }) } return nil, errors.New("configured transport does not support principal(...) context") } - return c.transport.Call(ctx, c.tenantID, c.resourceURI, payload) + return c.transport.Call(ctx, c.tenantID, c.resourceURA, payload) } func (c *Client) CallRaw(ctx context.Context, payload Payload) (Payload, error) { if c.tenantID == "" { return nil, errors.New("tenant(...) is required before callRaw(...)") } - if c.resourceURI == "" { + if c.resourceURA == "" { return nil, errors.New("ability(...) is required before callRaw(...)") } rawTransport, ok := c.transport.(RawTransport) @@ -333,11 +333,11 @@ func (c *Client) CallRaw(ctx context.Context, payload Payload) (Payload, error) if strings.TrimSpace(c.principalID) == "" { return nil, errors.New("principal(...) cannot be blank") } - return rawTransport.CallRaw(ctx, c.tenantID, c.resourceURI, payload, CallOptions{ + return rawTransport.CallRaw(ctx, c.tenantID, c.resourceURA, payload, CallOptions{ PrincipalID: c.principalID, }) } - return rawTransport.CallRaw(ctx, c.tenantID, c.resourceURI, payload, CallOptions{}) + return rawTransport.CallRaw(ctx, c.tenantID, c.resourceURA, payload, CallOptions{}) } func (c *Client) CallAny(ctx context.Context, payload Payload) (any, error) { @@ -355,7 +355,7 @@ func (c *Client) CallAny(ctx context.Context, payload Payload) (any, error) { type AbilityHandler func(ctx context.Context, in Payload) (Payload, error) type abilityBuilder struct { - uri string + ura string h AbilityHandler } @@ -364,8 +364,8 @@ var abilityRegistry = struct { m map[string]AbilityHandler }{m: map[string]AbilityHandler{}} -func Ability(resourceURI string) *abilityBuilder { - return &abilityBuilder{uri: resourceURI} +func Ability(resourceURA string) *abilityBuilder { + return &abilityBuilder{ura: resourceURA} } func (b *abilityBuilder) Handle(h AbilityHandler) *abilityBuilder { @@ -376,7 +376,7 @@ func (b *abilityBuilder) Handle(h AbilityHandler) *abilityBuilder { func (b *abilityBuilder) Expose() { if b.h != nil { abilityRegistry.Lock() - abilityRegistry.m[b.uri] = b.h + abilityRegistry.m[b.ura] = b.h abilityRegistry.Unlock() } } diff --git a/sdk/go/easynet/client_test.go b/sdk/go/easynet/client_test.go index 657e0277..84070aa6 100644 --- a/sdk/go/easynet/client_test.go +++ b/sdk/go/easynet/client_test.go @@ -7,18 +7,18 @@ import ( type captureTransport struct { tenantID string - resourceURI string + resourceURA string payload Payload } func (t *captureTransport) Call( _ context.Context, tenantID string, - resourceURI string, + resourceURA string, payload Payload, ) (Payload, error) { t.tenantID = tenantID - t.resourceURI = resourceURI + t.resourceURA = resourceURA t.payload = payload return Payload{"ok": true}, nil } @@ -31,12 +31,12 @@ type captureRawTransport struct { func (t *captureRawTransport) CallRaw( _ context.Context, tenantID string, - resourceURI string, + resourceURA string, payload Payload, _ CallOptions, ) (Payload, error) { t.tenantID = tenantID - t.resourceURI = resourceURI + t.resourceURA = resourceURA t.payload = payload return t.raw, nil } @@ -58,8 +58,8 @@ func TestClientFluentReturnsImmutableCopies(t *testing.T) { if transport.tenantID != "tenant-test" { t.Fatalf("tenant not propagated, got %q", transport.tenantID) } - if transport.resourceURI == "" { - t.Fatalf("resource uri not propagated") + if transport.resourceURA == "" { + t.Fatalf("resource ura not propagated") } } @@ -125,7 +125,7 @@ func TestClientCallAnyRequiresResultJSONField(t *testing.T) { } } -func TestPrincipalToSubjectIDMapsPubVisibilityFromResourceURI(t *testing.T) { +func TestPrincipalToSubjectIDMapsPubVisibilityFromResourceURA(t *testing.T) { subjectID := principalToSubjectID( "alice", "easynet:///r/pub/reg/agent.alice/abilities/voice.stream@1.0.0", @@ -135,7 +135,7 @@ func TestPrincipalToSubjectIDMapsPubVisibilityFromResourceURI(t *testing.T) { } } -func TestPrincipalToSubjectIDMapsOrgVisibilityForNonPubResourceURI(t *testing.T) { +func TestPrincipalToSubjectIDMapsOrgVisibilityForNonPubResourceURA(t *testing.T) { subjectID := principalToSubjectID( "alice", "easynet:///r/org/reg/agent.alice/abilities/order.quote@1?tenant_id=tenant-test", diff --git a/sdk/go/easynet/dendrite_bridge_capability_request.go b/sdk/go/easynet/dendrite_bridge_capability_request.go index 8b8bb06b..6631cfc9 100644 --- a/sdk/go/easynet/dendrite_bridge_capability_request.go +++ b/sdk/go/easynet/dendrite_bridge_capability_request.go @@ -54,7 +54,7 @@ type PublishCapabilityRequest struct { Tags []string Requirements map[string]string Metadata map[string]string - PayloadURI string + PayloadURA string PayloadSizeBytes *int64 PackageBytesBase64 string SignatureFingerprint string @@ -82,8 +82,8 @@ func (r PublishCapabilityRequest) validate() error { return err } if strings.TrimSpace(r.PackageBytesBase64) == "" && - strings.TrimSpace(r.PayloadURI) == "" { - return fmt.Errorf("payload_uri or package_bytes_base64 is required") + strings.TrimSpace(r.PayloadURA) == "" { + return fmt.Errorf("payload_ura or package_bytes_base64 is required") } if r.PayloadSizeBytes != nil && *r.PayloadSizeBytes < 0 { return fmt.Errorf("payload_size_bytes must be >= 0") @@ -115,7 +115,7 @@ func (r PublishCapabilityRequest) helperPayload() (map[string]any, error) { "metadata": metadata, } putOptionalTrimmedString(payload, "digest", r.Digest) - putOptionalTrimmedString(payload, "payload_uri", r.PayloadURI) + putOptionalTrimmedString(payload, "payload_ura", r.PayloadURA) if err := putOptionalPayloadSize(payload, "payload_size_bytes", r.PayloadSizeBytes); err != nil { return nil, err } diff --git a/sdk/go/easynet/dendrite_bridge_capability_request_test.go b/sdk/go/easynet/dendrite_bridge_capability_request_test.go index 27e13b78..234a8d56 100644 --- a/sdk/go/easynet/dendrite_bridge_capability_request_test.go +++ b/sdk/go/easynet/dendrite_bridge_capability_request_test.go @@ -83,7 +83,7 @@ func TestPublishCapabilityRequestPayloadOmitsUnsetOptionalFields(t *testing.T) { Tags: nil, Requirements: nil, Metadata: nil, - PayloadURI: " ", + PayloadURA: " ", PayloadSizeBytes: int64Ptr(0), PackageBytesBase64: "", PublisherKeyVersion: 0, @@ -93,8 +93,8 @@ func TestPublishCapabilityRequestPayloadOmitsUnsetOptionalFields(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - if _, ok := payload["payload_uri"]; ok { - t.Fatalf("payload_uri must be omitted for blank value") + if _, ok := payload["payload_ura"]; ok { + t.Fatalf("payload_ura must be omitted for blank value") } if _, ok := payload["payload_size_bytes"]; ok { t.Fatalf("payload_size_bytes must be omitted for zero value") @@ -168,7 +168,7 @@ func TestPublishCapabilityRequestValidateRejectsNegativeProofSize(t *testing.T) Version: "1.0.0", SignatureBase64: "c2ln", Digest: "sha256:abc", - PayloadURI: "payload://bucket/object", + PayloadURA: "payload://bucket/object", PayloadSizeBytes: int64Ptr(-1), } err := req.validate() @@ -188,16 +188,16 @@ func TestPublishCapabilityRequestValidateRequiresPayloadSource(t *testing.T) { Version: "1.0.0", Digest: "", SignatureBase64: "c2ln", - PayloadURI: "https://example.com/payload.json", + PayloadURA: "https://example.com/payload.json", PayloadSizeBytes: int64Ptr(1), } if err := req.validate(); err != nil { t.Fatalf("expected valid publish request, got %v", err) } - req.PayloadURI = "" + req.PayloadURA = "" if err := req.validate(); err == nil { - t.Fatalf("expected validate to reject missing payload_uri/package_bytes_base64") + t.Fatalf("expected validate to reject missing payload_ura/package_bytes_base64") } req.PackageBytesBase64 = "cGF5bG9hZA==" @@ -214,7 +214,7 @@ func TestPublishCapabilityRequestValidateRejectsDigestOnlyPayloadSource(t *testi Version: "1.0.0", Digest: "sha256:abc", SignatureBase64: "c2ln", - PayloadURI: "", + PayloadURA: "", } if err := req.validate(); err == nil { t.Fatalf("expected validate to reject digest-only publish request without payload source") @@ -249,7 +249,7 @@ func TestPublishCapabilityRequestValidateRejectsDigestWithoutSha256Prefix(t *tes Version: "1.0.0", Digest: "abc123", SignatureBase64: "c2ln", - PayloadURI: "https://example.com/payload.json", + PayloadURA: "https://example.com/payload.json", } err := req.validate() if err == nil { diff --git a/sdk/go/easynet/dendrite_bridge_cgo.go b/sdk/go/easynet/dendrite_bridge_cgo.go index 4f4541f6..9c1b2108 100644 --- a/sdk/go/easynet/dendrite_bridge_cgo.go +++ b/sdk/go/easynet/dendrite_bridge_cgo.go @@ -128,13 +128,13 @@ var placeholderDeploySignatureWarning sync.Once // DendriteError and its Error() method are in dendrite_bridge_types.go. type dendriteBridgeSymbols struct { - open unsafe.Pointer - close unsafe.Pointer - unary unsafe.Pointer - stream unsafe.Pointer - clientStream unsafe.Pointer - bidiStream unsafe.Pointer - invokeAbility unsafe.Pointer + open unsafe.Pointer + close unsafe.Pointer + unary unsafe.Pointer + stream unsafe.Pointer + clientStream unsafe.Pointer + bidiStream unsafe.Pointer + invokeAbility unsafe.Pointer // invokeAbilitySigned is the RFC-001 authenticated invocation // FFI verb. Resolved at OpenDendriteBridge time alongside the // legacy unsigned verb so a session opened with `signing` can @@ -143,7 +143,7 @@ type dendriteBridgeSymbols struct { // that does not export this symbol because such a library cannot // produce caller-signed envelopes per AXIOM §"Obligations on the // audit chain". - invokeAbilitySigned unsafe.Pointer + invokeAbilitySigned unsafe.Pointer // invokeAbilityStreamSigned is the streaming counterpart added // in P5-rewrite-14. Same session-bound caller signature // guarantees as the unary verb; opens a server-streaming RPC @@ -154,30 +154,30 @@ type dendriteBridgeSymbols struct { // InvokeAbilityStreamSigned receive a typed errSymbolNotFound // when the slot is nil. invokeAbilityStreamSigned unsafe.Pointer - protocolCatalog unsafe.Pointer - invokeProtocol unsafe.Pointer - listNodes unsafe.Pointer - publishAbility unsafe.Pointer - installAbility unsafe.Pointer - activateAbility unsafe.Pointer - uninstall unsafe.Pointer - voiceCreateCall unsafe.Pointer - voiceGetCall unsafe.Pointer - voiceJoinCall unsafe.Pointer - voiceLeaveCall unsafe.Pointer - voiceUpdatePath unsafe.Pointer - voiceReport unsafe.Pointer - voiceEndCall unsafe.Pointer - voiceWatchCall unsafe.Pointer - voiceCreateSess unsafe.Pointer - voiceGetSess unsafe.Pointer - voiceSetDesc unsafe.Pointer - voiceAddCand unsafe.Pointer - voiceRefresh unsafe.Pointer - voiceEndSess unsafe.Pointer - voiceWatchSess unsafe.Pointer - coverage unsafe.Pointer - stringFree unsafe.Pointer + protocolCatalog unsafe.Pointer + invokeProtocol unsafe.Pointer + listNodes unsafe.Pointer + publishAbility unsafe.Pointer + installAbility unsafe.Pointer + activateAbility unsafe.Pointer + uninstall unsafe.Pointer + voiceCreateCall unsafe.Pointer + voiceGetCall unsafe.Pointer + voiceJoinCall unsafe.Pointer + voiceLeaveCall unsafe.Pointer + voiceUpdatePath unsafe.Pointer + voiceReport unsafe.Pointer + voiceEndCall unsafe.Pointer + voiceWatchCall unsafe.Pointer + voiceCreateSess unsafe.Pointer + voiceGetSess unsafe.Pointer + voiceSetDesc unsafe.Pointer + voiceAddCand unsafe.Pointer + voiceRefresh unsafe.Pointer + voiceEndSess unsafe.Pointer + voiceWatchSess unsafe.Pointer + coverage unsafe.Pointer + stringFree unsafe.Pointer // Incremental streaming (optional — may be nil for older native libraries) serverStreamOpen unsafe.Pointer streamNext unsafe.Pointer @@ -876,7 +876,7 @@ func (b *DendriteBridge) BidiStreamCall( func (b *DendriteBridge) InvokeAbility( handle uint64, tenantID string, - resourceURI string, + resourceURA string, payloadJSON any, metadata map[string]string, timeoutMs int, @@ -884,7 +884,7 @@ func (b *DendriteBridge) InvokeAbility( return b.InvokeAbilityRawWithSubject( handle, tenantID, - resourceURI, + resourceURA, payloadJSON, "", metadata, @@ -895,7 +895,7 @@ func (b *DendriteBridge) InvokeAbility( func (b *DendriteBridge) InvokeAbilityWithSubject( handle uint64, tenantID string, - resourceURI string, + resourceURA string, payloadJSON any, subjectID string, metadata map[string]string, @@ -904,7 +904,7 @@ func (b *DendriteBridge) InvokeAbilityWithSubject( return b.InvokeAbilityRawWithSubject( handle, tenantID, - resourceURI, + resourceURA, payloadJSON, subjectID, metadata, @@ -915,7 +915,7 @@ func (b *DendriteBridge) InvokeAbilityWithSubject( func (b *DendriteBridge) InvokeAbilityRawWithSubject( handle uint64, tenantID string, - resourceURI string, + resourceURA string, payloadJSON any, subjectID string, metadata map[string]string, @@ -929,7 +929,7 @@ func (b *DendriteBridge) InvokeAbilityRawWithSubject( } payload := map[string]any{ "tenant_id": tenantID, - "resource_uri": resourceURI, + "resource_ura": resourceURA, "payload_json": payloadJSON, "metadata": metadata, "timeout_ms": timeoutMs, diff --git a/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo.go b/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo.go index 47456b37..a47677d0 100644 --- a/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo.go +++ b/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo.go @@ -193,16 +193,16 @@ type StreamDescriptor struct { // unary `validate()`: callee → subject pairing → ability → payload // → nonce → causal. func (r SignedInvokeBidiOpenRequest) helperPayload() (map[string]any, error) { - if err := requireNonBlank("callee.uri", r.Callee.URI); err != nil { + if err := requireNonBlank("callee.ura", r.Callee.URA); err != nil { return nil, err } if err := requireNonBlank("callee.profile", r.Callee.Profile); err != nil { return nil, err } - subjectURI := strings.TrimSpace(r.Subject.URI) + subjectURA := strings.TrimSpace(r.Subject.URA) subjectProfile := strings.TrimSpace(r.Subject.Profile) - if (subjectURI != "") != (subjectProfile != "") { - return nil, errors.New("subject.uri and subject.profile must both be set or both be empty") + if (subjectURA != "") != (subjectProfile != "") { + return nil, errors.New("subject.ura and subject.profile must both be set or both be empty") } if err := requireNonBlank("ability", r.Ability); err != nil { return nil, err @@ -239,14 +239,14 @@ func (r SignedInvokeBidiOpenRequest) helperPayload() (map[string]any, error) { payload := map[string]any{ "callee": map[string]any{ - "uri": strings.TrimSpace(r.Callee.URI), + "ura": strings.TrimSpace(r.Callee.URA), "profile": strings.TrimSpace(r.Callee.Profile), }, "ability": strings.TrimSpace(r.Ability), } - if subjectURI != "" { + if subjectURA != "" { payload["subject"] = map[string]any{ - "uri": subjectURI, + "ura": subjectURA, "profile": subjectProfile, } } @@ -662,11 +662,11 @@ func decodeBidiFrame(payload map[string]any) (BidiFrame, error) { // (`stream_handle`, `request_id`) plus the framing `ok` flag. // // Centralizing this avoids two failure modes: -// 1. Forgetting to strip a key when a new typed field is added -// to BidiOpenResult — the test fixture pins the strip set. -// 2. Mutating the bridge's response map in place, which would -// surprise callers re-using `resp.Payload` (we don't today, -// but the contract is cheap to honor). +// 1. Forgetting to strip a key when a new typed field is added +// to BidiOpenResult — the test fixture pins the strip set. +// 2. Mutating the bridge's response map in place, which would +// surprise callers re-using `resp.Payload` (we don't today, +// but the contract is cheap to honor). func stripHoistedKeys(src map[string]any) map[string]any { out := make(map[string]any, len(src)) for k, v := range src { diff --git a/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo_test.go b/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo_test.go index 7da52643..a7e53320 100644 --- a/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo_test.go +++ b/sdk/go/easynet/dendrite_bridge_signed_invoke_bidi_cgo_test.go @@ -38,7 +38,7 @@ import ( func TestSignedInvokeBidiOpenRequestHelperPayloadRenamesPayloadKeys(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, Ability: "demo.echo", PayloadBase64: base64.StdEncoding.EncodeToString([]byte("hello")), }, @@ -64,7 +64,7 @@ func TestSignedInvokeBidiOpenRequestHelperPayloadRenamesPayloadKeys(t *testing.T func TestSignedInvokeBidiOpenRequestHelperPayloadHonorsArgsContentType(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, Ability: "demo.echo", PayloadBase64: base64.StdEncoding.EncodeToString([]byte{}), }, @@ -90,7 +90,7 @@ func TestSignedInvokeBidiOpenRequestHelperPayloadHonorsArgsContentType(t *testin func TestSignedInvokeBidiOpenRequestHelperPayloadEmitsStreams(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, Ability: "demo.echo", PayloadBase64: base64.StdEncoding.EncodeToString([]byte{}), }, @@ -159,11 +159,11 @@ func TestDecodeBidiFrameReceipt(t *testing.T) { "kind": "receipt", "sequence": float64(0), "receipt": map[string]any{ - "index": float64(0), - "invocation_id": "inv-12345", - "receipt_type": "admitted", - "state": float64(1), - "self_hash_hex": "abcd1234", + "index": float64(0), + "invocation_id": "inv-12345", + "receipt_type": "admitted", + "state": float64(1), + "self_hash_hex": "abcd1234", "prev_receipt_hash_hex": "0000", }, } @@ -217,18 +217,18 @@ func TestDecodeBidiFrameUnknownKindReturnsTypedError(t *testing.T) { } } -// helperPayload rejects an envelope where callee.uri is blank +// helperPayload rejects an envelope where callee.ura is blank // (mirrors the bridge-side preflight). Catching this Go-side // avoids a wasted FFI round-trip for an obvious shape error. func TestSignedInvokeBidiOpenRequestHelperPayloadRejectsBlankCallee(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: " ", Profile: "easynet-strict-v2"}, + Callee: SignedAgentIdentity{URA: " ", Profile: "easynet-strict-v2"}, Ability: "demo.echo", }, } if _, err := req.helperPayload(); err == nil { - t.Fatal("blank callee.uri must be rejected") + t.Fatal("blank callee.ura must be rejected") } } @@ -237,7 +237,7 @@ func TestSignedInvokeBidiOpenRequestHelperPayloadRejectsBlankCallee(t *testing.T func TestSignedInvokeBidiOpenRequestHelperPayloadRejectsBothPayloads(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, Ability: "demo.echo", PayloadJSON: map[string]any{"a": 1}, PayloadBase64: base64.StdEncoding.EncodeToString([]byte("oops")), @@ -254,7 +254,7 @@ func TestSignedInvokeBidiOpenRequestHelperPayloadRejectsBothPayloads(t *testing. func TestSignedInvokeBidiOpenRequestHelperPayloadAcceptsNoInitialArgs(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "easynet-strict-v2"}, Ability: "demo.echo", }, } @@ -277,7 +277,7 @@ func TestUint64FromAnyHandlesAllNumericVariants(t *testing.T) { }{ {float64(42), 42}, {int(7), 7}, - {int64(-1), 0}, // negative clamped to 0 + {int64(-1), 0}, // negative clamped to 0 {uint64(99), 99}, {"not-a-number", 0}, {nil, 0}, @@ -336,19 +336,19 @@ func TestUint32FromAnyOverflowSaturates(t *testing.T) { // ─── helperPayload deeper validation paths ─────────────────────── func TestSignedInvokeBidiOpenRequestRejectsHalfPopulatedSubject(t *testing.T) { - // The "subject pairing rule" — both URI and Profile must be + // The "subject pairing rule" — both URA and Profile must be // set or both empty. A half-set subject would silently map // to an empty SubjectIdentity bridge-side (Rust converter is // trim-aware), defeating the AXIOM seven-tuple's // subject-binding contract. cases := []SignedAgentIdentity{ - {URI: "easynet:///r/test/agent/echo", Profile: ""}, - {URI: "", Profile: "easynet-strict-v2"}, + {URA: "easynet:///r/test/agent/echo", Profile: ""}, + {URA: "", Profile: "easynet-strict-v2"}, } for _, sub := range cases { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Subject: sub, Ability: "demo.echo", PayloadBase64: base64.StdEncoding.EncodeToString([]byte{}), @@ -363,8 +363,8 @@ func TestSignedInvokeBidiOpenRequestRejectsHalfPopulatedSubject(t *testing.T) { func TestSignedInvokeBidiOpenRequestEmitsSubjectWhenFullySet(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, - Subject: SignedAgentIdentity{URI: "easynet:///r/test/agent/sub", Profile: "ps"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, + Subject: SignedAgentIdentity{URA: "easynet:///r/test/agent/sub", Profile: "ps"}, Ability: "demo.echo", }, } @@ -376,8 +376,8 @@ func TestSignedInvokeBidiOpenRequestEmitsSubjectWhenFullySet(t *testing.T) { if !ok { t.Fatalf("subject missing or wrong shape: %#v", got["subject"]) } - if subj["uri"] != "easynet:///r/test/agent/sub" { - t.Errorf("subject.uri = %q", subj["uri"]) + if subj["ura"] != "easynet:///r/test/agent/sub" { + t.Errorf("subject.ura = %q", subj["ura"]) } if subj["profile"] != "ps" { t.Errorf("subject.profile = %q", subj["profile"]) @@ -387,7 +387,7 @@ func TestSignedInvokeBidiOpenRequestEmitsSubjectWhenFullySet(t *testing.T) { func TestSignedInvokeBidiOpenRequestRejectsBlankAbility(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: " ", }, } @@ -399,7 +399,7 @@ func TestSignedInvokeBidiOpenRequestRejectsBlankAbility(t *testing.T) { func TestSignedInvokeBidiOpenRequestRejectsBlankCalleeProfile(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: " "}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: " "}, Ability: "demo.echo", }, } @@ -415,7 +415,7 @@ func TestSignedInvokeBidiOpenRequestRejectsInvalidNonceLength(t *testing.T) { for _, b64 := range []string{"AAAA", "AAAAAAAAAAAAAAAAAAAA", "Q=="} { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", NonceBase64: b64, }, @@ -429,7 +429,7 @@ func TestSignedInvokeBidiOpenRequestRejectsInvalidNonceLength(t *testing.T) { func TestSignedInvokeBidiOpenRequestThreadsMetadata(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", Metadata: map[string]string{ "tenant_id": "t-1", @@ -453,7 +453,7 @@ func TestSignedInvokeBidiOpenRequestThreadsMetadata(t *testing.T) { func TestSignedInvokeBidiOpenRequestOmitsEmptyMetadata(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", Metadata: map[string]string{}, }, @@ -470,7 +470,7 @@ func TestSignedInvokeBidiOpenRequestThreadsBidiSpecificBuffers(t *testing.T) { // its own constants without being told "I asked for 0". req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", }, ChunkTimeoutMs: 1500, @@ -495,7 +495,7 @@ func TestSignedInvokeBidiOpenRequestThreadsBidiSpecificBuffers(t *testing.T) { func TestSignedInvokeBidiOpenRequestOmitsZeroBuffers(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", }, ChunkTimeoutMs: 0, @@ -516,7 +516,7 @@ func TestSignedInvokeBidiOpenRequestOmitsZeroBuffers(t *testing.T) { func TestSignedInvokeBidiOpenRequestThreadsTimeout(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", TimeoutMs: 5000, }, @@ -535,7 +535,7 @@ func TestSignedInvokeBidiOpenRequestEmitsStreamsVerbatim(t *testing.T) { // silently shorten the wire payload. req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", }, Streams: []StreamDescriptor{ @@ -832,7 +832,7 @@ func TestBidiStreamHandleAccessor(t *testing.T) { func TestSignedInvokeBidiOpenRequestHelperPayloadRejectsNonStrictOrdering(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", }, Streams: []StreamDescriptor{ @@ -854,7 +854,7 @@ func TestSignedInvokeBidiOpenRequestHelperPayloadAcceptsStrictAndEmptyOrdering(t for _, ordering := range []string{"", "STRICT"} { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", }, Streams: []StreamDescriptor{{StreamID: 1, ContentType: "x", Ordering: ordering}}, @@ -872,7 +872,7 @@ func TestSignedInvokeBidiOpenRequestHelperPayloadAcceptsStrictAndEmptyOrdering(t func TestSignedInvokeBidiOpenRequestHelperPayloadRejectsLowercaseStrict(t *testing.T) { req := SignedInvokeBidiOpenRequest{ SignedInvokeRequest: SignedInvokeRequest{ - Callee: SignedAgentIdentity{URI: "easynet:///r/test/agent/echo", Profile: "p"}, + Callee: SignedAgentIdentity{URA: "easynet:///r/test/agent/echo", Profile: "p"}, Ability: "demo.echo", }, Streams: []StreamDescriptor{{StreamID: 1, ContentType: "x", Ordering: "strict"}}, diff --git a/sdk/go/easynet/dendrite_bridge_signed_invoke_cgo.go b/sdk/go/easynet/dendrite_bridge_signed_invoke_cgo.go index c64166f4..5ea4c88f 100644 --- a/sdk/go/easynet/dendrite_bridge_signed_invoke_cgo.go +++ b/sdk/go/easynet/dendrite_bridge_signed_invoke_cgo.go @@ -117,10 +117,10 @@ type SigningConfig struct { // SDK does not retain it. Seed []byte - // CallerURI is the canonical URA bound to this session. Every + // CallerURA is the canonical URA bound to this session. Every // invocation on the resulting handle will carry - // `envelope.caller.uri = CallerURI` per RFC 001 §3.2. - CallerURI string + // `envelope.caller.ura = CallerURA` per RFC 001 §3.2. + CallerURA string // CallerProfile is the URA encoding profile selector. RFC 001 // §3.1 pins it to "easynet-strict-v2"; supplying any other value @@ -130,24 +130,24 @@ type SigningConfig struct { // NewSigningConfig is the safe constructor for `SigningConfig`. It // fixes `CallerProfile` to the spec-pinned `easynet-strict-v2` value -// and validates seed length + caller URI non-emptiness. +// and validates seed length + caller URA non-emptiness. // // Callers who need to set a different profile (reserved for a future // URA spec) should construct `SigningConfig{...}` directly; the // bridge will reject it today, which is the correct behaviour until // the new profile is normatively defined. -func NewSigningConfig(seed []byte, callerURI string) (SigningConfig, error) { +func NewSigningConfig(seed []byte, callerURA string) (SigningConfig, error) { if len(seed) != 32 { return SigningConfig{}, fmt.Errorf("signing seed must be exactly 32 bytes, got %d", len(seed)) } - if strings.TrimSpace(callerURI) == "" { - return SigningConfig{}, errors.New("signing caller_uri must be non-empty") + if strings.TrimSpace(callerURA) == "" { + return SigningConfig{}, errors.New("signing caller_ura must be non-empty") } cp := make([]byte, 32) copy(cp, seed) return SigningConfig{ Seed: cp, - CallerURI: strings.TrimSpace(callerURI), + CallerURA: strings.TrimSpace(callerURA), CallerProfile: uraProfileEasynetStrictV2, }, nil } @@ -160,8 +160,8 @@ func (s SigningConfig) validate() error { if len(s.Seed) != 32 { return fmt.Errorf("signing seed must be exactly 32 bytes, got %d", len(s.Seed)) } - if strings.TrimSpace(s.CallerURI) == "" { - return errors.New("signing caller_uri must be non-empty") + if strings.TrimSpace(s.CallerURA) == "" { + return errors.New("signing caller_ura must be non-empty") } if strings.TrimSpace(s.CallerProfile) != uraProfileEasynetStrictV2 { return fmt.Errorf( @@ -183,7 +183,7 @@ func (s SigningConfig) signingBlock() map[string]any { return map[string]any{ "algorithm": signingAlgorithmEd25519, "seed_base64": base64.StdEncoding.EncodeToString(s.Seed), - "caller_uri": strings.TrimSpace(s.CallerURI), + "caller_ura": strings.TrimSpace(s.CallerURA), "caller_profile": strings.TrimSpace(s.CallerProfile), } } diff --git a/sdk/go/easynet/dendrite_bridge_signed_invoke_stub.go b/sdk/go/easynet/dendrite_bridge_signed_invoke_stub.go index 5a89a66c..1cbd363b 100644 --- a/sdk/go/easynet/dendrite_bridge_signed_invoke_stub.go +++ b/sdk/go/easynet/dendrite_bridge_signed_invoke_stub.go @@ -55,26 +55,26 @@ const ( // against the same struct shape. type SigningConfig struct { Seed []byte - CallerURI string + CallerURA string CallerProfile string } -// NewSigningConfig validates seed length + caller URI even under the +// NewSigningConfig validates seed length + caller URA even under the // stub build, so unit tests that exercise request construction (and // only construction) can still use `NewSigningConfig` for parity // with cgo callers. -func NewSigningConfig(seed []byte, callerURI string) (SigningConfig, error) { +func NewSigningConfig(seed []byte, callerURA string) (SigningConfig, error) { if len(seed) != 32 { return SigningConfig{}, fmt.Errorf("signing seed must be exactly 32 bytes, got %d", len(seed)) } - if strings.TrimSpace(callerURI) == "" { - return SigningConfig{}, errors.New("signing caller_uri must be non-empty") + if strings.TrimSpace(callerURA) == "" { + return SigningConfig{}, errors.New("signing caller_ura must be non-empty") } cp := make([]byte, 32) copy(cp, seed) return SigningConfig{ Seed: cp, - CallerURI: strings.TrimSpace(callerURI), + CallerURA: strings.TrimSpace(callerURA), CallerProfile: uraProfileEasynetStrictV2, }, nil } diff --git a/sdk/go/easynet/federation.go b/sdk/go/easynet/federation.go index b9212e24..78ea33ce 100644 --- a/sdk/go/easynet/federation.go +++ b/sdk/go/easynet/federation.go @@ -50,8 +50,8 @@ func resolveFederationHeartbeatTimeout(timeoutMs int) int { // buildAdvertiseAgentBody assembles the federation.advertise_agent payload. // Empty / nil optional fields are omitted so the runtime can apply canonical // defaults. Pure function — kept private for direct conformance testing. -func buildAdvertiseAgentBody(agentURI string, publicKeyHex string, signingAuthority map[string]any) map[string]any { - body := map[string]any{"agent_uri": agentURI} +func buildAdvertiseAgentBody(agentURA string, publicKeyHex string, signingAuthority map[string]any) map[string]any { + body := map[string]any{"agent_ura": agentURA} if publicKeyHex != "" { body["public_key_hex"] = publicKeyHex } @@ -64,20 +64,20 @@ func buildAdvertiseAgentBody(agentURI string, publicKeyHex string, signingAuthor // buildAdvertiseAbilitiesBody assembles the federation.advertise_abilities // payload. A nil ability slice is normalised to an empty slice so the wire // shape is stable. -func buildAdvertiseAbilitiesBody(agentURI string, abilities []map[string]any) map[string]any { +func buildAdvertiseAbilitiesBody(agentURA string, abilities []map[string]any) map[string]any { if abilities == nil { abilities = []map[string]any{} } return map[string]any{ - "agent_uri": agentURI, + "agent_ura": agentURA, "abilities": abilities, } } // buildRevokeBody assembles the federation.revoke payload. A blank reason is // omitted; the runtime substitutes a canonical default in that case. -func buildRevokeBody(agentURI string, reason string) map[string]any { - body := map[string]any{"agent_uri": agentURI} +func buildRevokeBody(agentURA string, reason string) map[string]any { + body := map[string]any{"agent_ura": agentURA} if reason != "" { body["reason"] = reason } @@ -86,10 +86,10 @@ func buildRevokeBody(agentURI string, reason string) map[string]any { // buildResolveBody assembles the federation.resolve payload. The filter sub- // object is omitted entirely when no filter fields are supplied. -func buildResolveBody(agentURIPrefix string, includeAbilities bool) map[string]any { +func buildResolveBody(agentURAPrefix string, includeAbilities bool) map[string]any { filter := map[string]any{} - if agentURIPrefix != "" { - filter["agent_uri_prefix"] = agentURIPrefix + if agentURAPrefix != "" { + filter["agent_ura_prefix"] = agentURAPrefix } if includeAbilities { filter["include_abilities"] = true @@ -122,12 +122,12 @@ func buildJoinBody(realm string, publicKeyHex string, hostDescriptor any, pairin func (b *DendriteBridge) FederationAdvertiseAgent( handle uint64, tenantID string, - agentURI string, + agentURA string, publicKeyHex string, signingAuthority map[string]any, timeoutMs int, ) (map[string]any, error) { - body := buildAdvertiseAgentBody(agentURI, publicKeyHex, signingAuthority) + body := buildAdvertiseAgentBody(agentURA, publicKeyHex, signingAuthority) return b.InvokeAbility(handle, tenantID, "federation.advertise_agent", body, nil, resolveFederationTimeout(timeoutMs)) } @@ -136,11 +136,11 @@ func (b *DendriteBridge) FederationAdvertiseAgent( func (b *DendriteBridge) FederationAdvertiseAbilities( handle uint64, tenantID string, - agentURI string, + agentURA string, abilities []map[string]any, timeoutMs int, ) (map[string]any, error) { - body := buildAdvertiseAbilitiesBody(agentURI, abilities) + body := buildAdvertiseAbilitiesBody(agentURA, abilities) return b.InvokeAbility(handle, tenantID, "federation.advertise_abilities", body, nil, resolveFederationTimeout(timeoutMs)) } @@ -163,24 +163,24 @@ func (b *DendriteBridge) FederationHeartbeat( func (b *DendriteBridge) FederationRevoke( handle uint64, tenantID string, - agentURI string, + agentURA string, reason string, timeoutMs int, ) (map[string]any, error) { - body := buildRevokeBody(agentURI, reason) + body := buildRevokeBody(agentURA, reason) return b.InvokeAbility(handle, tenantID, "federation.revoke", body, nil, resolveFederationTimeout(timeoutMs)) } -// FederationResolve invokes federation.resolve. Pass empty agentURIPrefix +// FederationResolve invokes federation.resolve. Pass empty agentURAPrefix // to omit the prefix filter; pass timeoutMs = 0 for the default. func (b *DendriteBridge) FederationResolve( handle uint64, tenantID string, - agentURIPrefix string, + agentURAPrefix string, includeAbilities bool, timeoutMs int, ) (map[string]any, error) { - body := buildResolveBody(agentURIPrefix, includeAbilities) + body := buildResolveBody(agentURAPrefix, includeAbilities) return b.InvokeAbility(handle, tenantID, "federation.resolve", body, nil, resolveFederationTimeout(timeoutMs)) } diff --git a/sdk/go/easynet/federation_test.go b/sdk/go/easynet/federation_test.go index 17fe0a5d..e146b63e 100644 --- a/sdk/go/easynet/federation_test.go +++ b/sdk/go/easynet/federation_test.go @@ -26,23 +26,23 @@ func assertBodyEqual(t *testing.T, got, want map[string]any) { } } -// V1 — federation.advertise_agent, minimal: only agent_uri set, optional +// V1 — federation.advertise_agent, minimal: only agent_ura set, optional // fields omitted entirely. func TestV1_AdvertiseAgentMinimal(t *testing.T) { - got := buildAdvertiseAgentBody("axon://realm/foo", "", nil) - want := map[string]any{"agent_uri": "axon://realm/foo"} + got := buildAdvertiseAgentBody("easynet:///r/realm/agent/foo", "", nil) + want := map[string]any{"agent_ura": "easynet:///r/realm/agent/foo"} assertBodyEqual(t, got, want) } // V2 — federation.advertise_agent, full: every optional field populated. func TestV2_AdvertiseAgentFull(t *testing.T) { got := buildAdvertiseAgentBody( - "axon://realm/foo", + "easynet:///r/realm/agent/foo", "deadbeef", map[string]any{"kind": "self_signed"}, ) want := map[string]any{ - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "public_key_hex": "deadbeef", "signing_authority": map[string]any{"kind": "self_signed"}, } @@ -52,24 +52,24 @@ func TestV2_AdvertiseAgentFull(t *testing.T) { // V3 — federation.advertise_agent, omit empty/blank: blank pubkey and empty // signing_authority map are stripped before transmission. func TestV3_AdvertiseAgentOmitEmpty(t *testing.T) { - got := buildAdvertiseAgentBody("axon://realm/foo", "", map[string]any{}) - want := map[string]any{"agent_uri": "axon://realm/foo"} + got := buildAdvertiseAgentBody("easynet:///r/realm/agent/foo", "", map[string]any{}) + want := map[string]any{"agent_ura": "easynet:///r/realm/agent/foo"} assertBodyEqual(t, got, want) } // V5 — federation.revoke, no reason: blank reason omitted, runtime supplies // the canonical default. func TestV5_RevokeNoReason(t *testing.T) { - got := buildRevokeBody("axon://realm/foo", "") - want := map[string]any{"agent_uri": "axon://realm/foo"} + got := buildRevokeBody("easynet:///r/realm/agent/foo", "") + want := map[string]any{"agent_ura": "easynet:///r/realm/agent/foo"} assertBodyEqual(t, got, want) } // V6 — federation.revoke, with reason: explicit reason flows through verbatim. func TestV6_RevokeWithReason(t *testing.T) { - got := buildRevokeBody("axon://realm/foo", "operator: maintenance") + got := buildRevokeBody("easynet:///r/realm/agent/foo", "operator: maintenance") want := map[string]any{ - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "reason": "operator: maintenance", } assertBodyEqual(t, got, want) @@ -84,24 +84,24 @@ func TestV7_ResolveNoFilter(t *testing.T) { // V8 — federation.resolve, with filter: prefix and include_abilities both set. func TestV8_ResolveWithFilter(t *testing.T) { - got := buildResolveBody("axon://realm/edge-", true) + got := buildResolveBody("easynet:///r/realm/agent/edge-", true) want := map[string]any{ "filter": map[string]any{ - "agent_uri_prefix": "axon://realm/edge-", + "agent_ura_prefix": "easynet:///r/realm/agent/edge-", "include_abilities": true, }, } assertBodyEqual(t, got, want) } -// V9 — federation.advertise_abilities: agent_uri plus an abilities array. +// V9 — federation.advertise_abilities: agent_ura plus an abilities array. func TestV9_AdvertiseAbilities(t *testing.T) { got := buildAdvertiseAbilitiesBody( - "axon://realm/foo", + "easynet:///r/realm/agent/foo", []map[string]any{{"name": "echo"}}, ) want := map[string]any{ - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "abilities": []map[string]any{{"name": "echo"}}, } assertBodyEqual(t, got, want) diff --git a/sdk/go/easynet/invocation/admission.go b/sdk/go/easynet/invocation/admission.go index 979e1baa..f5e159a4 100644 --- a/sdk/go/easynet/invocation/admission.go +++ b/sdk/go/easynet/invocation/admission.go @@ -17,7 +17,7 @@ package invocation // Local-fast mode where identity is // self-asserted. // 4. NonceReplayStore.CheckAndRecord — always on. Dedup key is -// (caller.URI, ability, invocation_nonce); ability guards against +// (caller.URA, ability, invocation_nonce); ability guards against // cross-ability false-positives per review. // // All rejections map to KindInvalidArgument with one of three RFC §5.2 @@ -36,9 +36,9 @@ import ( // wire-visible contract. const ( - ReasonEnvelopeIncomplete = "AXON_AXIOM_ENVELOPE_INCOMPLETE" - ReasonCallerSignatureInvalid = "AXON_CALLER_SIGNATURE_INVALID" - ReasonNonceReplay = "AXON_NONCE_REPLAY" + ReasonEnvelopeIncomplete = "AXON_AXIOM_ENVELOPE_INCOMPLETE" + ReasonCallerSignatureInvalid = "AXON_CALLER_SIGNATURE_INVALID" + ReasonNonceReplay = "AXON_NONCE_REPLAY" // DefaultDedupWindowMs is the default nonce-replay window (7 days). // This is a correctness/idempotency guard, not a pure security // counter. Tunable via NonceReplayStore.WithWindowMs. @@ -60,7 +60,7 @@ func rejectEnvelope(detail string) *AxonError { // // Checks applied (RFC 001 §5.2 step 1, strengthened per review): // - Ability non-empty -// - Caller.URI / Callee.URI / Subject.URI non-empty +// - Caller.URA / Callee.URA / Subject.URA non-empty // - InvocationNonce is not the all-zero sentinel (a CSPRNG-generated // nonce being all-zero has probability ≈ 2⁻¹²⁸; we reject it as a // probable uninitialised-field mistake) @@ -70,14 +70,14 @@ func ValidateEnvelope(env InvocationEnvelope) *AxonError { if env.Ability == "" { return rejectEnvelope("ability_empty") } - if env.Caller.URI == "" { - return rejectEnvelope("caller_uri_empty") + if env.Caller.URA == "" { + return rejectEnvelope("caller_ura_empty") } - if env.Callee.URI == "" { - return rejectEnvelope("callee_uri_empty") + if env.Callee.URA == "" { + return rejectEnvelope("callee_ura_empty") } - if env.Subject.URI == "" { - return rejectEnvelope("subject_uri_empty") + if env.Subject.URA == "" { + return rejectEnvelope("subject_ura_empty") } if len(env.ArgsDigest) != 32 { return rejectEnvelope("args_digest_wrong_length") @@ -145,7 +145,7 @@ func VerifySignature(env InvocationEnvelope, sig CallerSignature, resolver KeyRe // ── Replay store ──────────────────────────────────────────────────── -// replayKey is (caller.URI, ability, nonce). The ability component +// replayKey is (caller.URA, ability, nonce). The ability component // guards against cross-ability false-positives per review feedback. type replayKey struct { caller string @@ -181,13 +181,13 @@ func (s *NonceReplayStore) WithWindowMs(windowMs int64) *NonceReplayStore { } } -// CheckAndRecord registers a (caller.URI, ability, nonce) observation +// CheckAndRecord registers a (caller.URA, ability, nonce) observation // as of nowMs. Returns ReasonNonceReplay on collision inside the // current window. Out-of-window entries are pruned before the check. // // Admission calls this *after* structure/verify, so a malformed or // unverified caller's nonce never enters the store. -func (s *NonceReplayStore) CheckAndRecord(callerURI, ability string, nonce [16]byte, nowMs int64) *AxonError { +func (s *NonceReplayStore) CheckAndRecord(callerURA, ability string, nonce [16]byte, nowMs int64) *AxonError { s.mu.Lock() defer s.mu.Unlock() @@ -199,7 +199,7 @@ func (s *NonceReplayStore) CheckAndRecord(callerURI, ability string, nonce [16]b } } - key := replayKey{caller: callerURI, ability: ability, nonce: nonce} + key := replayKey{caller: callerURA, ability: ability, nonce: nonce} if prev, ok := s.seen[key]; ok && prev >= cutoff { e := ErrInvalidArgument(ReasonNonceReplay) e.Message = fmt.Sprintf("dedup_window_hit:prev_ts=%d:window_ms=%d", prev, s.windowMs) @@ -247,7 +247,7 @@ func RunAdmission( return err } } - if err := replay.CheckAndRecord(env.Caller.URI, env.Ability, env.InvocationNonce, nowMs); err != nil { + if err := replay.CheckAndRecord(env.Caller.URA, env.Ability, env.InvocationNonce, nowMs); err != nil { return err } return nil diff --git a/sdk/go/easynet/invocation/admission_test.go b/sdk/go/easynet/invocation/admission_test.go index b44255af..fe95be8c 100644 --- a/sdk/go/easynet/invocation/admission_test.go +++ b/sdk/go/easynet/invocation/admission_test.go @@ -86,9 +86,9 @@ func TestValidateEnvelopeRejectsEmptyFields(t *testing.T) { detail string }{ {"ability", func(e *InvocationEnvelope) { e.Ability = "" }, "ability_empty"}, - {"caller_uri", func(e *InvocationEnvelope) { e.Caller.URI = "" }, "caller_uri_empty"}, - {"callee_uri", func(e *InvocationEnvelope) { e.Callee.URI = "" }, "callee_uri_empty"}, - {"subject_uri", func(e *InvocationEnvelope) { e.Subject.URI = "" }, "subject_uri_empty"}, + {"caller_ura", func(e *InvocationEnvelope) { e.Caller.URA = "" }, "caller_ura_empty"}, + {"callee_ura", func(e *InvocationEnvelope) { e.Callee.URA = "" }, "callee_ura_empty"}, + {"subject_ura", func(e *InvocationEnvelope) { e.Subject.URA = "" }, "subject_ura_empty"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -247,7 +247,7 @@ func TestRunAdmissionFederatedRejectsWrongKey(t *testing.T) { func TestRunAdmissionRejectsEnvelopeBeforeReplayStore(t *testing.T) { env := admSampleEnv() - env.Caller.URI = "" + env.Caller.URA = "" sig, _ := admSampleSig(env) s := NewNonceReplayStore() err := RunAdmission(env, sig, nil, s, 1000) diff --git a/sdk/go/easynet/invocation/audit.go b/sdk/go/easynet/invocation/audit.go index a8dc708a..b733b348 100644 --- a/sdk/go/easynet/invocation/audit.go +++ b/sdk/go/easynet/invocation/audit.go @@ -17,13 +17,13 @@ var ZeroHash = [32]byte{} // admission, stays stable across the Invocation's lifecycle, and is // echoed verbatim into every receipt's canonical bytes. type AxiomBinding struct { - Caller AgentIdentity - Callee AgentIdentity - Subject SubjectIdentity - InvocationNonce [16]byte - Causal CausalContext - PayloadDigest [32]byte - CalleeSignature *CalleeSignature // optional + Caller AgentIdentity + Callee AgentIdentity + Subject SubjectIdentity + InvocationNonce [16]byte + Causal CausalContext + PayloadDigest [32]byte + CalleeSignature *CalleeSignature // optional } // InvocationReceipt — one entry in the Invocation's hash-chained trail. @@ -53,20 +53,20 @@ type InvocationReceipt struct { func CanonicalSerialise(r *InvocationReceipt) ([]byte, error) { b := r.AxiomBinding body := ReceiptBody{ - Index: r.Index, - InvocationID: r.InvocationID, - ReceiptType: r.ReceiptType, - State: r.State, - TimestampUnixMs: r.TimestampUnixMs, - PrevReceiptHash: r.PrevReceiptHash, - PayloadDigest: b.PayloadDigest, - Reason: r.Reason, - CleanupComplete: r.CleanupComplete, - CallerBinding: b.Caller, - CalleeBinding: b.Callee, - SubjectBinding: b.Subject, - InvocationNonce: b.InvocationNonce, - CausalBinding: b.Causal, + Index: r.Index, + InvocationID: r.InvocationID, + ReceiptType: r.ReceiptType, + State: r.State, + TimestampUnixMs: r.TimestampUnixMs, + PrevReceiptHash: r.PrevReceiptHash, + PayloadDigest: b.PayloadDigest, + Reason: r.Reason, + CleanupComplete: r.CleanupComplete, + CallerBinding: b.Caller, + CalleeBinding: b.Callee, + SubjectBinding: b.Subject, + InvocationNonce: b.InvocationNonce, + CausalBinding: b.Causal, } return CanonicalReceiptBytes(body), nil } diff --git a/sdk/go/easynet/invocation/axiom.go b/sdk/go/easynet/invocation/axiom.go index 3d577389..e928e4cd 100644 --- a/sdk/go/easynet/invocation/axiom.go +++ b/sdk/go/easynet/invocation/axiom.go @@ -26,56 +26,56 @@ import ( // ── URA profile ────────────────────────────────────────────────────── -// UriProfile — URA profile selector. Bound structurally to the URI it +// UraProfile — URA profile selector. Bound structurally to the URA it // profiles (AXIOM §5.4 Axis B, RFC 001 INV-4). -type UriProfile string +type UraProfile string const ( - ProfileEasynetStrictV2 UriProfile = "easynet-strict-v2" - ProfileWebSafeV2 UriProfile = "web-safe-v2" + ProfileEasynetStrictV2 UraProfile = "easynet-strict-v2" + ProfileWebSafeV2 UraProfile = "web-safe-v2" ) -// ParseUriProfile parses a profile string or returns an error for +// ParseUraProfile parses a profile string or returns an error for // unknown values. -func ParseUriProfile(s string) (UriProfile, error) { - switch UriProfile(s) { +func ParseUraProfile(s string) (UraProfile, error) { + switch UraProfile(s) { case ProfileEasynetStrictV2, ProfileWebSafeV2: - return UriProfile(s), nil + return UraProfile(s), nil default: - return "", ErrInvalidArgument(fmt.Sprintf("unknown_uri_profile:%s", s)) + return "", ErrInvalidArgument(fmt.Sprintf("unknown_ura_profile:%s", s)) } } // ── Identity ───────────────────────────────────────────────────────── // AgentIdentity — URA v2 composite identity for an agent. `Profile` is -// bound structurally to `URI` per RFC 001 §3.1. +// bound structurally to `URA` per RFC 001 §3.1. type AgentIdentity struct { - URI string - Profile UriProfile + URA string + Profile UraProfile } // NewAgentIdentity constructs an AgentIdentity. -func NewAgentIdentity(uri string, profile UriProfile) AgentIdentity { - return AgentIdentity{URI: uri, Profile: profile} +func NewAgentIdentity(ura string, profile UraProfile) AgentIdentity { + return AgentIdentity{URA: ura, Profile: profile} } // SubjectIdentity — URA v2 composite identity for a subject. Separate // from AgentIdentity so the compiler catches accidental swaps (INV-7). type SubjectIdentity struct { - URI string - Profile UriProfile + URA string + Profile UraProfile } // NewSubjectIdentity constructs a SubjectIdentity. -func NewSubjectIdentity(uri string, profile UriProfile) SubjectIdentity { - return SubjectIdentity{URI: uri, Profile: profile} +func NewSubjectIdentity(ura string, profile UraProfile) SubjectIdentity { + return SubjectIdentity{URA: ura, Profile: profile} } // SubjectFromCallee — degenerate case (RFC 001 §5.1): executor equals target. // Used when a caller passes subject=nil to InvokeSignedAsync. func SubjectFromCallee(callee AgentIdentity) SubjectIdentity { - return SubjectIdentity{URI: callee.URI, Profile: callee.Profile} + return SubjectIdentity{URA: callee.URA, Profile: callee.Profile} } // ── Causal context ─────────────────────────────────────────────────── @@ -83,7 +83,7 @@ func SubjectFromCallee(callee AgentIdentity) SubjectIdentity { // ReceiptRef — reference to a prior receipt in the causal chain. type ReceiptRef struct { ReceiptHash [32]byte - ReceiptURI string + ReceiptURA string } // CausalForm identifies the branch of CausalContext. @@ -101,11 +101,11 @@ const ( // Go has no sum types; we use a discriminator + pointer fields. The // canonical encoder reads Form first and then the matching field. type CausalContext struct { - Form CausalForm - Scalar *ReceiptRef - List []ReceiptRef - MerkleRoot [32]byte - MerkleProofURI string + Form CausalForm + Scalar *ReceiptRef + List []ReceiptRef + MerkleRoot [32]byte + MerkleProofURA string } // CausalNoneCtx returns the empty (root) causal context. @@ -128,8 +128,8 @@ func CausalListCtx(refs []ReceiptRef) CausalContext { } // CausalMerkleCtx returns a merkle-root causal context. Wire-reserved. -func CausalMerkleCtx(root [32]byte, proofURI string) CausalContext { - return CausalContext{Form: CausalMerkle, MerkleRoot: root, MerkleProofURI: proofURI} +func CausalMerkleCtx(root [32]byte, proofURA string) CausalContext { + return CausalContext{Form: CausalMerkle, MerkleRoot: root, MerkleProofURA: proofURA} } // ── Signatures ─────────────────────────────────────────────────────── @@ -165,20 +165,20 @@ type InvocationEnvelope struct { // ReceiptBody — a receipt ready for canonical encoding and signing by // the callee. type ReceiptBody struct { - Index uint64 - InvocationID string - ReceiptType string - State string - TimestampUnixMs int64 - PrevReceiptHash [32]byte - PayloadDigest [32]byte - Reason string - CleanupComplete bool - CallerBinding AgentIdentity - CalleeBinding AgentIdentity - SubjectBinding SubjectIdentity - InvocationNonce [16]byte - CausalBinding CausalContext + Index uint64 + InvocationID string + ReceiptType string + State string + TimestampUnixMs int64 + PrevReceiptHash [32]byte + PayloadDigest [32]byte + Reason string + CleanupComplete bool + CallerBinding AgentIdentity + CalleeBinding AgentIdentity + SubjectBinding SubjectIdentity + InvocationNonce [16]byte + CausalBinding CausalContext } // ── Canonical bytes encoders (RFC 001 §4) ──────────────────────────── @@ -204,8 +204,8 @@ func putBytes(out *[]byte, b []byte) { *out = append(*out, b...) } -func putIdentity(out *[]byte, uri string, profile UriProfile) { - putStr(out, uri) +func putIdentity(out *[]byte, ura string, profile UraProfile) { + putStr(out, ura) putStr(out, string(profile)) } @@ -225,18 +225,18 @@ func CanonicalCausalContext(c CausalContext) []byte { } out = append(out, 0x01) out = append(out, c.Scalar.ReceiptHash[:]...) - putStr(&out, c.Scalar.ReceiptURI) + putStr(&out, c.Scalar.ReceiptURA) case CausalList: out = append(out, 0x02) putU32(&out, uint32(len(c.List))) for _, r := range c.List { out = append(out, r.ReceiptHash[:]...) - putStr(&out, r.ReceiptURI) + putStr(&out, r.ReceiptURA) } case CausalMerkle: out = append(out, 0x03) out = append(out, c.MerkleRoot[:]...) - putStr(&out, c.MerkleProofURI) + putStr(&out, c.MerkleProofURA) } return out } @@ -244,9 +244,9 @@ func CanonicalCausalContext(c CausalContext) []byte { // CanonicalInvocationBytes — input to the caller's signature (RFC 001 §4.1). func CanonicalInvocationBytes(env InvocationEnvelope) []byte { out := make([]byte, 0, 512) - putIdentity(&out, env.Caller.URI, env.Caller.Profile) - putIdentity(&out, env.Callee.URI, env.Callee.Profile) - putIdentity(&out, env.Subject.URI, env.Subject.Profile) + putIdentity(&out, env.Caller.URA, env.Caller.Profile) + putIdentity(&out, env.Callee.URA, env.Callee.Profile) + putIdentity(&out, env.Subject.URA, env.Subject.Profile) putStr(&out, env.Ability) out = append(out, env.ArgsDigest[:]...) out = append(out, env.InvocationNonce[:]...) @@ -269,9 +269,9 @@ func CanonicalReceiptBytes(r ReceiptBody) []byte { binary.BigEndian.PutUint64(ts[:], uint64(r.TimestampUnixMs)) out = append(out, ts[:]...) out = append(out, r.PrevReceiptHash[:]...) - putIdentity(&out, r.CallerBinding.URI, r.CallerBinding.Profile) - putIdentity(&out, r.CalleeBinding.URI, r.CalleeBinding.Profile) - putIdentity(&out, r.SubjectBinding.URI, r.SubjectBinding.Profile) + putIdentity(&out, r.CallerBinding.URA, r.CallerBinding.Profile) + putIdentity(&out, r.CalleeBinding.URA, r.CalleeBinding.Profile) + putIdentity(&out, r.SubjectBinding.URA, r.SubjectBinding.Profile) out = append(out, r.InvocationNonce[:]...) causal := CanonicalCausalContext(r.CausalBinding) putBytes(&out, causal) @@ -292,16 +292,16 @@ func Sha256(b []byte) [32]byte { // ── Key resolver (§5.4) ────────────────────────────────────────────── -// KeyResolver — pluggable agent_uri → Ed25519 public key lookup. +// KeyResolver — pluggable agent_ura → Ed25519 public key lookup. // // INTERFACE STABILITY: this is the boundary between RFC 001 (file // resolver) and RFC 002 (Registry-backed resolver). Signature-verify // paths MUST depend on this interface, not on a concrete resolver. type KeyResolver interface { - Resolve(agentURI string) (ed25519.PublicKey, error) + Resolve(agentURA string) (ed25519.PublicKey, error) } -// FileKeyResolver — RFC 001's shipped resolver. Maps agent_uri → path +// FileKeyResolver — RFC 001's shipped resolver. Maps agent_ura → path // containing the raw 32-byte public key. type FileKeyResolver struct { mapping map[string]string @@ -312,16 +312,16 @@ func NewFileKeyResolver() *FileKeyResolver { return &FileKeyResolver{mapping: map[string]string{}} } -// Insert registers a URI → pubkey-file mapping. -func (r *FileKeyResolver) Insert(agentURI, path string) { - r.mapping[agentURI] = path +// Insert registers a URA → pubkey-file mapping. +func (r *FileKeyResolver) Insert(agentURA, path string) { + r.mapping[agentURA] = path } // Resolve implements KeyResolver. -func (r *FileKeyResolver) Resolve(agentURI string) (ed25519.PublicKey, error) { - path, ok := r.mapping[agentURI] +func (r *FileKeyResolver) Resolve(agentURA string) (ed25519.PublicKey, error) { + path, ok := r.mapping[agentURA] if !ok { - return nil, ErrInvalidArgument(fmt.Sprintf("unknown_agent_key:%s", agentURI)) + return nil, ErrInvalidArgument(fmt.Sprintf("unknown_agent_key:%s", agentURA)) } b, err := os.ReadFile(path) if err != nil { @@ -358,7 +358,7 @@ func VerifyInvocationSignature(env InvocationEnvelope, sig CallerSignature, reso if sig.Algorithm != "ed25519" { return ErrInvalidArgument(fmt.Sprintf("unsupported_algorithm:%s", sig.Algorithm)) } - key, err := resolver.Resolve(env.Caller.URI) + key, err := resolver.Resolve(env.Caller.URA) if err != nil { return err } @@ -384,7 +384,7 @@ func VerifyReceiptSignature(r ReceiptBody, sig CalleeSignature, resolver KeyReso if sig.Algorithm != "ed25519" { return ErrInvalidArgument(fmt.Sprintf("unsupported_algorithm:%s", sig.Algorithm)) } - key, err := resolver.Resolve(r.CalleeBinding.URI) + key, err := resolver.Resolve(r.CalleeBinding.URA) if err != nil { return err } diff --git a/sdk/go/easynet/invocation/axiom_test.go b/sdk/go/easynet/invocation/axiom_test.go index b391be83..c73c0714 100644 --- a/sdk/go/easynet/invocation/axiom_test.go +++ b/sdk/go/easynet/invocation/axiom_test.go @@ -103,7 +103,7 @@ func TestCausalFormsAreDistinct(t *testing.T) { for i := range h32 { h32[i] = 0xAA } - r := ReceiptRef{ReceiptHash: h32, ReceiptURI: "u"} + r := ReceiptRef{ReceiptHash: h32, ReceiptURA: "u"} none := CanonicalCausalContext(CausalNoneCtx()) scalar := CanonicalCausalContext(CausalScalarCtx(r)) lst := CanonicalCausalContext(CausalListCtx([]ReceiptRef{r})) @@ -129,7 +129,7 @@ func TestCausalFormsAreDistinct(t *testing.T) { type fixedResolver struct{ key ed25519.PublicKey } -func (r *fixedResolver) Resolve(uri string) (ed25519.PublicKey, error) { return r.key, nil } +func (r *fixedResolver) Resolve(ura string) (ed25519.PublicKey, error) { return r.key, nil } func TestSignVerifyRoundtrip(t *testing.T) { var seed [32]byte @@ -204,20 +204,20 @@ func TestReceiptSignVerifyRoundtrip(t *testing.T) { env := sampleEnv() r := ReceiptBody{ - Index: 0, - InvocationID: "inv-1", - ReceiptType: "admitted", - State: "ADMITTED", - TimestampUnixMs: 1, - PrevReceiptHash: [32]byte{}, - PayloadDigest: Sha256(nil), - Reason: "", - CleanupComplete: false, - CallerBinding: env.Caller, - CalleeBinding: env.Callee, - SubjectBinding: env.Subject, - InvocationNonce: env.InvocationNonce, - CausalBinding: env.CausalContext, + Index: 0, + InvocationID: "inv-1", + ReceiptType: "admitted", + State: "ADMITTED", + TimestampUnixMs: 1, + PrevReceiptHash: [32]byte{}, + PayloadDigest: Sha256(nil), + Reason: "", + CleanupComplete: false, + CallerBinding: env.Caller, + CalleeBinding: env.Callee, + SubjectBinding: env.Subject, + InvocationNonce: env.InvocationNonce, + CausalBinding: env.CausalContext, } sig := SignReceipt(sk, r, "") if err := VerifyReceiptSignature(r, sig, &fixedResolver{key: vk}); err != nil { @@ -226,7 +226,7 @@ func TestReceiptSignVerifyRoundtrip(t *testing.T) { // Tamper the causal binding. var h [32]byte h[0] = 0x99 - r.CausalBinding = CausalScalarCtx(ReceiptRef{ReceiptHash: h, ReceiptURI: "evil"}) + r.CausalBinding = CausalScalarCtx(ReceiptRef{ReceiptHash: h, ReceiptURA: "evil"}) if err := VerifyReceiptSignature(r, sig, &fixedResolver{key: vk}); err == nil { t.Fatalf("tampered causal_binding should break receipt verify") } diff --git a/sdk/go/easynet/invocation/axiom_vectors_test.go b/sdk/go/easynet/invocation/axiom_vectors_test.go index 5045058e..c2980e77 100644 --- a/sdk/go/easynet/invocation/axiom_vectors_test.go +++ b/sdk/go/easynet/invocation/axiom_vectors_test.go @@ -34,17 +34,17 @@ type vectorFile struct { } type inputJ struct { - Caller IdentityJSON `json:"caller"` - Callee IdentityJSON `json:"callee"` - Subject IdentityJSON `json:"subject"` - Ability string `json:"ability"` - ArgsDigestHex string `json:"args_digest_hex"` - InvocationNonceHex string `json:"invocation_nonce_hex"` - CausalContext CausalJSON `json:"causal_context"` - CallerSecretHex string `json:"caller_secret_hex"` - CalleeSecretHex string `json:"callee_secret_hex"` - Tamper map[string]string `json:"tamper"` - ProfileSwapOnVerify map[string]string `json:"profile_swap_on_verify"` + Caller IdentityJSON `json:"caller"` + Callee IdentityJSON `json:"callee"` + Subject IdentityJSON `json:"subject"` + Ability string `json:"ability"` + ArgsDigestHex string `json:"args_digest_hex"` + InvocationNonceHex string `json:"invocation_nonce_hex"` + CausalContext CausalJSON `json:"causal_context"` + CallerSecretHex string `json:"caller_secret_hex"` + CalleeSecretHex string `json:"callee_secret_hex"` + Tamper map[string]string `json:"tamper"` + ProfileSwapOnVerify map[string]string `json:"profile_swap_on_verify"` } func (i inputJ) envelope(t *testing.T) InvocationEnvelope { @@ -259,7 +259,7 @@ func runE3(t *testing.T, vf vectorFile) { func runE4(t *testing.T, vf vectorFile) { inp := parseInput(t, vf.RawInputs) env := inp.envelope(t) - if env.Callee.URI == env.Subject.URI { + if env.Callee.URA == env.Subject.URA { t.Fatalf("e4 expects subject != callee") } sk, _ := SigningKeyFromBytes(mustHex(inp.CallerSecretHex)) @@ -350,7 +350,7 @@ func runProfileBinding(t *testing.T, vf vectorFile) { sig := SignInvocation(sk, env, "") newProfile := inp.ProfileSwapOnVerify["caller"] - p, err := ParseUriProfile(newProfile) + p, err := ParseUraProfile(newProfile) if err != nil { t.Fatal(err) } @@ -369,11 +369,11 @@ func runProfileBinding(t *testing.T, vf vectorFile) { func runSubjectSurvives(t *testing.T, vf vectorFile) { a := parseInput(t, vf.RawInputsA).envelope(t) b := parseInput(t, vf.RawInputsB).envelope(t) - if a.Subject.URI != b.Subject.URI || a.Subject.Profile != b.Subject.Profile { + if a.Subject.URA != b.Subject.URA || a.Subject.Profile != b.Subject.Profile { t.Fatalf("subject must be byte-identical across A and B") } - if a.Callee.URI == b.Callee.URI { - t.Fatalf("callee URIs must differ in this vector") + if a.Callee.URA == b.Callee.URA { + t.Fatalf("callee URAs must differ in this vector") } if string(CanonicalInvocationBytes(a)) == string(CanonicalInvocationBytes(b)) { t.Fatalf("overall canonical bytes must differ") diff --git a/sdk/go/easynet/invocation/axiom_worked_example_test.go b/sdk/go/easynet/invocation/axiom_worked_example_test.go index 83b4b9d0..bf82a6df 100644 --- a/sdk/go/easynet/invocation/axiom_worked_example_test.go +++ b/sdk/go/easynet/invocation/axiom_worked_example_test.go @@ -53,18 +53,18 @@ import ( // ── JSON shape (mirrors axiom-worked-example-authenticated.json) ───── type workedVectorInputs struct { - SigningSeedHex string `json:"signing_seed_hex"` - Caller workedVectorID `json:"caller"` - Callee workedVectorID `json:"callee"` - Subject workedVectorID `json:"subject"` - Ability string `json:"ability"` - PayloadBase64 string `json:"payload_base64"` - InvocationNonceHex string `json:"invocation_nonce_hex"` + SigningSeedHex string `json:"signing_seed_hex"` + Caller workedVectorID `json:"caller"` + Callee workedVectorID `json:"callee"` + Subject workedVectorID `json:"subject"` + Ability string `json:"ability"` + PayloadBase64 string `json:"payload_base64"` + InvocationNonceHex string `json:"invocation_nonce_hex"` CausalContext workedVectorCausal `json:"causal_context"` } type workedVectorID struct { - URI string `json:"uri"` + URA string `json:"ura"` Profile string `json:"profile"` } @@ -165,15 +165,15 @@ func parseHex16(t *testing.T, s string) [16]byte { func buildWorkedEnvelope(t *testing.T, in workedVectorInputs) InvocationEnvelope { t.Helper() - callerProfile, err := ParseUriProfile(in.Caller.Profile) + callerProfile, err := ParseUraProfile(in.Caller.Profile) if err != nil { t.Fatalf("caller profile: %v", err) } - calleeProfile, err := ParseUriProfile(in.Callee.Profile) + calleeProfile, err := ParseUraProfile(in.Callee.Profile) if err != nil { t.Fatalf("callee profile: %v", err) } - subjectProfile, err := ParseUriProfile(in.Subject.Profile) + subjectProfile, err := ParseUraProfile(in.Subject.Profile) if err != nil { t.Fatalf("subject profile: %v", err) } @@ -185,9 +185,9 @@ func buildWorkedEnvelope(t *testing.T, in workedVectorInputs) InvocationEnvelope t.Fatalf("this vector requires causal_context.form=\"none\"; got %q", in.CausalContext.Form) } return InvocationEnvelope{ - Caller: NewAgentIdentity(in.Caller.URI, callerProfile), - Callee: NewAgentIdentity(in.Callee.URI, calleeProfile), - Subject: NewSubjectIdentity(in.Subject.URI, subjectProfile), + Caller: NewAgentIdentity(in.Caller.URA, callerProfile), + Callee: NewAgentIdentity(in.Callee.URA, calleeProfile), + Subject: NewSubjectIdentity(in.Subject.URA, subjectProfile), Ability: in.Ability, ArgsDigest: Sha256(payload), InvocationNonce: parseHex16(t, in.InvocationNonceHex), diff --git a/sdk/go/easynet/invocation/bundle.go b/sdk/go/easynet/invocation/bundle.go index 3a823039..2461fac3 100644 --- a/sdk/go/easynet/invocation/bundle.go +++ b/sdk/go/easynet/invocation/bundle.go @@ -20,54 +20,54 @@ import ( // IdentityJSON — common shape for AgentIdentity and SubjectIdentity. type IdentityJSON struct { - URI string `json:"uri"` + URA string `json:"ura"` Profile string `json:"profile"` } // FromAgent builds an IdentityJSON from an AgentIdentity. func IdentityFromAgent(a AgentIdentity) IdentityJSON { - return IdentityJSON{URI: a.URI, Profile: string(a.Profile)} + return IdentityJSON{URA: a.URA, Profile: string(a.Profile)} } // FromSubject builds an IdentityJSON from a SubjectIdentity. func IdentityFromSubject(s SubjectIdentity) IdentityJSON { - return IdentityJSON{URI: s.URI, Profile: string(s.Profile)} + return IdentityJSON{URA: s.URA, Profile: string(s.Profile)} } // ToAgent converts back to an AgentIdentity. func (i IdentityJSON) ToAgent() (AgentIdentity, error) { - p, err := ParseUriProfile(i.Profile) + p, err := ParseUraProfile(i.Profile) if err != nil { return AgentIdentity{}, err } - return AgentIdentity{URI: i.URI, Profile: p}, nil + return AgentIdentity{URA: i.URA, Profile: p}, nil } // ToSubject converts back to a SubjectIdentity. func (i IdentityJSON) ToSubject() (SubjectIdentity, error) { - p, err := ParseUriProfile(i.Profile) + p, err := ParseUraProfile(i.Profile) if err != nil { return SubjectIdentity{}, err } - return SubjectIdentity{URI: i.URI, Profile: p}, nil + return SubjectIdentity{URA: i.URA, Profile: p}, nil } // ── Causal context JSON ────────────────────────────────────────────── // CausalJSON — tagged union of all four causal forms. type CausalJSON struct { - Form string `json:"form"` - ReceiptHashHex string `json:"receipt_hash_hex,omitempty"` - ReceiptURI string `json:"receipt_uri,omitempty"` - Prior []ReceiptRefJSON `json:"prior,omitempty"` - RootHex string `json:"root_hex,omitempty"` - ProofURI string `json:"proof_uri,omitempty"` + Form string `json:"form"` + ReceiptHashHex string `json:"receipt_hash_hex,omitempty"` + ReceiptURA string `json:"receipt_ura,omitempty"` + Prior []ReceiptRefJSON `json:"prior,omitempty"` + RootHex string `json:"root_hex,omitempty"` + ProofURA string `json:"proof_ura,omitempty"` } // ReceiptRefJSON — serialisation of a ReceiptRef. type ReceiptRefJSON struct { ReceiptHashHex string `json:"receipt_hash_hex"` - ReceiptURI string `json:"receipt_uri"` + ReceiptURA string `json:"receipt_ura"` } // CausalFromCtx encodes a CausalContext into a CausalJSON. @@ -82,14 +82,14 @@ func CausalFromCtx(c CausalContext) CausalJSON { return CausalJSON{ Form: "scalar", ReceiptHashHex: hex.EncodeToString(c.Scalar.ReceiptHash[:]), - ReceiptURI: c.Scalar.ReceiptURI, + ReceiptURA: c.Scalar.ReceiptURA, } case CausalList: prior := make([]ReceiptRefJSON, 0, len(c.List)) for _, r := range c.List { prior = append(prior, ReceiptRefJSON{ ReceiptHashHex: hex.EncodeToString(r.ReceiptHash[:]), - ReceiptURI: r.ReceiptURI, + ReceiptURA: r.ReceiptURA, }) } return CausalJSON{Form: "list", Prior: prior} @@ -97,7 +97,7 @@ func CausalFromCtx(c CausalContext) CausalJSON { return CausalJSON{ Form: "merkle", RootHex: hex.EncodeToString(c.MerkleRoot[:]), - ProofURI: c.MerkleProofURI, + ProofURA: c.MerkleProofURA, } } return CausalJSON{Form: "none"} @@ -113,7 +113,7 @@ func (c CausalJSON) ToCtx() (CausalContext, error) { if err != nil { return CausalContext{}, err } - return CausalScalarCtx(ReceiptRef{ReceiptHash: h, ReceiptURI: c.ReceiptURI}), nil + return CausalScalarCtx(ReceiptRef{ReceiptHash: h, ReceiptURA: c.ReceiptURA}), nil case "list": refs := make([]ReceiptRef, 0, len(c.Prior)) for _, p := range c.Prior { @@ -121,7 +121,7 @@ func (c CausalJSON) ToCtx() (CausalContext, error) { if err != nil { return CausalContext{}, err } - refs = append(refs, ReceiptRef{ReceiptHash: h, ReceiptURI: p.ReceiptURI}) + refs = append(refs, ReceiptRef{ReceiptHash: h, ReceiptURA: p.ReceiptURA}) } return CausalListCtx(refs), nil case "merkle": @@ -129,7 +129,7 @@ func (c CausalJSON) ToCtx() (CausalContext, error) { if err != nil { return CausalContext{}, err } - return CausalMerkleCtx(root, c.ProofURI), nil + return CausalMerkleCtx(root, c.ProofURA), nil default: return CausalContext{}, ErrInvalidArgument(fmt.Sprintf("unknown_causal_form:%s", c.Form)) } @@ -139,16 +139,16 @@ func (c CausalJSON) ToCtx() (CausalContext, error) { // InvocationJSON is the wire shape for an envelope + caller signature. type InvocationJSON struct { - InvocationID string `json:"invocation_id"` - Caller IdentityJSON `json:"caller"` - Callee IdentityJSON `json:"callee"` - Subject IdentityJSON `json:"subject"` - Ability string `json:"ability"` - ArgsDigestHex string `json:"args_digest_hex"` - InvocationNonceHex string `json:"invocation_nonce_hex"` - CausalContext CausalJSON `json:"causal_context"` - CallerSignatureHex string `json:"caller_signature_hex"` - CallerSignatureAlg string `json:"caller_signature_alg"` + InvocationID string `json:"invocation_id"` + Caller IdentityJSON `json:"caller"` + Callee IdentityJSON `json:"callee"` + Subject IdentityJSON `json:"subject"` + Ability string `json:"ability"` + ArgsDigestHex string `json:"args_digest_hex"` + InvocationNonceHex string `json:"invocation_nonce_hex"` + CausalContext CausalJSON `json:"causal_context"` + CallerSignatureHex string `json:"caller_signature_hex"` + CallerSignatureAlg string `json:"caller_signature_alg"` } // NewInvocationJSON builds an InvocationJSON from a signed envelope. diff --git a/sdk/go/easynet/invocation/cross_language_verify_test.go b/sdk/go/easynet/invocation/cross_language_verify_test.go index 5550bdcc..f46b407a 100644 --- a/sdk/go/easynet/invocation/cross_language_verify_test.go +++ b/sdk/go/easynet/invocation/cross_language_verify_test.go @@ -92,18 +92,18 @@ func emitTwoReceiptChain( // r0 — admitted r0 := ReceiptBody{ - Index: 0, - InvocationID: invID, - ReceiptType: "admitted", - State: "ADMITTED", - TimestampUnixMs: 1_700_000_000_000, - PrevReceiptHash: [32]byte{}, - PayloadDigest: Sha256(nil), - CallerBinding: env.Caller, - CalleeBinding: env.Callee, - SubjectBinding: env.Subject, - InvocationNonce: env.InvocationNonce, - CausalBinding: env.CausalContext, + Index: 0, + InvocationID: invID, + ReceiptType: "admitted", + State: "ADMITTED", + TimestampUnixMs: 1_700_000_000_000, + PrevReceiptHash: [32]byte{}, + PayloadDigest: Sha256(nil), + CallerBinding: env.Caller, + CalleeBinding: env.Callee, + SubjectBinding: env.Subject, + InvocationNonce: env.InvocationNonce, + CausalBinding: env.CausalContext, } sig0 := SignReceipt(calleeSk, r0, "") writeJSON(t, filepath.Join(bundle, "receipts", invID, "0.json"), @@ -113,19 +113,19 @@ func emitTwoReceiptChain( // r1 — completed r1 := ReceiptBody{ - Index: 1, - InvocationID: invID, - ReceiptType: "completed", - State: "COMPLETED", - TimestampUnixMs: 1_700_000_001_000, - PrevReceiptHash: prevHash, - PayloadDigest: Sha256(nil), - CleanupComplete: true, - CallerBinding: env.Caller, - CalleeBinding: env.Callee, - SubjectBinding: env.Subject, - InvocationNonce: env.InvocationNonce, - CausalBinding: env.CausalContext, + Index: 1, + InvocationID: invID, + ReceiptType: "completed", + State: "COMPLETED", + TimestampUnixMs: 1_700_000_001_000, + PrevReceiptHash: prevHash, + PayloadDigest: Sha256(nil), + CleanupComplete: true, + CallerBinding: env.Caller, + CalleeBinding: env.Callee, + SubjectBinding: env.Subject, + InvocationNonce: env.InvocationNonce, + CausalBinding: env.CausalContext, } sig1 := SignReceipt(calleeSk, r1, "") writeJSON(t, filepath.Join(bundle, "receipts", invID, "1.json"), @@ -210,7 +210,7 @@ func buildBundle(t *testing.T, bundle string) { InvocationNonce: nonceB, CausalContext: CausalScalarCtx(ReceiptRef{ ReceiptHash: aTerminalHash, - ReceiptURI: "bundle:///receipts/inv-a/1", + ReceiptURA: "bundle:///receipts/inv-a/1", }), } _ = emitTwoReceiptChain(t, bundle, "inv-b", envB, sk1, sk2) diff --git a/sdk/go/easynet/invocation/error.go b/sdk/go/easynet/invocation/error.go index ecf11613..5ef081fb 100644 --- a/sdk/go/easynet/invocation/error.go +++ b/sdk/go/easynet/invocation/error.go @@ -22,12 +22,12 @@ const ( // AxonError is the canonical Invocation-level error. Uniform across SDKs. type AxonError struct { - Kind AxonErrorKind - Reason string - Message string - InvocationID string - RetryAfterMs int64 // 0 = unset - CauseChain []string + Kind AxonErrorKind + Reason string + Message string + InvocationID string + RetryAfterMs int64 // 0 = unset + CauseChain []string } func (e *AxonError) Error() string { diff --git a/sdk/go/easynet/invocation/handle.go b/sdk/go/easynet/invocation/handle.go index 09833616..e2fbd81a 100644 --- a/sdk/go/easynet/invocation/handle.go +++ b/sdk/go/easynet/invocation/handle.go @@ -75,13 +75,13 @@ type InvocationCore struct { ParentInvocationID string AxiomBinding AxiomBinding - mu sync.Mutex - cond *sync.Cond - state InvocationState - events []*InvocationEvent - receipts []*InvocationReceipt - terminal chan struct{} - extTerm bool + mu sync.Mutex + cond *sync.Cond + state InvocationState + events []*InvocationEvent + receipts []*InvocationReceipt + terminal chan struct{} + extTerm bool } // NewInvocationCore constructs a fresh core. @@ -322,11 +322,11 @@ func NewHandle(core *InvocationCore, inbox *MessageInbox) *InvocationHandle { return &InvocationHandle{core: core, inbox: inbox} } -func (h *InvocationHandle) InvocationID() string { return h.core.InvocationID } -func (h *InvocationHandle) ParentInvocationID() string { return h.core.ParentInvocationID } -func (h *InvocationHandle) Core() *InvocationCore { return h.core } +func (h *InvocationHandle) InvocationID() string { return h.core.InvocationID } +func (h *InvocationHandle) ParentInvocationID() string { return h.core.ParentInvocationID } +func (h *InvocationHandle) Core() *InvocationCore { return h.core } func (h *InvocationHandle) CurrentState() InvocationState { return h.core.CurrentState() } -func (h *InvocationHandle) IsTerminal() bool { return h.core.IsTerminal() } +func (h *InvocationHandle) IsTerminal() bool { return h.core.IsTerminal() } // Events opens a new EventStream from offset. func (h *InvocationHandle) Events(fromOffset uint64) *EventStream { diff --git a/sdk/go/easynet/invocation/invocation_tools.go b/sdk/go/easynet/invocation/invocation_tools.go index b6db7ae4..07848d18 100644 --- a/sdk/go/easynet/invocation/invocation_tools.go +++ b/sdk/go/easynet/invocation/invocation_tools.go @@ -7,9 +7,9 @@ import ( // ToolSchema describes one tool for LLM function-calling. type ToolSchema struct { - Name string `json:"name"` - Description string `json:"description"` - Parameters map[string]any `json:"parameters"` + Name string `json:"name"` + Description string `json:"description"` + Parameters map[string]any `json:"parameters"` } func (s ToolSchema) AsOpenAIFunction() map[string]any { diff --git a/sdk/go/easynet/invocation/invoke_signed_test.go b/sdk/go/easynet/invocation/invoke_signed_test.go index 1f426324..312c3f5c 100644 --- a/sdk/go/easynet/invocation/invoke_signed_test.go +++ b/sdk/go/easynet/invocation/invoke_signed_test.go @@ -59,7 +59,7 @@ func TestInvokeSigned_ExplicitSubjectAndNonce_Verifies(t *testing.T) { if !ok { t.Fatalf("envelope not stored") } - if stored.Envelope.Subject.URI != subject.URI { + if stored.Envelope.Subject.URA != subject.URA { t.Fatalf("subject mismatch") } if stored.Envelope.InvocationNonce != nonce { @@ -91,7 +91,7 @@ func TestInvokeSigned_SubjectDefaultsToCallee(t *testing.T) { if axErr != nil { t.Fatalf("invoke_signed: %v", axErr) } - if signed.Envelope.Subject.URI != signed.Envelope.Callee.URI { + if signed.Envelope.Subject.URA != signed.Envelope.Callee.URA { t.Fatalf("subject should default to callee") } if signed.Envelope.Subject.Profile != signed.Envelope.Callee.Profile { @@ -208,7 +208,7 @@ func TestInvokeSigned_TamperedCausalContextBreaksVerification(t *testing.T) { } tampered.CausalContext = CausalScalarCtx(ReceiptRef{ ReceiptHash: fakeHash, - ReceiptURI: "evil", + ReceiptURA: "evil", }) vk := sk.Public().(ed25519.PublicKey) err := VerifyInvocationSignature(tampered, signed.Signature, &staticResolver{key: vk}) diff --git a/sdk/go/easynet/invocation/local_runtime.go b/sdk/go/easynet/invocation/local_runtime.go index 94f5f9d2..745c651b 100644 --- a/sdk/go/easynet/invocation/local_runtime.go +++ b/sdk/go/easynet/invocation/local_runtime.go @@ -20,9 +20,9 @@ type AbilityContext struct { Supervisor *Supervisor Runtime *LocalRuntime - core *InvocationCore - cancelled *atomic.Bool - cancelCh chan struct{} + core *InvocationCore + cancelled *atomic.Bool + cancelCh chan struct{} } // EmitProgress emits a `progress` event on the ability's behalf. @@ -57,15 +57,15 @@ func (a *AbilityContext) CancelCh() <-chan struct{} { // LocalRuntime — in-process runtime mirroring Python/Rust semantics. type LocalRuntime struct { - mu sync.Mutex - abilities map[string]AbilityFn - cores map[string]*InvocationCore - supervisors map[string]*Supervisor - inboxes map[string]*MessageInbox - children map[string]map[string]struct{} - cancelFlags map[string]chan struct{} - cancelledBs map[string]*atomic.Bool - tasksWG map[string]*sync.WaitGroup + mu sync.Mutex + abilities map[string]AbilityFn + cores map[string]*InvocationCore + supervisors map[string]*Supervisor + inboxes map[string]*MessageInbox + children map[string]map[string]struct{} + cancelFlags map[string]chan struct{} + cancelledBs map[string]*atomic.Bool + tasksWG map[string]*sync.WaitGroup // RFC 001 §5.1 — caller-signed envelopes retained for audit. // Populated only by InvokeSignedAsync; plain InvokeAsync callers // use a SystemAgent binding (AXIOM §3.2) which is axiom-bound at @@ -193,7 +193,7 @@ func (r *LocalRuntime) ChildrenOf(invocationID string) []string { // and delegates execution to InvokeAsync. // // Parameter defaulting (§5.1): -// - subject (zero value with empty URI) ⇒ synthesised from `callee`. +// - subject (zero value with empty URA) ⇒ synthesised from `callee`. // - nonce ([16]byte zero value) ⇒ a caller passes `nil` to // force SDK-side CSPRNG generation; any non-zero nonce is used as-is. // @@ -460,15 +460,15 @@ func (r *LocalRuntime) Cancel(ctx context.Context, invocationID, reason string) return nil } -// Well-known local-runtime SystemAgent URI used when no caller identity +// Well-known local-runtime SystemAgent URA used when no caller identity // is provided. AXIOM.tex §3.2 permits this: infrastructure-initiated // invocations carry a SystemAgent identity and are still axiom-bound. -const systemLocalURI = "easynet:///r/_system/agents/local@1" +const systemLocalURA = "easynet:///r/_system/agents/local@1" func systemLocalBinding(payload []byte) AxiomBinding { - system := AgentIdentity{URI: systemLocalURI, Profile: ProfileEasynetStrictV2} - callee := AgentIdentity{URI: systemLocalURI, Profile: ProfileEasynetStrictV2} - subject := SubjectIdentity{URI: systemLocalURI, Profile: ProfileEasynetStrictV2} + system := AgentIdentity{URA: systemLocalURA, Profile: ProfileEasynetStrictV2} + callee := AgentIdentity{URA: systemLocalURA, Profile: ProfileEasynetStrictV2} + subject := SubjectIdentity{URA: systemLocalURA, Profile: ProfileEasynetStrictV2} return AxiomBinding{ Caller: system, Callee: callee, diff --git a/sdk/go/easynet/invocation/messaging.go b/sdk/go/easynet/invocation/messaging.go index 7a07d57d..395f24ea 100644 --- a/sdk/go/easynet/invocation/messaging.go +++ b/sdk/go/easynet/invocation/messaging.go @@ -10,11 +10,11 @@ import ( // InboundMessage — a message delivered to a running Invocation. type InboundMessage struct { - MessageID string - AcceptedSequence uint64 - Payload []byte - ContentType string - AcceptedAtUnixMs int64 + MessageID string + AcceptedSequence uint64 + Payload []byte + ContentType string + AcceptedAtUnixMs int64 } // MessageAck — runtime-side ack for SendInvocationMessage. diff --git a/sdk/go/easynet/invocation/supervisor.go b/sdk/go/easynet/invocation/supervisor.go index 70d89d6d..0359584c 100644 --- a/sdk/go/easynet/invocation/supervisor.go +++ b/sdk/go/easynet/invocation/supervisor.go @@ -23,10 +23,10 @@ type ResourceLimit struct { // SupervisorSpec — process-guard + resource-limit configuration. type SupervisorSpec struct { - ResourceLimit ResourceLimit - CancelGraceSeconds float64 // default 5.0 if 0 - PersistForRecovery bool - Tags map[string]string + ResourceLimit ResourceLimit + CancelGraceSeconds float64 // default 5.0 if 0 + PersistForRecovery bool + Tags map[string]string } // ProcessHandle — a spawned child process in its own process group. diff --git a/sdk/go/easynet/mcp/server_stream_test.go b/sdk/go/easynet/mcp/server_stream_test.go index b467aac1..fdea6a35 100644 --- a/sdk/go/easynet/mcp/server_stream_test.go +++ b/sdk/go/easynet/mcp/server_stream_test.go @@ -17,9 +17,9 @@ import ( // inMemoryStreamHandle replays a fixed sequence of chunks and then signals done. type inMemoryStreamHandle struct { - chunks [][]byte - index int - closed atomic.Bool + chunks [][]byte + index int + closed atomic.Bool closeErr error } @@ -40,11 +40,11 @@ func (m *inMemoryStreamHandle) Close() error { // errorStreamHandle returns an error after delivering a configurable number of // chunks. type errorStreamHandle struct { - chunks [][]byte - index int - closed atomic.Bool - errOnRecv error - errAfterN int // deliver this many chunks before returning the error + chunks [][]byte + index int + closed atomic.Bool + errOnRecv error + errAfterN int // deliver this many chunks before returning the error } func (e *errorStreamHandle) Recv() ([]byte, bool, error) { @@ -63,9 +63,9 @@ func (e *errorStreamHandle) Close() error { // largeChunkStreamHandle produces chunks of a given size, up to a limit. type largeChunkStreamHandle struct { - chunkSize int - remaining int - closed atomic.Bool + chunkSize int + remaining int + closed atomic.Bool } func (l *largeChunkStreamHandle) Recv() ([]byte, bool, error) { diff --git a/sdk/go/easynet/orchestrator_lifecycle.go b/sdk/go/easynet/orchestrator_lifecycle.go index 6fe3e3c1..d3abc0fb 100644 --- a/sdk/go/easynet/orchestrator_lifecycle.go +++ b/sdk/go/easynet/orchestrator_lifecycle.go @@ -98,7 +98,7 @@ func (o *Orchestrator) PublishInstallActivate( Tags: nil, Requirements: nil, Metadata: metadata, - PayloadURI: "", + PayloadURA: "", PayloadSizeBytes: nil, PackageBytesBase64: bundle.Base64, SignatureFingerprint: "", @@ -250,7 +250,7 @@ func (o *Orchestrator) DeployAbilityPackage( Tags: tags, Requirements: map[string]string{}, Metadata: metadata, - PayloadURI: "", + PayloadURA: "", PayloadSizeBytes: nil, PackageBytesBase64: pkgBase64, SignatureFingerprint: "", diff --git a/sdk/go/easynet/reconnect.go b/sdk/go/easynet/reconnect.go index 860441c1..5519e656 100644 --- a/sdk/go/easynet/reconnect.go +++ b/sdk/go/easynet/reconnect.go @@ -266,8 +266,8 @@ func isTransportError(err error) bool { "deadline exceeded", // treat connection-phase deadline as transport failure "unavailable", // gRPC UNAVAILABLE "eof", - "axon_node_unreachable", // server-emitted code from sweeper - "axon_federation_disconnected", // server-emitted when hub connection drops + "axon_node_unreachable", // server-emitted code from sweeper + "axon_federation_disconnected", // server-emitted when hub connection drops } for _, m := range markers { if strings.Contains(msg, m) { diff --git a/sdk/go/easynet/semantic.go b/sdk/go/easynet/semantic.go index fd078550..ee971def 100644 --- a/sdk/go/easynet/semantic.go +++ b/sdk/go/easynet/semantic.go @@ -172,11 +172,11 @@ func (s *SemanticBridge) Tenant(tenantID string) *TenantScope { return &TenantScope{semantic: s, tenantID: tenantID} } -func (s *SemanticBridge) Ability(tenantID string, resourceURI string) *AbilityCallBuilder { +func (s *SemanticBridge) Ability(tenantID string, resourceURA string) *AbilityCallBuilder { return &AbilityCallBuilder{ semantic: s, tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, payloadJSON: map[string]any{}, metadata: map[string]string{}, timeoutMs: DefaultTimeoutMs, @@ -186,7 +186,7 @@ func (s *SemanticBridge) Ability(tenantID string, resourceURI string) *AbilityCa type AbilityCallBuilder struct { semantic *SemanticBridge tenantID string - resourceURI string + resourceURA string payloadJSON any metadata map[string]string timeoutMs int @@ -224,8 +224,8 @@ func (b *AbilityCallBuilder) Invoke() (map[string]any, error) { if strings.TrimSpace(b.tenantID) == "" { return nil, errors.New("tenantID is required") } - if strings.TrimSpace(b.resourceURI) == "" { - return nil, errors.New("resourceURI is required") + if strings.TrimSpace(b.resourceURA) == "" { + return nil, errors.New("resourceURA is required") } timeoutMs := b.timeoutMs if timeoutMs <= 0 { @@ -242,7 +242,7 @@ func (b *AbilityCallBuilder) Invoke() (map[string]any, error) { return b.semantic.bridge.InvokeAbility( b.semantic.handle, b.tenantID, - b.resourceURI, + b.resourceURA, payloadJSON, metadata, timeoutMs, diff --git a/sdk/go/easynet/signed_invoke_request.go b/sdk/go/easynet/signed_invoke_request.go index be5b5c3e..a2fc9d90 100644 --- a/sdk/go/easynet/signed_invoke_request.go +++ b/sdk/go/easynet/signed_invoke_request.go @@ -39,7 +39,7 @@ // or neither yields a typed Go error before any FFI call is made. // - Hand-rolled JSON marshalling for `causal_context` keeps the // on-wire field names locked (`form`, `receipt_hash_hex`, -// `receipt_uri`, `prior`, `root_hex`, `proof_uri`). Default +// `receipt_ura`, `prior`, `root_hex`, `proof_ura`). Default // serde-tag interaction with omitempty is fragile across Go // reflect; explicit emission is the simpler audit surface. // @@ -91,14 +91,14 @@ import ( // same rule client-side so the failure mode is consistent regardless // of which language constructed the request. type SignedAgentIdentity struct { - // URI is the canonical URA of the agent. Examples: + // URA is the canonical URA of the agent. Examples: // // easynet:///r/acme/agent/01HUB // easynet:///r/acme/private/hub/acme // easynet:///r/acme/agent/01LLM-host-A-claude // // MUST be non-empty after trimming. - URI string + URA string // Profile is the URA encoding profile selector. RFC 001 §3.1 // pins this to "easynet-strict-v2" today; setting any other @@ -130,7 +130,7 @@ const ( // bridge-side AXON_AXIOM_ENVELOPE_INCOMPLETE. type SignedCausalRef struct { ReceiptHashHex string - ReceiptURI string + ReceiptURA string } // SignedCausalContext is the wire-typed Go counterpart to the Rust @@ -164,7 +164,7 @@ func CausalNone() SignedCausalContext { // CausalScalar constructs the single-predecessor (linear-successor) // form per AXIOM §"Audit closure under the four causal_context forms" // `scalar receipt reference` bullet. Both ReceiptHashHex and -// ReceiptURI MUST be non-empty; ReceiptHashHex MUST decode as 32 +// ReceiptURA MUST be non-empty; ReceiptHashHex MUST decode as 32 // bytes of valid hex (validated bridge-side, mirrored by `Validate`). func CausalScalar(ref SignedCausalRef) SignedCausalContext { return SignedCausalContext{form: signedCausalFormScalar, scalar: &ref} @@ -188,15 +188,15 @@ func CausalList(refs []SignedCausalRef) SignedCausalContext { // CausalMerkle constructs the unbounded-fan-in form per AXIOM // §"Audit closure under the four causal_context forms" `Merkle root // with URA proof pointer` bullet. `rootHex` is the lowercase hex of -// the 32-byte Merkle root (32 bytes after decode); `proofURI` is the +// the 32-byte Merkle root (32 bytes after decode); `proofURA` is the // URA at which the auditor can fetch the proof artefact (itself a // receipt or sequence of receipts containing the leaf set + inclusion // proofs). -func CausalMerkle(rootHex string, proofURI string) SignedCausalContext { +func CausalMerkle(rootHex string, proofURA string) SignedCausalContext { return SignedCausalContext{ form: signedCausalFormMerkle, merkleRoot: rootHex, - merkleProof: proofURI, + merkleProof: proofURA, } } @@ -229,8 +229,8 @@ func (c SignedCausalContext) validate() error { if err := validateReceiptHashHex("causal_context.scalar.receipt_hash_hex", c.scalar.ReceiptHashHex); err != nil { return err } - if strings.TrimSpace(c.scalar.ReceiptURI) == "" { - return errors.New("causal_context.scalar.receipt_uri must be non-empty") + if strings.TrimSpace(c.scalar.ReceiptURA) == "" { + return errors.New("causal_context.scalar.receipt_ura must be non-empty") } return nil case signedCausalFormList: @@ -243,8 +243,8 @@ func (c SignedCausalContext) validate() error { ); err != nil { return err } - if strings.TrimSpace(r.ReceiptURI) == "" { - return fmt.Errorf("causal_context.list.prior[%d].receipt_uri must be non-empty", i) + if strings.TrimSpace(r.ReceiptURA) == "" { + return fmt.Errorf("causal_context.list.prior[%d].receipt_ura must be non-empty", i) } } return nil @@ -253,7 +253,7 @@ func (c SignedCausalContext) validate() error { return err } if strings.TrimSpace(c.merkleProof) == "" { - return errors.New("causal_context.merkle.proof_uri must be non-empty") + return errors.New("causal_context.merkle.proof_ura must be non-empty") } return nil default: @@ -273,14 +273,14 @@ func (c SignedCausalContext) jsonMap() map[string]any { return map[string]any{ "form": string(signedCausalFormScalar), "receipt_hash_hex": c.scalar.ReceiptHashHex, - "receipt_uri": c.scalar.ReceiptURI, + "receipt_ura": c.scalar.ReceiptURA, } case signedCausalFormList: entries := make([]map[string]any, 0, len(c.list)) for _, r := range c.list { entries = append(entries, map[string]any{ "receipt_hash_hex": r.ReceiptHashHex, - "receipt_uri": r.ReceiptURI, + "receipt_ura": r.ReceiptURA, }) } return map[string]any{ @@ -291,7 +291,7 @@ func (c SignedCausalContext) jsonMap() map[string]any { return map[string]any{ "form": string(signedCausalFormMerkle), "root_hex": c.merkleRoot, - "proof_uri": c.merkleProof, + "proof_ura": c.merkleProof, } default: // Defensive: validate() would have caught this; jsonMap is @@ -307,7 +307,7 @@ func (c SignedCausalContext) jsonMap() map[string]any { // session-bound (set at OpenSignedClient time) and intentionally // absent from this struct — see file-level docs. type SignedInvokeRequest struct { - // Callee is the agent the invocation targets. URI + Profile both + // Callee is the agent the invocation targets. URA + Profile both // MUST be non-empty. Callee SignedAgentIdentity @@ -366,7 +366,7 @@ type SignedInvokeRequest struct { // `dendrite-bridge::invoke_signed::*` so the failure mode is the // same regardless of where the rule trips first. func (r SignedInvokeRequest) validate() error { - if err := requireNonBlank("callee.uri", r.Callee.URI); err != nil { + if err := requireNonBlank("callee.ura", r.Callee.URA); err != nil { return err } if err := requireNonBlank("callee.profile", r.Callee.Profile); err != nil { @@ -374,10 +374,10 @@ func (r SignedInvokeRequest) validate() error { } // Subject is optional. When ANY field is set, BOTH must be set — // half-populated subject is a bridge-side preflight rejection. - subjURI := strings.TrimSpace(r.Subject.URI) + subjURA := strings.TrimSpace(r.Subject.URA) subjProf := strings.TrimSpace(r.Subject.Profile) - if (subjURI == "") != (subjProf == "") { - return errors.New("subject.uri and subject.profile must both be set or both be empty") + if (subjURA == "") != (subjProf == "") { + return errors.New("subject.ura and subject.profile must both be set or both be empty") } if err := requireNonBlank("ability", r.Ability); err != nil { return err @@ -417,14 +417,14 @@ func (r SignedInvokeRequest) helperPayload() (map[string]any, error) { } payload := map[string]any{ "callee": map[string]any{ - "uri": strings.TrimSpace(r.Callee.URI), + "ura": strings.TrimSpace(r.Callee.URA), "profile": strings.TrimSpace(r.Callee.Profile), }, "ability": strings.TrimSpace(r.Ability), } - if strings.TrimSpace(r.Subject.URI) != "" { + if strings.TrimSpace(r.Subject.URA) != "" { payload["subject"] = map[string]any{ - "uri": strings.TrimSpace(r.Subject.URI), + "ura": strings.TrimSpace(r.Subject.URA), "profile": strings.TrimSpace(r.Subject.Profile), } } diff --git a/sdk/go/easynet/signed_invoke_request_test.go b/sdk/go/easynet/signed_invoke_request_test.go index aaab216e..548e9804 100644 --- a/sdk/go/easynet/signed_invoke_request_test.go +++ b/sdk/go/easynet/signed_invoke_request_test.go @@ -49,7 +49,7 @@ func helperPayloadJSON(t *testing.T, req SignedInvokeRequest) map[string]any { func minimalValidRequest() SignedInvokeRequest { return SignedInvokeRequest{ Callee: SignedAgentIdentity{ - URI: "easynet:///r/acme/agent/01HUB", + URA: "easynet:///r/acme/agent/01HUB", Profile: "easynet-strict-v2", }, Ability: "federation.resolve", @@ -68,8 +68,8 @@ func TestSignedInvokeRequest_MinimalValid(t *testing.T) { if !ok { t.Fatalf("callee not a map: %T", got["callee"]) } - if callee["uri"] != "easynet:///r/acme/agent/01HUB" { - t.Errorf("callee.uri = %v", callee["uri"]) + if callee["ura"] != "easynet:///r/acme/agent/01HUB" { + t.Errorf("callee.ura = %v", callee["ura"]) } if callee["profile"] != "easynet-strict-v2" { t.Errorf("callee.profile = %v", callee["profile"]) @@ -130,14 +130,14 @@ func TestSignedInvokeRequest_PayloadBase64Path(t *testing.T) { func TestSignedInvokeRequest_RejectsHalfPopulatedSubject(t *testing.T) { req := minimalValidRequest() - req.Subject.URI = "easynet:///r/acme/agent/01USR-x" + req.Subject.URA = "easynet:///r/acme/agent/01USR-x" // Profile deliberately empty. _, err := req.helperPayload() if err == nil { t.Fatalf("expected error for half-populated subject") } - if !strings.Contains(err.Error(), "subject.uri and subject.profile") { + if !strings.Contains(err.Error(), "subject.ura and subject.profile") { t.Errorf("error should name both subject fields, got: %v", err) } } @@ -145,7 +145,7 @@ func TestSignedInvokeRequest_RejectsHalfPopulatedSubject(t *testing.T) { func TestSignedInvokeRequest_FullSubjectIncluded(t *testing.T) { req := minimalValidRequest() req.Subject = SignedAgentIdentity{ - URI: "easynet:///r/acme/agent/01USR-silan", + URA: "easynet:///r/acme/agent/01USR-silan", Profile: "easynet-strict-v2", } @@ -154,8 +154,8 @@ func TestSignedInvokeRequest_FullSubjectIncluded(t *testing.T) { if !ok { t.Fatalf("subject missing or wrong type: %T", got["subject"]) } - if subj["uri"] != "easynet:///r/acme/agent/01USR-silan" { - t.Errorf("subject.uri mismatch: %v", subj["uri"]) + if subj["ura"] != "easynet:///r/acme/agent/01USR-silan" { + t.Errorf("subject.ura mismatch: %v", subj["ura"]) } if subj["profile"] != "easynet-strict-v2" { t.Errorf("subject.profile mismatch: %v", subj["profile"]) @@ -212,7 +212,7 @@ func TestSignedInvokeRequest_CausalScalar(t *testing.T) { hash := strings.Repeat("ab", 32) // 64 lowercase hex chars = 32 bytes req.CausalContext = CausalScalar(SignedCausalRef{ ReceiptHashHex: hash, - ReceiptURI: "easynet:///r/acme/receipt/01RCP-1", + ReceiptURA: "easynet:///r/acme/receipt/01RCP-1", }) got := helperPayloadJSON(t, req) @@ -226,8 +226,8 @@ func TestSignedInvokeRequest_CausalScalar(t *testing.T) { if cc["receipt_hash_hex"] != hash { t.Errorf("receipt_hash_hex round-trip mismatch") } - if cc["receipt_uri"] != "easynet:///r/acme/receipt/01RCP-1" { - t.Errorf("receipt_uri round-trip mismatch") + if cc["receipt_ura"] != "easynet:///r/acme/receipt/01RCP-1" { + t.Errorf("receipt_ura round-trip mismatch") } } @@ -235,7 +235,7 @@ func TestSignedInvokeRequest_CausalScalar_RejectsBadHex(t *testing.T) { req := minimalValidRequest() req.CausalContext = CausalScalar(SignedCausalRef{ ReceiptHashHex: "ZZZZ", // not hex - ReceiptURI: "easynet:///r/acme/receipt/01RCP-1", + ReceiptURA: "easynet:///r/acme/receipt/01RCP-1", }) _, err := req.helperPayload() @@ -248,7 +248,7 @@ func TestSignedInvokeRequest_CausalScalar_RejectsWrongHexLength(t *testing.T) { req := minimalValidRequest() req.CausalContext = CausalScalar(SignedCausalRef{ ReceiptHashHex: strings.Repeat("ab", 16), // 32 chars = 16 bytes; want 32 - ReceiptURI: "easynet:///r/acme/receipt/01RCP-1", + ReceiptURA: "easynet:///r/acme/receipt/01RCP-1", }) _, err := req.helperPayload() @@ -261,7 +261,7 @@ func TestSignedInvokeRequest_CausalScalar_RejectsUppercaseHex(t *testing.T) { req := minimalValidRequest() req.CausalContext = CausalScalar(SignedCausalRef{ ReceiptHashHex: strings.Repeat("AB", 32), - ReceiptURI: "easynet:///r/acme/receipt/01RCP-1", + ReceiptURA: "easynet:///r/acme/receipt/01RCP-1", }) _, err := req.helperPayload() @@ -275,8 +275,8 @@ func TestSignedInvokeRequest_CausalList(t *testing.T) { hashA := strings.Repeat("aa", 32) hashB := strings.Repeat("bb", 32) req.CausalContext = CausalList([]SignedCausalRef{ - {ReceiptHashHex: hashA, ReceiptURI: "easynet:///r/acme/receipt/01RCP-A"}, - {ReceiptHashHex: hashB, ReceiptURI: "easynet:///r/acme/receipt/01RCP-B"}, + {ReceiptHashHex: hashA, ReceiptURA: "easynet:///r/acme/receipt/01RCP-A"}, + {ReceiptHashHex: hashB, ReceiptURA: "easynet:///r/acme/receipt/01RCP-B"}, }) got := helperPayloadJSON(t, req) @@ -323,8 +323,8 @@ func TestSignedInvokeRequest_CausalMerkle(t *testing.T) { if cc["root_hex"] != root { t.Errorf("root_hex round-trip mismatch") } - if cc["proof_uri"] != "easynet:///r/acme/proof/01PRF-1" { - t.Errorf("proof_uri round-trip mismatch") + if cc["proof_ura"] != "easynet:///r/acme/proof/01PRF-1" { + t.Errorf("proof_ura round-trip mismatch") } } @@ -394,11 +394,11 @@ func TestSignedInvokeRequest_RejectsEmptyAbility(t *testing.T) { func TestSignedInvokeRequest_RejectsEmptyCalleeURI(t *testing.T) { req := minimalValidRequest() - req.Callee.URI = "" + req.Callee.URA = "" _, err := req.helperPayload() if err == nil { - t.Fatalf("expected error for blank callee.uri") + t.Fatalf("expected error for blank callee.ura") } } @@ -423,7 +423,7 @@ func TestSignedCausalContext_FormAccessor(t *testing.T) { "scalar", CausalScalar(SignedCausalRef{ ReceiptHashHex: strings.Repeat("ab", 32), - ReceiptURI: "easynet:///r/acme/receipt/x", + ReceiptURA: "easynet:///r/acme/receipt/x", }), "scalar", }, @@ -431,7 +431,7 @@ func TestSignedCausalContext_FormAccessor(t *testing.T) { "list", CausalList([]SignedCausalRef{{ ReceiptHashHex: strings.Repeat("ab", 32), - ReceiptURI: "easynet:///r/acme/receipt/x", + ReceiptURA: "easynet:///r/acme/receipt/x", }}), "list", }, @@ -460,7 +460,7 @@ func TestSignedCausalContext_IsNoneCoversZeroValue(t *testing.T) { } scalar := CausalScalar(SignedCausalRef{ ReceiptHashHex: strings.Repeat("ab", 32), - ReceiptURI: "easynet:///r/acme/receipt/x", + ReceiptURA: "easynet:///r/acme/receipt/x", }) if scalar.IsNone() { t.Errorf("Scalar form must not report IsNone()") @@ -479,9 +479,9 @@ func TestSigningConfig_SeedLengthRule(t *testing.T) { } } -func TestSigningConfig_RequiresCallerURI(t *testing.T) { +func TestSigningConfig_RequiresCallerURA(t *testing.T) { if _, err := NewSigningConfig(make([]byte, 32), " "); err == nil { - t.Errorf("blank caller URI should be rejected") + t.Errorf("blank caller URA should be rejected") } } diff --git a/sdk/go/easynet/streaming.go b/sdk/go/easynet/streaming.go index 02d65954..de9ecd86 100644 --- a/sdk/go/easynet/streaming.go +++ b/sdk/go/easynet/streaming.go @@ -40,10 +40,10 @@ func DefaultPhraseStreamerConfig() PhraseStreamerConfig { } type PhraseStreamer struct { - cfg PhraseStreamerConfig - acc string - tokensSince int - phrasesEmitted int + cfg PhraseStreamerConfig + acc string + tokensSince int + phrasesEmitted int } func NewPhraseStreamer(cfg PhraseStreamerConfig) *PhraseStreamer { diff --git a/sdk/go/easynet/tool_adapter.go b/sdk/go/easynet/tool_adapter.go index aacd21dd..6de10115 100644 --- a/sdk/go/easynet/tool_adapter.go +++ b/sdk/go/easynet/tool_adapter.go @@ -6,7 +6,7 @@ // // Protocol Responsibility: // - Converts between LLM tool-call schemas (OpenAI function-calling, Anthropic tool-use) and Axon ability request/response envelopes. -// - Preserves ability identity via resource URI mapping and invocation semantics. +// - Preserves ability identity via resource URA mapping and invocation semantics. // // Implementation Approach: // - Uses functional options pattern consistent with existing Go SDK style. @@ -42,7 +42,7 @@ import ( type ToolSpec struct { Name string `json:"name"` Description string `json:"description"` - ResourceURI string `json:"resource_uri"` + ResourceURA string `json:"resource_ura"` Parameters map[string]any `json:"parameters"` // MCP safety hints — mirrors ability-level hints on AbilityDescriptor. These // are NOT tagged `omitempty`: the fail-closed defaults (destructive=true, @@ -90,7 +90,7 @@ func (s *ToolSpec) ToDict() map[string]any { return map[string]any{ "name": s.Name, "description": s.Description, - "resource_uri": s.ResourceURI, + "resource_ura": s.ResourceURA, "parameters": s.Parameters, "read_only_hint": s.ReadOnlyHint, "destructive_hint": s.DestructiveHint, @@ -115,7 +115,7 @@ type RegisterOption func(*registerConfig) type registerConfig struct { description string - resourceURI string + resourceURA string parameters map[string]any } @@ -124,9 +124,9 @@ func WithToolDescription(desc string) RegisterOption { return func(c *registerConfig) { c.description = desc } } -// WithToolResourceURI overrides the default resource URI. -func WithToolResourceURI(uri string) RegisterOption { - return func(c *registerConfig) { c.resourceURI = uri } +// WithToolResourceURA overrides the default resource URA. +func WithToolResourceURA(ura string) RegisterOption { + return func(c *registerConfig) { c.resourceURA = ura } } // WithToolParameters sets explicit JSON Schema parameters. @@ -174,9 +174,9 @@ func (a *AbilityToolAdapter) Register(name string, handler ToolHandler, opts ... opt(cfg) } } - uri := cfg.resourceURI - if uri == "" { - uri = "easynet:///r/org/" + name + ura := cfg.resourceURA + if ura == "" { + ura = ResourceDotURA("org", "tool."+name, "") } params := cfg.parameters if params == nil { @@ -185,7 +185,7 @@ func (a *AbilityToolAdapter) Register(name string, handler ToolHandler, opts ... spec := &ToolSpec{ Name: name, Description: cfg.description, - ResourceURI: uri, + ResourceURA: ura, Parameters: params, } a.mu.Lock() @@ -199,7 +199,7 @@ func (a *AbilityToolAdapter) Register(name string, handler ToolHandler, opts ... } // RegisterAbility adds a remote ability as a tool (no local handler). -func (a *AbilityToolAdapter) RegisterAbility(name string, resourceURI string, opts ...RegisterOption) *AbilityToolAdapter { +func (a *AbilityToolAdapter) RegisterAbility(name string, resourceURA string, opts ...RegisterOption) *AbilityToolAdapter { cfg := ®isterConfig{} for _, opt := range opts { if opt != nil { @@ -213,7 +213,7 @@ func (a *AbilityToolAdapter) RegisterAbility(name string, resourceURI string, op spec := &ToolSpec{ Name: name, Description: cfg.description, - ResourceURI: resourceURI, + ResourceURA: resourceURA, Parameters: params, } a.mu.Lock() @@ -318,11 +318,11 @@ func (a *AbilityToolAdapter) Execute(ctx context.Context, name string, arguments if !ok { return nil, errors.New("configured transport does not support principal(...) context") } - return principalTransport.CallWithOptions(ctx, a.TenantID, spec.ResourceURI, arguments, CallOptions{ + return principalTransport.CallWithOptions(ctx, a.TenantID, spec.ResourceURA, arguments, CallOptions{ PrincipalID: a.PrincipalID, }) } - return a.Transport.Call(ctx, a.TenantID, spec.ResourceURI, arguments) + return a.Transport.Call(ctx, a.TenantID, spec.ResourceURA, arguments) } // ExecuteJSON runs a tool call with a JSON string argument and returns JSON string result. diff --git a/sdk/go/easynet/tool_adapter_test.go b/sdk/go/easynet/tool_adapter_test.go index d0da6779..e0bc7ec6 100644 --- a/sdk/go/easynet/tool_adapter_test.go +++ b/sdk/go/easynet/tool_adapter_test.go @@ -33,25 +33,25 @@ import ( type principalCaptureTransport struct { tenantID string - resourceURI string + resourceURA string options CallOptions } -func (t *principalCaptureTransport) Call(_ context.Context, tenantID string, resourceURI string, payload Payload) (Payload, error) { +func (t *principalCaptureTransport) Call(_ context.Context, tenantID string, resourceURA string, payload Payload) (Payload, error) { t.tenantID = tenantID - t.resourceURI = resourceURI + t.resourceURA = resourceURA return payload, nil } func (t *principalCaptureTransport) CallWithOptions( _ context.Context, tenantID string, - resourceURI string, + resourceURA string, payload Payload, options CallOptions, ) (Payload, error) { t.tenantID = tenantID - t.resourceURI = resourceURI + t.resourceURA = resourceURA t.options = options return payload, nil } @@ -68,8 +68,8 @@ func TestToolAdapterPrincipalContextFlowsToRemoteTransport(t *testing.T) { if got := transport.options.PrincipalID; got != "agent.alice" { t.Fatalf("principal not propagated: got %q", got) } - if got := transport.resourceURI; got != "easynet:///r/prv/camera" { - t.Fatalf("resource uri mismatch: got %q", got) + if got := transport.resourceURA; got != "easynet:///r/prv/camera" { + t.Fatalf("resource ura mismatch: got %q", got) } if got := result["mode"]; got != "photo" { t.Fatalf("payload mismatch: got %#v", got) diff --git a/sdk/go/easynet/ura.go b/sdk/go/easynet/ura.go new file mode 100644 index 00000000..df5dbde4 --- /dev/null +++ b/sdk/go/easynet/ura.go @@ -0,0 +1,313 @@ +package easynet + +import ( + "fmt" + "net/url" + "strings" +) + +const URAScheme = "easynet:///r/" + +type URAKind string + +const ( + URAKindUnknown URAKind = "unknown" + URAKindUser URAKind = "user" + URAKindDevice URAKind = "device" + URAKindAgent URAKind = "agent" + URAKindAbility URAKind = "ability" + URAKindHub URAKind = "hub" + URAKindResource URAKind = "resource" +) + +// Ura is the Go SDK value object for canonical EasyNet URAs. +// +// Axon-owned code should construct URAs through this object or the +// package-level façade functions below. Application layers should treat +// returned values as opaque protocol addresses and avoid rebuilding them +// from path fragments. +type Ura struct { + raw string +} + +type ParsedURA struct { + Raw string + Realm string + Kind URAKind + UserID string + DeviceID string + AgentID string + AbilityID string + OwnerID string + Path string +} + +func ParseURA(raw string) (Ura, error) { + if _, err := ParseURAParts(raw); err != nil { + return Ura{}, err + } + return Ura{raw: raw}, nil +} + +func (u Ura) String() string { return u.raw } + +func (u Ura) Parts() ParsedURA { + parts, err := ParseURAParts(u.raw) + if err != nil { + panic("Ura stores only validated canonical addresses") + } + return parts +} + +func (u Ura) Kind() URAKind { return u.Parts().Kind } + +func (u Ura) AbilityName() string { + parts := u.Parts() + if parts.Kind != URAKindAbility { + return "" + } + if parts.UserID == "hub" { + return parts.AgentID + "." + parts.AbilityID + } + return parts.AbilityID +} + +func (u Ura) PublicAbilityName(registeredName string) string { + registeredName = strings.TrimSpace(registeredName) + if registeredName == "" { + return "" + } + parts := u.Parts() + if parts.Kind == URAKindAgent && parts.AgentID != "" { + return strings.TrimPrefix(registeredName, parts.AgentID+".") + } + return registeredName +} + +func (u Ura) PublicAbilityNameForOwner(ownerURA string) string { + name, ok := PublicAbilityNameFromAbilityURA(ownerURA, u.raw) + if !ok { + return "" + } + return name +} + +func AbilityNameFromURA(raw string) string { + u, err := ParseURA(raw) + if err != nil { + return "" + } + return u.AbilityName() +} + +func PublicAbilityNameForOwner(ownerURA, registeredName string) string { + u, err := ParseURA(ownerURA) + if err != nil { + return strings.TrimSpace(registeredName) + } + return u.PublicAbilityName(registeredName) +} + +func PublicAbilityNameFromAbilityURA(ownerURA, abilityURA string) (string, bool) { + owner, ownerErr := ParseURA(ownerURA) + ability, abilityErr := ParseURA(abilityURA) + if ownerErr != nil || abilityErr != nil { + return "", false + } + ownerParts := owner.Parts() + abilityParts := ability.Parts() + if abilityParts.Kind != URAKindAbility { + return "", false + } + switch ownerParts.Kind { + case URAKindAgent: + if ownerParts.Realm == abilityParts.Realm && + ownerParts.UserID == abilityParts.UserID && + ownerParts.AgentID == abilityParts.AgentID { + return abilityParts.AbilityID, true + } + case URAKindHub: + if ownerParts.Realm == abilityParts.Realm && abilityParts.UserID == "hub" { + return ability.AbilityName(), true + } + } + return "", false +} + +func UserURA(realm, userID string) string { + return Ura{raw: fmt.Sprintf("%s%s/user/%s", URAScheme, realm, userID)}.String() +} + +func DeviceURA(realm, deviceID string) string { + return Ura{raw: fmt.Sprintf("%s%s/device/%s", URAScheme, realm, deviceID)}.String() +} + +func AgentURA(realm, userID, agentID string) string { + return Ura{raw: fmt.Sprintf("%s%s/agent/%s.%s", URAScheme, realm, userID, agentID)}.String() +} + +func AbilityURA(realm, userID, agentID, abilityID string) string { + return Ura{raw: fmt.Sprintf("%s%s/ability/%s.%s.%s", URAScheme, realm, userID, agentID, abilityID)}.String() +} + +func HubURA(realm string) string { + return Ura{raw: fmt.Sprintf("%s%s/hub", URAScheme, realm)}.String() +} + +func HubAbilityURA(realm, abilityName string) string { + if realm == "" || abilityName == "" { + return "" + } + tail := abilityName + switch { + case strings.HasPrefix(tail, "hub."): + case strings.HasPrefix(tail, "01HUB."): + tail = "hub." + strings.TrimPrefix(tail, "01HUB.") + default: + if !strings.Contains(tail, ".") { + return "" + } + tail = "hub." + tail + } + raw := fmt.Sprintf("%s%s/ability/%s", URAScheme, realm, tail) + if _, err := ParseURA(raw); err != nil { + return "" + } + return raw +} + +func ResourceDotURA(realm, ownerID, path string) string { + clean := strings.TrimPrefix(path, "/") + if clean == "" { + return fmt.Sprintf("%s%s/resource/%s", URAScheme, realm, ownerID) + } + return fmt.Sprintf("%s%s/resource/%s/%s", URAScheme, realm, ownerID, clean) +} + +func DeviceAbilityResourceURA(realm, deviceID, abilityID string) string { + if realm == "" || deviceID == "" || abilityID == "" { + return "" + } + raw := ResourceDotURA(realm, "device."+deviceID, "ability/"+abilityID) + if _, err := ParseURA(raw); err != nil { + return "" + } + return raw +} + +func ResourceURA(realm, userID, namespace, path string) string { + clean := strings.TrimPrefix(path, "/") + return fmt.Sprintf("%s%s/resource/%s/%s/%s", URAScheme, realm, userID, namespace, clean) +} + +func FilesResourceURA(realm, username, sha256Hex string) string { + return ResourceDotURA(realm, username+".files", sha256Hex) +} + +func APIKeyResourceURA(realm, token string) string { + return fmt.Sprintf("%s%s/resource/api_key.%s", URAScheme, realm, token) +} + +func PagesResourceURA(realm, username, project, path string) string { + if path != "" && !strings.HasPrefix(path, "/") { + path = "/" + path + } + return fmt.Sprintf("%s%s/resource/%s.%s%s", URAScheme, realm, username, project, path) +} + +func AgentSkillResourceURA(realm, username, agentID, skillName string) string { + if realm == "" || username == "" || agentID == "" || skillName == "" { + return "" + } + raw := ResourceDotURA( + url.PathEscape(realm), + "agent."+url.PathEscape(username)+"."+url.PathEscape(agentID), + "skill/"+url.PathEscape(skillName), + ) + if _, err := ParseURA(raw); err != nil { + return "" + } + return raw +} + +func AgentSkillFileResourceURA(realm, username, agentID, skillName, relPath string) string { + base := AgentSkillResourceURA(realm, username, agentID, skillName) + if base == "" { + return "" + } + relPath = strings.TrimPrefix(relPath, "/") + if relPath == "" { + return base + } + parts := strings.Split(relPath, "/") + for i := range parts { + parts[i] = url.PathEscape(parts[i]) + } + raw := base + "/file/" + strings.Join(parts, "/") + if _, err := ParseURA(raw); err != nil { + return "" + } + return raw +} + +func RealmUserPrefix(realm string) string { return fmt.Sprintf("%s%s/user/", URAScheme, realm) } +func RealmDevicePrefix(realm string) string { return fmt.Sprintf("%s%s/device/", URAScheme, realm) } +func RealmAgentPrefix(realm string) string { return fmt.Sprintf("%s%s/agent/", URAScheme, realm) } +func UserAgentPrefix(realm, userID string) string { + return fmt.Sprintf("%s%s/agent/%s.", URAScheme, realm, userID) +} +func RealmAbilityPrefix(realm string) string { return fmt.Sprintf("%s%s/ability/", URAScheme, realm) } +func RealmResourcePrefix(realm string) string { return fmt.Sprintf("%s%s/resource/", URAScheme, realm) } + +func ParseURAParts(raw string) (ParsedURA, error) { + rest, ok := strings.CutPrefix(raw, URAScheme) + if !ok { + return ParsedURA{}, fmt.Errorf("URA must start with %s", URAScheme) + } + realm, afterRealm, ok := strings.Cut(rest, "/") + if !ok || realm == "" { + return ParsedURA{}, fmt.Errorf("URA missing realm segment") + } + role, tail, ok := strings.Cut(afterRealm, "/") + if !ok { + role, tail = afterRealm, "" + } + out := ParsedURA{Raw: raw, Realm: realm, Kind: URAKind(role)} + switch role { + case "user": + if tail == "" || strings.Contains(tail, "/") || strings.Contains(tail, ".") { + return ParsedURA{}, fmt.Errorf("user URA requires one user-id segment") + } + out.UserID = tail + case "device": + if tail == "" || strings.Contains(tail, "/") || strings.Contains(tail, ".") { + return ParsedURA{}, fmt.Errorf("device URA requires one device-id segment") + } + out.DeviceID = tail + case "agent": + userID, agentID, ok := strings.Cut(tail, ".") + if !ok || userID == "" || agentID == "" || strings.Contains(agentID, ".") || strings.Contains(tail, "/") { + return ParsedURA{}, fmt.Errorf("agent URA tail must be .") + } + out.UserID, out.AgentID = userID, agentID + case "ability": + parts := strings.SplitN(tail, ".", 3) + if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" || strings.Contains(parts[0], "/") || strings.Contains(parts[1], "/") || strings.Contains(parts[1], ".") { + return ParsedURA{}, fmt.Errorf("ability URA tail must be ..") + } + out.UserID, out.AgentID, out.AbilityID = parts[0], parts[1], parts[2] + case "hub": + if tail != "" { + return ParsedURA{}, fmt.Errorf("hub URA is realm singleton") + } + case "resource": + owner, path, _ := strings.Cut(tail, "/") + if owner == "" { + return ParsedURA{}, fmt.Errorf("resource URA requires owner segment") + } + out.OwnerID, out.UserID, out.Path = owner, owner, path + default: + return ParsedURA{}, fmt.Errorf("unknown URA role %q", role) + } + return out, nil +} diff --git a/sdk/go/easynet/ura_test.go b/sdk/go/easynet/ura_test.go new file mode 100644 index 00000000..6762ef23 --- /dev/null +++ b/sdk/go/easynet/ura_test.go @@ -0,0 +1,50 @@ +package easynet + +import "testing" + +func TestUraValueObjectBuildsAndParsesCanonicalShapes(t *testing.T) { + ability := AbilityURA("localhost", "dev", "frontend-engineer", "chat") + if ability != "easynet:///r/localhost/ability/dev.frontend-engineer.chat" { + t.Fatalf("ability URA = %q", ability) + } + parsed, err := ParseURAParts(ability) + if err != nil { + t.Fatalf("parse ability URA: %v", err) + } + if parsed.Kind != URAKindAbility || parsed.UserID != "dev" || parsed.AgentID != "frontend-engineer" || parsed.AbilityID != "chat" { + t.Fatalf("parsed ability = %#v", parsed) + } + uAbility, err := ParseURA(ability) + if err != nil { + t.Fatalf("parse ability value object: %v", err) + } + if uAbility.AbilityName() != "chat" { + t.Fatalf("ability name = %q, want chat", uAbility.AbilityName()) + } + if AbilityNameFromURA(HubAbilityURA("localhost", "federation.resolve")) != "federation.resolve" { + t.Fatalf("hub ability name projection failed") + } + if PublicAbilityNameForOwner(AgentURA("localhost", "dev", "frontend-engineer"), "frontend-engineer.chat") != "chat" { + t.Fatalf("agent owner public ability name projection failed") + } + if PublicAbilityNameForOwner(HubURA("localhost"), "federation.resolve") != "federation.resolve" { + t.Fatalf("hub owner public ability name projection failed") + } + if name, ok := PublicAbilityNameFromAbilityURA(AgentURA("localhost", "dev", "frontend-engineer"), ability); !ok || name != "chat" { + t.Fatalf("owner + ability URA public name = %q %v, want chat true", name, ok) + } + + u, err := ParseURA(DeviceURA("localhost", "device-a")) + if err != nil { + t.Fatalf("parse device URA: %v", err) + } + if u.String() != "easynet:///r/localhost/device/device-a" || u.Kind() != URAKindDevice { + t.Fatalf("device value object mismatch: %q %s", u.String(), u.Kind()) + } +} + +func TestUraRejectsTransportEndpoint(t *testing.T) { + if _, err := ParseURA("axon://localhost:50051"); err == nil { + t.Fatal("transport endpoints must not parse as URAs") + } +} diff --git a/sdk/go/tests/industrial/audit_receipt_chain_verify_test.go b/sdk/go/tests/industrial/audit_receipt_chain_verify_test.go index cac696f3..ef88fbff 100644 --- a/sdk/go/tests/industrial/audit_receipt_chain_verify_test.go +++ b/sdk/go/tests/industrial/audit_receipt_chain_verify_test.go @@ -12,15 +12,23 @@ func Test_audit_receipt_chain_verify(t *testing.T) { rt := inv.NewLocalRuntime() rt.RegisterAbility("chain_verify", func(ctx context.Context, ac *inv.AbilityContext) ([]byte, *inv.AxonError) { for i := 0; i < 5; i++ { - if e := ac.EmitProgress([]byte{byte('a' + i)}, ""); e != nil { return nil, e } + if e := ac.EmitProgress([]byte{byte('a' + i)}, ""); e != nil { + return nil, e + } } return []byte("ok"), nil }) h, e := rt.InvokeAsync(context.Background(), "chain_verify", nil, "", nil) - if e != nil { t.Fatal(e) } + if e != nil { + t.Fatal(e) + } h.Wait(context.Background()) receipts := rt.CoreOf(h.InvocationID()).SnapshotReceipts() r := inv.VerifyReceiptChain(receipts) - if !r.OK { t.Fatalf("chain broken: %s", r.Detail) } - if len(receipts) < 10 { t.Fatalf("receipts=%d", len(receipts)) } + if !r.OK { + t.Fatalf("chain broken: %s", r.Detail) + } + if len(receipts) < 10 { + t.Fatalf("receipts=%d", len(receipts)) + } } diff --git a/sdk/go/tests/industrial/audit_tamper_detection_test.go b/sdk/go/tests/industrial/audit_tamper_detection_test.go index 992bc01e..39cab5d6 100644 --- a/sdk/go/tests/industrial/audit_tamper_detection_test.go +++ b/sdk/go/tests/industrial/audit_tamper_detection_test.go @@ -19,12 +19,16 @@ func Test_audit_tamper_detection(t *testing.T) { h, _ := rt.InvokeAsync(context.Background(), "tamper", nil, "", nil) h.Wait(context.Background()) receipts := rt.CoreOf(h.InvocationID()).SnapshotReceipts() - if !inv.VerifyReceiptChain(receipts).OK { t.Fatal("baseline chain failed") } + if !inv.VerifyReceiptChain(receipts).OK { + t.Fatal("baseline chain failed") + } i := len(receipts) / 2 receipts[i].Reason += "_tampered" r := inv.VerifyReceiptChain(receipts) - if r.OK { t.Fatal("tamper not detected") } + if r.OK { + t.Fatal("tamper not detected") + } if r.BrokenIndex != int64(i) && r.BrokenIndex != int64(i+1) { t.Fatalf("broken_index %d not in {%d,%d}", r.BrokenIndex, i, i+1) } diff --git a/sdk/go/tests/industrial/error_retriable_hints_test.go b/sdk/go/tests/industrial/error_retriable_hints_test.go index b065dd79..4d9900f3 100644 --- a/sdk/go/tests/industrial/error_retriable_hints_test.go +++ b/sdk/go/tests/industrial/error_retriable_hints_test.go @@ -9,11 +9,19 @@ import ( func Test_error_retriable_hints(t *testing.T) { u := inv.ErrUnavailable("transient").WithRetryAfterMs(150) - if !u.Retriable() || u.RetryAfterMs != 150 { t.Fatal("unavailable") } + if !u.Retriable() || u.RetryAfterMs != 150 { + t.Fatal("unavailable") + } r := inv.ErrResourceExhausted("queue_full").WithRetryAfterMs(50) - if !r.Retriable() || r.RetryAfterMs != 50 { t.Fatal("rex") } + if !r.Retriable() || r.RetryAfterMs != 50 { + t.Fatal("rex") + } c := inv.ErrCancelled("user") - if c.Retriable() || c.RetryAfterMs != 0 { t.Fatal("cancelled") } + if c.Retriable() || c.RetryAfterMs != 0 { + t.Fatal("cancelled") + } i := inv.ErrInternal("bug") - if i.Retriable() { t.Fatal("internal") } + if i.Retriable() { + t.Fatal("internal") + } } diff --git a/sdk/go/tests/industrial/error_taxonomy_mapping_test.go b/sdk/go/tests/industrial/error_taxonomy_mapping_test.go index 6b0d551a..dbf459f6 100644 --- a/sdk/go/tests/industrial/error_taxonomy_mapping_test.go +++ b/sdk/go/tests/industrial/error_taxonomy_mapping_test.go @@ -8,23 +8,53 @@ import ( ) func Test_error_taxonomy_mapping(t *testing.T) { - if inv.ErrCancelled("x").Kind != inv.KindCancelled { t.Fatal("cancelled") } - if inv.ErrDeadlineExceeded("x").Kind != inv.KindDeadlineExceeded { t.Fatal("deadline") } - if inv.ErrUnavailable("x").Kind != inv.KindUnavailable { t.Fatal("unavailable") } - if inv.ErrInvalidArgument("x").Kind != inv.KindInvalidArgument { t.Fatal("invalid") } - if inv.ErrResourceExhausted("x").Kind != inv.KindResourceExhausted { t.Fatal("rex") } - if inv.ErrPermissionDenied("x").Kind != inv.KindPermissionDenied { t.Fatal("perm") } - if inv.ErrInternal("x").Kind != inv.KindInternal { t.Fatal("internal") } + if inv.ErrCancelled("x").Kind != inv.KindCancelled { + t.Fatal("cancelled") + } + if inv.ErrDeadlineExceeded("x").Kind != inv.KindDeadlineExceeded { + t.Fatal("deadline") + } + if inv.ErrUnavailable("x").Kind != inv.KindUnavailable { + t.Fatal("unavailable") + } + if inv.ErrInvalidArgument("x").Kind != inv.KindInvalidArgument { + t.Fatal("invalid") + } + if inv.ErrResourceExhausted("x").Kind != inv.KindResourceExhausted { + t.Fatal("rex") + } + if inv.ErrPermissionDenied("x").Kind != inv.KindPermissionDenied { + t.Fatal("perm") + } + if inv.ErrInternal("x").Kind != inv.KindInternal { + t.Fatal("internal") + } kind, reason := inv.MapProtoCode(1) - if kind != inv.KindCancelled || reason != "" { t.Fatal("proto 1") } - if k,_ := inv.MapProtoCode(3); k != inv.KindInvalidArgument { t.Fatal("3") } - if k,_ := inv.MapProtoCode(4); k != inv.KindDeadlineExceeded { t.Fatal("4") } - if k,_ := inv.MapProtoCode(7); k != inv.KindPermissionDenied { t.Fatal("7") } - if k,_ := inv.MapProtoCode(8); k != inv.KindResourceExhausted { t.Fatal("8") } - if k,_ := inv.MapProtoCode(13); k != inv.KindInternal { t.Fatal("13") } - if k,_ := inv.MapProtoCode(14); k != inv.KindUnavailable { t.Fatal("14") } + if kind != inv.KindCancelled || reason != "" { + t.Fatal("proto 1") + } + if k, _ := inv.MapProtoCode(3); k != inv.KindInvalidArgument { + t.Fatal("3") + } + if k, _ := inv.MapProtoCode(4); k != inv.KindDeadlineExceeded { + t.Fatal("4") + } + if k, _ := inv.MapProtoCode(7); k != inv.KindPermissionDenied { + t.Fatal("7") + } + if k, _ := inv.MapProtoCode(8); k != inv.KindResourceExhausted { + t.Fatal("8") + } + if k, _ := inv.MapProtoCode(13); k != inv.KindInternal { + t.Fatal("13") + } + if k, _ := inv.MapProtoCode(14); k != inv.KindUnavailable { + t.Fatal("14") + } k, r := inv.MapProtoCode(99999) - if k != inv.KindInternal || r != "unknown_error_code" { t.Fatalf("unknown: %v %q", k, r) } + if k != inv.KindInternal || r != "unknown_error_code" { + t.Fatalf("unknown: %v %q", k, r) + } } diff --git a/sdk/go/tests/industrial/event_stream_resumption_test.go b/sdk/go/tests/industrial/event_stream_resumption_test.go index 73deaad3..b05f5f6a 100644 --- a/sdk/go/tests/industrial/event_stream_resumption_test.go +++ b/sdk/go/tests/industrial/event_stream_resumption_test.go @@ -24,11 +24,19 @@ func Test_event_stream_resumption(t *testing.T) { s1 := h.Events(0) for { ev := s1.Next(context.Background()) - if ev == nil { break } + if ev == nil { + break + } firstHalf = append(firstHalf, ev) pc := 0 - for _, e := range firstHalf { if e.EventType == "progress" { pc++ } } - if pc >= 50 { break } + for _, e := range firstHalf { + if e.EventType == "progress" { + pc++ + } + } + if pc >= 50 { + break + } } s1.Close() @@ -37,7 +45,9 @@ func Test_event_stream_resumption(t *testing.T) { secondHalf := []*inv.InvocationEvent{} for { ev := s2.Next(context.Background()) - if ev == nil { break } + if ev == nil { + break + } secondHalf = append(secondHalf, ev) } h.Wait(context.Background()) @@ -45,19 +55,31 @@ func Test_event_stream_resumption(t *testing.T) { seen := map[uint64]bool{} var prev int64 = -1 for _, ev := range append(firstHalf, secondHalf...) { - if int64(ev.Sequence) <= prev { t.Fatalf("non-monotonic: %d <= %d", ev.Sequence, prev) } + if int64(ev.Sequence) <= prev { + t.Fatalf("non-monotonic: %d <= %d", ev.Sequence, prev) + } prev = int64(ev.Sequence) - if seen[ev.Sequence] { t.Fatalf("duplicate seq %d", ev.Sequence) } + if seen[ev.Sequence] { + t.Fatalf("duplicate seq %d", ev.Sequence) + } seen[ev.Sequence] = true } pc := 0 for seq := range seen { for _, ev := range firstHalf { - if ev.Sequence == seq && ev.EventType == "progress" { pc++; break } + if ev.Sequence == seq && ev.EventType == "progress" { + pc++ + break + } } for _, ev := range secondHalf { - if ev.Sequence == seq && ev.EventType == "progress" { pc++; break } + if ev.Sequence == seq && ev.EventType == "progress" { + pc++ + break + } } } - if pc != 100 { t.Fatalf("progress count=%d", pc) } + if pc != 100 { + t.Fatalf("progress count=%d", pc) + } } diff --git a/sdk/go/tests/industrial/event_stream_sequence_monotonic_test.go b/sdk/go/tests/industrial/event_stream_sequence_monotonic_test.go index 981281f4..ef529a7a 100644 --- a/sdk/go/tests/industrial/event_stream_sequence_monotonic_test.go +++ b/sdk/go/tests/industrial/event_stream_sequence_monotonic_test.go @@ -12,15 +12,21 @@ import ( func Test_event_stream_sequence_monotonic(t *testing.T) { rt := inv.NewLocalRuntime() rt.RegisterAbility("tricky", func(ctx context.Context, ac *inv.AbilityContext) ([]byte, *inv.AxonError) { - for i := 0; i < 20; i++ { _ = ac.EmitProgress([]byte{byte('a')}, "") } + for i := 0; i < 20; i++ { + _ = ac.EmitProgress([]byte{byte('a')}, "") + } time.Sleep(10 * time.Millisecond) - for i := 0; i < 20; i++ { _ = ac.EmitProgress([]byte{byte('b')}, "") } + for i := 0; i < 20; i++ { + _ = ac.EmitProgress([]byte{byte('b')}, "") + } return []byte("ok"), nil }) h, _ := rt.InvokeAsync(context.Background(), "tricky", nil, "", nil) h.Wait(context.Background()) events := rt.CoreOf(h.InvocationID()).SnapshotEvents() for i, ev := range events { - if ev.Sequence != uint64(i) { t.Fatalf("seq[%d]=%d", i, ev.Sequence) } + if ev.Sequence != uint64(i) { + t.Fatalf("seq[%d]=%d", i, ev.Sequence) + } } } diff --git a/sdk/go/tests/industrial/invocation_parent_child_cancel_propagation_test.go b/sdk/go/tests/industrial/invocation_parent_child_cancel_propagation_test.go index 3e68c638..ae24dd66 100644 --- a/sdk/go/tests/industrial/invocation_parent_child_cancel_propagation_test.go +++ b/sdk/go/tests/industrial/invocation_parent_child_cancel_propagation_test.go @@ -27,17 +27,29 @@ func Test_invocation_parent_child_cancel_propagation(t *testing.T) { h, _ := rt.InvokeAsync(context.Background(), "root", nil, "", nil) deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { - if len(rt.ChildrenOf(h.InvocationID())) == 5 { break } + if len(rt.ChildrenOf(h.InvocationID())) == 5 { + break + } time.Sleep(20 * time.Millisecond) } - if len(rt.ChildrenOf(h.InvocationID())) != 5 { t.Fatal("children did not spawn") } + if len(rt.ChildrenOf(h.InvocationID())) != 5 { + t.Fatal("children did not spawn") + } t0 := time.Now() - if e := rt.Cancel(context.Background(), h.InvocationID(), "probe"); e != nil { t.Fatal(e) } + if e := rt.Cancel(context.Background(), h.InvocationID(), "probe"); e != nil { + t.Fatal(e) + } elapsed := time.Since(t0) for _, id := range rt.ChildrenOf(h.InvocationID()) { c := rt.CoreOf(id) - if !c.IsTerminal() { t.Fatalf("child %s not terminal", id) } - if c.CurrentState() != inv.StateCancelled { t.Fatalf("child %s state=%s", id, c.CurrentState()) } + if !c.IsTerminal() { + t.Fatalf("child %s not terminal", id) + } + if c.CurrentState() != inv.StateCancelled { + t.Fatalf("child %s state=%s", id, c.CurrentState()) + } + } + if elapsed > 500*time.Millisecond { + t.Fatalf("propagation too slow: %s", elapsed) } - if elapsed > 500*time.Millisecond { t.Fatalf("propagation too slow: %s", elapsed) } } diff --git a/sdk/go/tests/industrial/invocation_terminal_monotonicity_test.go b/sdk/go/tests/industrial/invocation_terminal_monotonicity_test.go index 4ef1b094..d4148da4 100644 --- a/sdk/go/tests/industrial/invocation_terminal_monotonicity_test.go +++ b/sdk/go/tests/industrial/invocation_terminal_monotonicity_test.go @@ -15,11 +15,19 @@ func Test_invocation_terminal_monotonicity(t *testing.T) { }) h, _ := rt.InvokeAsync(context.Background(), "once", nil, "", nil) state := h.Wait(context.Background()) - if state != inv.StateCompleted { t.Fatalf("state=%s", state) } - if !h.IsTerminal() { t.Fatal("not terminal") } + if state != inv.StateCompleted { + t.Fatalf("state=%s", state) + } + if !h.IsTerminal() { + t.Fatal("not terminal") + } - if err := h.Cancel("post_terminal"); err != nil { t.Fatal(err) } - if h.CurrentState() != inv.StateCompleted { t.Fatal("state mutated") } + if err := h.Cancel("post_terminal"); err != nil { + t.Fatal(err) + } + if h.CurrentState() != inv.StateCompleted { + t.Fatal("state mutated") + } _, err := h.Send([]byte("ignored"), "") if err == nil || err.Kind != inv.KindInvalidArgument || err.Reason != "invocation_terminal" { diff --git a/sdk/go/tests/industrial/message_inbox_bounded_test.go b/sdk/go/tests/industrial/message_inbox_bounded_test.go index 561e6961..12720e53 100644 --- a/sdk/go/tests/industrial/message_inbox_bounded_test.go +++ b/sdk/go/tests/industrial/message_inbox_bounded_test.go @@ -10,9 +10,17 @@ import ( func Test_message_inbox_bounded(t *testing.T) { inbox := inv.NewMessageInbox("inv_bounded", 2) - if _, e := inbox.Deliver(context.Background(), []byte("a"), "", ""); e != nil { t.Fatal(e) } - if _, e := inbox.Deliver(context.Background(), []byte("b"), "", ""); e != nil { t.Fatal(e) } + if _, e := inbox.Deliver(context.Background(), []byte("a"), "", ""); e != nil { + t.Fatal(e) + } + if _, e := inbox.Deliver(context.Background(), []byte("b"), "", ""); e != nil { + t.Fatal(e) + } _, e := inbox.Deliver(context.Background(), []byte("c"), "", "") - if e == nil || e.Kind != inv.KindResourceExhausted { t.Fatalf("expected resource_exhausted, got %v", e) } - if e.RetryAfterMs <= 0 { t.Fatal("retry_after_ms not set") } + if e == nil || e.Kind != inv.KindResourceExhausted { + t.Fatalf("expected resource_exhausted, got %v", e) + } + if e.RetryAfterMs <= 0 { + t.Fatal("retry_after_ms not set") + } } diff --git a/sdk/go/tests/industrial/message_inbox_fifo_test.go b/sdk/go/tests/industrial/message_inbox_fifo_test.go index 92551841..5a4928f6 100644 --- a/sdk/go/tests/industrial/message_inbox_fifo_test.go +++ b/sdk/go/tests/industrial/message_inbox_fifo_test.go @@ -16,7 +16,9 @@ func Test_message_inbox_fifo(t *testing.T) { observed := make([]int64, 0, 100) for i := 0; i < 100; i++ { msg := ac.RecvMessage(ctx, 5*time.Second) - if msg == nil { return nil, inv.ErrInternal("timeout") } + if msg == nil { + return nil, inv.ErrInternal("timeout") + } var body map[string]int64 _ = json.Unmarshal(msg.Payload, &body) observed = append(observed, body["seq"]) @@ -35,12 +37,19 @@ func Test_message_inbox_fifo(t *testing.T) { events := rt.CoreOf(h.InvocationID()).SnapshotEvents() var completed *inv.InvocationEvent for i := len(events) - 1; i >= 0; i-- { - if events[i].EventType == "completed" { completed = events[i]; break } + if events[i].EventType == "completed" { + completed = events[i] + break + } + } + if completed == nil { + t.Fatal("no completed event") } - if completed == nil { t.Fatal("no completed event") } var got []int64 _ = json.Unmarshal(completed.Payload, &got) for i, v := range got { - if v != int64(i) { t.Fatalf("FIFO breach at %d: got %d", i, v) } + if v != int64(i) { + t.Fatalf("FIFO breach at %d: got %d", i, v) + } } } diff --git a/sdk/go/tests/industrial/message_inbox_idempotent_test.go b/sdk/go/tests/industrial/message_inbox_idempotent_test.go index 51db8492..1eb47e5a 100644 --- a/sdk/go/tests/industrial/message_inbox_idempotent_test.go +++ b/sdk/go/tests/industrial/message_inbox_idempotent_test.go @@ -16,16 +16,26 @@ func Test_message_inbox_idempotent(t *testing.T) { rt.RegisterAbility("counter", func(ctx context.Context, ac *inv.AbilityContext) ([]byte, *inv.AxonError) { for { m := ac.RecvMessage(ctx, 500*time.Millisecond) - if m == nil { return []byte("done"), nil } + if m == nil { + return []byte("done"), nil + } count.Add(1) } }) h, _ := rt.InvokeAsync(context.Background(), "counter", nil, "", nil) a1, _ := rt.SendMessage(context.Background(), h.InvocationID(), []byte("x"), "dup-42") a2, _ := rt.SendMessage(context.Background(), h.InvocationID(), []byte("x"), "dup-42") - if a1.Deduplicated { t.Fatal("first delivery must not be dedup") } - if !a2.Deduplicated { t.Fatal("second delivery must be dedup") } - if a1.AcceptedSequence != a2.AcceptedSequence { t.Fatal("seq mismatch") } + if a1.Deduplicated { + t.Fatal("first delivery must not be dedup") + } + if !a2.Deduplicated { + t.Fatal("second delivery must be dedup") + } + if a1.AcceptedSequence != a2.AcceptedSequence { + t.Fatal("seq mismatch") + } h.Wait(context.Background()) - if count.Load() != 1 { t.Fatalf("expected 1 delivery, got %d", count.Load()) } + if count.Load() != 1 { + t.Fatalf("expected 1 delivery, got %d", count.Load()) + } } diff --git a/sdk/go/tests/industrial/supervisor_cleanup_before_receipt_test.go b/sdk/go/tests/industrial/supervisor_cleanup_before_receipt_test.go index a8cb38de..9e7e35ba 100644 --- a/sdk/go/tests/industrial/supervisor_cleanup_before_receipt_test.go +++ b/sdk/go/tests/industrial/supervisor_cleanup_before_receipt_test.go @@ -26,11 +26,19 @@ func Test_supervisor_cleanup_before_receipt(t *testing.T) { spec := inv.SupervisorSpec{CancelGraceSeconds: 0.2} h, _ := rt.InvokeAsync(context.Background(), "guarded", nil, "", &spec) time.Sleep(100 * time.Millisecond) - if e := rt.Cancel(context.Background(), h.InvocationID(), "probe"); e != nil { t.Fatal(e) } + if e := rt.Cancel(context.Background(), h.InvocationID(), "probe"); e != nil { + t.Fatal(e) + } core := rt.CoreOf(h.InvocationID()) - if core.CurrentState() != inv.StateCancelled { t.Fatalf("state=%s", core.CurrentState()) } + if core.CurrentState() != inv.StateCancelled { + t.Fatalf("state=%s", core.CurrentState()) + } receipts := core.SnapshotReceipts() terminal := receipts[len(receipts)-1] - if !terminal.CleanupComplete { t.Fatal("cleanup_complete=false on terminal receipt") } - if !cleanup.Load() { t.Fatal("cleanup callback did not run") } + if !terminal.CleanupComplete { + t.Fatal("cleanup_complete=false on terminal receipt") + } + if !cleanup.Load() { + t.Fatal("cleanup callback did not run") + } } diff --git a/sdk/go/tests/industrial/supervisor_grace_period_test.go b/sdk/go/tests/industrial/supervisor_grace_period_test.go index 498a55a5..d72db10f 100644 --- a/sdk/go/tests/industrial/supervisor_grace_period_test.go +++ b/sdk/go/tests/industrial/supervisor_grace_period_test.go @@ -14,7 +14,9 @@ import ( func Test_supervisor_grace_period(t *testing.T) { sup := inv.NewSupervisor("inv_g", inv.SupervisorSpec{CancelGraceSeconds: 1.0}) _, e := sup.SpawnProcessGroup([]string{"sh", "-c", "trap 'exit 0' TERM; sleep 30"}) - if e != nil { t.Fatal(e) } + if e != nil { + t.Fatal(e) + } t0 := time.Now() sup.RunCancelFlow(context.Background()) if elapsed := time.Since(t0); elapsed > 1200*time.Millisecond { diff --git a/sdk/go/tests/industrial/supervisor_orphan_reap_test.go b/sdk/go/tests/industrial/supervisor_orphan_reap_test.go index 14c66444..b0a2ed50 100644 --- a/sdk/go/tests/industrial/supervisor_orphan_reap_test.go +++ b/sdk/go/tests/industrial/supervisor_orphan_reap_test.go @@ -22,7 +22,9 @@ func Test_supervisor_orphan_reap(t *testing.T) { spec := inv.SupervisorSpec{PersistForRecovery: true, CancelGraceSeconds: 0.2} sup := inv.NewSupervisor("inv_orphan", spec) _, e := sup.SpawnProcessGroup([]string{"sh", "-c", "sleep 60"}) - if e != nil { t.Fatal(e) } + if e != nil { + t.Fatal(e) + } pgid := sup.SpawnedPGIDs()[0] sup = nil // simulate host crash: drop the supervisor @@ -32,9 +34,13 @@ func Test_supervisor_orphan_reap(t *testing.T) { for _, rec := range reaped { if arr, ok := rec["pgids"].([]any); ok { for _, v := range arr { - if f, ok := v.(float64); ok && int(f) == pgid { found = true } + if f, ok := v.(float64); ok && int(f) == pgid { + found = true + } } } } - if !found { t.Fatalf("orphan pgid %d not reaped (got %v)", pgid, reaped) } + if !found { + t.Fatalf("orphan pgid %d not reaped (got %v)", pgid, reaped) + } } diff --git a/sdk/go/tests/industrial/supervisor_process_group_test.go b/sdk/go/tests/industrial/supervisor_process_group_test.go index b6269080..40fd768a 100644 --- a/sdk/go/tests/industrial/supervisor_process_group_test.go +++ b/sdk/go/tests/industrial/supervisor_process_group_test.go @@ -14,8 +14,12 @@ import ( func Test_supervisor_process_group(t *testing.T) { sup := inv.NewSupervisor("inv_test", inv.SupervisorSpec{CancelGraceSeconds: 0.5}) h, e := sup.SpawnProcessGroup([]string{"sh", "-c", "sleep 30 & sleep 30 & wait"}) - if e != nil { t.Fatal(e) } - if h.Pgid == syscall.Getpgrp() { t.Fatal("setsid failed") } + if e != nil { + t.Fatal(e) + } + if h.Pgid == syscall.Getpgrp() { + t.Fatal("setsid failed") + } _ = syscall.Kill(-h.Pgid, syscall.SIGTERM) // Use Wait — it reaps the zombie, unlike signal-0 which can return // EPERM on macOS after the process has exited. diff --git a/sdk/go/tests/industrial/supervisor_resource_limit_test.go b/sdk/go/tests/industrial/supervisor_resource_limit_test.go index 8d5df051..1c5ab027 100644 --- a/sdk/go/tests/industrial/supervisor_resource_limit_test.go +++ b/sdk/go/tests/industrial/supervisor_resource_limit_test.go @@ -18,7 +18,9 @@ func Test_supervisor_resource_limit(t *testing.T) { _, e1 := sup.SpawnProcessGroup([]string{"sh", "-c", "sleep 0.5"}) _, e2 := sup.SpawnProcessGroup([]string{"sh", "-c", "sleep 0.5"}) _, e3 := sup.SpawnProcessGroup([]string{"sh", "-c", "sleep 0.5"}) - if e1 != nil || e2 != nil { t.Fatal("first two must succeed") } + if e1 != nil || e2 != nil { + t.Fatal("first two must succeed") + } if e3 == nil || e3.Kind != inv.KindResourceExhausted { t.Fatalf("third must be rex, got %v", e3) } diff --git a/sdk/java/src/main/java/run/easynet/axon/Ability.java b/sdk/java/src/main/java/run/easynet/axon/Ability.java index 8ec93297..c988e744 100644 --- a/sdk/java/src/main/java/run/easynet/axon/Ability.java +++ b/sdk/java/src/main/java/run/easynet/axon/Ability.java @@ -37,15 +37,15 @@ public interface Handler { private static final ConcurrentHashMap REGISTRY = new ConcurrentHashMap<>(); - private final String resourceUri; + private final String resourceUra; private Handler handler; - private Ability(String resourceUri) { - this.resourceUri = resourceUri; + private Ability(String resourceUra) { + this.resourceUra = resourceUra; } - public static Ability named(String resourceUri) { - return new Ability(resourceUri); + public static Ability named(String resourceUra) { + return new Ability(resourceUra); } public Ability handle(Handler handler) { @@ -55,7 +55,7 @@ public Ability handle(Handler handler) { public void expose(String agentId) { if (handler != null) { - REGISTRY.put(resourceUri, handler); + REGISTRY.put(resourceUra, handler); } } } diff --git a/sdk/java/src/main/java/run/easynet/axon/AbilityLifecycle.java b/sdk/java/src/main/java/run/easynet/axon/AbilityLifecycle.java index 502b8c6d..1c91fbf1 100644 --- a/sdk/java/src/main/java/run/easynet/axon/AbilityLifecycle.java +++ b/sdk/java/src/main/java/run/easynet/axon/AbilityLifecycle.java @@ -6,7 +6,7 @@ // // Protocol Responsibility: // - Defines typed ability descriptors, export targets, and deployment helpers exposed to SDK users. -// - Keeps cross-language ability naming, resource-uri, and tool-spec semantics aligned. +// - Keeps cross-language ability naming, resource-ura, and tool-spec semantics aligned. // // Implementation Approach: // - Separates pure descriptor/export helpers from bridge-backed deployment and invocation flows. @@ -89,7 +89,7 @@ public static final class AbilityDescriptor { public final Map outputSchema; public final String version; public final List tags; - public final String resourceUri; + public final String resourceUra; // Agent extension fields public final String instructions; public final List inputExamples; @@ -111,7 +111,7 @@ public static final class AbilityDescriptor { AbilityDescriptor( String name, String toolName, String description, String commandTemplate, Map inputSchema, Map outputSchema, - String version, List tags, String resourceUri, + String version, List tags, String resourceUra, String instructions, List inputExamples, List prerequisites, Map contextBindings, String category, @@ -125,7 +125,7 @@ public static final class AbilityDescriptor { this.outputSchema = Collections.unmodifiableMap(outputSchema); this.version = version; this.tags = Collections.unmodifiableList(tags); - this.resourceUri = resourceUri; + this.resourceUra = resourceUra; this.instructions = instructions != null ? instructions : ""; this.inputExamples = Collections.unmodifiableList( inputExamples != null ? inputExamples : Collections.emptyList()); @@ -147,7 +147,7 @@ public Map toToolSpec() { Map spec = new LinkedHashMap<>(); spec.put("name", toolName); spec.put("description", description); - spec.put("resource_uri", resourceUri); + spec.put("resource_ura", resourceUra); spec.put("parameters", inputSchema); spec.put("read_only_hint", readOnly); spec.put("destructive_hint", destructive); @@ -210,7 +210,7 @@ public static final class ForgetAllFailure { public static AbilityDescriptor buildAbilityDescriptor( String name, String description, String commandTemplate, Map inputSchema, Map outputSchema, - String version, List tags, String resourceUri) { + String version, List tags, String resourceUra) { if (name == null || name.trim().isEmpty()) throw new AxonConfigException("ability name cannot be empty"); if (commandTemplate == null || commandTemplate.trim().isEmpty()) @@ -225,12 +225,12 @@ public static AbilityDescriptor buildAbilityDescriptor( version = "1.0.0"; if (tags == null) tags = Collections.emptyList(); - if (resourceUri == null || resourceUri.isEmpty()) - resourceUri = "easynet:///r/org/" + token; + if (resourceUra == null || resourceUra.isEmpty()) + resourceUra = "easynet:///r/org/" + token; return new AbilityDescriptor( name, token, description, commandTemplate, - inputSchema, outputSchema, version, tags, resourceUri, + inputSchema, outputSchema, version, tags, resourceUra, "", Collections.emptyList(), Collections.emptyList(), Collections.emptyMap(), "", /* readOnly */ false, /* destructive */ true, @@ -248,7 +248,7 @@ public static AbilityExportResult exportAbility( String token = descriptor.toolName; if (axonEndpoint == null || axonEndpoint.isEmpty()) axonEndpoint = "http://127.0.0.1:" + DEFAULT_AXON_PORT; - String invokeScript = generateInvokeScript(descriptor.resourceUri, axonEndpoint); + String invokeScript = generateInvokeScript(descriptor.resourceUra, axonEndpoint); String abilityMd = generateAbilityMd(descriptor, target, token); return new AbilityExportResult(abilityMd, invokeScript, token); } @@ -371,7 +371,7 @@ public static class DeployException extends AxonInvocationException { // invocation (`invokeAbility`) plus their `executeCommand` / `forgetAll` / // `listRemoteTools` companions were removed by RFC-001 §A1 — the // directory is now federation-scoped (`federation.resolve`) and - // invocation is target-typed (`Invoke(callee=, ability=...)`) + // invocation is target-typed (`Invoke(callee=, ability=...)`) // rather than node-id + tool-name. Use `bridge.federationResolve(...)` // and `bridge.invokeAbilityRaw(...)` directly. @@ -764,18 +764,18 @@ private static String sanitizeShellValue(String value, String label) { return value; } - private static String generateInvokeScript(String resourceUri, String endpoint) { + private static String generateInvokeScript(String resourceUra, String endpoint) { String safeEndpoint = sanitizeShellValue(endpoint, "endpoint"); - String safeUri = sanitizeShellValue(resourceUri, "resource_uri"); + String safeUra = sanitizeShellValue(resourceUra, "resource_ura"); return "#!/usr/bin/env bash\n" + "set -euo pipefail\n" + "AXON_ENDPOINT=\"${AXON_ENDPOINT:-" + safeEndpoint + "}\"\n" + "TENANT=\"${AXON_TENANT:-default}\"\n" - + "RESOURCE_URI=\"" + safeUri + "\"\n" + + "RESOURCE_URA=\"" + safeUra + "\"\n" + "ARGS=\"${1:-{}}\"\n" + "curl -sS -X POST \"${AXON_ENDPOINT}/v1/invoke\" \\\n" + " -H \"Content-Type: application/json\" \\\n" - + " -d \"{\\\"tenant_id\\\":\\\"${TENANT}\\\",\\\"resource_uri\\\":\\\"${RESOURCE_URI}\\\",\\\"payload\\\":${ARGS}}\"\n"; + + " -d \"{\\\"tenant_id\\\":\\\"${TENANT}\\\",\\\"resource_ura\\\":\\\"${RESOURCE_URA}\\\",\\\"payload\\\":${ARGS}}\"\n"; } @SuppressWarnings("unchecked") @@ -884,7 +884,7 @@ private static String generateAbilityMd(AbilityDescriptor descriptor, AbilityTar b.append("${").append(skillDirVar).append("}/scripts/invoke.sh '{\"param\": \"value\"}'\n"); b.append("```\n\n"); b.append("## Axon Resource\n\n"); - b.append("- **URI**: `").append(descriptor.resourceUri).append("`\n"); + b.append("- **URA**: `").append(descriptor.resourceUra).append("`\n"); b.append("- **Version**: ").append(descriptor.version).append('\n'); // Category @@ -899,7 +899,7 @@ private static void appendMetadata(StringBuilder b, AbilityDescriptor descriptor b.append("metadata:\n"); b.append(" author: easynet-axon\n"); b.append(" version: \"").append(descriptor.version).append("\"\n"); - b.append(" axon-resource-uri: \"").append(descriptor.resourceUri).append("\"\n"); + b.append(" axon-resource-ura: \"").append(descriptor.resourceUra).append("\"\n"); } private static String shellSingleQuote(String raw) { diff --git a/sdk/java/src/main/java/run/easynet/axon/AbilityToolAdapter.java b/sdk/java/src/main/java/run/easynet/axon/AbilityToolAdapter.java index f7547803..18cb8c7f 100644 --- a/sdk/java/src/main/java/run/easynet/axon/AbilityToolAdapter.java +++ b/sdk/java/src/main/java/run/easynet/axon/AbilityToolAdapter.java @@ -72,19 +72,19 @@ public final class AbilityToolAdapter { public static final class ToolSpec { private final String name; private final String description; - private final String resourceUri; + private final String resourceUra; private final Map parameters; - ToolSpec(String name, String description, String resourceUri, Map parameters) { + ToolSpec(String name, String description, String resourceUra, Map parameters) { this.name = name; this.description = description; - this.resourceUri = resourceUri; + this.resourceUra = resourceUra; this.parameters = parameters; } public String name() { return name; } public String description() { return description; } - public String resourceUri() { return resourceUri; } + public String resourceUra() { return resourceUra; } public Map parameters() { return parameters; } public Map toOpenAI() { @@ -119,7 +119,7 @@ public Map toDict() { Map tool = new LinkedHashMap<>(); tool.put("name", name); tool.put("description", description); - tool.put("resource_uri", resourceUri); + tool.put("resource_ura", resourceUra); tool.put("parameters", parameters); return tool; } @@ -129,7 +129,7 @@ public Map toDict() { public static final class Options { private String description = ""; - private String resourceUri; + private String resourceUra; private Map parameters; private Options() {} @@ -139,8 +139,8 @@ public Options description(String description) { return this; } - public Options resourceUri(String resourceUri) { - this.resourceUri = resourceUri; + public Options resourceUra(String resourceUra) { + this.resourceUra = resourceUra; return this; } @@ -196,7 +196,7 @@ public AbilityToolAdapter register( Function, Map> handler, Options opts) { if (opts == null) opts = new Options(); - String uri = opts.resourceUri != null ? opts.resourceUri : "easynet:///r/org/" + name; + String uri = opts.resourceUra != null ? opts.resourceUra : "easynet:///r/org/" + name; Map params = opts.parameters != null ? opts.parameters : defaultParameters(); @@ -214,12 +214,12 @@ public AbilityToolAdapter register( /** * Register a remote ability as a tool (no local handler). */ - public AbilityToolAdapter registerAbility(String name, String resourceUri, Options opts) { + public AbilityToolAdapter registerAbility(String name, String resourceUra, Options opts) { if (opts == null) opts = new Options(); Map params = opts.parameters != null ? opts.parameters : defaultParameters(); - ToolSpec spec = new ToolSpec(name, opts.description, resourceUri, params); + ToolSpec spec = new ToolSpec(name, opts.description, resourceUra, params); rwLock.writeLock().lock(); try { specs.put(name, spec); @@ -322,9 +322,9 @@ public Map execute(String name, Map arguments) { throw new IllegalStateException("no transport configured for remote ability calls"); } if (principalId != null && !principalId.isBlank()) { - return transport.call(tenantId, spec.resourceUri, arguments, principalId); + return transport.call(tenantId, spec.resourceUra, arguments, principalId); } - return transport.call(tenantId, spec.resourceUri, arguments); + return transport.call(tenantId, spec.resourceUra, arguments); } private static Map defaultParameters() { diff --git a/sdk/java/src/main/java/run/easynet/axon/Client.java b/sdk/java/src/main/java/run/easynet/axon/Client.java index 9aff8222..4c80488c 100644 --- a/sdk/java/src/main/java/run/easynet/axon/Client.java +++ b/sdk/java/src/main/java/run/easynet/axon/Client.java @@ -31,13 +31,13 @@ public final class Client { private final Transport transport; private final String tenantId; - private final String resourceUri; + private final String resourceUra; private final String principalId; - private Client(Transport transport, String tenantId, String resourceUri, String principalId) { + private Client(Transport transport, String tenantId, String resourceUra, String principalId) { this.transport = transport; this.tenantId = tenantId; - this.resourceUri = resourceUri; + this.resourceUra = resourceUra; this.principalId = principalId; } @@ -50,38 +50,38 @@ public static Client of(Transport transport) { } public Client tenant(String tenantId) { - return new Client(this.transport, tenantId, this.resourceUri, this.principalId); + return new Client(this.transport, tenantId, this.resourceUra, this.principalId); } - public Client ability(String resourceUri) { - return new Client(this.transport, this.tenantId, resourceUri, this.principalId); + public Client ability(String resourceUra) { + return new Client(this.transport, this.tenantId, resourceUra, this.principalId); } public Client principal(String principalId) { if (principalId == null || principalId.isBlank()) { throw new IllegalArgumentException("principal(...) cannot be blank"); } - return new Client(this.transport, this.tenantId, this.resourceUri, principalId); + return new Client(this.transport, this.tenantId, this.resourceUra, principalId); } public Map call(Map payload) { if (tenantId == null || tenantId.isBlank()) { throw new IllegalStateException("tenant(...) is required before call(...)"); } - if (resourceUri == null || resourceUri.isBlank()) { + if (resourceUra == null || resourceUra.isBlank()) { throw new IllegalStateException("ability(...) is required before call(...)"); } - return transport.call(tenantId, resourceUri, payload, principalId); + return transport.call(tenantId, resourceUra, payload, principalId); } public Map callRaw(Map payload) { if (tenantId == null || tenantId.isBlank()) { throw new IllegalStateException("tenant(...) is required before callRaw(...)"); } - if (resourceUri == null || resourceUri.isBlank()) { + if (resourceUra == null || resourceUra.isBlank()) { throw new IllegalStateException("ability(...) is required before callRaw(...)"); } - return transport.callRaw(tenantId, resourceUri, payload, principalId); + return transport.callRaw(tenantId, resourceUra, payload, principalId); } public Object callAny(Map payload) { diff --git a/sdk/java/src/main/java/run/easynet/axon/DendriteBridge.java b/sdk/java/src/main/java/run/easynet/axon/DendriteBridge.java index 146fb9fa..e25ccb7c 100644 --- a/sdk/java/src/main/java/run/easynet/axon/DendriteBridge.java +++ b/sdk/java/src/main/java/run/easynet/axon/DendriteBridge.java @@ -494,23 +494,23 @@ public StreamResult bidiStreamCall( public Map invokeAbility( String tenantId, - String resourceUri, + String resourceUra, Map payload, Map metadata, int timeoutMs) { - return invokeAbility(tenantId, resourceUri, payload, null, metadata, timeoutMs); + return invokeAbility(tenantId, resourceUra, payload, null, metadata, timeoutMs); } public Map invokeAbility( String tenantId, - String resourceUri, + String resourceUra, Map payload, String subjectId, Map metadata, int timeoutMs) { return invokeAbilityRaw( tenantId, - resourceUri, + resourceUra, payload, subjectId, metadata, @@ -519,28 +519,28 @@ public Map invokeAbility( public Map invokeAbilityRaw( String tenantId, - String resourceUri, + String resourceUra, Map payload, Map metadata, int timeoutMs) { - return invokeAbilityRaw(tenantId, resourceUri, payload, null, metadata, timeoutMs); + return invokeAbilityRaw(tenantId, resourceUra, payload, null, metadata, timeoutMs); } public Map invokeAbilityRaw( String tenantId, - String resourceUri, + String resourceUra, Map payload, String subjectId, Map metadata, int timeoutMs) { ensureOpen(); Objects.requireNonNull(tenantId, "tenantId"); - Objects.requireNonNull(resourceUri, "resourceUri"); + Objects.requireNonNull(resourceUra, "resourceUra"); Objects.requireNonNull(payload, "payload"); Map req = new LinkedHashMap<>(); req.put("tenant_id", tenantId); - req.put("resource_uri", resourceUri); + req.put("resource_ura", resourceUra); req.put("payload_json", payload); if (subjectId != null && !subjectId.isBlank()) { req.put("subject_id", subjectId); diff --git a/sdk/java/src/main/java/run/easynet/axon/FederationBody.java b/sdk/java/src/main/java/run/easynet/axon/FederationBody.java index 73bed74e..233b3864 100644 --- a/sdk/java/src/main/java/run/easynet/axon/FederationBody.java +++ b/sdk/java/src/main/java/run/easynet/axon/FederationBody.java @@ -31,7 +31,7 @@ static Map advertiseAgent( String publicKeyHex, Map signingAuthority) { Map body = new LinkedHashMap<>(); - body.put("agent_uri", agentUri); + body.put("agent_ura", agentUri); if (publicKeyHex != null && !publicKeyHex.isEmpty()) { body.put("public_key_hex", publicKeyHex); } @@ -44,14 +44,14 @@ static Map advertiseAgent( static Map advertiseAbilities( String agentUri, List> abilities) { Map body = new LinkedHashMap<>(); - body.put("agent_uri", agentUri); + body.put("agent_ura", agentUri); body.put("abilities", abilities == null ? List.of() : abilities); return body; } static Map revoke(String agentUri, String reason) { Map body = new LinkedHashMap<>(); - body.put("agent_uri", agentUri); + body.put("agent_ura", agentUri); if (reason != null && !reason.isBlank()) { body.put("reason", reason); } @@ -61,7 +61,7 @@ static Map revoke(String agentUri, String reason) { static Map resolve(String agentUriPrefix, boolean includeAbilities) { Map filter = new LinkedHashMap<>(); if (agentUriPrefix != null && !agentUriPrefix.isEmpty()) { - filter.put("agent_uri_prefix", agentUriPrefix); + filter.put("agent_ura_prefix", agentUriPrefix); } if (includeAbilities) { filter.put("include_abilities", true); diff --git a/sdk/java/src/main/java/run/easynet/axon/PublishCapabilityRequest.java b/sdk/java/src/main/java/run/easynet/axon/PublishCapabilityRequest.java index 88ca6699..1fa13349 100644 --- a/sdk/java/src/main/java/run/easynet/axon/PublishCapabilityRequest.java +++ b/sdk/java/src/main/java/run/easynet/axon/PublishCapabilityRequest.java @@ -43,7 +43,7 @@ public final class PublishCapabilityRequest { private List tags; private Map requirements; private Map metadata; - private String payloadUri; + private String payloadUra; private Long payloadSizeBytes; private String packageBytesBase64; private String signatureFingerprint; @@ -59,7 +59,7 @@ public final class PublishCapabilityRequest { public PublishCapabilityRequest tags(List tags) { this.tags = tags; return this; } public PublishCapabilityRequest requirements(Map requirements) { this.requirements = requirements; return this; } public PublishCapabilityRequest metadata(Map metadata) { this.metadata = metadata; return this; } - public PublishCapabilityRequest payloadUri(String payloadUri) { this.payloadUri = payloadUri; return this; } + public PublishCapabilityRequest payloadUra(String payloadUra) { this.payloadUra = payloadUra; return this; } public PublishCapabilityRequest payloadSizeBytes(Long payloadSizeBytes) { this.payloadSizeBytes = payloadSizeBytes; return this; } public PublishCapabilityRequest packageBytesBase64(String packageBytesBase64) { this.packageBytesBase64 = packageBytesBase64; return this; } public PublishCapabilityRequest signatureFingerprint(String signatureFingerprint) { this.signatureFingerprint = signatureFingerprint; return this; } @@ -73,10 +73,10 @@ public void validate() { requireNonBlank("version", version); validateDigestPrefix("digest", digest); requireNonBlank("signatureBase64", signatureBase64); - if ((payloadUri == null || payloadUri.isBlank()) + if ((payloadUra == null || payloadUra.isBlank()) && (packageBytesBase64 == null || packageBytesBase64.isBlank())) { throw new IllegalArgumentException( - "payloadUri or packageBytesBase64 is required"); + "payloadUra or packageBytesBase64 is required"); } if (payloadSizeBytes != null && payloadSizeBytes < 0L) { throw new IllegalArgumentException("payloadSizeBytes must be >= 0"); @@ -94,7 +94,7 @@ public Map toPayload() { req.put("tags", tags == null ? List.of() : tags); req.put("requirements", requirements == null ? Map.of() : requirements); req.put("metadata", metadata == null ? Map.of() : metadata); - putOptionalNonBlank(req, "payload_uri", payloadUri); + putOptionalNonBlank(req, "payload_ura", payloadUra); putOptionalPayloadSize(req, "payload_size_bytes", payloadSizeBytes); putOptionalNonBlank(req, "package_bytes_base64", packageBytesBase64); putOptionalNonBlank(req, "signature_fingerprint", signatureFingerprint); diff --git a/sdk/java/src/main/java/run/easynet/axon/SemanticBridge.java b/sdk/java/src/main/java/run/easynet/axon/SemanticBridge.java index 929ee299..99f59855 100644 --- a/sdk/java/src/main/java/run/easynet/axon/SemanticBridge.java +++ b/sdk/java/src/main/java/run/easynet/axon/SemanticBridge.java @@ -79,8 +79,8 @@ public TenantScope tenant(String tenantId) { return new TenantScope(this, tenantId); } - public AbilityCall ability(String tenantId, String resourceUri) { - return new AbilityCall(this, tenantId, resourceUri); + public AbilityCall ability(String tenantId, String resourceUra) { + return new AbilityCall(this, tenantId, resourceUra); } public DendriteBridge bridge() { @@ -295,15 +295,15 @@ private static List decodeChunks(Object raw) { public static final class AbilityCall { private final SemanticBridge semantic; private final String tenantId; - private final String resourceUri; + private final String resourceUra; private Map payloadJson = new LinkedHashMap<>(); private Map metadata = new LinkedHashMap<>(); private int timeoutMs = 30000; - private AbilityCall(SemanticBridge semantic, String tenantId, String resourceUri) { + private AbilityCall(SemanticBridge semantic, String tenantId, String resourceUra) { this.semantic = semantic; this.tenantId = Objects.requireNonNull(tenantId, "tenantId"); - this.resourceUri = Objects.requireNonNull(resourceUri, "resourceUri"); + this.resourceUra = Objects.requireNonNull(resourceUra, "resourceUra"); } public AbilityCall payload(Map payloadJson) { @@ -325,12 +325,12 @@ public Map invoke() { if (tenantId.isBlank()) { throw new DendriteBridge.DendriteBridgeException("tenantId is required"); } - if (resourceUri.isBlank()) { - throw new DendriteBridge.DendriteBridgeException("resourceUri is required"); + if (resourceUra.isBlank()) { + throw new DendriteBridge.DendriteBridgeException("resourceUra is required"); } return semantic.bridge.invokeAbility( tenantId, - resourceUri, + resourceUra, payloadJson, metadata, timeoutMs); @@ -354,8 +354,8 @@ public List> listNodes(String ownerId) { return semantic.bridge.listNodes(tenantId, ownerId == null ? "" : ownerId); } - public AbilityCall ability(String resourceUri) { - return new AbilityCall(semantic, tenantId, resourceUri); + public AbilityCall ability(String resourceUra) { + return new AbilityCall(semantic, tenantId, resourceUra); } public NodeScope node(String nodeId) { @@ -374,7 +374,7 @@ private NodeScope(TenantScope tenant, String nodeId) { // The legacy MCP catalog/call/deploy/update verbs were removed by // RFC-001 §A1; their replacements are ordinary Invoke calls against - // the mcp-bridge Agent. Use {@code ability(resourceUri).call(...)} + // the mcp-bridge Agent. Use {@code ability(resourceUra).call(...)} // on the parent {@link TenantScope} instead. public Map uninstallCapability(String installId) { diff --git a/sdk/java/src/main/java/run/easynet/axon/SidecarTransport.java b/sdk/java/src/main/java/run/easynet/axon/SidecarTransport.java index 6134b825..997548a6 100644 --- a/sdk/java/src/main/java/run/easynet/axon/SidecarTransport.java +++ b/sdk/java/src/main/java/run/easynet/axon/SidecarTransport.java @@ -66,11 +66,11 @@ private synchronized DendriteBridge ensureBridge() { return bridge; } - private static String subjectVisibilityFromResourceUri(String resourceUri) { - if (resourceUri == null) { + private static String subjectVisibilityFromResourceUra(String resourceUra) { + if (resourceUra == null) { return "org"; } - String normalized = resourceUri.trim().toLowerCase(); + String normalized = resourceUra.trim().toLowerCase(); if (normalized.startsWith("easynet:///r/pub/")) { return "pub"; } @@ -80,7 +80,7 @@ private static String subjectVisibilityFromResourceUri(String resourceUri) { return "org"; } - private static String principalToSubjectId(String principalId, String resourceUri) { + private static String principalToSubjectId(String principalId, String resourceUra) { if (principalId == null) { return null; } @@ -91,7 +91,7 @@ private static String principalToSubjectId(String principalId, String resourceUr if (normalized.startsWith("easynet:")) { return normalized; } - return "easynet:" + subjectVisibilityFromResourceUri(resourceUri) + ":reg:agent." + normalized; + return "easynet:" + subjectVisibilityFromResourceUra(resourceUra) + ":reg:agent." + normalized; } public synchronized void close() { @@ -103,20 +103,20 @@ public synchronized void close() { } @Override - public Map call(String tenantId, String resourceUri, Map payload) { - return call(tenantId, resourceUri, payload, null); + public Map call(String tenantId, String resourceUra, Map payload) { + return call(tenantId, resourceUra, payload, null); } @Override public Map call( String tenantId, - String resourceUri, + String resourceUra, Map payload, String principalId) { - String subjectId = principalToSubjectId(principalId, resourceUri); + String subjectId = principalToSubjectId(principalId, resourceUra); return ensureBridge().invokeAbility( tenantId, - resourceUri, + resourceUra, payload, subjectId, Map.of(), @@ -126,13 +126,13 @@ public Map call( @Override public Map callRaw( String tenantId, - String resourceUri, + String resourceUra, Map payload, String principalId) { - String subjectId = principalToSubjectId(principalId, resourceUri); + String subjectId = principalToSubjectId(principalId, resourceUra); return ensureBridge().invokeAbilityRaw( tenantId, - resourceUri, + resourceUra, payload, subjectId, Map.of(), diff --git a/sdk/java/src/main/java/run/easynet/axon/Transport.java b/sdk/java/src/main/java/run/easynet/axon/Transport.java index c08f1a76..5f8c9f16 100644 --- a/sdk/java/src/main/java/run/easynet/axon/Transport.java +++ b/sdk/java/src/main/java/run/easynet/axon/Transport.java @@ -30,33 +30,33 @@ import java.util.Map; public interface Transport { - Map call(String tenantId, String resourceUri, Map payload); + Map call(String tenantId, String resourceUra, Map payload); default Map call( String tenantId, - String resourceUri, + String resourceUra, Map payload, String principalId) { if (principalId != null && !principalId.isBlank()) { throw new UnsupportedOperationException( "configured transport does not support principal(...) context"); } - return call(tenantId, resourceUri, payload); + return call(tenantId, resourceUra, payload); } default Map callRaw( String tenantId, - String resourceUri, + String resourceUra, Map payload) { - return callRaw(tenantId, resourceUri, payload, null); + return callRaw(tenantId, resourceUra, payload, null); } default Map callRaw( String tenantId, - String resourceUri, + String resourceUra, Map payload, String principalId) { - Map result = call(tenantId, resourceUri, payload, principalId); + Map result = call(tenantId, resourceUra, payload, principalId); if (result.containsKey("result_json")) { return result; } diff --git a/sdk/java/src/main/java/run/easynet/axon/invocation/Admission.java b/sdk/java/src/main/java/run/easynet/axon/invocation/Admission.java index da715ec4..402b1fdb 100644 --- a/sdk/java/src/main/java/run/easynet/axon/invocation/Admission.java +++ b/sdk/java/src/main/java/run/easynet/axon/invocation/Admission.java @@ -23,7 +23,7 @@ * being installed (Federated/Trusted mode). Without a resolver, * runs in Local-fast mode where identity is self-asserted. *
  • {@link NonceReplayStore#checkAndRecord} — always on. Dedup key - * is {@code (caller.uri, ability, invocation_nonce)}; ability + * is {@code (caller.ura, ability, invocation_nonce)}; ability * guards against cross-ability false-positives per review.
  • * * @@ -73,8 +73,8 @@ private static AxonError rejectEnvelope(String detail) { *

    Checks applied (RFC 001 §5.2 step 1, strengthened per review): *

      *
    • {@code ability} non-empty
    • - *
    • {@code caller.uri} / {@code callee.uri} / - * {@code subject.uri} non-empty
    • + *
    • {@code caller.ura} / {@code callee.ura} / + * {@code subject.ura} non-empty
    • *
    • {@code invocationNonce} is not the all-zero sentinel (a * CSPRNG-generated nonce being all-zero has probability ≈ * 2⁻¹²⁸; we reject as a probable uninitialised-field @@ -86,14 +86,14 @@ public static void validateEnvelope(Axiom.InvocationEnvelope env) { if (env.ability == null || env.ability.isEmpty()) { throw rejectEnvelope("ability_empty"); } - if (env.caller == null || env.caller.uri == null || env.caller.uri.isEmpty()) { - throw rejectEnvelope("caller_uri_empty"); + if (env.caller == null || env.caller.ura == null || env.caller.ura.isEmpty()) { + throw rejectEnvelope("caller_ura_empty"); } - if (env.callee == null || env.callee.uri == null || env.callee.uri.isEmpty()) { - throw rejectEnvelope("callee_uri_empty"); + if (env.callee == null || env.callee.ura == null || env.callee.ura.isEmpty()) { + throw rejectEnvelope("callee_ura_empty"); } - if (env.subject == null || env.subject.uri == null || env.subject.uri.isEmpty()) { - throw rejectEnvelope("subject_uri_empty"); + if (env.subject == null || env.subject.ura == null || env.subject.ura.isEmpty()) { + throw rejectEnvelope("subject_ura_empty"); } if (env.argsDigest == null || env.argsDigest.length != 32) { throw rejectEnvelope("args_digest_wrong_length"); @@ -195,7 +195,7 @@ public static void verifySignature( * production runtime's durability contract is wired up. */ public static final class NonceReplayStore { - /** Key: (caller.uri, ability, 16-byte nonce) — per review feedback. */ + /** Key: (caller.ura, ability, 16-byte nonce) — per review feedback. */ private static final class Key { final String caller; final String ability; @@ -230,7 +230,7 @@ public static NonceReplayStore withWindowMs(long windowMs) { } /** - * Register a {@code (caller.uri, ability, nonce)} observation + * Register a {@code (caller.ura, ability, nonce)} observation * as of {@code nowMs}. Throws with * {@link #REASON_NONCE_REPLAY} on collision inside the * current window. Out-of-window entries are pruned before @@ -241,7 +241,7 @@ public static NonceReplayStore withWindowMs(long windowMs) { * store. */ public synchronized void checkAndRecord( - String callerUri, + String callerUra, String ability, byte[] nonce, long nowMs @@ -253,7 +253,7 @@ public synchronized void checkAndRecord( if (it.next().getValue() < cutoff) it.remove(); } - Key k = new Key(callerUri, ability, nonce); + Key k = new Key(callerUra, ability, nonce); Long prev = seen.get(k); if (prev != null && prev >= cutoff) { throw new AxonError( @@ -297,7 +297,7 @@ public static void runAdmission( if (resolver != null) { verifySignature(env, sig, resolver); } - replay.checkAndRecord(env.caller.uri, env.ability, env.invocationNonce, nowMs); + replay.checkAndRecord(env.caller.ura, env.ability, env.invocationNonce, nowMs); } /** Wall-clock helper (ms). Centralised so tests can substitute it. */ diff --git a/sdk/java/src/main/java/run/easynet/axon/invocation/Axiom.java b/sdk/java/src/main/java/run/easynet/axon/invocation/Axiom.java index 0e929fd2..285665a9 100644 --- a/sdk/java/src/main/java/run/easynet/axon/invocation/Axiom.java +++ b/sdk/java/src/main/java/run/easynet/axon/invocation/Axiom.java @@ -38,52 +38,52 @@ private Axiom() {} // ── Types ──────────────────────────────────────────────────────── - public enum UriProfile { + public enum UraProfile { EASYNET_STRICT_V2("easynet-strict-v2"), WEB_SAFE_V2("web-safe-v2"); private final String s; - UriProfile(String s) { this.s = s; } + UraProfile(String s) { this.s = s; } public String asString() { return s; } - public static UriProfile parse(String s) { - for (UriProfile p : values()) { + public static UraProfile parse(String s) { + for (UraProfile p : values()) { if (p.s.equals(s)) return p; } - throw new IllegalArgumentException("unknown_uri_profile:" + s); + throw new IllegalArgumentException("unknown_ura_profile:" + s); } } public static final class AgentIdentity { - public final String uri; - public final UriProfile profile; - public AgentIdentity(String uri, UriProfile profile) { - this.uri = Objects.requireNonNull(uri); + public final String ura; + public final UraProfile profile; + public AgentIdentity(String ura, UraProfile profile) { + this.ura = Objects.requireNonNull(ura); this.profile = Objects.requireNonNull(profile); } } public static final class SubjectIdentity { - public final String uri; - public final UriProfile profile; - public SubjectIdentity(String uri, UriProfile profile) { - this.uri = Objects.requireNonNull(uri); + public final String ura; + public final UraProfile profile; + public SubjectIdentity(String ura, UraProfile profile) { + this.ura = Objects.requireNonNull(ura); this.profile = Objects.requireNonNull(profile); } public static SubjectIdentity fromCallee(AgentIdentity callee) { - return new SubjectIdentity(callee.uri, callee.profile); + return new SubjectIdentity(callee.ura, callee.profile); } } public static final class ReceiptRef { public final byte[] receiptHash; // 32 bytes - public final String receiptUri; - public ReceiptRef(byte[] receiptHash, String receiptUri) { + public final String receiptUra; + public ReceiptRef(byte[] receiptHash, String receiptUra) { if (receiptHash.length != 32) { throw new IllegalArgumentException("receipt_hash_wrong_length:" + receiptHash.length); } this.receiptHash = receiptHash.clone(); - this.receiptUri = Objects.requireNonNull(receiptUri); + this.receiptUra = Objects.requireNonNull(receiptUra); } } @@ -95,14 +95,14 @@ public enum Form { NONE, SCALAR, LIST, MERKLE } public final ReceiptRef scalar; // form == SCALAR public final List prior; // form == LIST public final byte[] merkleRoot; // form == MERKLE - public final String merkleProofUri; // form == MERKLE + public final String merkleProofUra; // form == MERKLE private CausalContext(Form f, ReceiptRef s, List l, byte[] root, String proof) { this.form = f; this.scalar = s; this.prior = l; this.merkleRoot = root; - this.merkleProofUri = proof; + this.merkleProofUra = proof; } public static CausalContext none() { @@ -114,11 +114,11 @@ public static CausalContext scalar(ReceiptRef ref) { public static CausalContext list(List prior) { return new CausalContext(Form.LIST, null, List.copyOf(prior), null, null); } - public static CausalContext merkle(byte[] root, String proofUri) { + public static CausalContext merkle(byte[] root, String proofUra) { if (root.length != 32) { throw new IllegalArgumentException("merkle_root_wrong_length:" + root.length); } - return new CausalContext(Form.MERKLE, null, null, root.clone(), Objects.requireNonNull(proofUri)); + return new CausalContext(Form.MERKLE, null, null, root.clone(), Objects.requireNonNull(proofUra)); } } @@ -214,7 +214,7 @@ public CalleeSignature(String algorithm, byte[] signature, String keyIdHint) { public interface KeyResolver { /** @return raw 32-byte Ed25519 public key. */ - byte[] resolve(String agentUri); + byte[] resolve(String agentUra); } // ── Canonical encoders (byte-for-byte with Rust/Python/Go/Node) ── @@ -254,8 +254,8 @@ private static void putBytes(ByteArrayOutputStream out, byte[] b) { } } - private static void putIdentityUriProfile(ByteArrayOutputStream out, String uri, UriProfile profile) { - putStr(out, uri); + private static void putIdentityUraProfile(ByteArrayOutputStream out, String ura, UraProfile profile) { + putStr(out, ura); putStr(out, profile.asString()); } @@ -270,7 +270,7 @@ public static byte[] canonicalCausalContext(CausalContext ctx) { } catch (IOException e) { throw new AssertionError(e); } - putStr(out, ctx.scalar.receiptUri); + putStr(out, ctx.scalar.receiptUra); } case LIST -> { out.write(0x02); @@ -281,7 +281,7 @@ public static byte[] canonicalCausalContext(CausalContext ctx) { } catch (IOException e) { throw new AssertionError(e); } - putStr(out, r.receiptUri); + putStr(out, r.receiptUra); } } case MERKLE -> { @@ -291,7 +291,7 @@ public static byte[] canonicalCausalContext(CausalContext ctx) { } catch (IOException e) { throw new AssertionError(e); } - putStr(out, ctx.merkleProofUri); + putStr(out, ctx.merkleProofUra); } } return out.toByteArray(); @@ -299,9 +299,9 @@ public static byte[] canonicalCausalContext(CausalContext ctx) { public static byte[] canonicalInvocationBytes(InvocationEnvelope env) { ByteArrayOutputStream out = new ByteArrayOutputStream(); - putIdentityUriProfile(out, env.caller.uri, env.caller.profile); - putIdentityUriProfile(out, env.callee.uri, env.callee.profile); - putIdentityUriProfile(out, env.subject.uri, env.subject.profile); + putIdentityUraProfile(out, env.caller.ura, env.caller.profile); + putIdentityUraProfile(out, env.callee.ura, env.callee.profile); + putIdentityUraProfile(out, env.subject.ura, env.subject.profile); putStr(out, env.ability); try { out.write(env.argsDigest); @@ -326,9 +326,9 @@ public static byte[] canonicalReceiptBytes(ReceiptBody r) { } catch (IOException e) { throw new AssertionError(e); } - putIdentityUriProfile(out, r.callerBinding.uri, r.callerBinding.profile); - putIdentityUriProfile(out, r.calleeBinding.uri, r.calleeBinding.profile); - putIdentityUriProfile(out, r.subjectBinding.uri, r.subjectBinding.profile); + putIdentityUraProfile(out, r.callerBinding.ura, r.callerBinding.profile); + putIdentityUraProfile(out, r.calleeBinding.ura, r.calleeBinding.profile); + putIdentityUraProfile(out, r.subjectBinding.ura, r.subjectBinding.profile); try { out.write(r.invocationNonce); } catch (IOException e) { @@ -444,7 +444,7 @@ public static void verifyInvocationSignature(InvocationEnvelope env, throw new IllegalArgumentException("signature_wrong_length:expected_64_got_" + sig.signature.length); } try { - byte[] raw = resolver.resolve(env.caller.uri); + byte[] raw = resolver.resolve(env.caller.ura); PublicKey pk = ed25519PublicKeyFromRaw(raw); byte[] bytes = canonicalInvocationBytes(env); Signature v = Signature.getInstance("Ed25519"); @@ -483,7 +483,7 @@ public static void verifyReceiptSignature(ReceiptBody r, throw new IllegalArgumentException("signature_wrong_length:expected_64_got_" + sig.signature.length); } try { - byte[] raw = resolver.resolve(r.calleeBinding.uri); + byte[] raw = resolver.resolve(r.calleeBinding.ura); PublicKey pk = ed25519PublicKeyFromRaw(raw); byte[] bytes = canonicalReceiptBytes(r); Signature v = Signature.getInstance("Ed25519"); diff --git a/sdk/java/src/main/java/run/easynet/axon/invocation/Bundle.java b/sdk/java/src/main/java/run/easynet/axon/invocation/Bundle.java index c0495de1..5d561dc3 100644 --- a/sdk/java/src/main/java/run/easynet/axon/invocation/Bundle.java +++ b/sdk/java/src/main/java/run/easynet/axon/invocation/Bundle.java @@ -24,7 +24,7 @@ import run.easynet.axon.invocation.Axiom.ReceiptBody; import run.easynet.axon.invocation.Axiom.ReceiptRef; import run.easynet.axon.invocation.Axiom.SubjectIdentity; -import run.easynet.axon.invocation.Axiom.UriProfile; +import run.easynet.axon.invocation.Axiom.UraProfile; /** * Portable JSON bundle format for RFC 001 v2 receipts and invocation @@ -47,29 +47,29 @@ private Bundle() {} public static JsonObject identityFromAgent(AgentIdentity a) { JsonObject o = new JsonObject(); - o.addProperty("uri", a.uri); + o.addProperty("ura", a.ura); o.addProperty("profile", a.profile.asString()); return o; } public static JsonObject identityFromSubject(SubjectIdentity s) { JsonObject o = new JsonObject(); - o.addProperty("uri", s.uri); + o.addProperty("ura", s.ura); o.addProperty("profile", s.profile.asString()); return o; } public static AgentIdentity identityToAgent(JsonObject d) { return new AgentIdentity( - d.get("uri").getAsString(), - UriProfile.parse(d.get("profile").getAsString()) + d.get("ura").getAsString(), + UraProfile.parse(d.get("profile").getAsString()) ); } public static SubjectIdentity identityToSubject(JsonObject d) { return new SubjectIdentity( - d.get("uri").getAsString(), - UriProfile.parse(d.get("profile").getAsString()) + d.get("ura").getAsString(), + UraProfile.parse(d.get("profile").getAsString()) ); } @@ -84,7 +84,7 @@ public static JsonObject causalToJson(CausalContext c) { case SCALAR: o.addProperty("form", "scalar"); o.addProperty("receipt_hash_hex", HEX.formatHex(c.scalar.receiptHash)); - o.addProperty("receipt_uri", c.scalar.receiptUri); + o.addProperty("receipt_ura", c.scalar.receiptUra); return o; case LIST: o.addProperty("form", "list"); @@ -92,7 +92,7 @@ public static JsonObject causalToJson(CausalContext c) { for (ReceiptRef r : c.prior) { JsonObject e = new JsonObject(); e.addProperty("receipt_hash_hex", HEX.formatHex(r.receiptHash)); - e.addProperty("receipt_uri", r.receiptUri); + e.addProperty("receipt_ura", r.receiptUra); arr.add(e); } o.add("prior", arr); @@ -100,7 +100,7 @@ public static JsonObject causalToJson(CausalContext c) { case MERKLE: o.addProperty("form", "merkle"); o.addProperty("root_hex", HEX.formatHex(c.merkleRoot)); - o.addProperty("proof_uri", c.merkleProofUri); + o.addProperty("proof_ura", c.merkleProofUra); return o; } throw new AssertionError("exhaustive"); @@ -114,7 +114,7 @@ public static CausalContext causalFromJson(JsonObject d) { case "scalar": return CausalContext.scalar(new ReceiptRef( HEX.parseHex(d.get("receipt_hash_hex").getAsString()), - d.get("receipt_uri").getAsString() + d.get("receipt_ura").getAsString() )); case "list": List refs = new ArrayList<>(); @@ -122,14 +122,14 @@ public static CausalContext causalFromJson(JsonObject d) { JsonObject p = el.getAsJsonObject(); refs.add(new ReceiptRef( HEX.parseHex(p.get("receipt_hash_hex").getAsString()), - p.get("receipt_uri").getAsString() + p.get("receipt_ura").getAsString() )); } return CausalContext.list(refs); case "merkle": return CausalContext.merkle( HEX.parseHex(d.get("root_hex").getAsString()), - d.get("proof_uri").getAsString() + d.get("proof_ura").getAsString() ); default: throw new IllegalArgumentException("unknown_causal_form:" + form); diff --git a/sdk/java/src/main/java/run/easynet/axon/invocation/LocalRuntime.java b/sdk/java/src/main/java/run/easynet/axon/invocation/LocalRuntime.java index 18492011..66d25704 100644 --- a/sdk/java/src/main/java/run/easynet/axon/invocation/LocalRuntime.java +++ b/sdk/java/src/main/java/run/easynet/axon/invocation/LocalRuntime.java @@ -388,16 +388,16 @@ private static final class Registration { } /** - * Well-known local-runtime SystemAgent URI used when no caller identity + * Well-known local-runtime SystemAgent URA used when no caller identity * is provided. AXIOM.tex §3.2 permits this: infrastructure-initiated * invocations carry a SystemAgent identity and are still axiom-bound. */ private static final String SYSTEM_URI = "easynet:///r/_system/agents/local@1"; private static InvocationReceipt.AxiomBinding systemLocalBinding(byte[] payload) { - Axiom.AgentIdentity system = new Axiom.AgentIdentity(SYSTEM_URI, Axiom.UriProfile.EASYNET_STRICT_V2); - Axiom.AgentIdentity callee = new Axiom.AgentIdentity(SYSTEM_URI, Axiom.UriProfile.EASYNET_STRICT_V2); - Axiom.SubjectIdentity subject = new Axiom.SubjectIdentity(SYSTEM_URI, Axiom.UriProfile.EASYNET_STRICT_V2); + Axiom.AgentIdentity system = new Axiom.AgentIdentity(SYSTEM_URI, Axiom.UraProfile.EASYNET_STRICT_V2); + Axiom.AgentIdentity callee = new Axiom.AgentIdentity(SYSTEM_URI, Axiom.UraProfile.EASYNET_STRICT_V2); + Axiom.SubjectIdentity subject = new Axiom.SubjectIdentity(SYSTEM_URI, Axiom.UraProfile.EASYNET_STRICT_V2); byte[] nonce = Axiom.freshNonce(); byte[] digest = Axiom.sha256(payload == null ? new byte[0] : payload); return new InvocationReceipt.AxiomBinding( diff --git a/sdk/java/src/test/java/run/easynet/axon/AbilityToolAdapterTest.java b/sdk/java/src/test/java/run/easynet/axon/AbilityToolAdapterTest.java index 5288b8de..ff8c1df4 100644 --- a/sdk/java/src/test/java/run/easynet/axon/AbilityToolAdapterTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/AbilityToolAdapterTest.java @@ -58,11 +58,11 @@ void exportsPreserveRegistrationOrder() { void registerAbilityReplacesLocalHandlerForSameName() { Transport transport = new Transport() { @Override - public Map call(String tenantId, String resourceUri, Map payload) { + public Map call(String tenantId, String resourceUra, Map payload) { return Map.of( "source", "remote", "tenant_id", tenantId, - "resource_uri", resourceUri, + "resource_ura", resourceUra, "payload", payload ); } @@ -74,7 +74,7 @@ public Map call(String tenantId, String resourceUri, Map result = adapter.execute("shared", Map.of("x", 1)); assertEquals("remote", result.get("source")); - assertEquals("easynet:///r/org/shared-remote", result.get("resource_uri")); + assertEquals("easynet:///r/org/shared-remote", result.get("resource_ura")); assertEquals(1, adapter.specs().size()); } @@ -85,20 +85,20 @@ void principalContextFlowsToRemoteTransport() { Transport transport = new Transport() { @Override - public Map call(String tenantId, String resourceUri, Map payload) { + public Map call(String tenantId, String resourceUra, Map payload) { capturedPrincipal.set(null); - capturedResource.set(resourceUri); + capturedResource.set(resourceUra); return payload; } @Override public Map call( String tenantId, - String resourceUri, + String resourceUra, Map payload, String principalId) { capturedPrincipal.set(principalId); - capturedResource.set(resourceUri); + capturedResource.set(resourceUra); return payload; } }; diff --git a/sdk/java/src/test/java/run/easynet/axon/CapabilityRequestTest.java b/sdk/java/src/test/java/run/easynet/axon/CapabilityRequestTest.java index 358aab8c..e46b0673 100644 --- a/sdk/java/src/test/java/run/easynet/axon/CapabilityRequestTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/CapabilityRequestTest.java @@ -31,7 +31,7 @@ void publishValidateRequiresPayloadSource() { .capabilityName("cap-a") .version("1.0.0") .signatureBase64("c2ln") - .payloadUri("https://example.com/payload.gz"); + .payloadUra("https://example.com/payload.gz"); assertDoesNotThrow(req::validate); @@ -44,7 +44,7 @@ void publishValidateRequiresPayloadSource() { .signatureBase64("c2ln"); IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, noSource::validate); - assertTrue(ex.getMessage().contains("payloadUri")); + assertTrue(ex.getMessage().contains("payloadUra")); // packageBytesBase64 satisfies requirement PublishCapabilityRequest withBytes = new PublishCapabilityRequest() @@ -66,7 +66,7 @@ void publishValidateRejectsNegativePayloadSize() { .capabilityName("cap-a") .version("1.0.0") .signatureBase64("c2ln") - .payloadUri("https://example.com/p.gz") + .payloadUra("https://example.com/p.gz") .payloadSizeBytes(-1L); IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, req::validate); @@ -82,7 +82,7 @@ void publishValidateRejectsDigestWithoutSha256Prefix() { .version("1.0.0") .digest("abc123") .signatureBase64("c2ln") - .payloadUri("https://example.com/payload.gz"); + .payloadUra("https://example.com/payload.gz"); IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, req::validate); assertTrue(ex.getMessage().contains("sha256:")); @@ -96,7 +96,7 @@ void publishPayloadOmitsUnsetOptionalFields() { .capabilityName("cap-a") .version("1.0.0") .signatureBase64("c2ln") - .payloadUri(" ") + .payloadUra(" ") .packageBytesBase64("cGF5bG9hZA==") .payloadSizeBytes(0L) .publisherKeyVersion(0); @@ -104,7 +104,7 @@ void publishPayloadOmitsUnsetOptionalFields() { req.validate(); Map payload = req.toPayload(); - assertFalse(payload.containsKey("payload_uri"), "blank payload_uri must be omitted"); + assertFalse(payload.containsKey("payload_ura"), "blank payload_ura must be omitted"); assertFalse(payload.containsKey("payload_size_bytes"), "zero payload_size_bytes must be omitted"); assertFalse(payload.containsKey("publisher_key_version"), "zero publisher_key_version must be omitted"); assertFalse(payload.containsKey("signature_fingerprint"), "null signature_fingerprint must be omitted"); @@ -119,7 +119,7 @@ void publishPayloadIncludesProofFieldsWhenSet() { .capabilityName("cap-a") .version("1.0.0") .signatureBase64("c2ln") - .payloadUri("https://example.com/p.gz") + .payloadUra("https://example.com/p.gz") .payloadSizeBytes(42L) .signatureFingerprint("sig:abc") .packageFingerprint("pkg:abc") @@ -142,7 +142,7 @@ void publishPayloadTrimsStrings() { .capabilityName(" cap-a ") .version(" 1.0.0 ") .signatureBase64(" c2ln ") - .payloadUri(" https://example.com/p.gz "); + .payloadUra(" https://example.com/p.gz "); req.validate(); Map payload = req.toPayload(); @@ -152,7 +152,7 @@ void publishPayloadTrimsStrings() { assertEquals("cap-a", payload.get("capability_name")); assertEquals("1.0.0", payload.get("version")); assertEquals("c2ln", payload.get("signature_base64")); - assertEquals("https://example.com/p.gz", payload.get("payload_uri")); + assertEquals("https://example.com/p.gz", payload.get("payload_ura")); } // --------------------------------------------------------------- diff --git a/sdk/java/src/test/java/run/easynet/axon/FederationBodyTest.java b/sdk/java/src/test/java/run/easynet/axon/FederationBodyTest.java index fac281db..a4e011cf 100644 --- a/sdk/java/src/test/java/run/easynet/axon/FederationBodyTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/FederationBodyTest.java @@ -24,19 +24,19 @@ class FederationBodyTest { @Test void v1_advertise_agent_minimal() { assertEquals( - Map.of("agent_uri", "axon://realm/foo"), - FederationBody.advertiseAgent("axon://realm/foo", null, null)); + Map.of("agent_ura", "easynet:///r/realm/agent/foo"), + FederationBody.advertiseAgent("easynet:///r/realm/agent/foo", null, null)); } @Test void v2_advertise_agent_full() { assertEquals( Map.of( - "agent_uri", "axon://realm/foo", + "agent_ura", "easynet:///r/realm/agent/foo", "public_key_hex", "deadbeef", "signing_authority", Map.of("kind", "self_signed")), FederationBody.advertiseAgent( - "axon://realm/foo", + "easynet:///r/realm/agent/foo", "deadbeef", Map.of("kind", "self_signed"))); } @@ -44,31 +44,31 @@ void v2_advertise_agent_full() { @Test void v3_advertise_agent_omit_empty() { assertEquals( - Map.of("agent_uri", "axon://realm/foo"), - FederationBody.advertiseAgent("axon://realm/foo", "", Map.of())); + Map.of("agent_ura", "easynet:///r/realm/agent/foo"), + FederationBody.advertiseAgent("easynet:///r/realm/agent/foo", "", Map.of())); } @Test void v5_revoke_no_reason() { assertEquals( - Map.of("agent_uri", "axon://realm/foo"), - FederationBody.revoke("axon://realm/foo", null)); + Map.of("agent_ura", "easynet:///r/realm/agent/foo"), + FederationBody.revoke("easynet:///r/realm/agent/foo", null)); } @Test void v5b_revoke_blank_reason_omitted() { assertEquals( - Map.of("agent_uri", "axon://realm/foo"), - FederationBody.revoke("axon://realm/foo", " ")); + Map.of("agent_ura", "easynet:///r/realm/agent/foo"), + FederationBody.revoke("easynet:///r/realm/agent/foo", " ")); } @Test void v6_revoke_with_reason() { assertEquals( Map.of( - "agent_uri", "axon://realm/foo", + "agent_ura", "easynet:///r/realm/agent/foo", "reason", "operator: maintenance"), - FederationBody.revoke("axon://realm/foo", "operator: maintenance")); + FederationBody.revoke("easynet:///r/realm/agent/foo", "operator: maintenance")); } @Test @@ -80,19 +80,19 @@ void v7_resolve_no_filter() { void v8_resolve_with_filter() { assertEquals( Map.of("filter", Map.of( - "agent_uri_prefix", "axon://realm/edge-", + "agent_ura_prefix", "easynet:///r/realm/agent/edge-", "include_abilities", true)), - FederationBody.resolve("axon://realm/edge-", true)); + FederationBody.resolve("easynet:///r/realm/agent/edge-", true)); } @Test void v9_advertise_abilities() { assertEquals( Map.of( - "agent_uri", "axon://realm/foo", + "agent_ura", "easynet:///r/realm/agent/foo", "abilities", List.of(Map.of("name", "echo"))), FederationBody.advertiseAbilities( - "axon://realm/foo", + "easynet:///r/realm/agent/foo", List.of(Map.of("name", "echo")))); } diff --git a/sdk/java/src/test/java/run/easynet/axon/invocation/AdmissionTest.java b/sdk/java/src/test/java/run/easynet/axon/invocation/AdmissionTest.java index b30fb39c..36f93bb4 100644 --- a/sdk/java/src/test/java/run/easynet/axon/invocation/AdmissionTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/invocation/AdmissionTest.java @@ -21,9 +21,9 @@ class AdmissionTest { private LocalRuntime rt; private static final Axiom.AgentIdentity SILAN = - new Axiom.AgentIdentity("easynet:///r/silan/agents/t@1", Axiom.UriProfile.EASYNET_STRICT_V2); + new Axiom.AgentIdentity("easynet:///r/silan/agents/t@1", Axiom.UraProfile.EASYNET_STRICT_V2); private static final Axiom.AgentIdentity OPENAI = - new Axiom.AgentIdentity("easynet:///r/openai/agents/t@1", Axiom.UriProfile.EASYNET_STRICT_V2); + new Axiom.AgentIdentity("easynet:///r/openai/agents/t@1", Axiom.UraProfile.EASYNET_STRICT_V2); @BeforeEach void setUp() { @@ -50,7 +50,7 @@ private static Axiom.InvocationEnvelope sampleEnv() { return new Axiom.InvocationEnvelope( SILAN, OPENAI, new Axiom.SubjectIdentity("easynet:///r/silan/papers/p@d1", - Axiom.UriProfile.EASYNET_STRICT_V2), + Axiom.UraProfile.EASYNET_STRICT_V2), "echo", Axiom.sha256(new byte[0]), nonce(0x11), @@ -180,7 +180,7 @@ void runAdmissionFederatedAcceptsVerifiedSignature() { Axiom.InvocationEnvelope env = sampleEnv(); Axiom.CallerSignature sig = sampleSig(env); byte[] pub = Axiom.publicKeyFromSeed(seed(0x42)); - Admission.runAdmission(env, sig, uri -> pub, new Admission.NonceReplayStore(), 1000); + Admission.runAdmission(env, sig, ura -> pub, new Admission.NonceReplayStore(), 1000); } @Test @@ -190,7 +190,7 @@ void runAdmissionFederatedRejectsWrongKey() { byte[] otherPub = Axiom.publicKeyFromSeed(seed(0x99)); Admission.NonceReplayStore s = new Admission.NonceReplayStore(); AxonError ex = assertThrows(AxonError.class, () -> - Admission.runAdmission(env, sig, uri -> otherPub, s, 1000)); + Admission.runAdmission(env, sig, ura -> otherPub, s, 1000)); assertEquals(Admission.REASON_CALLER_SIGNATURE_INVALID, ex.reason()); assertEquals(0, s.size(), "replay store must not be mutated on crypto reject"); } @@ -198,7 +198,7 @@ void runAdmissionFederatedRejectsWrongKey() { @Test void runAdmissionRejectsEnvelopeBeforeReplayStore() { Axiom.InvocationEnvelope env = new Axiom.InvocationEnvelope( - new Axiom.AgentIdentity("", Axiom.UriProfile.EASYNET_STRICT_V2), + new Axiom.AgentIdentity("", Axiom.UraProfile.EASYNET_STRICT_V2), OPENAI, Axiom.SubjectIdentity.fromCallee(OPENAI), "echo", Axiom.sha256(new byte[0]), nonce(0x11), Axiom.CausalContext.none() @@ -246,7 +246,7 @@ void admissionEmptyAbilityViaRuntime() { @Test void admissionFederatedWrongKeyViaRuntime() { - rt.setAdmissionKeyResolver(uri -> Axiom.publicKeyFromSeed(seed(0x99))); + rt.setAdmissionKeyResolver(ura -> Axiom.publicKeyFromSeed(seed(0x99))); AxonError ex = assertThrows(AxonError.class, () -> rt.invokeSignedAsync(SILAN, OPENAI, null, "echo", new byte[0], Axiom.CausalContext.none(), nonce(0x22), seed(3), null, null)); @@ -309,7 +309,7 @@ void admissionMalformedEnvelopeLeavesReplayStoreClean() { @Test void admissionClearResolverReturnsToLocalFast() { byte[] s = seed(10); - rt.setAdmissionKeyResolver(uri -> Axiom.publicKeyFromSeed(seed(11))); + rt.setAdmissionKeyResolver(ura -> Axiom.publicKeyFromSeed(seed(11))); assertThrows(AxonError.class, () -> rt.invokeSignedAsync(SILAN, OPENAI, null, "echo", new byte[0], Axiom.CausalContext.none(), nonce(0xAA), s, null, null)); diff --git a/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomVectorsTest.java b/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomVectorsTest.java index 5e78f58e..35e01a2d 100644 --- a/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomVectorsTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomVectorsTest.java @@ -126,7 +126,7 @@ private void runOne(Path path) throws Exception { byte[] seed = HexFormat.of().parseHex(inputs.get("caller_secret_hex").getAsString()); Axiom.CallerSignature sig = Axiom.signInvocation(seed, env, "vk"); byte[] pub = Axiom.publicKeyFromSeed(seed); - Axiom.KeyResolver resolver = agentUri -> pub; + Axiom.KeyResolver resolver = agentUra -> pub; Axiom.verifyInvocationSignature(env, sig, resolver); } } @@ -134,14 +134,14 @@ private void runOne(Path path) throws Exception { private Axiom.AgentIdentity parseAgent(JsonObject o) { return new Axiom.AgentIdentity( - o.get("uri").getAsString(), - Axiom.UriProfile.parse(o.get("profile").getAsString())); + o.get("ura").getAsString(), + Axiom.UraProfile.parse(o.get("profile").getAsString())); } private Axiom.SubjectIdentity parseSubject(JsonObject o) { return new Axiom.SubjectIdentity( - o.get("uri").getAsString(), - Axiom.UriProfile.parse(o.get("profile").getAsString())); + o.get("ura").getAsString(), + Axiom.UraProfile.parse(o.get("profile").getAsString())); } private Axiom.CausalContext parseCausal(JsonObject o) { @@ -153,20 +153,20 @@ private Axiom.CausalContext parseCausal(JsonObject o) { return switch (form) { case "scalar" -> Axiom.CausalContext.scalar(new Axiom.ReceiptRef( hex.parseHex(o.get("receipt_hash_hex").getAsString()), - o.get("receipt_uri").getAsString())); + o.get("receipt_ura").getAsString())); case "list" -> { List prior = new ArrayList<>(); for (var je : o.getAsJsonArray("prior")) { JsonObject po = je.getAsJsonObject(); prior.add(new Axiom.ReceiptRef( hex.parseHex(po.get("receipt_hash_hex").getAsString()), - po.get("receipt_uri").getAsString())); + po.get("receipt_ura").getAsString())); } yield Axiom.CausalContext.list(prior); } case "merkle" -> Axiom.CausalContext.merkle( hex.parseHex(o.get("root_hex").getAsString()), - o.get("proof_uri").getAsString()); + o.get("proof_ura").getAsString()); default -> throw new IllegalArgumentException("unknown_causal_form:" + form); }; } diff --git a/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomWorkedExampleTest.java b/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomWorkedExampleTest.java index 7e34be63..c3ca0b29 100644 --- a/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomWorkedExampleTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/invocation/AxiomWorkedExampleTest.java @@ -190,14 +190,14 @@ private static Axiom.InvocationEnvelope buildEnvelope(JsonObject inputs) { "this vector requires causal_context.form=\"none\", got " + form); Axiom.AgentIdentity caller = new Axiom.AgentIdentity( - requireString(callerObj, "uri", "inputs.caller"), - Axiom.UriProfile.parse(requireString(callerObj, "profile", "inputs.caller"))); + requireString(callerObj, "ura", "inputs.caller"), + Axiom.UraProfile.parse(requireString(callerObj, "profile", "inputs.caller"))); Axiom.AgentIdentity callee = new Axiom.AgentIdentity( - requireString(calleeObj, "uri", "inputs.callee"), - Axiom.UriProfile.parse(requireString(calleeObj, "profile", "inputs.callee"))); + requireString(calleeObj, "ura", "inputs.callee"), + Axiom.UraProfile.parse(requireString(calleeObj, "profile", "inputs.callee"))); Axiom.SubjectIdentity subject = new Axiom.SubjectIdentity( - requireString(subjectObj, "uri", "inputs.subject"), - Axiom.UriProfile.parse(requireString(subjectObj, "profile", "inputs.subject"))); + requireString(subjectObj, "ura", "inputs.subject"), + Axiom.UraProfile.parse(requireString(subjectObj, "profile", "inputs.subject"))); return new Axiom.InvocationEnvelope( caller, callee, subject, ability, diff --git a/sdk/java/src/test/java/run/easynet/axon/invocation/CrossLanguageVerifyTest.java b/sdk/java/src/test/java/run/easynet/axon/invocation/CrossLanguageVerifyTest.java index 98f5db5b..26cfce75 100644 --- a/sdk/java/src/test/java/run/easynet/axon/invocation/CrossLanguageVerifyTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/invocation/CrossLanguageVerifyTest.java @@ -118,11 +118,11 @@ private static void buildBundle(Path bundle) throws IOException { writeKey(bundle, "openai", openaiSeed); Axiom.AgentIdentity silan = new Axiom.AgentIdentity( - "easynet:///r/silan/agents/writer@1", Axiom.UriProfile.EASYNET_STRICT_V2); + "easynet:///r/silan/agents/writer@1", Axiom.UraProfile.EASYNET_STRICT_V2); Axiom.AgentIdentity openai = new Axiom.AgentIdentity( - "easynet:///r/openai/agents/reviewer@1", Axiom.UriProfile.EASYNET_STRICT_V2); + "easynet:///r/openai/agents/reviewer@1", Axiom.UraProfile.EASYNET_STRICT_V2); Axiom.SubjectIdentity paper = new Axiom.SubjectIdentity( - "easynet:///r/silan/papers/p@draft-1", Axiom.UriProfile.EASYNET_STRICT_V2); + "easynet:///r/silan/papers/p@draft-1", Axiom.UraProfile.EASYNET_STRICT_V2); Axiom.InvocationEnvelope envA = new Axiom.InvocationEnvelope( silan, openai, paper, "review", diff --git a/sdk/java/src/test/java/run/easynet/axon/invocation/InvokeSignedTest.java b/sdk/java/src/test/java/run/easynet/axon/invocation/InvokeSignedTest.java index bbf3e5a8..e8bab655 100644 --- a/sdk/java/src/test/java/run/easynet/axon/invocation/InvokeSignedTest.java +++ b/sdk/java/src/test/java/run/easynet/axon/invocation/InvokeSignedTest.java @@ -22,9 +22,9 @@ class InvokeSignedTest { private LocalRuntime rt; private static final Axiom.AgentIdentity SILAN = - new Axiom.AgentIdentity("easynet:///r/silan/agents/t@1", Axiom.UriProfile.EASYNET_STRICT_V2); + new Axiom.AgentIdentity("easynet:///r/silan/agents/t@1", Axiom.UraProfile.EASYNET_STRICT_V2); private static final Axiom.AgentIdentity OPENAI = - new Axiom.AgentIdentity("easynet:///r/openai/agents/t@1", Axiom.UriProfile.EASYNET_STRICT_V2); + new Axiom.AgentIdentity("easynet:///r/openai/agents/t@1", Axiom.UraProfile.EASYNET_STRICT_V2); @BeforeEach void setUp() { @@ -53,7 +53,7 @@ private static byte[] nonce(int b) { void invokeSignedWithExplicitSubjectAndNonceVerifies() throws Exception { byte[] s = seed(7); Axiom.SubjectIdentity subject = - new Axiom.SubjectIdentity("easynet:///r/silan/papers/p@d1", Axiom.UriProfile.EASYNET_STRICT_V2); + new Axiom.SubjectIdentity("easynet:///r/silan/papers/p@d1", Axiom.UraProfile.EASYNET_STRICT_V2); byte[] n = nonce(0xAB); LocalRuntime.SignedInvocation result = rt.invokeSignedAsync( @@ -64,7 +64,7 @@ void invokeSignedWithExplicitSubjectAndNonceVerifies() throws Exception { LocalRuntime.SignedEnvelope stored = rt.axiomEnvelopeOf(result.handle.invocationId()); assertNotNull(stored, "envelope must be stored"); - assertEquals(subject.uri, stored.envelope.subject.uri); + assertEquals(subject.ura, stored.envelope.subject.ura); assertArrayEquals(n, stored.envelope.invocationNonce); // Independent verification via the same seed → pubkey derivation. @@ -72,7 +72,7 @@ void invokeSignedWithExplicitSubjectAndNonceVerifies() throws Exception { Axiom.verifyInvocationSignature( result.signed.envelope, result.signed.signature, - uri -> pub + ura -> pub ); // Canonical bytes stable across signed and stored views. @@ -89,8 +89,8 @@ void invokeSignedDefaultsSubjectToCalleeWhenNull() { Axiom.CausalContext.none(), nonce(0x11), seed(8), null, null ); assertEquals( - result.signed.envelope.callee.uri, - result.signed.envelope.subject.uri + result.signed.envelope.callee.ura, + result.signed.envelope.subject.ura ); assertEquals( result.signed.envelope.callee.profile, @@ -157,25 +157,25 @@ void tamperedSubjectBreaksVerification() { byte[] s = seed(21); byte[] n = nonce(0x11); Axiom.SubjectIdentity subj = - new Axiom.SubjectIdentity("easynet:///r/silan/papers/p@1", Axiom.UriProfile.EASYNET_STRICT_V2); + new Axiom.SubjectIdentity("easynet:///r/silan/papers/p@1", Axiom.UraProfile.EASYNET_STRICT_V2); LocalRuntime.SignedInvocation res = rt.invokeSignedAsync( SILAN, OPENAI, subj, "echo", new byte[0], Axiom.CausalContext.none(), n, s, null, null ); byte[] pub = Axiom.publicKeyFromSeed(s); - // Build a tampered envelope with a different subject URI. + // Build a tampered envelope with a different subject URA. Axiom.InvocationEnvelope tampered = new Axiom.InvocationEnvelope( res.signed.envelope.caller, res.signed.envelope.callee, new Axiom.SubjectIdentity( - "easynet:///r/mallory/papers/evil@1", Axiom.UriProfile.EASYNET_STRICT_V2), + "easynet:///r/mallory/papers/evil@1", Axiom.UraProfile.EASYNET_STRICT_V2), res.signed.envelope.ability, res.signed.envelope.argsDigest, res.signed.envelope.invocationNonce, res.signed.envelope.causalContext ); SecurityException ex = assertThrows(SecurityException.class, () -> - Axiom.verifyInvocationSignature(tampered, res.signed.signature, uri -> pub)); + Axiom.verifyInvocationSignature(tampered, res.signed.signature, ura -> pub)); assertTrue(ex.getMessage().contains("caller_signature_invalid"), ex.getMessage()); } @@ -200,7 +200,7 @@ void tamperedCausalContextBreaksVerification() { Axiom.CausalContext.scalar(new Axiom.ReceiptRef(fakeHash, "evil")) ); SecurityException ex = assertThrows(SecurityException.class, () -> - Axiom.verifyInvocationSignature(tampered, res.signed.signature, uri -> pub)); + Axiom.verifyInvocationSignature(tampered, res.signed.signature, ura -> pub)); assertTrue(ex.getMessage().contains("caller_signature_invalid"), ex.getMessage()); } @@ -215,7 +215,7 @@ void wrongPubkeyRejectsValidSignature() { ); byte[] imposterPub = Axiom.publicKeyFromSeed(imposterSeed); SecurityException ex = assertThrows(SecurityException.class, () -> - Axiom.verifyInvocationSignature(res.signed.envelope, res.signed.signature, uri -> imposterPub)); + Axiom.verifyInvocationSignature(res.signed.envelope, res.signed.signature, ura -> imposterPub)); assertTrue(ex.getMessage().contains("caller_signature_invalid"), ex.getMessage()); } @@ -224,7 +224,7 @@ void storedEnvelopeCanonicalBytesStable() throws Exception { byte[] s = seed(25); byte[] n = nonce(0x44); Axiom.SubjectIdentity subj = new Axiom.SubjectIdentity( - "easynet:///r/silan/papers/p@stable", Axiom.UriProfile.EASYNET_STRICT_V2); + "easynet:///r/silan/papers/p@stable", Axiom.UraProfile.EASYNET_STRICT_V2); LocalRuntime.SignedInvocation res = rt.invokeSignedAsync( SILAN, OPENAI, subj, "echo", "stable".getBytes(), Axiom.CausalContext.none(), n, s, null, null diff --git a/sdk/node/scripts/run-axiom-vectors.mjs b/sdk/node/scripts/run-axiom-vectors.mjs index ea59323e..05142294 100644 --- a/sdk/node/scripts/run-axiom-vectors.mjs +++ b/sdk/node/scripts/run-axiom-vectors.mjs @@ -35,7 +35,7 @@ const { // ── Vector parsing ──────────────────────────────────────────────────── function parseIdentity(v) { - return { uri: v.uri, profile: parseProfile(v.profile) }; + return { ura: v.ura, profile: parseProfile(v.profile) }; } function parseCausal(c) { @@ -43,19 +43,19 @@ function parseCausal(c) { if (c.form === "scalar") { return CausalContext.scalar({ receiptHash: Buffer.from(c.receipt_hash_hex, "hex"), - receiptUri: c.receipt_uri, + receiptUra: c.receipt_ura, }); } if (c.form === "list") { return CausalContext.list( c.prior.map((r) => ({ receiptHash: Buffer.from(r.receipt_hash_hex, "hex"), - receiptUri: r.receipt_uri, + receiptUra: r.receipt_ura, })), ); } if (c.form === "merkle") { - return CausalContext.merkle(Buffer.from(c.root_hex, "hex"), c.proof_uri); + return CausalContext.merkle(Buffer.from(c.root_hex, "hex"), c.proof_ura); } throw new Error(`unknown_causal_form:${c.form}`); } diff --git a/sdk/node/src/ability_lifecycle.ts b/sdk/node/src/ability_lifecycle.ts index 87d775ab..8244ab02 100644 --- a/sdk/node/src/ability_lifecycle.ts +++ b/sdk/node/src/ability_lifecycle.ts @@ -6,7 +6,7 @@ // // Protocol Responsibility: // - Defines typed ability descriptors, export targets, and deployment helpers exposed to SDK users. -// - Keeps cross-language ability naming, resource-uri, and tool-spec semantics aligned. +// - Keeps cross-language ability naming, resource-ura, and tool-spec semantics aligned. // // Implementation Approach: // - Separates pure descriptor/export helpers from bridge-backed deployment and invocation flows. @@ -51,7 +51,7 @@ export interface AbilityDescriptor { outputSchema: Record; version: string; tags: string[]; - resourceUri: string; + resourceUra: string; // Agent ecosystem extensions (SKILL.md / MCP / CLI) instructions: string; inputExamples: unknown[]; @@ -369,7 +369,7 @@ export function buildAbilityDescriptor(opts: { outputSchema?: Record; version?: string; tags?: string[]; - resourceUri?: string; + resourceUra?: string; instructions?: string; inputExamples?: unknown[]; prerequisites?: string[]; @@ -399,7 +399,7 @@ export function buildAbilityDescriptor(opts: { outputSchema: opts.outputSchema ?? { type: "object", properties: {} }, version: opts.version ?? "1.0.0", tags: opts.tags ?? [], - resourceUri: opts.resourceUri ?? `easynet:///r/org/${token}`, + resourceUra: opts.resourceUra ?? `easynet:///r/org/${token}`, instructions: opts.instructions ?? "", inputExamples: opts.inputExamples ?? [], prerequisites: opts.prerequisites ?? [], @@ -428,7 +428,7 @@ export function toToolSpec(descriptor: AbilityDescriptor): ToolSpec & { return { name: descriptor.toolName, description: descriptor.description, - resourceUri: descriptor.resourceUri, + resourceUra: descriptor.resourceUra, parameters: descriptor.inputSchema as ToolParameters, readOnlyHint: descriptor.readOnly, destructiveHint: descriptor.destructive, @@ -448,7 +448,7 @@ export function exportAbility( ): AbilityExportResult { const token = descriptor.toolName; const endpoint = axonEndpoint ?? `http://127.0.0.1:${DEFAULT_AXON_PORT}`; - const invokeScript = generateInvokeScript(descriptor.resourceUri, endpoint); + const invokeScript = generateInvokeScript(descriptor.resourceUra, endpoint); const abilityMd = generateAbilityMd(descriptor, target, token); return { abilityMd, invokeScript, abilityName: token }; } @@ -536,7 +536,7 @@ export async function deployToNode( // Per-device ability catalog (`listAbilities`) and tool-name-keyed // invocation (`invokeAbility`) were removed by RFC-001 §A1 — the directory is // now federation-scoped (`federation.resolve`) and invocation is target-typed -// (`Invoke(callee=, ability=...)`) rather than node-id + tool-name. +// (`Invoke(callee=, ability=...)`) rather than node-id + tool-name. // Use `bridge.federationResolve(...)` and `bridge.abilityCallRaw(...)` directly. // --------------------------------------------------------------------------- @@ -657,26 +657,26 @@ function sanitizeShellValue(value: string, label: string): string { return value; } -function generateInvokeScript(resourceUri: string, endpoint: string): string { +function generateInvokeScript(resourceUra: string, endpoint: string): string { const safeEP = sanitizeShellValue(endpoint, "endpoint"); - const safeURI = sanitizeShellValue(resourceUri, "resource_uri"); + const safeURA = sanitizeShellValue(resourceUra, "resource_ura"); return `#!/usr/bin/env bash set -euo pipefail AXON_ENDPOINT="\${AXON_ENDPOINT:-${safeEP}}" TENANT="\${AXON_TENANT:-default}" -RESOURCE_URI="${safeURI}" +RESOURCE_URA="${safeURA}" ARGS="\${1:-{}}" curl -sS -X POST "\${AXON_ENDPOINT}/v1/invoke" \\ -H "Content-Type: application/json" \\ - -d "{\\"tenant_id\\":\\"\${TENANT}\\",\\"resource_uri\\":\\"\${RESOURCE_URI}\\",\\"payload\\":\${ARGS}}" + -d "{\\"tenant_id\\":\\"\${TENANT}\\",\\"resource_ura\\":\\"\${RESOURCE_URA}\\",\\"payload\\":\${ARGS}}" `; } -function pushMetadata(lines: string[], version: string, resourceUri: string): void { +function pushMetadata(lines: string[], version: string, resourceUra: string): void { lines.push("metadata:"); lines.push(" author: easynet-axon"); lines.push(` version: "${version}"`); - lines.push(` axon-resource-uri: "${resourceUri}"`); + lines.push(` axon-resource-ura: "${resourceUra}"`); } function generateAbilityMd( @@ -690,7 +690,7 @@ function generateAbilityMd( lines.push(`description: ${descriptor.description}`); lines.push("compatibility: Requires network access to Axon runtime"); - pushMetadata(lines, descriptor.version, descriptor.resourceUri); + pushMetadata(lines, descriptor.version, descriptor.resourceUra); if (target === "claude") { lines.push("allowed-tools: Bash(*)"); } else if (target === "openclaw") { @@ -780,7 +780,7 @@ function generateAbilityMd( lines.push(""); lines.push("## Axon Resource"); lines.push(""); - lines.push(`- **URI**: \`${descriptor.resourceUri}\``); + lines.push(`- **URA**: \`${descriptor.resourceUra}\``); lines.push(`- **Version**: ${descriptor.version}`); if (descriptor.category) { lines.push(`- **Category**: ${descriptor.category}`); diff --git a/sdk/node/src/capability_request.test.ts b/sdk/node/src/capability_request.test.ts index 2739d3cd..47271609 100644 --- a/sdk/node/src/capability_request.test.ts +++ b/sdk/node/src/capability_request.test.ts @@ -33,7 +33,7 @@ describe("PublishCapabilityRequest", () => { validatePublishCapabilityRequest("", "pkg-a", "cap-a", { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", }), (err: unknown) => err instanceof AxonConfigError && err.message.includes("tenantId"), @@ -46,7 +46,7 @@ describe("PublishCapabilityRequest", () => { validatePublishCapabilityRequest("tenant-a", "", "cap-a", { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", }), (err: unknown) => err instanceof AxonConfigError && err.message.includes("packageId"), @@ -59,7 +59,7 @@ describe("PublishCapabilityRequest", () => { validatePublishCapabilityRequest("tenant-a", "pkg-a", "", { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", }), (err: unknown) => err instanceof AxonConfigError && err.message.includes("capabilityName"), @@ -72,7 +72,7 @@ describe("PublishCapabilityRequest", () => { validatePublishCapabilityRequest("tenant-a", "pkg-a", "cap-a", { version: "", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", }), (err: unknown) => err instanceof AxonConfigError && err.message.includes("version"), @@ -85,7 +85,7 @@ describe("PublishCapabilityRequest", () => { validatePublishCapabilityRequest("tenant-a", "pkg-a", "cap-a", { version: "1.0.0", signatureBase64: "", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", }), (err: unknown) => err instanceof AxonConfigError && @@ -100,7 +100,7 @@ describe("PublishCapabilityRequest", () => { version: "1.0.0", digest: "abc123", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", }), (err: unknown) => err instanceof AxonConfigError && err.message.includes("sha256:"), @@ -112,7 +112,7 @@ describe("PublishCapabilityRequest", () => { version: "1.0.0", digest: "sha256:abc", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", tags: ["tag-a"], requirements: { cpu: "arm64" }, metadata: { author: "test" }, @@ -131,7 +131,7 @@ describe("PublishCapabilityRequest", () => { assert.equal(payload.version, "1.0.0"); assert.equal(payload.digest, "sha256:abc"); assert.equal(payload.signature_base64, "c2ln"); - assert.equal(payload.payload_uri, "https://example.com/p.gz"); + assert.equal(payload.payload_ura, "https://example.com/p.gz"); assert.deepEqual(payload.tags, ["tag-a"]); assert.deepEqual(payload.requirements, { cpu: "arm64" }); assert.deepEqual(payload.metadata, { author: "test" }); @@ -141,7 +141,7 @@ describe("PublishCapabilityRequest", () => { const opts = { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", digest: " ", }; validatePublishCapabilityRequest("tenant-a", "pkg-a", "cap-a", opts); @@ -159,7 +159,7 @@ describe("PublishCapabilityRequest", () => { const opts = { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: " ", + payloadUra: " ", packageBytesBase64: "cGF5bG9hZA==", payloadSizeBytes: 0, publisherKeyVersion: 0, @@ -175,9 +175,9 @@ describe("PublishCapabilityRequest", () => { ); assert.equal( - "payload_uri" in payload, + "payload_ura" in payload, false, - "blank payload_uri must be omitted", + "blank payload_ura must be omitted", ); assert.equal( "payload_size_bytes" in payload, @@ -205,7 +205,7 @@ describe("PublishCapabilityRequest", () => { const opts = { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", payloadSizeBytes: 42, }; validatePublishCapabilityRequest("tenant-a", "pkg-a", "cap-a", opts); @@ -223,7 +223,7 @@ describe("PublishCapabilityRequest", () => { const opts = { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", publisherKeyVersion: 3, }; validatePublishCapabilityRequest("tenant-a", "pkg-a", "cap-a", opts); @@ -243,7 +243,7 @@ describe("PublishCapabilityRequest", () => { validatePublishCapabilityRequest("tenant-a", "pkg-a", "cap-a", { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", payloadSizeBytes: -1, }), (err: unknown) => @@ -252,7 +252,7 @@ describe("PublishCapabilityRequest", () => { ); }); - it("requires payloadUri or packageBytesBase64", () => { + it("requires payloadUra or packageBytesBase64", () => { // Neither provided assert.throws( () => @@ -261,15 +261,15 @@ describe("PublishCapabilityRequest", () => { signatureBase64: "c2ln", }), (err: unknown) => - err instanceof AxonConfigError && err.message.includes("payloadUri"), + err instanceof AxonConfigError && err.message.includes("payloadUra"), ); - // payloadUri provided + // payloadUra provided assert.doesNotThrow(() => validatePublishCapabilityRequest("tenant-a", "pkg-a", "cap-a", { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", }), ); @@ -287,7 +287,7 @@ describe("PublishCapabilityRequest", () => { const opts = { version: "1.0.0", signatureBase64: "c2ln", - payloadUri: "https://example.com/p.gz", + payloadUra: "https://example.com/p.gz", payloadSizeBytes: 42, signatureFingerprint: "sig:abc", packageFingerprint: "pkg:abc", @@ -311,7 +311,7 @@ describe("PublishCapabilityRequest", () => { const opts = { version: " 1.0.0 ", signatureBase64: " c2ln ", - payloadUri: " https://example.com/p.gz ", + payloadUra: " https://example.com/p.gz ", }; validatePublishCapabilityRequest( " tenant-a ", @@ -331,7 +331,7 @@ describe("PublishCapabilityRequest", () => { assert.equal(payload.capability_name, "cap-a"); assert.equal(payload.version, "1.0.0"); assert.equal(payload.signature_base64, "c2ln"); - assert.equal(payload.payload_uri, "https://example.com/p.gz"); + assert.equal(payload.payload_ura, "https://example.com/p.gz"); }); }); diff --git a/sdk/node/src/capability_request.ts b/sdk/node/src/capability_request.ts index 1ffe4734..7a5eb5c5 100644 --- a/sdk/node/src/capability_request.ts +++ b/sdk/node/src/capability_request.ts @@ -98,10 +98,10 @@ export function validatePublishCapabilityRequest( validateDigestPrefix("digest", options.digest); requireNonBlank("signatureBase64", options.signatureBase64); if ( - (!options.payloadUri || !options.payloadUri.trim()) && + (!options.payloadUra || !options.payloadUra.trim()) && (!options.packageBytesBase64 || !options.packageBytesBase64.trim()) ) { - throw new AxonConfigError("payloadUri or packageBytesBase64 is required"); + throw new AxonConfigError("payloadUra or packageBytesBase64 is required"); } if (options.payloadSizeBytes !== undefined && options.payloadSizeBytes < 0) { throw new AxonConfigError("payloadSizeBytes must be >= 0"); @@ -125,7 +125,7 @@ export function buildPublishCapabilityPayload( payload.version = options.version.trim(); putOptionalNonBlank(payload, "digest", options.digest); payload.signature_base64 = options.signatureBase64.trim(); - putOptionalNonBlank(payload, "payload_uri", options.payloadUri); + putOptionalNonBlank(payload, "payload_ura", options.payloadUra); putOptionalPayloadSize(payload, "payload_size_bytes", options.payloadSizeBytes); putOptionalNonBlank(payload, "package_bytes_base64", options.packageBytesBase64); putOptionalNonBlank(payload, "signature_fingerprint", options.signatureFingerprint); diff --git a/sdk/node/src/dendrite_bridge/bridge.ts b/sdk/node/src/dendrite_bridge/bridge.ts index a1fe08ec..2a19dd63 100644 --- a/sdk/node/src/dendrite_bridge/bridge.ts +++ b/sdk/node/src/dendrite_bridge/bridge.ts @@ -220,23 +220,23 @@ export class DendriteBridge { abilityCall( tenantId: string, - resourceUri: string, + resourceUra: string, payload: unknown, options: DendriteAbilityCallOptions = {} ): Record { - return this.abilityCallRaw(tenantId, resourceUri, payload, options); + return this.abilityCallRaw(tenantId, resourceUra, payload, options); } abilityCallRaw( tenantId: string, - resourceUri: string, + resourceUra: string, payload: unknown, options: DendriteAbilityCallOptions = {} ): Record { if (this.handle <= 0n) throw new DendriteError("dendrite bridge already closed"); const req = JSON.stringify({ tenant_id: tenantId, - resource_uri: resourceUri, + resource_ura: resourceUra, payload_json: payload, subject_id: options.subjectId, timeout_ms: options.timeoutMs ?? DEFAULT_TIMEOUT_MS, @@ -280,7 +280,7 @@ export class DendriteBridge { timeoutMs?: number; } = {} ): Record { - const body: Record = { agent_uri: agentUri }; + const body: Record = { agent_ura: agentUri }; if (options.publicKeyHex) body.public_key_hex = options.publicKeyHex; if (options.signingAuthority && Object.keys(options.signingAuthority).length > 0) { body.signing_authority = options.signingAuthority; @@ -300,7 +300,7 @@ export class DendriteBridge { return this.abilityCallRaw( tenantId, "federation.advertise_abilities", - { agent_uri: agentUri, abilities: abilities ?? [] }, + { agent_ura: agentUri, abilities: abilities ?? [] }, { timeoutMs: options.timeoutMs ?? FEDERATION_DEFAULT_TIMEOUT_MS } ); } @@ -325,7 +325,7 @@ export class DendriteBridge { agentUri: string, options: { reason?: string; timeoutMs?: number } = {} ): Record { - const body: Record = { agent_uri: agentUri }; + const body: Record = { agent_ura: agentUri }; if (options.reason && options.reason.length > 0) { body.reason = options.reason; } @@ -341,7 +341,7 @@ export class DendriteBridge { ): Record { const filter: Record = {}; if (options.agentUriPrefix && options.agentUriPrefix.length > 0) { - filter.agent_uri_prefix = options.agentUriPrefix; + filter.agent_ura_prefix = options.agentUriPrefix; } if (options.includeAbilities) filter.include_abilities = true; const body: Record = Object.keys(filter).length ? { filter } : {}; diff --git a/sdk/node/src/dendrite_bridge/types.ts b/sdk/node/src/dendrite_bridge/types.ts index 97ceca62..6e691706 100644 --- a/sdk/node/src/dendrite_bridge/types.ts +++ b/sdk/node/src/dendrite_bridge/types.ts @@ -94,7 +94,7 @@ export interface DendritePublishCapabilityOptions { tags?: string[]; requirements?: Record; metadata?: Record; - payloadUri?: string; + payloadUra?: string; payloadSizeBytes?: number; packageBytesBase64?: string; signatureFingerprint?: string; diff --git a/sdk/node/src/federation_conformance.test.ts b/sdk/node/src/federation_conformance.test.ts index a7dbd084..2158f667 100644 --- a/sdk/node/src/federation_conformance.test.ts +++ b/sdk/node/src/federation_conformance.test.ts @@ -11,7 +11,7 @@ import assert from "node:assert/strict"; import { DendriteBridge } from "./dendrite_bridge.js"; class CapturingBridge extends DendriteBridge { - public lastResourceUri: string | null = null; + public lastResourceUra: string | null = null; public lastPayload: unknown = null; public lastTimeoutMs: number | null = null; @@ -21,11 +21,11 @@ class CapturingBridge extends DendriteBridge { override abilityCallRaw( _tenantId: string, - resourceUri: string, + resourceUra: string, payload: unknown, options: { timeoutMs?: number; subjectId?: string; metadata?: Record } = {} ): Record { - this.lastResourceUri = resourceUri; + this.lastResourceUra = resourceUra; this.lastPayload = payload; this.lastTimeoutMs = options.timeoutMs ?? null; return {}; @@ -36,7 +36,7 @@ function makeBridge(): CapturingBridge { // The CapturingBridge `super({...})` will fail to open the native handle. // Build it without calling super by going through Object.create. const b = Object.create(CapturingBridge.prototype) as CapturingBridge; - (b as { lastResourceUri: string | null }).lastResourceUri = null; + (b as { lastResourceUra: string | null }).lastResourceUra = null; (b as { lastPayload: unknown }).lastPayload = null; (b as { lastTimeoutMs: number | null }).lastTimeoutMs = null; return b; @@ -45,19 +45,19 @@ function makeBridge(): CapturingBridge { describe("federation conformance vectors", () => { it("V1 advertise_agent minimal", () => { const b = makeBridge(); - b.federationAdvertiseAgent("t", "axon://realm/foo"); - assert.equal(b.lastResourceUri, "federation.advertise_agent"); - assert.deepEqual(b.lastPayload, { agent_uri: "axon://realm/foo" }); + b.federationAdvertiseAgent("t", "easynet:///r/realm/agent/foo"); + assert.equal(b.lastResourceUra, "federation.advertise_agent"); + assert.deepEqual(b.lastPayload, { agent_ura: "easynet:///r/realm/agent/foo" }); }); it("V2 advertise_agent full", () => { const b = makeBridge(); - b.federationAdvertiseAgent("t", "axon://realm/foo", { + b.federationAdvertiseAgent("t", "easynet:///r/realm/agent/foo", { publicKeyHex: "deadbeef", signingAuthority: { kind: "self_signed" }, }); assert.deepEqual(b.lastPayload, { - agent_uri: "axon://realm/foo", + agent_ura: "easynet:///r/realm/agent/foo", public_key_hex: "deadbeef", signing_authority: { kind: "self_signed" }, }); @@ -65,39 +65,39 @@ describe("federation conformance vectors", () => { it("V3 advertise_agent omits empty/blank", () => { const b = makeBridge(); - b.federationAdvertiseAgent("t", "axon://realm/foo", { + b.federationAdvertiseAgent("t", "easynet:///r/realm/agent/foo", { publicKeyHex: "", signingAuthority: {}, }); - assert.deepEqual(b.lastPayload, { agent_uri: "axon://realm/foo" }); + assert.deepEqual(b.lastPayload, { agent_ura: "easynet:///r/realm/agent/foo" }); }); it("V4 heartbeat empty body", () => { const b = makeBridge(); b.federationHeartbeat("t"); - assert.equal(b.lastResourceUri, "federation.heartbeat"); + assert.equal(b.lastResourceUra, "federation.heartbeat"); assert.deepEqual(b.lastPayload, {}); }); it("V5 revoke no reason", () => { const b = makeBridge(); - b.federationRevoke("t", "axon://realm/foo"); - assert.deepEqual(b.lastPayload, { agent_uri: "axon://realm/foo" }); + b.federationRevoke("t", "easynet:///r/realm/agent/foo"); + assert.deepEqual(b.lastPayload, { agent_ura: "easynet:///r/realm/agent/foo" }); }); it("V5b revoke blank reason omitted", () => { const b = makeBridge(); - b.federationRevoke("t", "axon://realm/foo", { reason: "" }); - assert.deepEqual(b.lastPayload, { agent_uri: "axon://realm/foo" }); + b.federationRevoke("t", "easynet:///r/realm/agent/foo", { reason: "" }); + assert.deepEqual(b.lastPayload, { agent_ura: "easynet:///r/realm/agent/foo" }); }); it("V6 revoke with reason", () => { const b = makeBridge(); - b.federationRevoke("t", "axon://realm/foo", { + b.federationRevoke("t", "easynet:///r/realm/agent/foo", { reason: "operator: maintenance", }); assert.deepEqual(b.lastPayload, { - agent_uri: "axon://realm/foo", + agent_ura: "easynet:///r/realm/agent/foo", reason: "operator: maintenance", }); }); @@ -105,19 +105,19 @@ describe("federation conformance vectors", () => { it("V7 resolve no filter", () => { const b = makeBridge(); b.federationResolve("t"); - assert.equal(b.lastResourceUri, "federation.resolve"); + assert.equal(b.lastResourceUra, "federation.resolve"); assert.deepEqual(b.lastPayload, {}); }); it("V8 resolve with filter", () => { const b = makeBridge(); b.federationResolve("t", { - agentUriPrefix: "axon://realm/edge-", + agentUriPrefix: "easynet:///r/realm/agent/edge-", includeAbilities: true, }); assert.deepEqual(b.lastPayload, { filter: { - agent_uri_prefix: "axon://realm/edge-", + agent_ura_prefix: "easynet:///r/realm/agent/edge-", include_abilities: true, }, }); @@ -125,9 +125,9 @@ describe("federation conformance vectors", () => { it("V9 advertise_abilities", () => { const b = makeBridge(); - b.federationAdvertiseAbilities("t", "axon://realm/foo", [{ name: "echo" }]); + b.federationAdvertiseAbilities("t", "easynet:///r/realm/agent/foo", [{ name: "echo" }]); assert.deepEqual(b.lastPayload, { - agent_uri: "axon://realm/foo", + agent_ura: "easynet:///r/realm/agent/foo", abilities: [{ name: "echo" }], }); }); @@ -135,7 +135,7 @@ describe("federation conformance vectors", () => { it("V10 join minimal", () => { const b = makeBridge(); b.federationJoin("t", "easynet", "deadbeef"); - assert.equal(b.lastResourceUri, "federation.join"); + assert.equal(b.lastResourceUra, "federation.join"); assert.deepEqual(b.lastPayload, { realm: "easynet", public_key_hex: "deadbeef" }); }); @@ -161,7 +161,7 @@ describe("federation conformance vectors", () => { it("other helpers default timeout is 30s", () => { const b = makeBridge(); - b.federationAdvertiseAgent("t", "axon://realm/foo"); + b.federationAdvertiseAgent("t", "easynet:///r/realm/agent/foo"); assert.equal(b.lastTimeoutMs, 30_000); }); }); diff --git a/sdk/node/src/index.ts b/sdk/node/src/index.ts index 87847469..938fc2e8 100644 --- a/sdk/node/src/index.ts +++ b/sdk/node/src/index.ts @@ -48,20 +48,20 @@ export interface ClientCallOptions { export interface Transport { call( tenantId: string, - resourceUri: string, + resourceUra: string, payload: JsonValue, options?: ClientCallOptions ): Promise; callRaw?( tenantId: string, - resourceUri: string, + resourceUra: string, payload: JsonValue, options?: ClientCallOptions ): Promise>; } -function visibilityFromResourceUri(resourceUri: string): "pub" | "org" | "prv" { - const normalized = resourceUri.trim().toLowerCase(); +function visibilityFromResourceUra(resourceUra: string): "pub" | "org" | "prv" { + const normalized = resourceUra.trim().toLowerCase(); if (normalized.startsWith("easynet:///r/pub/")) { return "pub"; } @@ -71,7 +71,7 @@ function visibilityFromResourceUri(resourceUri: string): "pub" | "org" | "prv" { return "org"; } -function principalToSubjectId(principalId: string, resourceUri: string): string { +function principalToSubjectId(principalId: string, resourceUra: string): string { const normalized = principalId.trim(); if (!normalized) { throw new AxonConfigError("principal(...) cannot be blank"); @@ -79,7 +79,7 @@ function principalToSubjectId(principalId: string, resourceUri: string): string if (normalized.startsWith("easynet:")) { return normalized; } - const visibility = visibilityFromResourceUri(resourceUri); + const visibility = visibilityFromResourceUra(resourceUra); return `easynet:${visibility}:reg:agent.${normalized}`; } @@ -124,14 +124,14 @@ export class SidecarTransport implements Transport { */ call( tenantId: string, - resourceUri: string, + resourceUra: string, payload: JsonValue, options: ClientCallOptions = {} ): Promise { const subjectId = options.principalId - ? principalToSubjectId(options.principalId, resourceUri) + ? principalToSubjectId(options.principalId, resourceUra) : undefined; - const raw = this.ensureBridge().abilityCallRaw(tenantId, resourceUri, payload, { + const raw = this.ensureBridge().abilityCallRaw(tenantId, resourceUra, payload, { timeoutMs: this.timeoutMs, subjectId, }); @@ -146,15 +146,15 @@ export class SidecarTransport implements Transport { */ callRaw( tenantId: string, - resourceUri: string, + resourceUra: string, payload: JsonValue, options: ClientCallOptions = {} ): Promise> { const subjectId = options.principalId - ? principalToSubjectId(options.principalId, resourceUri) + ? principalToSubjectId(options.principalId, resourceUra) : undefined; return Promise.resolve( - this.ensureBridge().abilityCallRaw(tenantId, resourceUri, payload, { + this.ensureBridge().abilityCallRaw(tenantId, resourceUra, payload, { timeoutMs: this.timeoutMs, subjectId, }) @@ -171,37 +171,37 @@ export class Client { constructor( private readonly transport: Transport = new SidecarTransport(), private readonly tenantId = "", - private readonly resourceUri = "", + private readonly resourceUra = "", private readonly principalId = "" ) { } tenant(tenantId: string): Client { - return new Client(this.transport, tenantId, this.resourceUri, this.principalId); + return new Client(this.transport, tenantId, this.resourceUra, this.principalId); } - ability(resourceUri: string): Client { - return new Client(this.transport, this.tenantId, resourceUri, this.principalId); + ability(resourceUra: string): Client { + return new Client(this.transport, this.tenantId, resourceUra, this.principalId); } principal(principalId: string): Client { - return new Client(this.transport, this.tenantId, this.resourceUri, principalId); + return new Client(this.transport, this.tenantId, this.resourceUra, principalId); } async call(payload: JsonValue): Promise { if (!this.tenantId) throw new AxonConfigError("tenant(...) is required before call(...)"); - if (!this.resourceUri) throw new AxonConfigError("ability(...) is required before call(...)"); - return this.transport.call(this.tenantId, this.resourceUri, payload, { + if (!this.resourceUra) throw new AxonConfigError("ability(...) is required before call(...)"); + return this.transport.call(this.tenantId, this.resourceUra, payload, { principalId: this.principalId || undefined, }); } async callRaw(payload: JsonValue): Promise> { if (!this.tenantId) throw new AxonConfigError("tenant(...) is required before callRaw(...)"); - if (!this.resourceUri) throw new AxonConfigError("ability(...) is required before callRaw(...)"); + if (!this.resourceUra) throw new AxonConfigError("ability(...) is required before callRaw(...)"); if (!this.transport.callRaw) { throw new AxonConfigError("configured transport does not support callRaw(...)"); } - return this.transport.callRaw(this.tenantId, this.resourceUri, payload, { + return this.transport.callRaw(this.tenantId, this.resourceUra, payload, { principalId: this.principalId || undefined, }); } diff --git a/sdk/node/src/invocation/admission.ts b/sdk/node/src/invocation/admission.ts index 3f7b7884..4593b27a 100644 --- a/sdk/node/src/invocation/admission.ts +++ b/sdk/node/src/invocation/admission.ts @@ -13,7 +13,7 @@ * being installed (Federated/Trusted mode). Without a resolver, * runs in Local-fast mode where identity is self-asserted. * 4. NonceReplayStore.checkAndRecord — always on. Dedup key is - * `(caller.uri, ability, invocation_nonce)`; `ability` guards + * `(caller.ura, ability, invocation_nonce)`; `ability` guards * against cross-ability false-positives per review. * * All rejections map to {@link AxonErrorKind.InvalidArgument} with one @@ -62,7 +62,7 @@ function rejectEnvelope(detail: string): AxonError { * * Checks applied (RFC 001 §5.2 step 1, strengthened per review): * - `ability` non-empty - * - `caller.uri` / `callee.uri` / `subject.uri` non-empty + * - `caller.ura` / `callee.ura` / `subject.ura` non-empty * - `invocationNonce` is not the all-zero sentinel (CSPRNG all-zero * has probability ≈ 2⁻¹²⁸; we reject as a probable * uninitialised-field mistake) @@ -70,9 +70,9 @@ function rejectEnvelope(detail: string): AxonError { */ export function validateEnvelope(env: InvocationEnvelope): void { if (!env.ability) throw rejectEnvelope("ability_empty"); - if (!env.caller.uri) throw rejectEnvelope("caller_uri_empty"); - if (!env.callee.uri) throw rejectEnvelope("callee_uri_empty"); - if (!env.subject.uri) throw rejectEnvelope("subject_uri_empty"); + if (!env.caller.ura) throw rejectEnvelope("caller_ura_empty"); + if (!env.callee.ura) throw rejectEnvelope("callee_ura_empty"); + if (!env.subject.ura) throw rejectEnvelope("subject_ura_empty"); if (env.argsDigest.length !== 32) throw rejectEnvelope("args_digest_wrong_length"); if (env.invocationNonce.length !== 16) throw rejectEnvelope("invocation_nonce_wrong_length"); let allZero = true; @@ -170,7 +170,7 @@ export class NonceReplayStore { } /** - * Register a `(caller.uri, ability, nonce)` observation as of + * Register a `(caller.ura, ability, nonce)` observation as of * `nowMs`. Throws {@link AxonError} with reason * {@link REASON_NONCE_REPLAY} on collision inside the current window. * Out-of-window entries are pruned before the check. @@ -179,7 +179,7 @@ export class NonceReplayStore { * unverified caller's nonce never enters the store. */ checkAndRecord( - callerUri: string, + callerUra: string, ability: string, nonce: Uint8Array, nowMs: number, @@ -190,7 +190,7 @@ export class NonceReplayStore { if (ts < cutoff) this.seen.delete(k); } // Hex-encoded tuple keeps the Map key strictly by value. - const key = `${callerUri}\x00${ability}\x00${Buffer.from(nonce).toString("hex")}`; + const key = `${callerUra}\x00${ability}\x00${Buffer.from(nonce).toString("hex")}`; const prev = this.seen.get(key); if (prev !== undefined && prev >= cutoff) { throw new AxonError({ @@ -234,7 +234,7 @@ export function runAdmission( if (resolver !== undefined) { verifySignature(env, sig, resolver); } - replay.checkAndRecord(env.caller.uri, env.ability, env.invocationNonce, nowMs); + replay.checkAndRecord(env.caller.ura, env.ability, env.invocationNonce, nowMs); } /** Wall-clock helper, milliseconds. Centralised for test substitution. */ diff --git a/sdk/node/src/invocation/axiom.ts b/sdk/node/src/invocation/axiom.ts index 65b4216a..f071106d 100644 --- a/sdk/node/src/invocation/axiom.ts +++ b/sdk/node/src/invocation/axiom.ts @@ -16,53 +16,53 @@ import { createHash, randomBytes, createPrivateKey, createPublicKey, sign as cry // ── Types ──────────────────────────────────────────────────────────── -export enum UriProfile { +export enum UraProfile { EasynetStrictV2 = "easynet-strict-v2", WebSafeV2 = "web-safe-v2", } const KNOWN_PROFILES: ReadonlySet = new Set([ - UriProfile.EasynetStrictV2, - UriProfile.WebSafeV2, + UraProfile.EasynetStrictV2, + UraProfile.WebSafeV2, ]); -export function parseProfile(s: string): UriProfile { +export function parseProfile(s: string): UraProfile { if (!KNOWN_PROFILES.has(s)) { - throw new Error(`unknown_uri_profile:${s}`); + throw new Error(`unknown_ura_profile:${s}`); } - return s as UriProfile; + return s as UraProfile; } export interface AgentIdentity { - readonly uri: string; - readonly profile: UriProfile; + readonly ura: string; + readonly profile: UraProfile; } export interface SubjectIdentity { - readonly uri: string; - readonly profile: UriProfile; + readonly ura: string; + readonly profile: UraProfile; } export function subjectFromCallee(callee: AgentIdentity): SubjectIdentity { - return { uri: callee.uri, profile: callee.profile }; + return { ura: callee.ura, profile: callee.profile }; } export interface ReceiptRef { readonly receiptHash: Buffer; // 32 bytes - readonly receiptUri: string; + readonly receiptUra: string; } export type CausalContext = | { readonly form: "none" } | { readonly form: "scalar"; readonly ref: ReceiptRef } | { readonly form: "list"; readonly prior: readonly ReceiptRef[] } - | { readonly form: "merkle"; readonly root: Buffer; readonly proofUri: string }; + | { readonly form: "merkle"; readonly root: Buffer; readonly proofUra: string }; export const CausalContext = { none: (): CausalContext => ({ form: "none" }), scalar: (ref: ReceiptRef): CausalContext => ({ form: "scalar", ref }), list: (prior: readonly ReceiptRef[]): CausalContext => ({ form: "list", prior }), - merkle: (root: Buffer, proofUri: string): CausalContext => ({ form: "merkle", root, proofUri }), + merkle: (root: Buffer, proofUra: string): CausalContext => ({ form: "merkle", root, proofUra }), }; export interface InvocationEnvelope { @@ -139,8 +139,8 @@ function putBytes(b: Buffer): Buffer { return Buffer.concat([putU32Be(b.length), b]); } -function putIdentityUriProfile(uri: string, profile: UriProfile): Buffer { - return Buffer.concat([putStr(uri), putStr(profile)]); +function putIdentityUraProfile(ura: string, profile: UraProfile): Buffer { + return Buffer.concat([putStr(ura), putStr(profile)]); } export function canonicalCausalContext(ctx: CausalContext): Buffer { @@ -152,7 +152,7 @@ export function canonicalCausalContext(ctx: CausalContext): Buffer { if (r.receiptHash.length !== 32) { throw new Error(`receipt_hash_wrong_length:${r.receiptHash.length}`); } - return Buffer.concat([Buffer.from([0x01]), r.receiptHash, putStr(r.receiptUri)]); + return Buffer.concat([Buffer.from([0x01]), r.receiptHash, putStr(r.receiptUra)]); } case "list": { const parts: Buffer[] = [Buffer.from([0x02]), putU32Be(ctx.prior.length)]; @@ -160,7 +160,7 @@ export function canonicalCausalContext(ctx: CausalContext): Buffer { if (r.receiptHash.length !== 32) { throw new Error(`receipt_hash_wrong_length:${r.receiptHash.length}`); } - parts.push(r.receiptHash, putStr(r.receiptUri)); + parts.push(r.receiptHash, putStr(r.receiptUra)); } return Buffer.concat(parts); } @@ -168,7 +168,7 @@ export function canonicalCausalContext(ctx: CausalContext): Buffer { if (ctx.root.length !== 32) { throw new Error(`merkle_root_wrong_length:${ctx.root.length}`); } - return Buffer.concat([Buffer.from([0x03]), ctx.root, putStr(ctx.proofUri)]); + return Buffer.concat([Buffer.from([0x03]), ctx.root, putStr(ctx.proofUra)]); } } } @@ -182,9 +182,9 @@ export function canonicalInvocationBytes(env: InvocationEnvelope): Buffer { } const causal = canonicalCausalContext(env.causalContext); return Buffer.concat([ - putIdentityUriProfile(env.caller.uri, env.caller.profile), - putIdentityUriProfile(env.callee.uri, env.callee.profile), - putIdentityUriProfile(env.subject.uri, env.subject.profile), + putIdentityUraProfile(env.caller.ura, env.caller.profile), + putIdentityUraProfile(env.callee.ura, env.callee.profile), + putIdentityUraProfile(env.subject.ura, env.subject.profile), putStr(env.ability), env.argsDigest, env.invocationNonce, @@ -210,9 +210,9 @@ export function canonicalReceiptBytes(r: ReceiptBody): Buffer { putStr(r.state), putI64Be(r.timestampUnixMs), r.prevReceiptHash, - putIdentityUriProfile(r.callerBinding.uri, r.callerBinding.profile), - putIdentityUriProfile(r.calleeBinding.uri, r.calleeBinding.profile), - putIdentityUriProfile(r.subjectBinding.uri, r.subjectBinding.profile), + putIdentityUraProfile(r.callerBinding.ura, r.callerBinding.profile), + putIdentityUraProfile(r.calleeBinding.ura, r.calleeBinding.profile), + putIdentityUraProfile(r.subjectBinding.ura, r.subjectBinding.profile), r.invocationNonce, putBytes(causal), r.payloadDigest, @@ -280,7 +280,7 @@ export function publicKeyFromSeed(seed: Buffer): Buffer { } export interface KeyResolver { - resolve(agentUri: string): Buffer; // raw 32-byte public key + resolve(agentUra: string): Buffer; // raw 32-byte public key } export function signInvocation( @@ -305,7 +305,7 @@ export function verifyInvocationSignature( if (sig.signature.length !== 64) { throw new Error(`signature_wrong_length:expected_64_got_${sig.signature.length}`); } - const raw = resolver.resolve(env.caller.uri); + const raw = resolver.resolve(env.caller.ura); const pk = ed25519PublicKeyFromRaw(raw); const bytes = canonicalInvocationBytes(env); const ok = cryptoVerify(null, bytes, pk, sig.signature); @@ -336,7 +336,7 @@ export function verifyReceiptSignature( if (sig.signature.length !== 64) { throw new Error(`signature_wrong_length:expected_64_got_${sig.signature.length}`); } - const raw = resolver.resolve(r.calleeBinding.uri); + const raw = resolver.resolve(r.calleeBinding.ura); const pk = ed25519PublicKeyFromRaw(raw); const bytes = canonicalReceiptBytes(r); const ok = cryptoVerify(null, bytes, pk, sig.signature); diff --git a/sdk/node/src/invocation/bundle.ts b/sdk/node/src/invocation/bundle.ts index c4c6fb58..a8c598cf 100644 --- a/sdk/node/src/invocation/bundle.ts +++ b/sdk/node/src/invocation/bundle.ts @@ -17,34 +17,34 @@ import { type ReceiptBody, type ReceiptRef, type SubjectIdentity, - UriProfile, + UraProfile, parseProfile, } from "./axiom.js"; // ── Identity JSON ──────────────────────────────────────────────────── export interface IdentityJSON { - uri: string; + ura: string; profile: string; } export const identityFromAgent = (a: AgentIdentity): IdentityJSON => ({ - uri: a.uri, + ura: a.ura, profile: a.profile, }); export const identityFromSubject = (s: SubjectIdentity): IdentityJSON => ({ - uri: s.uri, + ura: s.ura, profile: s.profile, }); export const identityToAgent = (d: IdentityJSON): AgentIdentity => ({ - uri: d.uri, + ura: d.ura, profile: parseProfile(d.profile), }); export const identityToSubject = (d: IdentityJSON): SubjectIdentity => ({ - uri: d.uri, + ura: d.ura, profile: parseProfile(d.profile), }); @@ -52,9 +52,9 @@ export const identityToSubject = (d: IdentityJSON): SubjectIdentity => ({ export type CausalJSON = | { form: "none" } - | { form: "scalar"; receipt_hash_hex: string; receipt_uri: string } - | { form: "list"; prior: Array<{ receipt_hash_hex: string; receipt_uri: string }> } - | { form: "merkle"; root_hex: string; proof_uri: string }; + | { form: "scalar"; receipt_hash_hex: string; receipt_ura: string } + | { form: "list"; prior: Array<{ receipt_hash_hex: string; receipt_ura: string }> } + | { form: "merkle"; root_hex: string; proof_ura: string }; export function causalToJson(c: CausalContext): CausalJSON { switch (c.form) { @@ -64,21 +64,21 @@ export function causalToJson(c: CausalContext): CausalJSON { return { form: "scalar", receipt_hash_hex: Buffer.from(c.ref.receiptHash).toString("hex"), - receipt_uri: c.ref.receiptUri, + receipt_ura: c.ref.receiptUra, }; case "list": return { form: "list", prior: c.prior.map((r) => ({ receipt_hash_hex: Buffer.from(r.receiptHash).toString("hex"), - receipt_uri: r.receiptUri, + receipt_ura: r.receiptUra, })), }; case "merkle": return { form: "merkle", root_hex: Buffer.from(c.root).toString("hex"), - proof_uri: c.proofUri, + proof_ura: c.proofUra, }; } } @@ -92,7 +92,7 @@ export function causalFromJson(d: CausalJSON): CausalContext { form: "scalar", ref: { receiptHash: Buffer.from(d.receipt_hash_hex, "hex"), - receiptUri: d.receipt_uri, + receiptUra: d.receipt_ura, }, }; case "list": @@ -100,14 +100,14 @@ export function causalFromJson(d: CausalJSON): CausalContext { form: "list", prior: d.prior.map((p) => ({ receiptHash: Buffer.from(p.receipt_hash_hex, "hex"), - receiptUri: p.receipt_uri, + receiptUra: p.receipt_ura, })), }; case "merkle": return { form: "merkle", root: Buffer.from(d.root_hex, "hex"), - proofUri: d.proof_uri, + proofUra: d.proof_ura, }; } } diff --git a/sdk/node/src/invocation/local-runtime.ts b/sdk/node/src/invocation/local-runtime.ts index 8ea74c9e..d985d25c 100644 --- a/sdk/node/src/invocation/local-runtime.ts +++ b/sdk/node/src/invocation/local-runtime.ts @@ -12,7 +12,7 @@ import { type KeyResolver, type SubjectIdentity, CausalContext as CausalContextNS, - UriProfile, + UraProfile, canonicalInvocationBytes, freshNonce, sha256, @@ -425,18 +425,18 @@ export class LocalRuntime { } /** - * Well-known local-runtime SystemAgent URI used when no caller identity + * Well-known local-runtime SystemAgent URA used when no caller identity * is provided. AXIOM.tex §3.2 permits this: infrastructure-initiated * invocations carry a SystemAgent identity and are still axiom-bound. */ const SYSTEM_URI = "easynet:///r/_system/agents/local@1"; function systemLocalBinding(payload: Uint8Array): AxiomBinding { - const system: AgentIdentity = { uri: SYSTEM_URI, profile: UriProfile.EasynetStrictV2 }; + const system: AgentIdentity = { ura: SYSTEM_URI, profile: UraProfile.EasynetStrictV2 }; return { caller: system, callee: system, - subject: { uri: SYSTEM_URI, profile: UriProfile.EasynetStrictV2 }, + subject: { ura: SYSTEM_URI, profile: UraProfile.EasynetStrictV2 }, invocationNonce: freshNonce(), causal: CausalContextNS.none(), payloadDigest: Buffer.from(sha256(Buffer.from(payload))), diff --git a/sdk/node/src/presets/ability_dispatch/orchestrator.ts b/sdk/node/src/presets/ability_dispatch/orchestrator.ts index 50112812..db569a58 100644 --- a/sdk/node/src/presets/ability_dispatch/orchestrator.ts +++ b/sdk/node/src/presets/ability_dispatch/orchestrator.ts @@ -84,7 +84,7 @@ export class Orchestrator { sendA2ATask(nodeId: string, skillId: string, inputJson: Json): Json { // RFC-001 §A1 removed `send_a2a_task`; A2A tasks are now ordinary // Invoke calls against the resolved agent's ability id. `nodeId` is - // the canonical agent_uri and `skillId` is the ability id. + // the canonical agent_ura and `skillId` is the ability id. return this.bridge.abilityCallRaw(this.tenant, skillId, inputJson, { subjectId: nodeId, }) as Json; diff --git a/sdk/node/src/presets/remote_control/descriptor.ts b/sdk/node/src/presets/remote_control/descriptor.ts index cdab2cf1..259ab9e1 100644 --- a/sdk/node/src/presets/remote_control/descriptor.ts +++ b/sdk/node/src/presets/remote_control/descriptor.ts @@ -40,7 +40,7 @@ export interface AbilityDescriptorLite { outputSchema: JsonRecord; version: string; tags: string[]; - resourceUri: string; + resourceUra: string; instructions: string; inputExamples: JsonRecord[]; prerequisites: string[]; @@ -353,7 +353,7 @@ export function createAbilityDescriptor(args: JsonRecord): AbilityDescriptorLite : { type: "object", properties: {} }, version: asString(args.version) || "1.0.0", tags: asStringArray(args.tags), - resourceUri: asString(args.resource_uri) || `easynet:///r/org/${token}`, + resourceUra: asString(args.resource_ura) || `easynet:///r/org/${token}`, instructions: asString(args.instructions), inputExamples, prerequisites, @@ -377,26 +377,26 @@ function sanitizeShellValue(value: string, label: string): string { return value; } -function generateExportInvokeScript(resourceUri: string, endpoint: string): string { +function generateExportInvokeScript(resourceUra: string, endpoint: string): string { const safeEndpoint = sanitizeShellValue(endpoint, "endpoint"); - const safeUri = sanitizeShellValue(resourceUri, "resource_uri"); + const safeUra = sanitizeShellValue(resourceUra, "resource_ura"); return `#!/usr/bin/env bash set -euo pipefail AXON_ENDPOINT="\${AXON_ENDPOINT:-${safeEndpoint}}" TENANT="\${AXON_TENANT:-default}" -RESOURCE_URI="${safeUri}" +RESOURCE_URA="${safeUra}" ARGS="\${1:-{}}" curl -sS -X POST "\${AXON_ENDPOINT}/v1/invoke" \\ -H "Content-Type: application/json" \\ - -d "{\\"tenant_id\\":\\"\${TENANT}\\",\\"resource_uri\\":\\"\${RESOURCE_URI}\\",\\"payload\\":\${ARGS}}" + -d "{\\"tenant_id\\":\\"\${TENANT}\\",\\"resource_ura\\":\\"\${RESOURCE_URA}\\",\\"payload\\":\${ARGS}}" `; } -function pushSkillMetadata(lines: string[], version: string, resourceUri: string): void { +function pushSkillMetadata(lines: string[], version: string, resourceUra: string): void { lines.push("metadata:"); lines.push(" author: easynet-axon"); lines.push(` version: "${version}"`); - lines.push(` axon-resource-uri: "${resourceUri}"`); + lines.push(` axon-resource-ura: "${resourceUra}"`); } function generateExportAbilityMd(descriptor: AbilityDescriptorLite, target: AbilityTarget, token: string): string { @@ -406,7 +406,7 @@ function generateExportAbilityMd(descriptor: AbilityDescriptorLite, target: Abil lines.push(`description: ${descriptor.description}`); lines.push("compatibility: Requires network access to Axon runtime"); - pushSkillMetadata(lines, descriptor.version, descriptor.resourceUri); + pushSkillMetadata(lines, descriptor.version, descriptor.resourceUra); if (target === "claude") { lines.push("allowed-tools: Bash(*)"); } else if (target === "openclaw") { @@ -503,7 +503,7 @@ function generateExportAbilityMd(descriptor: AbilityDescriptorLite, target: Abil // Axon Resource footer lines.push("## Axon Resource"); lines.push(""); - lines.push(`- **URI**: \`${descriptor.resourceUri}\``); + lines.push(`- **URA**: \`${descriptor.resourceUra}\``); lines.push(`- **Version**: ${descriptor.version}`); if (descriptor.category) { lines.push(`- **Category**: ${descriptor.category}`); @@ -528,7 +528,7 @@ export function exportAbilitySkill( ): AbilityExportResult { const token = descriptor.toolName; const endpoint = axonEndpoint ?? `http://127.0.0.1:${DEFAULT_AXON_PORT}`; - const invokeScript = generateExportInvokeScript(descriptor.resourceUri, endpoint); + const invokeScript = generateExportInvokeScript(descriptor.resourceUra, endpoint); const abilityMd = generateExportAbilityMd(descriptor, target, token); return { abilityMd, invokeScript, abilityName: token }; } diff --git a/sdk/node/src/tool_adapter.ts b/sdk/node/src/tool_adapter.ts index 0fb98f40..371ddb75 100644 --- a/sdk/node/src/tool_adapter.ts +++ b/sdk/node/src/tool_adapter.ts @@ -41,7 +41,7 @@ export interface ToolParameters { export interface ToolSpec { name: string; description: string; - resourceUri: string; + resourceUra: string; parameters: ToolParameters; } @@ -70,7 +70,7 @@ export interface AnthropicTool { export interface ToolDict { name: string; description: string; - resource_uri: string; + resource_ura: string; parameters: ToolParameters; } @@ -106,7 +106,7 @@ function specToDict(spec: ToolSpec): ToolDict { return { name: spec.name, description: spec.description, - resource_uri: spec.resourceUri, + resource_ura: spec.resourceUra, parameters: spec.parameters, }; } @@ -119,7 +119,7 @@ export type LocalHandler = (args: Record) => JsonValue | Prom export interface RegisterOptions { description?: string; - resourceUri?: string; + resourceUra?: string; parameters?: ToolParameters; } @@ -151,7 +151,7 @@ export class AbilityToolAdapter { const spec: ToolSpec = { name, description: options.description ?? "", - resourceUri: options.resourceUri ?? `easynet:///r/org/${name}`, + resourceUra: options.resourceUra ?? `easynet:///r/org/${name}`, parameters: options.parameters ?? { type: "object", properties: {} }, }; this._specs.set(name, spec); @@ -164,13 +164,13 @@ export class AbilityToolAdapter { */ registerAbility( name: string, - resourceUri: string, + resourceUra: string, options: { description?: string; parameters?: ToolParameters } = {} ): this { const spec: ToolSpec = { name, description: options.description ?? "", - resourceUri, + resourceUra, parameters: options.parameters ?? { type: "object", properties: {} }, }; this._specs.set(name, spec); @@ -238,7 +238,7 @@ export class AbilityToolAdapter { const client = new Client( transport, this.tenantId, - spec.resourceUri, + spec.resourceUra, this.principalId ?? "" ); return client.call(parsed as JsonValue); diff --git a/sdk/node/tests/admission.test.mjs b/sdk/node/tests/admission.test.mjs index a1c50e09..5af51369 100644 --- a/sdk/node/tests/admission.test.mjs +++ b/sdk/node/tests/admission.test.mjs @@ -25,8 +25,8 @@ import { } from "../src/invocation/admission.js"; import { LocalRuntime } from "../src/invocation/local-runtime.js"; -const silan = { uri: "easynet:///r/silan/agents/t@1", profile: "easynet-strict-v2" }; -const openai = { uri: "easynet:///r/openai/agents/t@1", profile: "easynet-strict-v2" }; +const silan = { ura: "easynet:///r/silan/agents/t@1", profile: "easynet-strict-v2" }; +const openai = { ura: "easynet:///r/openai/agents/t@1", profile: "easynet-strict-v2" }; function echoRuntime() { const rt = new LocalRuntime(); @@ -43,7 +43,7 @@ function sampleEnv() { return { caller: silan, callee: openai, - subject: { uri: "easynet:///r/silan/papers/p@d1", profile: "easynet-strict-v2" }, + subject: { ura: "easynet:///r/silan/papers/p@d1", profile: "easynet-strict-v2" }, ability: "echo", argsDigest: sha256(Buffer.alloc(0)), invocationNonce: Buffer.alloc(16, 0x11), @@ -196,7 +196,7 @@ test("run_admission Federated rejects wrong key", () => { }); test("run_admission rejects envelope before replay store", () => { - const env = { ...sampleEnv(), caller: { ...silan, uri: "" } }; + const env = { ...sampleEnv(), caller: { ...silan, ura: "" } }; const { sig } = sampleSig(env); const s = new NonceReplayStore(); try { diff --git a/sdk/node/tests/axiom-vectors.test.mjs b/sdk/node/tests/axiom-vectors.test.mjs index ab80b614..508f3acd 100644 --- a/sdk/node/tests/axiom-vectors.test.mjs +++ b/sdk/node/tests/axiom-vectors.test.mjs @@ -44,19 +44,19 @@ function causalFromJson(d) { case "scalar": return CausalContext.scalar({ receiptHash: Buffer.from(d.receipt_hash_hex, "hex"), - receiptUri: d.receipt_uri, + receiptUra: d.receipt_ura, }); case "list": return CausalContext.list( d.prior.map((p) => ({ receiptHash: Buffer.from(p.receipt_hash_hex, "hex"), - receiptUri: p.receipt_uri, + receiptUra: p.receipt_ura, })), ); case "merkle": return CausalContext.merkle( Buffer.from(d.root_hex, "hex"), - d.proof_uri, + d.proof_ura, ); default: throw new Error(`unknown_form:${d.form}`); @@ -65,9 +65,9 @@ function causalFromJson(d) { function envFrom(inp) { return { - caller: { uri: inp.caller.uri, profile: parseProfile(inp.caller.profile) }, - callee: { uri: inp.callee.uri, profile: parseProfile(inp.callee.profile) }, - subject: { uri: inp.subject.uri, profile: parseProfile(inp.subject.profile) }, + caller: { ura: inp.caller.ura, profile: parseProfile(inp.caller.profile) }, + callee: { ura: inp.callee.ura, profile: parseProfile(inp.callee.profile) }, + subject: { ura: inp.subject.ura, profile: parseProfile(inp.subject.profile) }, ability: inp.ability, argsDigest: Buffer.from(inp.args_digest_hex, "hex"), invocationNonce: Buffer.from(inp.invocation_nonce_hex, "hex"), @@ -143,7 +143,7 @@ function runE3(v) { function runE4(v) { const env = envFrom(v.inputs); - assert.notStrictEqual(env.callee.uri, env.subject.uri); + assert.notStrictEqual(env.callee.ura, env.subject.ura); const seed = Buffer.from(v.inputs.caller_secret_hex, "hex"); const sig = signInvocation(seed, env, ""); verifyInvocationSignature(env, sig, new FixedResolver(publicKeyFromSeed(seed))); @@ -185,7 +185,7 @@ function runProfileBinding(v) { const swap = v.inputs.profile_swap_on_verify.caller; const tampered = { ...env, - caller: { uri: env.caller.uri, profile: parseProfile(swap) }, + caller: { ura: env.caller.ura, profile: parseProfile(swap) }, }; assert.throws( () => verifyInvocationSignature(tampered, sig, new FixedResolver(pub)), @@ -196,9 +196,9 @@ function runProfileBinding(v) { function runSubjectSurvives(v) { const a = envFrom(v.inputs_a); const b = envFrom(v.inputs_b); - assert.strictEqual(a.subject.uri, b.subject.uri); + assert.strictEqual(a.subject.ura, b.subject.ura); assert.strictEqual(a.subject.profile, b.subject.profile); - assert.notStrictEqual(a.callee.uri, b.callee.uri); + assert.notStrictEqual(a.callee.ura, b.callee.ura); assert.notDeepStrictEqual( canonicalInvocationBytes(a), canonicalInvocationBytes(b), diff --git a/sdk/node/tests/axiom-worked-example.test.mjs b/sdk/node/tests/axiom-worked-example.test.mjs index 41de3d68..d2efa5f0 100644 --- a/sdk/node/tests/axiom-worked-example.test.mjs +++ b/sdk/node/tests/axiom-worked-example.test.mjs @@ -233,15 +233,15 @@ function buildEnvelope(inputs) { return { caller: { - uri: requireString(caller, "uri", { field: "inputs.caller" }), + ura: requireString(caller, "ura", { field: "inputs.caller" }), profile: parseProfile(requireString(caller, "profile", { field: "inputs.caller" })), }, callee: { - uri: requireString(callee, "uri", { field: "inputs.callee" }), + ura: requireString(callee, "ura", { field: "inputs.callee" }), profile: parseProfile(requireString(callee, "profile", { field: "inputs.callee" })), }, subject: { - uri: requireString(subject, "uri", { field: "inputs.subject" }), + ura: requireString(subject, "ura", { field: "inputs.subject" }), profile: parseProfile(requireString(subject, "profile", { field: "inputs.subject" })), }, ability, diff --git a/sdk/node/tests/cross-language-verify.test.mjs b/sdk/node/tests/cross-language-verify.test.mjs index 57dc71e4..0357bc15 100644 --- a/sdk/node/tests/cross-language-verify.test.mjs +++ b/sdk/node/tests/cross-language-verify.test.mjs @@ -116,15 +116,15 @@ function buildBundle(bundle) { writeKey(bundle, "openai", openaiSeed); const silan = { - uri: "easynet:///r/silan/agents/writer@1", + ura: "easynet:///r/silan/agents/writer@1", profile: "easynet-strict-v2", }; const openai = { - uri: "easynet:///r/openai/agents/reviewer@1", + ura: "easynet:///r/openai/agents/reviewer@1", profile: "easynet-strict-v2", }; const paper = { - uri: "easynet:///r/silan/papers/p@draft-1", + ura: "easynet:///r/silan/papers/p@draft-1", profile: "easynet-strict-v2", }; @@ -154,7 +154,7 @@ function buildBundle(bundle) { invocationNonce: Buffer.alloc(16, 0xbb), causalContext: CausalContext.scalar({ receiptHash: aTerminalHash, - receiptUri: "bundle:///receipts/inv-a/1", + receiptUra: "bundle:///receipts/inv-a/1", }), }; emitTwoReceiptChain(bundle, "inv-b", envB, silanSeed, openaiSeed); diff --git a/sdk/node/tests/invoke-signed.test.mjs b/sdk/node/tests/invoke-signed.test.mjs index b194f9fa..edcdbf93 100644 --- a/sdk/node/tests/invoke-signed.test.mjs +++ b/sdk/node/tests/invoke-signed.test.mjs @@ -13,8 +13,8 @@ import { } from "../src/invocation/axiom.js"; import { LocalRuntime } from "../src/invocation/local-runtime.js"; -const silan = { uri: "easynet:///r/silan/agents/t@1", profile: "easynet-strict-v2" }; -const openai = { uri: "easynet:///r/openai/agents/t@1", profile: "easynet-strict-v2" }; +const silan = { ura: "easynet:///r/silan/agents/t@1", profile: "easynet-strict-v2" }; +const openai = { ura: "easynet:///r/openai/agents/t@1", profile: "easynet-strict-v2" }; function echoRuntime() { const rt = new LocalRuntime(); @@ -30,7 +30,7 @@ class FixedResolver { test("invokeSignedAsync — explicit subject + nonce verifies under the same seed", async () => { const rt = echoRuntime(); const seed = Buffer.alloc(32, 0x07); - const subject = { uri: "easynet:///r/silan/papers/p@d1", profile: "easynet-strict-v2" }; + const subject = { ura: "easynet:///r/silan/papers/p@d1", profile: "easynet-strict-v2" }; const nonce = Buffer.alloc(16, 0xab); const { handle, signed } = await rt.invokeSignedAsync({ caller: silan, @@ -45,7 +45,7 @@ test("invokeSignedAsync — explicit subject + nonce verifies under the same see const stored = rt.axiomEnvelopeOf(handle.invocationId); assert.ok(stored, "envelope stored"); - assert.strictEqual(stored.envelope.subject.uri, subject.uri); + assert.strictEqual(stored.envelope.subject.ura, subject.ura); assert.deepStrictEqual(Buffer.from(stored.envelope.invocationNonce), nonce); const pub = publicKeyFromSeed(seed); @@ -68,7 +68,7 @@ test("invokeSignedAsync — subject defaults to callee when undefined", async () signingSeed: Buffer.alloc(32, 0x08), nonce: Buffer.alloc(16, 0x11), }); - assert.strictEqual(signed.envelope.subject.uri, signed.envelope.callee.uri); + assert.strictEqual(signed.envelope.subject.ura, signed.envelope.callee.ura); assert.strictEqual(signed.envelope.subject.profile, signed.envelope.callee.profile); }); @@ -136,14 +136,14 @@ test("payload enters args_digest (two payloads → two signatures)", async () => test("tampered subject breaks verification", async () => { const rt = echoRuntime(); const seed = Buffer.alloc(32, 0x15); - const subject = { uri: "easynet:///r/silan/papers/p@1", profile: "easynet-strict-v2" }; + const subject = { ura: "easynet:///r/silan/papers/p@1", profile: "easynet-strict-v2" }; const { signed } = await rt.invokeSignedAsync({ caller: silan, callee: openai, ability: "echo", payload: Buffer.alloc(0), signingSeed: seed, subject, nonce: Buffer.alloc(16, 0x11), }); const tampered = { ...signed.envelope, - subject: { uri: "easynet:///r/mallory/papers/evil@1", profile: "easynet-strict-v2" }, + subject: { ura: "easynet:///r/mallory/papers/evil@1", profile: "easynet-strict-v2" }, }; const pub = publicKeyFromSeed(seed); assert.throws( @@ -163,7 +163,7 @@ test("tampered causal_context breaks verification", async () => { ...signed.envelope, causalContext: CausalContext.scalar({ receiptHash: Buffer.alloc(32, 0x99), - receiptUri: "evil", + receiptUra: "evil", }), }; const pub = publicKeyFromSeed(seed); @@ -192,7 +192,7 @@ test("stored envelope canonical bytes are stable", async () => { const rt = echoRuntime(); const seed = Buffer.alloc(32, 0x19); const subject = { - uri: "easynet:///r/silan/papers/p@stable", + ura: "easynet:///r/silan/papers/p@stable", profile: "easynet-strict-v2", }; const { handle, signed } = await rt.invokeSignedAsync({ diff --git a/sdk/python/easynet_axon/ability.py b/sdk/python/easynet_axon/ability.py index bfd22496..201c6caa 100644 --- a/sdk/python/easynet_axon/ability.py +++ b/sdk/python/easynet_axon/ability.py @@ -33,11 +33,11 @@ _ABILITY_REGISTRY: dict[str, Callable[..., Any]] = {} -def ability(resource_uri: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]: +def ability(resource_ura: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]: """Decorator-style ability registration for Python MVP surface.""" def wrapper(fn: Callable[..., Any]) -> Callable[..., Any]: - _ABILITY_REGISTRY[resource_uri] = fn + _ABILITY_REGISTRY[resource_ura] = fn return fn return wrapper diff --git a/sdk/python/easynet_axon/ability_lifecycle.py b/sdk/python/easynet_axon/ability_lifecycle.py index 784a859e..f6d0b8c3 100644 --- a/sdk/python/easynet_axon/ability_lifecycle.py +++ b/sdk/python/easynet_axon/ability_lifecycle.py @@ -6,7 +6,7 @@ # # Protocol Responsibility: # - Defines typed ability descriptors, export targets, and deployment helpers exposed to SDK users. -# - Keeps cross-language ability naming, resource-uri, and tool-spec semantics aligned. +# - Keeps cross-language ability naming, resource-ura, and tool-spec semantics aligned. # # Implementation Approach: # - Separates pure descriptor/export helpers from bridge-backed deployment and invocation flows. @@ -55,7 +55,7 @@ class BridgeProtocol(Protocol): def deploy_ability_package(self, tenant: str, node_id: str, args: dict) -> dict: ... def uninstall_ability_with_reason(self, tenant: str, node_id: str, install_id: str, reason: str) -> dict: ... def list_nodes(self, tenant: str, owner_id: Optional[str]) -> list: ... - def federation_revoke(self, tenant: str, agent_uri: str, *, reason: Optional[str] = None) -> dict: ... + def federation_revoke(self, tenant: str, agent_ura: str, *, reason: Optional[str] = None) -> dict: ... def _normalize_ability_name(raw: str) -> str: @@ -97,7 +97,7 @@ class AbilityDescriptor: output_schema: Dict[str, Any] = field(default_factory=lambda: {"type": "object", "properties": {}}) version: str = "1.0.0" tags: List[str] = field(default_factory=list) - resource_uri: str = "" + resource_ura: str = "" # Agent ecosystem extensions (SKILL.md / MCP / CLI) instructions: str = "" input_examples: List[Any] = field(default_factory=list) @@ -123,14 +123,14 @@ def __post_init__(self): if not self.command_template or not self.command_template.strip(): raise AxonConfigError("command_template cannot be empty") self.tool_name = _normalize_ability_name(self.name) - if not self.resource_uri: - self.resource_uri = f"easynet:///r/org/{self.tool_name}" + if not self.resource_ura: + self.resource_ura = f"easynet:///r/org/{self.tool_name}" def to_tool_spec(self) -> Dict[str, Any]: return { "name": self.tool_name, "description": self.description, - "resource_uri": self.resource_uri, + "resource_ura": self.resource_ura, "parameters": self.input_schema, "read_only_hint": self.read_only, "destructive_hint": self.destructive, @@ -411,7 +411,7 @@ def build_ability_descriptor( output_schema: Optional[Dict[str, Any]] = None, version: Optional[str] = None, tags: Optional[List[str]] = None, - resource_uri: Optional[str] = None, + resource_ura: Optional[str] = None, instructions: Optional[str] = None, input_examples: Optional[List[Any]] = None, prerequisites: Optional[List[str]] = None, @@ -441,8 +441,8 @@ def build_ability_descriptor( kwargs["version"] = version if tags is not None: kwargs["tags"] = tags - if resource_uri is not None: - kwargs["resource_uri"] = resource_uri + if resource_ura is not None: + kwargs["resource_ura"] = resource_ura if instructions is not None: kwargs["instructions"] = instructions if input_examples is not None: @@ -479,7 +479,7 @@ def export_ability( ) -> AbilityExportResult: token = descriptor.tool_name endpoint = axon_endpoint or f"http://127.0.0.1:{DEFAULT_AXON_PORT}" - invoke_script = _generate_invoke_script(descriptor.resource_uri, endpoint) + invoke_script = _generate_invoke_script(descriptor.resource_ura, endpoint) ability_md = _generate_ability_md(descriptor, target, token) return AbilityExportResult( ability_md=ability_md, @@ -573,7 +573,7 @@ def deploy_to_node( # Per-device ability catalog (`list_abilities`) and tool-name-keyed # invocation (`invoke_ability`) were removed by RFC-001 §A1 — the # directory is now federation-scoped (`federation.resolve`) and -# invocation is target-typed (`Invoke(callee=, ability=...)`) +# invocation is target-typed (`Invoke(callee=, ability=...)`) # rather than node-id + tool-name. Use `bridge.federation_resolve(...)` # and `bridge.ability_call_raw(...)` directly. @@ -608,7 +608,7 @@ def discover_nodes( # # 1. `bridge.federation_resolve(tenant, include_abilities=True)` to get # the directory snapshot of agents and their advertised abilities. -# 2. `bridge.ability_call_raw(tenant, resource_uri="", ...)` +# 2. `bridge.ability_call_raw(tenant, resource_ura="", ...)` # to invoke a specific ability by id. # # A whole-device "forget all abilities" sweep is no longer the SDK's @@ -620,24 +620,24 @@ def discover_nodes( def disconnect_device( bridge: BridgeProtocol, tenant: str, - agent_uri: str, + agent_ura: str, reason: Optional[str] = None, ) -> Dict[str, Any]: """Withdraw an agent from the realm directory. RFC-001 §A1 collapsed `deregister_node` and `drain_node` into a single `federation.revoke` ability. The previous ``node_id`` parameter is now - interpreted as the canonical ``agent_uri``. + interpreted as the canonical ``agent_ura``. """ return bridge.federation_revoke( - tenant, agent_uri, reason=reason or "sdk: disconnect_device" + tenant, agent_ura, reason=reason or "sdk: disconnect_device" ) def drain_device( bridge: BridgeProtocol, tenant: str, - agent_uri: str, + agent_ura: str, reason: Optional[str] = None, ) -> Dict[str, Any]: """Alias of `disconnect_device` retained for caller continuity. @@ -645,7 +645,7 @@ def drain_device( Drain-then-deregister is no longer expressible as two distinct verbs; both surface through `federation.revoke`. """ - return disconnect_device(bridge, tenant, agent_uri, reason or "sdk: drain_device") + return disconnect_device(bridge, tenant, agent_ura, reason or "sdk: drain_device") def build_deploy_package( @@ -676,27 +676,27 @@ def _sanitize_shell_value(value: str, label: str) -> str: return value -def _generate_invoke_script(resource_uri: str, endpoint: str) -> str: +def _generate_invoke_script(resource_ura: str, endpoint: str) -> str: safe_ep = _sanitize_shell_value(endpoint, "endpoint") - safe_uri = _sanitize_shell_value(resource_uri, "resource_uri") + safe_uri = _sanitize_shell_value(resource_ura, "resource_ura") return f"""#!/usr/bin/env bash set -euo pipefail AXON_ENDPOINT="${{AXON_ENDPOINT:-{safe_ep}}}" TENANT="${{AXON_TENANT:-default}}" -RESOURCE_URI="{safe_uri}" +RESOURCE_URA="{safe_uri}" ARGS="${{1:-{{}}}}" curl -sS -X POST "${{AXON_ENDPOINT}}/v1/invoke" \\ -H "Content-Type: application/json" \\ - -d "{{\\"tenant_id\\":\\"${{TENANT}}\\",\\"resource_uri\\":\\"${{RESOURCE_URI}}\\",\\"payload\\":${{ARGS}}}}" + -d "{{\\"tenant_id\\":\\"${{TENANT}}\\",\\"resource_ura\\":\\"${{RESOURCE_URA}}\\",\\"payload\\":${{ARGS}}}}" """ -def _push_metadata(lines: List[str], version: str, resource_uri: str) -> None: +def _push_metadata(lines: List[str], version: str, resource_ura: str) -> None: """Append the common metadata block shared by all ability targets.""" lines.append("metadata:") lines.append(" author: easynet-axon") lines.append(f' version: "{version}"') - lines.append(f' axon-resource-uri: "{resource_uri}"') + lines.append(f' axon-resource-ura: "{resource_ura}"') def _generate_ability_md( @@ -710,7 +710,7 @@ def _generate_ability_md( lines.append(f"description: {descriptor.description}") lines.append("compatibility: Requires network access to Axon runtime") - _push_metadata(lines, descriptor.version, descriptor.resource_uri) + _push_metadata(lines, descriptor.version, descriptor.resource_ura) if target == AbilityTarget.CLAUDE: lines.append("allowed-tools: Bash(*)") elif target == AbilityTarget.OPENCLAW: @@ -789,7 +789,7 @@ def _generate_ability_md( lines.append("") lines.append("## Axon Resource") lines.append("") - lines.append(f"- **URI**: `{descriptor.resource_uri}`") + lines.append(f"- **URA**: `{descriptor.resource_ura}`") lines.append(f"- **Version**: {descriptor.version}") if descriptor.category: lines.append(f"- **Category**: {descriptor.category}") diff --git a/sdk/python/easynet_axon/capability_request.py b/sdk/python/easynet_axon/capability_request.py index 5cb3b04f..b7ac206f 100644 --- a/sdk/python/easynet_axon/capability_request.py +++ b/sdk/python/easynet_axon/capability_request.py @@ -60,7 +60,7 @@ class PublishCapabilityRequest: tags: list[str] | None = None requirements: dict[str, str] | None = None metadata: dict[str, str] | None = None - payload_uri: str | None = None + payload_ura: str | None = None payload_size_bytes: int | None = None package_bytes_base64: str | None = None signature_fingerprint: str | None = None @@ -74,11 +74,11 @@ def validate(self) -> None: _require_nonblank("version", self.version) _validate_digest_prefix("digest", self.digest) _require_nonblank("signature", self.signature) - has_uri = self.payload_uri and self.payload_uri.strip() + has_uri = self.payload_ura and self.payload_ura.strip() has_bytes = self.package_bytes_base64 and self.package_bytes_base64.strip() if not has_uri and not has_bytes: raise AxonConfigError( - "payload_uri or package_bytes_base64 is required" + "payload_ura or package_bytes_base64 is required" ) if self.payload_size_bytes is not None and self.payload_size_bytes < 0: raise AxonConfigError("payload_size_bytes must be >= 0") @@ -96,7 +96,7 @@ def to_payload(self) -> dict[str, Any]: "metadata": self.metadata or {}, } _put_optional_nonblank(req, "digest", self.digest) - _put_optional_nonblank(req, "payload_uri", self.payload_uri) + _put_optional_nonblank(req, "payload_ura", self.payload_ura) _put_optional_payload_size(req, "payload_size_bytes", self.payload_size_bytes) _put_optional_nonblank(req, "package_bytes_base64", self.package_bytes_base64) _put_optional_nonblank(req, "signature_fingerprint", self.signature_fingerprint) diff --git a/sdk/python/easynet_axon/client.py b/sdk/python/easynet_axon/client.py index c3a386c9..e9adc890 100644 --- a/sdk/python/easynet_axon/client.py +++ b/sdk/python/easynet_axon/client.py @@ -45,7 +45,7 @@ class Transport(Protocol): def call( self, tenant_id: str, - resource_uri: str, + resource_ura: str, payload: dict[str, Any], *, principal_id: str | None = None, @@ -53,8 +53,8 @@ def call( ... -def _subject_visibility_from_resource_uri(resource_uri: str) -> str: - normalized = (resource_uri or "").strip().lower() +def _subject_visibility_from_resource_ura(resource_ura: str) -> str: + normalized = (resource_ura or "").strip().lower() if normalized.startswith("easynet:///r/pub/"): return "pub" if normalized.startswith("easynet:///r/prv/"): @@ -62,13 +62,13 @@ def _subject_visibility_from_resource_uri(resource_uri: str) -> str: return "org" -def _principal_to_subject_id(principal_id: str, resource_uri: str) -> str: +def _principal_to_subject_id(principal_id: str, resource_ura: str) -> str: normalized = principal_id.strip() if not normalized: raise AxonConfigError("principal(...) cannot be blank") if normalized.startswith("easynet:"): return normalized - visibility = _subject_visibility_from_resource_uri(resource_uri) + visibility = _subject_visibility_from_resource_ura(resource_ura) return f"easynet:{visibility}:reg:agent.{normalized}" @@ -186,7 +186,7 @@ def __del__(self) -> None: def _invoke_with_reconnect( self, fn: Callable[[DendriteBridge, str | None], dict[str, Any]], - resource_uri: str, + resource_ura: str, principal_id: str | None, ) -> dict[str, Any]: """Call `fn(bridge, subject_id)` with automatic transport-failure @@ -194,7 +194,7 @@ def _invoke_with_reconnect( direct-call path (no retries, no hidden latency).""" bridge = self._ensure_bridge() subject_id = ( - _principal_to_subject_id(principal_id, resource_uri) if principal_id else None + _principal_to_subject_id(principal_id, resource_ura) if principal_id else None ) try: return fn(bridge, subject_id) @@ -209,7 +209,7 @@ def _invoke_with_reconnect( def call( self, tenant_id: str, - resource_uri: str, + resource_ura: str, payload: dict[str, Any], *, principal_id: str | None = None, @@ -217,19 +217,19 @@ def call( return self._invoke_with_reconnect( lambda bridge, subject_id: bridge.ability_call( tenant_id=tenant_id, - resource_uri=resource_uri, + resource_ura=resource_ura, payload_json=payload, subject_id=subject_id, timeout_ms=self.timeout_ms, ), - resource_uri, + resource_ura, principal_id, ) def call_raw( self, tenant_id: str, - resource_uri: str, + resource_ura: str, payload: dict[str, Any], *, principal_id: str | None = None, @@ -237,12 +237,12 @@ def call_raw( return self._invoke_with_reconnect( lambda bridge, subject_id: bridge.ability_call_raw( tenant_id=tenant_id, - resource_uri=resource_uri, + resource_ura=resource_ura, payload_json=payload, subject_id=subject_id, timeout_ms=self.timeout_ms, ), - resource_uri, + resource_ura, principal_id, ) @@ -253,27 +253,27 @@ def __init__( transport: Transport | None = None, *, tenant_id: str | None = None, - resource_uri: str | None = None, + resource_ura: str | None = None, principal_id: str | None = None, ) -> None: self._transport: Transport = transport or SidecarTransport() self._tenant_id: str | None = tenant_id - self._resource_uri: str | None = resource_uri + self._resource_ura: str | None = resource_ura self._principal_id: str | None = principal_id def tenant(self, tenant_id: str) -> "Client": return Client( self._transport, tenant_id=tenant_id, - resource_uri=self._resource_uri, + resource_ura=self._resource_ura, principal_id=self._principal_id, ) - def ability(self, resource_uri: str) -> "Client": + def ability(self, resource_ura: str) -> "Client": return Client( self._transport, tenant_id=self._tenant_id, - resource_uri=resource_uri, + resource_ura=resource_ura, principal_id=self._principal_id, ) @@ -283,30 +283,30 @@ def principal(self, principal_id: str) -> "Client": return Client( self._transport, tenant_id=self._tenant_id, - resource_uri=self._resource_uri, + resource_ura=self._resource_ura, principal_id=principal_id, ) def call(self, payload: dict[str, Any]) -> dict[str, Any]: if not self._tenant_id: raise AxonConfigError("tenant(...) is required before call(...)") - if not self._resource_uri: + if not self._resource_ura: raise AxonConfigError("ability(...) is required before call(...)") if self._principal_id: if not _transport_supports_principal(self._transport): raise TypeError("configured transport does not support principal(...) context") return self._transport.call( self._tenant_id, - self._resource_uri, + self._resource_ura, payload, principal_id=self._principal_id, ) - return self._transport.call(self._tenant_id, self._resource_uri, payload) + return self._transport.call(self._tenant_id, self._resource_ura, payload) def call_raw(self, payload: dict[str, Any]) -> dict[str, Any]: if not self._tenant_id: raise AxonConfigError("tenant(...) is required before call_raw(...)") - if not self._resource_uri: + if not self._resource_ura: raise AxonConfigError("ability(...) is required before call_raw(...)") call_raw = getattr(self._transport, "call_raw", None) if not callable(call_raw): @@ -316,11 +316,11 @@ def call_raw(self, payload: dict[str, Any]) -> dict[str, Any]: raise TypeError("configured transport does not support principal(...) context") return call_raw( self._tenant_id, - self._resource_uri, + self._resource_ura, payload, principal_id=self._principal_id, ) - return call_raw(self._tenant_id, self._resource_uri, payload) + return call_raw(self._tenant_id, self._resource_ura, payload) def call_any(self, payload: dict[str, Any]) -> Any: raw = self.call_raw(payload) diff --git a/sdk/python/easynet_axon/dendrite_bridge.py b/sdk/python/easynet_axon/dendrite_bridge.py index 2216a0bf..5c8826a7 100644 --- a/sdk/python/easynet_axon/dendrite_bridge.py +++ b/sdk/python/easynet_axon/dendrite_bridge.py @@ -457,7 +457,7 @@ def _bidi_stream_finish_send(self, stream_handle: int) -> bool: def ability_call( self, tenant_id: str, - resource_uri: str, + resource_ura: str, payload_json: Any, *, subject_id: str | None = None, @@ -466,7 +466,7 @@ def ability_call( ) -> dict[str, Any]: return self.ability_call_raw( tenant_id=tenant_id, - resource_uri=resource_uri, + resource_ura=resource_ura, payload_json=payload_json, subject_id=subject_id, metadata=metadata, @@ -476,7 +476,7 @@ def ability_call( def ability_call_raw( self, tenant_id: str, - resource_uri: str, + resource_ura: str, payload_json: Any, *, subject_id: str | None = None, @@ -485,7 +485,7 @@ def ability_call_raw( ) -> dict[str, Any]: payload = { "tenant_id": tenant_id, - "resource_uri": resource_uri, + "resource_ura": resource_ura, "payload_json": payload_json, "metadata": metadata or {}, "timeout_ms": timeout_ms, @@ -590,21 +590,21 @@ def list_nodes( def federation_advertise_agent( self, tenant_id: str, - agent_uri: str, + agent_ura: str, *, public_key_hex: str | None = None, signing_authority: dict[str, Any] | None = None, timeout_ms: int = FEDERATION_DEFAULT_TIMEOUT_MS, ) -> dict[str, Any]: """Invoke ``federation.advertise_agent``. Receipt: ``{"ack", "replaced_prior"}``.""" - body: dict[str, Any] = {"agent_uri": agent_uri} + body: dict[str, Any] = {"agent_ura": agent_ura} if public_key_hex: body["public_key_hex"] = public_key_hex if signing_authority: body["signing_authority"] = signing_authority return self.ability_call_raw( tenant_id=tenant_id, - resource_uri="federation.advertise_agent", + resource_ura="federation.advertise_agent", payload_json=body, timeout_ms=timeout_ms, ) @@ -612,7 +612,7 @@ def federation_advertise_agent( def federation_advertise_abilities( self, tenant_id: str, - agent_uri: str, + agent_ura: str, abilities: list[dict[str, Any]], *, timeout_ms: int = FEDERATION_DEFAULT_TIMEOUT_MS, @@ -620,8 +620,8 @@ def federation_advertise_abilities( """Invoke ``federation.advertise_abilities``. Receipt: ``{"ack", "count"}``.""" return self.ability_call_raw( tenant_id=tenant_id, - resource_uri="federation.advertise_abilities", - payload_json={"agent_uri": agent_uri, "abilities": list(abilities)}, + resource_ura="federation.advertise_abilities", + payload_json={"agent_ura": agent_ura, "abilities": list(abilities)}, timeout_ms=timeout_ms, ) @@ -637,7 +637,7 @@ def federation_heartbeat( """ return self.ability_call_raw( tenant_id=tenant_id, - resource_uri="federation.heartbeat", + resource_ura="federation.heartbeat", payload_json={}, timeout_ms=timeout_ms, ) @@ -645,7 +645,7 @@ def federation_heartbeat( def federation_revoke( self, tenant_id: str, - agent_uri: str, + agent_ura: str, *, reason: str | None = None, timeout_ms: int = FEDERATION_DEFAULT_TIMEOUT_MS, @@ -654,12 +654,12 @@ def federation_revoke( payload when ``None`` or empty; the runtime substitutes a canonical default. Receipt: ``{"ack", "was_active"}``. """ - body: dict[str, Any] = {"agent_uri": agent_uri} + body: dict[str, Any] = {"agent_ura": agent_ura} if reason: body["reason"] = reason return self.ability_call_raw( tenant_id=tenant_id, - resource_uri="federation.revoke", + resource_ura="federation.revoke", payload_json=body, timeout_ms=timeout_ms, ) @@ -668,19 +668,19 @@ def federation_resolve( self, tenant_id: str, *, - agent_uri_prefix: str | None = None, + agent_ura_prefix: str | None = None, include_abilities: bool = False, timeout_ms: int = FEDERATION_DEFAULT_TIMEOUT_MS, ) -> dict[str, Any]: """Invoke ``federation.resolve``. Receipt: ``{"agents": [...]}``.""" filt: dict[str, Any] = {} - if agent_uri_prefix: - filt["agent_uri_prefix"] = agent_uri_prefix + if agent_ura_prefix: + filt["agent_ura_prefix"] = agent_ura_prefix if include_abilities: filt["include_abilities"] = True return self.ability_call_raw( tenant_id=tenant_id, - resource_uri="federation.resolve", + resource_ura="federation.resolve", payload_json={"filter": filt} if filt else {}, timeout_ms=timeout_ms, ) @@ -695,7 +695,7 @@ def federation_join( pairing_secret: str | None = None, timeout_ms: int = FEDERATION_DEFAULT_TIMEOUT_MS, ) -> dict[str, Any]: - """Invoke ``federation.join``. Receipt: ``{"canonical_agent_uri", + """Invoke ``federation.join``. Receipt: ``{"canonical_agent_ura", "realm", "join_receipt_hash"}``. """ body: dict[str, Any] = { @@ -708,7 +708,7 @@ def federation_join( body["pairing_secret"] = pairing_secret return self.ability_call_raw( tenant_id=tenant_id, - resource_uri="federation.join", + resource_ura="federation.join", payload_json=body, timeout_ms=timeout_ms, ) @@ -726,7 +726,7 @@ def publish_capability( tags: list[str] | None = None, requirements: dict[str, str] | None = None, metadata: dict[str, str] | None = None, - payload_uri: str | None = None, + payload_ura: str | None = None, payload_size_bytes: int | None = None, package_bytes_base64: str | None = None, signature_fingerprint: str | None = None, @@ -745,7 +745,7 @@ def publish_capability( tags=tags, requirements=requirements, metadata=metadata, - payload_uri=payload_uri, + payload_ura=payload_ura, payload_size_bytes=payload_size_bytes, package_bytes_base64=package_bytes_base64, signature_fingerprint=signature_fingerprint, diff --git a/sdk/python/easynet_axon/invocation/__init__.py b/sdk/python/easynet_axon/invocation/__init__.py index a7a58db3..d692ce01 100644 --- a/sdk/python/easynet_axon/invocation/__init__.py +++ b/sdk/python/easynet_axon/invocation/__init__.py @@ -52,7 +52,7 @@ ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, canonical_causal_context, canonical_invocation_bytes, canonical_receipt_bytes, @@ -138,7 +138,7 @@ # RFC 001 axiom surface "AgentIdentity", "SubjectIdentity", - "UriProfile", + "UraProfile", "CausalContext", "ReceiptRef", "InvocationEnvelope", diff --git a/sdk/python/easynet_axon/invocation/admission.py b/sdk/python/easynet_axon/invocation/admission.py index 2e5b2ffc..1ad92c34 100644 --- a/sdk/python/easynet_axon/invocation/admission.py +++ b/sdk/python/easynet_axon/invocation/admission.py @@ -12,7 +12,7 @@ Local-fast mode where identity is self-asserted — documented trust model, not a gap. 4. :meth:`NonceReplayStore.check_and_record` — always on. Dedup key is - ``(caller.uri, ability, invocation_nonce)``; ``ability`` guards + ``(caller.ura, ability, invocation_nonce)``; ``ability`` guards against cross-ability false-positives per review. All rejections map to :class:`AxonErrorKind.INVALID_ARGUMENT` with one @@ -78,7 +78,7 @@ def validate_envelope(env: InvocationEnvelope) -> None: Checks applied (RFC 001 §5.2 step 1, strengthened per review): - ``ability`` non-empty - - ``caller.uri`` / ``callee.uri`` / ``subject.uri`` non-empty + - ``caller.ura`` / ``callee.ura`` / ``subject.ura`` non-empty - ``invocation_nonce`` is not the all-zero sentinel (CSPRNG-generated nonce being all-zero has probability ≈ 2⁻¹²⁸; we reject it as a probable uninitialised-field mistake rather than accepting a @@ -87,18 +87,18 @@ def validate_envelope(env: InvocationEnvelope) -> None: constructor already enforces this; we re-check defensively so admission is self-contained) - Left intentionally cheap: no URI-scheme parsing here. That's + Left intentionally cheap: no URA-scheme parsing here. That's URA §3's job and belongs to a profile-level validator, not admission. """ if not env.ability: raise _reject_envelope("ability_empty") - if not env.caller.uri: - raise _reject_envelope("caller_uri_empty") - if not env.callee.uri: - raise _reject_envelope("callee_uri_empty") - if not env.subject.uri: - raise _reject_envelope("subject_uri_empty") + if not env.caller.ura: + raise _reject_envelope("caller_ura_empty") + if not env.callee.ura: + raise _reject_envelope("callee_ura_empty") + if not env.subject.ura: + raise _reject_envelope("subject_ura_empty") if len(env.args_digest) != 32: raise _reject_envelope("args_digest_wrong_length") if env.invocation_nonce == b"\x00" * 16: @@ -199,12 +199,12 @@ def with_window_ms(cls, window_ms: int) -> "NonceReplayStore": def check_and_record( self, - caller_uri: str, + caller_ura: str, ability: str, nonce: bytes, now_ms: int, ) -> None: - """Register a ``(caller.uri, ability, nonce)`` observation. + """Register a ``(caller.ura, ability, nonce)`` observation. Raises :class:`AxonError` with reason :data:`REASON_NONCE_REPLAY` on collision inside the current @@ -220,7 +220,7 @@ def check_and_record( for k in stale: del self._seen[k] - key: _ReplayKey = (caller_uri, ability, bytes(nonce)) + key: _ReplayKey = (caller_ura, ability, bytes(nonce)) prev_ts = self._seen.get(key) if prev_ts is not None and prev_ts >= cutoff: raise AxonError( @@ -258,7 +258,7 @@ def run_admission( if resolver is not None: verify_signature(env, sig, resolver) replay.check_and_record( - env.caller.uri, env.ability, env.invocation_nonce, now_ms + env.caller.ura, env.ability, env.invocation_nonce, now_ms ) diff --git a/sdk/python/easynet_axon/invocation/axiom.py b/sdk/python/easynet_axon/invocation/axiom.py index 9c58468b..6d87cb94 100644 --- a/sdk/python/easynet_axon/invocation/axiom.py +++ b/sdk/python/easynet_axon/invocation/axiom.py @@ -35,8 +35,8 @@ # ── URA profile ────────────────────────────────────────────────────── -class UriProfile(str, Enum): - """URA profile selector. Bound structurally to the URI it profiles +class UraProfile(str, Enum): + """URA profile selector. Bound structurally to the URA it profiles (AXIOM §5.4 Axis B, RFC 001 INV-4). The string value is the stable wire form. It is what the canonical @@ -47,13 +47,13 @@ class UriProfile(str, Enum): WEB_SAFE_V2 = "web-safe-v2" @classmethod - def parse(cls, s: str) -> "UriProfile": + def parse(cls, s: str) -> "UraProfile": try: return cls(s) except ValueError as exc: raise AxonError( kind=AxonErrorKind.INVALID_ARGUMENT, - reason=f"unknown_uri_profile:{s}", + reason=f"unknown_ura_profile:{s}", ) from exc @@ -61,29 +61,29 @@ def parse(cls, s: str) -> "UriProfile": @dataclass(frozen=True) class AgentIdentity: - uri: str - profile: UriProfile + ura: str + profile: UraProfile @dataclass(frozen=True) class SubjectIdentity: """Distinct type from AgentIdentity so the compiler can enforce - INV-7 — a subject URI can differ in namespace/scope/subject-type - from the callee URI. + INV-7 — a subject URA can differ in namespace/scope/subject-type + from the callee URA. The class is intentionally not a subclass of AgentIdentity; the - canonical-bytes encoder emits the same `uri || profile` layout for + canonical-bytes encoder emits the same `ura || profile` layout for both, but treating them as separate types makes accidental swaps into loud type errors. """ - uri: str - profile: UriProfile + ura: str + profile: UraProfile @classmethod def from_callee(cls, callee: AgentIdentity) -> "SubjectIdentity": """Degenerate case (RFC 001 §5.1): executor equals target.""" - return cls(uri=callee.uri, profile=callee.profile) + return cls(ura=callee.ura, profile=callee.profile) # ── Causal context ─────────────────────────────────────────────────── @@ -91,7 +91,7 @@ def from_callee(cls, callee: AgentIdentity) -> "SubjectIdentity": @dataclass(frozen=True) class ReceiptRef: receipt_hash: bytes # 32 bytes - receipt_uri: str + receipt_ura: str def __post_init__(self) -> None: if len(self.receipt_hash) != 32: @@ -108,17 +108,17 @@ class CausalContext: classmethods — mirrors the Rust ``CausalContext`` enum arms. """ - __slots__ = ("_tag", "_scalar", "_list", "_merkle_root", "_merkle_proof_uri") + __slots__ = ("_tag", "_scalar", "_list", "_merkle_root", "_merkle_proof_ura") def __init__(self, *, _tag: int, _scalar: Optional[ReceiptRef] = None, _list: Optional[Tuple[ReceiptRef, ...]] = None, _merkle_root: Optional[bytes] = None, - _merkle_proof_uri: Optional[str] = None) -> None: + _merkle_proof_ura: Optional[str] = None) -> None: self._tag = _tag self._scalar = _scalar self._list = _list self._merkle_root = _merkle_root - self._merkle_proof_uri = _merkle_proof_uri + self._merkle_proof_ura = _merkle_proof_ura @classmethod def none(cls) -> "CausalContext": @@ -133,13 +133,13 @@ def list_(cls, refs: List[ReceiptRef]) -> "CausalContext": return cls(_tag=0x02, _list=tuple(refs)) @classmethod - def merkle(cls, root: bytes, proof_uri: str) -> "CausalContext": + def merkle(cls, root: bytes, proof_ura: str) -> "CausalContext": if len(root) != 32: raise AxonError( kind=AxonErrorKind.INVALID_ARGUMENT, reason=f"merkle_root_wrong_length:{len(root)}", ) - return cls(_tag=0x03, _merkle_root=root, _merkle_proof_uri=proof_uri) + return cls(_tag=0x03, _merkle_root=root, _merkle_proof_ura=proof_ura) @property def tag(self) -> int: @@ -156,7 +156,7 @@ def as_list(self) -> Optional[Tuple[ReceiptRef, ...]]: def as_merkle(self) -> Optional[Tuple[bytes, str]]: if self._tag == 0x03: - return (self._merkle_root, self._merkle_proof_uri) # type: ignore[return-value] + return (self._merkle_root, self._merkle_proof_ura) # type: ignore[return-value] return None def __eq__(self, other: object) -> bool: @@ -167,11 +167,11 @@ def __eq__(self, other: object) -> bool: and self._scalar == other._scalar and self._list == other._list and self._merkle_root == other._merkle_root - and self._merkle_proof_uri == other._merkle_proof_uri + and self._merkle_proof_ura == other._merkle_proof_ura ) def __hash__(self) -> int: - return hash((self._tag, self._scalar, self._list, self._merkle_root, self._merkle_proof_uri)) + return hash((self._tag, self._scalar, self._list, self._merkle_root, self._merkle_proof_ura)) def __repr__(self) -> str: # pragma: no cover - debug only if self._tag == 0: @@ -180,7 +180,7 @@ def __repr__(self) -> str: # pragma: no cover - debug only return f"CausalContext.scalar({self._scalar!r})" if self._tag == 2: return f"CausalContext.list({list(self._list or [])!r})" - return f"CausalContext.merkle(root=..., proof_uri={self._merkle_proof_uri!r})" + return f"CausalContext.merkle(root=..., proof_ura={self._merkle_proof_ura!r})" # ── Signatures ─────────────────────────────────────────────────────── @@ -261,8 +261,8 @@ def _put_bytes(out: bytearray, b: bytes) -> None: out.extend(b) -def _put_identity_uri_profile(out: bytearray, uri: str, profile: UriProfile) -> None: - _put_str(out, uri) +def _put_identity_ura_profile(out: bytearray, ura: str, profile: UraProfile) -> None: + _put_str(out, ura) _put_str(out, profile.value) @@ -281,7 +281,7 @@ def canonical_causal_context(ctx: CausalContext) -> bytes: if scalar is not None: out.append(0x01) out.extend(scalar.receipt_hash) - _put_str(out, scalar.receipt_uri) + _put_str(out, scalar.receipt_ura) return bytes(out) lst = ctx.as_list() if lst is not None: @@ -289,14 +289,14 @@ def canonical_causal_context(ctx: CausalContext) -> bytes: out.extend(struct.pack(">I", len(lst))) for r in lst: out.extend(r.receipt_hash) - _put_str(out, r.receipt_uri) + _put_str(out, r.receipt_ura) return bytes(out) merkle = ctx.as_merkle() if merkle is not None: - root, proof_uri = merkle + root, proof_ura = merkle out.append(0x03) out.extend(root) - _put_str(out, proof_uri) + _put_str(out, proof_ura) return bytes(out) raise AxonError( # pragma: no cover - exhaustive kind=AxonErrorKind.INTERNAL, @@ -311,9 +311,9 @@ def canonical_invocation_bytes(env: InvocationEnvelope) -> bytes: is length-prefixed so no two valid envelopes collide. """ out = bytearray() - _put_identity_uri_profile(out, env.caller.uri, env.caller.profile) - _put_identity_uri_profile(out, env.callee.uri, env.callee.profile) - _put_identity_uri_profile(out, env.subject.uri, env.subject.profile) + _put_identity_ura_profile(out, env.caller.ura, env.caller.profile) + _put_identity_ura_profile(out, env.callee.ura, env.callee.profile) + _put_identity_ura_profile(out, env.subject.ura, env.subject.profile) _put_str(out, env.ability) out.extend(env.args_digest) # 32 bytes fixed out.extend(env.invocation_nonce) # 16 bytes fixed @@ -335,9 +335,9 @@ def canonical_receipt_bytes(r: ReceiptBody) -> bytes: _put_str(out, r.state) out.extend(struct.pack(">q", r.timestamp_unix_ms)) out.extend(r.prev_receipt_hash) # 32 - _put_identity_uri_profile(out, r.caller_binding.uri, r.caller_binding.profile) - _put_identity_uri_profile(out, r.callee_binding.uri, r.callee_binding.profile) - _put_identity_uri_profile(out, r.subject_binding.uri, r.subject_binding.profile) + _put_identity_ura_profile(out, r.caller_binding.ura, r.caller_binding.profile) + _put_identity_ura_profile(out, r.callee_binding.ura, r.callee_binding.profile) + _put_identity_ura_profile(out, r.subject_binding.ura, r.subject_binding.profile) out.extend(r.invocation_nonce) # 16 causal = canonical_causal_context(r.causal_binding) _put_bytes(out, causal) @@ -355,41 +355,41 @@ def sha256(b: bytes) -> bytes: # ── Key resolver interface (§5.4) ──────────────────────────────────── class KeyResolver: - """Resolve an agent's verifying (Ed25519 public) key by its URI. + """Resolve an agent's verifying (Ed25519 public) key by its URA. RFC 002 will add a Registry-backed resolver that implements this same interface. Signature verification paths MUST depend on the interface, not on a specific concrete resolver. """ - def resolve(self, agent_uri: str) -> "ed25519.Ed25519PublicKey": + def resolve(self, agent_ura: str) -> "ed25519.Ed25519PublicKey": raise NotImplementedError class FileKeyResolver(KeyResolver): - """RFC 001's shipped resolver: file-path per agent URI. + """RFC 001's shipped resolver: file-path per agent URA. Each file contains the raw 32-byte Ed25519 public key. Mapping is - ``agent_uri -> path``. + ``agent_ura -> path``. """ def __init__(self) -> None: self._mapping: dict[str, str] = {} - def insert(self, agent_uri: str, path: str) -> None: - self._mapping[agent_uri] = path + def insert(self, agent_ura: str, path: str) -> None: + self._mapping[agent_ura] = path - def resolve(self, agent_uri: str) -> "ed25519.Ed25519PublicKey": + def resolve(self, agent_ura: str) -> "ed25519.Ed25519PublicKey": if ed25519 is None: # pragma: no cover raise AxonError( kind=AxonErrorKind.INTERNAL, reason="cryptography_not_installed", ) - path = self._mapping.get(agent_uri) + path = self._mapping.get(agent_ura) if path is None: raise AxonError( kind=AxonErrorKind.INVALID_ARGUMENT, - reason=f"unknown_agent_key:{agent_uri}", + reason=f"unknown_agent_key:{agent_ura}", ) try: with open(path, "rb") as f: @@ -449,7 +449,7 @@ def verify_invocation_signature(env: InvocationEnvelope, sig: CallerSignature, kind=AxonErrorKind.INVALID_ARGUMENT, reason=f"unsupported_algorithm:{sig.algorithm}", ) - key = resolver.resolve(env.caller.uri) + key = resolver.resolve(env.caller.ura) bytes_ = canonical_invocation_bytes(env) if len(sig.signature) != 64: raise AxonError( @@ -481,7 +481,7 @@ def verify_receipt_signature(r: ReceiptBody, sig: CalleeSignature, kind=AxonErrorKind.INVALID_ARGUMENT, reason=f"unsupported_algorithm:{sig.algorithm}", ) - key = resolver.resolve(r.callee_binding.uri) + key = resolver.resolve(r.callee_binding.ura) bytes_ = canonical_receipt_bytes(r) if len(sig.signature) != 64: raise AxonError( diff --git a/sdk/python/easynet_axon/invocation/bundle.py b/sdk/python/easynet_axon/invocation/bundle.py index 3c4311c5..5a2e3c47 100644 --- a/sdk/python/easynet_axon/invocation/bundle.py +++ b/sdk/python/easynet_axon/invocation/bundle.py @@ -30,7 +30,7 @@ ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, ) from .error import AxonError, AxonErrorKind @@ -38,19 +38,19 @@ # ── Identity JSON ──────────────────────────────────────────────────── def identity_to_json(a: AgentIdentity) -> Dict[str, str]: - return {"uri": a.uri, "profile": a.profile.value} + return {"ura": a.ura, "profile": a.profile.value} def subject_to_json(s: SubjectIdentity) -> Dict[str, str]: - return {"uri": s.uri, "profile": s.profile.value} + return {"ura": s.ura, "profile": s.profile.value} def identity_from_json(d: Dict[str, Any]) -> AgentIdentity: - return AgentIdentity(uri=d["uri"], profile=UriProfile.parse(d["profile"])) + return AgentIdentity(ura=d["ura"], profile=UraProfile.parse(d["profile"])) def subject_from_json(d: Dict[str, Any]) -> SubjectIdentity: - return SubjectIdentity(uri=d["uri"], profile=UriProfile.parse(d["profile"])) + return SubjectIdentity(ura=d["ura"], profile=UraProfile.parse(d["profile"])) # ── Causal context JSON ────────────────────────────────────────────── @@ -63,21 +63,21 @@ def causal_to_json(c: CausalContext) -> Dict[str, Any]: return { "form": "scalar", "receipt_hash_hex": scalar.receipt_hash.hex(), - "receipt_uri": scalar.receipt_uri, + "receipt_ura": scalar.receipt_ura, } lst = c.as_list() if lst is not None: return { "form": "list", "prior": [ - {"receipt_hash_hex": r.receipt_hash.hex(), "receipt_uri": r.receipt_uri} + {"receipt_hash_hex": r.receipt_hash.hex(), "receipt_ura": r.receipt_ura} for r in lst ], } merkle = c.as_merkle() if merkle is not None: root, proof = merkle - return {"form": "merkle", "root_hex": root.hex(), "proof_uri": proof} + return {"form": "merkle", "root_hex": root.hex(), "proof_ura": proof} raise AxonError(kind=AxonErrorKind.INTERNAL, reason="unreachable_causal_form") @@ -89,14 +89,14 @@ def causal_from_json(d: Dict[str, Any]) -> CausalContext: return CausalContext.scalar( ReceiptRef( receipt_hash=bytes.fromhex(d["receipt_hash_hex"]), - receipt_uri=d["receipt_uri"], + receipt_ura=d["receipt_ura"], ) ) if form == "list": refs = [ ReceiptRef( receipt_hash=bytes.fromhex(p["receipt_hash_hex"]), - receipt_uri=p["receipt_uri"], + receipt_ura=p["receipt_ura"], ) for p in d.get("prior", []) ] @@ -104,7 +104,7 @@ def causal_from_json(d: Dict[str, Any]) -> CausalContext: if form == "merkle": return CausalContext.merkle( root=bytes.fromhex(d["root_hex"]), - proof_uri=d["proof_uri"], + proof_ura=d["proof_ura"], ) raise AxonError( kind=AxonErrorKind.INVALID_ARGUMENT, diff --git a/sdk/python/easynet_axon/invocation/local_runtime.py b/sdk/python/easynet_axon/invocation/local_runtime.py index 819be191..f63bdf99 100644 --- a/sdk/python/easynet_axon/invocation/local_runtime.py +++ b/sdk/python/easynet_axon/invocation/local_runtime.py @@ -24,7 +24,7 @@ InvocationEnvelope, KeyResolver, SubjectIdentity, - UriProfile, + UraProfile, canonical_invocation_bytes, fresh_nonce, sha256, @@ -453,7 +453,7 @@ async def cancel(self, invocation_id: str, *, reason: str = "user_request") -> N await self.cancel(child_id, reason=f"parent_terminal:CANCELLED") -# Well-known local-runtime SystemAgent URI used when no caller identity +# Well-known local-runtime SystemAgent URA used when no caller identity # is provided. AXIOM.tex §3.2 permits this: infrastructure-initiated # invocations carry a SystemAgent identity and are still axiom-bound. _SYSTEM_URI = "easynet:///r/_system/agents/local@1" @@ -467,9 +467,9 @@ def _system_local_binding(payload: bytes) -> AxiomBinding: only the caller's cryptographic signature. Industrial tests and local orchestration rely on this path. """ - system = AgentIdentity(uri=_SYSTEM_URI, profile=UriProfile.EASYNET_STRICT_V2) - callee = AgentIdentity(uri=_SYSTEM_URI, profile=UriProfile.EASYNET_STRICT_V2) - subject = SubjectIdentity(uri=_SYSTEM_URI, profile=UriProfile.EASYNET_STRICT_V2) + system = AgentIdentity(ura=_SYSTEM_URI, profile=UraProfile.EASYNET_STRICT_V2) + callee = AgentIdentity(ura=_SYSTEM_URI, profile=UraProfile.EASYNET_STRICT_V2) + subject = SubjectIdentity(ura=_SYSTEM_URI, profile=UraProfile.EASYNET_STRICT_V2) return AxiomBinding( caller=system, callee=callee, diff --git a/sdk/python/easynet_axon/orchestrator.py b/sdk/python/easynet_axon/orchestrator.py index 34814d81..07b35965 100644 --- a/sdk/python/easynet_axon/orchestrator.py +++ b/sdk/python/easynet_axon/orchestrator.py @@ -305,7 +305,7 @@ def cleanup_installs(self, installs: list[dict[str, str]], *, deactivate_reason: def invoke_agent_ability( self, - agent_uri: str, + agent_ura: str, ability_id: str, payload: Any, *, @@ -315,15 +315,15 @@ def invoke_agent_ability( Replaces the legacy ``send_a2a_task`` helper that routed via the deleted A2A direct-RPC. Post RFC-001 §A1 every cross-agent call - is an ordinary Invoke; ``agent_uri`` is forwarded as the subject + is an ordinary Invoke; ``agent_ura`` is forwarded as the subject so the runtime resolves it to the hosting node, and ``ability_id`` is the ability the target advertises. """ return self._ensure_bridge().ability_call_raw( tenant_id=self.tenant, - resource_uri=ability_id, + resource_ura=ability_id, payload_json=payload, - subject_id=agent_uri, + subject_id=agent_ura, timeout_ms=timeout_ms, ) @@ -349,7 +349,7 @@ def disconnect_device(self, node_id: str, reason: str | None = None) -> dict[str RFC-001 §A1 collapsed `deregister_node` and `drain_node` into a single `federation.revoke` ability invocation. ``node_id`` is - treated as the agent_uri for backwards compatibility with the + treated as the agent_ura for backwards compatibility with the pre-§A1 callers. """ return self._ensure_bridge().federation_revoke( diff --git a/sdk/python/easynet_axon/presets/federation/handlers.py b/sdk/python/easynet_axon/presets/federation/handlers.py index f429c865..4e3eaaf6 100644 --- a/sdk/python/easynet_axon/presets/federation/handlers.py +++ b/sdk/python/easynet_axon/presets/federation/handlers.py @@ -194,11 +194,11 @@ def handle_federated_invoke( return {"ok": False, "error": "function_name is required"} bridge = orch._ensure_bridge() - resource_uri = f"easynet:///r/org/{capability_name}" + resource_ura = f"easynet:///r/org/{capability_name}" try: result = bridge.invoke_ability( tenant_id=tenant, - resource_uri=resource_uri, + resource_ura=resource_ura, payload_json=json.dumps(arguments), metadata={ "node_id": node_id, diff --git a/sdk/python/easynet_axon/semantic.py b/sdk/python/easynet_axon/semantic.py index 1586eb3e..9c0db6c7 100644 --- a/sdk/python/easynet_axon/semantic.py +++ b/sdk/python/easynet_axon/semantic.py @@ -268,7 +268,7 @@ def tenant(self, tenant_id: str) -> TenantControl: class AbilityCallBuilder: bridge: DendriteBridge tenant_id: str - resource_uri: str + resource_ura: str payload_json: Any = field(default_factory=dict) request_metadata: dict[str, str] = field(default_factory=dict) request_timeout_ms: int = 30000 @@ -289,12 +289,12 @@ def invoke(self) -> dict[str, Any]: tenant_id = self.tenant_id.strip() if not tenant_id: raise AxonConfigError("tenant_id is required") - resource_uri = self.resource_uri.strip() - if not resource_uri: - raise AxonConfigError("resource_uri is required") + resource_ura = self.resource_ura.strip() + if not resource_ura: + raise AxonConfigError("resource_ura is required") return self.bridge.ability_call( tenant_id=tenant_id, - resource_uri=resource_uri, + resource_ura=resource_ura, payload_json=self.payload_json, metadata=self.request_metadata, timeout_ms=self.request_timeout_ms, @@ -306,8 +306,8 @@ class AbilityTenantScope: bridge: DendriteBridge tenant_id: str - def resource(self, resource_uri: str) -> AbilityCallBuilder: - return AbilityCallBuilder(self.bridge, self.tenant_id, resource_uri) + def resource(self, resource_ura: str) -> AbilityCallBuilder: + return AbilityCallBuilder(self.bridge, self.tenant_id, resource_ura) @dataclass @@ -317,8 +317,8 @@ class AbilityDSL: def tenant(self, tenant_id: str) -> AbilityTenantScope: return AbilityTenantScope(self.bridge, tenant_id) - def call(self, tenant_id: str, resource_uri: str) -> AbilityCallBuilder: - return AbilityCallBuilder(self.bridge, tenant_id, resource_uri) + def call(self, tenant_id: str, resource_ura: str) -> AbilityCallBuilder: + return AbilityCallBuilder(self.bridge, tenant_id, resource_ura) @dataclass @@ -339,7 +339,7 @@ def __post_init__(self) -> None: def ability_call( tenant_id: str, - resource_uri: str, + resource_ura: str, *, endpoint: str | None = None, connect_timeout_ms: int = 5000, @@ -365,7 +365,7 @@ def wrapper(*args: Any, **kwargs: Any) -> dict[str, Any]: try: return bridge.ability_call( tenant_id=tenant_id, - resource_uri=resource_uri, + resource_ura=resource_ura, payload_json=payload, metadata=metadata or {}, timeout_ms=max(timeout_ms, 1), diff --git a/sdk/python/easynet_axon/tool_adapter.py b/sdk/python/easynet_axon/tool_adapter.py index 233d0aa0..51770c59 100644 --- a/sdk/python/easynet_axon/tool_adapter.py +++ b/sdk/python/easynet_axon/tool_adapter.py @@ -115,7 +115,7 @@ class ToolSpec: name: str description: str - resource_uri: str + resource_ura: str parameters: dict[str, Any] = field(default_factory=lambda: {"type": "object", "properties": {}}) # -- Format exporters --------------------------------------------------- @@ -153,7 +153,7 @@ def to_dict(self) -> dict[str, Any]: return { "name": self.name, "description": self.description, - "resource_uri": self.resource_uri, + "resource_ura": self.resource_ura, "parameters": self.parameters, } @@ -178,7 +178,7 @@ def get_horoscope(sign: str) -> str: # Or register with explicit schema adapter.register_ability( name="photo_capture", - resource_uri="easynet:///r/org/photo_capture", + resource_ura="easynet:///r/org/photo_capture", description="Capture a photo.", parameters={"type": "object", "properties": {"mode": {"type": "string"}}, "required": ["mode"]}, ) @@ -198,7 +198,7 @@ def get_horoscope(sign: str) -> str: _fallback_transport: Transport | None = field(init=False, default=None, repr=False) - def _client(self, resource_uri: str) -> Client: + def _client(self, resource_ura: str) -> Client: transport = self.transport if transport is None: if self._fallback_transport is None: @@ -207,7 +207,7 @@ def _client(self, resource_uri: str) -> Client: return Client( transport, tenant_id=self.tenant_id, - resource_uri=resource_uri, + resource_ura=resource_ura, principal_id=self.principal_id, ) @@ -218,7 +218,7 @@ def register( name: str, *, description: str = "", - resource_uri: str | None = None, + resource_ura: str | None = None, parameters: dict[str, Any] | None = None, ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: """Decorator that registers a local function as both a tool definition and a local handler. @@ -228,13 +228,13 @@ def register( """ def decorator(func: Callable[..., Any]) -> Callable[..., Any]: - resolved_uri = resource_uri or f"easynet:///r/org/{name}" + resolved_uri = resource_ura or f"easynet:///r/org/{name}" resolved_params = parameters or _schema_from_callable(func) resolved_desc = description or func.__doc__ or "" spec = ToolSpec( name=name, description=resolved_desc.strip(), - resource_uri=resolved_uri, + resource_ura=resolved_uri, parameters=resolved_params, ) self._specs[name] = spec @@ -247,7 +247,7 @@ def register_ability( self, name: str, *, - resource_uri: str, + resource_ura: str, description: str = "", parameters: dict[str, Any] | None = None, ) -> None: @@ -255,7 +255,7 @@ def register_ability( spec = ToolSpec( name=name, description=description, - resource_uri=resource_uri, + resource_ura=resource_ura, parameters=parameters or {"type": "object", "properties": {}}, ) self._specs[name] = spec @@ -313,7 +313,7 @@ def execute(self, name: str, arguments: dict[str, Any] | str) -> Any: spec = self._specs.get(name) if spec is None: raise KeyError(f"unknown tool: {name}") - client = self._client(spec.resource_uri) + client = self._client(spec.resource_ura) return client.call(arguments) def execute_to_json(self, name: str, arguments: dict[str, Any] | str) -> str: diff --git a/sdk/python/tests/test_admission.py b/sdk/python/tests/test_admission.py index b692be2d..914eadde 100644 --- a/sdk/python/tests/test_admission.py +++ b/sdk/python/tests/test_admission.py @@ -32,7 +32,7 @@ InvocationEnvelope, KeyResolver, SubjectIdentity, - UriProfile, + UraProfile, canonical_invocation_bytes, sha256, sign_invocation, @@ -43,11 +43,11 @@ def _silan() -> AgentIdentity: - return AgentIdentity("easynet:///r/silan/agents/t@1", UriProfile.EASYNET_STRICT_V2) + return AgentIdentity("easynet:///r/silan/agents/t@1", UraProfile.EASYNET_STRICT_V2) def _openai() -> AgentIdentity: - return AgentIdentity("easynet:///r/openai/agents/t@1", UriProfile.EASYNET_STRICT_V2) + return AgentIdentity("easynet:///r/openai/agents/t@1", UraProfile.EASYNET_STRICT_V2) async def _echo(ctx): @@ -64,7 +64,7 @@ class _FixedResolver(KeyResolver): def __init__(self, key): self._key = key - def resolve(self, agent_uri: str): + def resolve(self, agent_ura: str): return self._key diff --git a/sdk/python/tests/test_audit.py b/sdk/python/tests/test_audit.py index 401f5b0f..d5ae060e 100644 --- a/sdk/python/tests/test_audit.py +++ b/sdk/python/tests/test_audit.py @@ -39,7 +39,7 @@ ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, canonical_receipt_bytes, sha256, ) @@ -47,9 +47,9 @@ def _sample_binding() -> AxiomBinding: return AxiomBinding( - caller=AgentIdentity("easynet:///r/silan/agents/a@1", UriProfile.EASYNET_STRICT_V2), - callee=AgentIdentity("easynet:///r/openai/agents/b@1", UriProfile.EASYNET_STRICT_V2), - subject=SubjectIdentity("easynet:///r/silan/papers/p@1", UriProfile.EASYNET_STRICT_V2), + caller=AgentIdentity("easynet:///r/silan/agents/a@1", UraProfile.EASYNET_STRICT_V2), + callee=AgentIdentity("easynet:///r/openai/agents/b@1", UraProfile.EASYNET_STRICT_V2), + subject=SubjectIdentity("easynet:///r/silan/papers/p@1", UraProfile.EASYNET_STRICT_V2), invocation_nonce=b"\x42" * 16, causal=CausalContext.none(), payload_digest=b"\x00" * 32, @@ -122,16 +122,16 @@ def test_tampering_any_binding_field_breaks_self_hash() -> None: r = _receipt(0, ZERO_HASH) b = r.axiom_binding if mutation == 0: - new_b = dataclasses.replace(b, caller=AgentIdentity("evil", UriProfile.EASYNET_STRICT_V2)) + new_b = dataclasses.replace(b, caller=AgentIdentity("evil", UraProfile.EASYNET_STRICT_V2)) elif mutation == 1: - new_b = dataclasses.replace(b, callee=AgentIdentity("evil", UriProfile.EASYNET_STRICT_V2)) + new_b = dataclasses.replace(b, callee=AgentIdentity("evil", UraProfile.EASYNET_STRICT_V2)) elif mutation == 2: - new_b = dataclasses.replace(b, subject=SubjectIdentity("evil", UriProfile.EASYNET_STRICT_V2)) + new_b = dataclasses.replace(b, subject=SubjectIdentity("evil", UraProfile.EASYNET_STRICT_V2)) elif mutation == 3: new_b = dataclasses.replace(b, invocation_nonce=b"\xFF" * 16) elif mutation == 4: new_b = dataclasses.replace( - b, causal=CausalContext.scalar(ReceiptRef(receipt_hash=b"\xAA" * 32, receipt_uri="r")) + b, causal=CausalContext.scalar(ReceiptRef(receipt_hash=b"\xAA" * 32, receipt_ura="r")) ) r.axiom_binding = new_b fresh = compute_receipt_hash(r) diff --git a/sdk/python/tests/test_axiom_vectors.py b/sdk/python/tests/test_axiom_vectors.py index ce42c380..69a1e221 100644 --- a/sdk/python/tests/test_axiom_vectors.py +++ b/sdk/python/tests/test_axiom_vectors.py @@ -28,7 +28,7 @@ KeyResolver, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, canonical_causal_context, canonical_invocation_bytes, sha256, @@ -51,7 +51,7 @@ def _causal_from(d: dict) -> CausalContext: return CausalContext.scalar( ReceiptRef( receipt_hash=bytes.fromhex(d["receipt_hash_hex"]), - receipt_uri=d["receipt_uri"], + receipt_ura=d["receipt_ura"], ) ) if form == "list": @@ -59,7 +59,7 @@ def _causal_from(d: dict) -> CausalContext: [ ReceiptRef( receipt_hash=bytes.fromhex(p["receipt_hash_hex"]), - receipt_uri=p["receipt_uri"], + receipt_ura=p["receipt_ura"], ) for p in d.get("prior", []) ] @@ -67,7 +67,7 @@ def _causal_from(d: dict) -> CausalContext: if form == "merkle": return CausalContext.merkle( root=bytes.fromhex(d["root_hex"]), - proof_uri=d["proof_uri"], + proof_ura=d["proof_ura"], ) raise AssertionError(f"unknown causal form: {form}") @@ -75,16 +75,16 @@ def _causal_from(d: dict) -> CausalContext: def _env_from(inp: dict) -> InvocationEnvelope: return InvocationEnvelope( caller=AgentIdentity( - uri=inp["caller"]["uri"], - profile=UriProfile.parse(inp["caller"]["profile"]), + ura=inp["caller"]["ura"], + profile=UraProfile.parse(inp["caller"]["profile"]), ), callee=AgentIdentity( - uri=inp["callee"]["uri"], - profile=UriProfile.parse(inp["callee"]["profile"]), + ura=inp["callee"]["ura"], + profile=UraProfile.parse(inp["callee"]["profile"]), ), subject=SubjectIdentity( - uri=inp["subject"]["uri"], - profile=UriProfile.parse(inp["subject"]["profile"]), + ura=inp["subject"]["ura"], + profile=UraProfile.parse(inp["subject"]["profile"]), ), ability=inp["ability"], args_digest=bytes.fromhex(inp["args_digest_hex"]), @@ -97,7 +97,7 @@ class _FixedResolver(KeyResolver): def __init__(self, key) -> None: self._key = key - def resolve(self, agent_uri: str): # type: ignore[override] + def resolve(self, agent_ura: str): # type: ignore[override] return self._key @@ -155,7 +155,7 @@ def _run_e3(v: dict) -> None: def _run_e4(v: dict) -> None: inp = v["inputs"] env = _env_from(inp) - assert env.callee.uri != env.subject.uri + assert env.callee.ura != env.subject.ura sk = signing_key_from_bytes(bytes.fromhex(inp["caller_secret_hex"])) sig = sign_invocation(sk, env) verify_invocation_signature(env, sig, _FixedResolver(sk.public_key())) @@ -194,9 +194,9 @@ def _run_profile_binding(v: dict) -> None: sk = signing_key_from_bytes(bytes.fromhex(inp["caller_secret_hex"])) sig = sign_invocation(sk, env) - new_profile = UriProfile.parse(inp["profile_swap_on_verify"]["caller"]) + new_profile = UraProfile.parse(inp["profile_swap_on_verify"]["caller"]) import dataclasses - tampered = dataclasses.replace(env, caller=AgentIdentity(uri=env.caller.uri, profile=new_profile)) + tampered = dataclasses.replace(env, caller=AgentIdentity(ura=env.caller.ura, profile=new_profile)) with pytest.raises(AxonError) as ex: verify_invocation_signature(tampered, sig, _FixedResolver(sk.public_key())) assert v["expect"]["expected_error_contains"] in ex.value.reason @@ -205,9 +205,9 @@ def _run_profile_binding(v: dict) -> None: def _run_subject_survives(v: dict) -> None: a = _env_from(v["inputs_a"]) b = _env_from(v["inputs_b"]) - assert a.subject.uri == b.subject.uri + assert a.subject.ura == b.subject.ura assert a.subject.profile == b.subject.profile - assert a.callee.uri != b.callee.uri + assert a.callee.ura != b.callee.ura assert canonical_invocation_bytes(a) != canonical_invocation_bytes(b) diff --git a/sdk/python/tests/test_axiom_worked_example.py b/sdk/python/tests/test_axiom_worked_example.py index 5dd95c52..db1a1e82 100644 --- a/sdk/python/tests/test_axiom_worked_example.py +++ b/sdk/python/tests/test_axiom_worked_example.py @@ -65,7 +65,7 @@ InvocationEnvelope, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, canonical_invocation_bytes, sha256, sign_invocation, @@ -171,20 +171,20 @@ def _build_envelope(inputs: dict) -> InvocationEnvelope: return InvocationEnvelope( caller=AgentIdentity( - uri=_require_str(caller["uri"], field="inputs.caller.uri"), - profile=UriProfile.parse( + ura=_require_str(caller["ura"], field="inputs.caller.ura"), + profile=UraProfile.parse( _require_str(caller["profile"], field="inputs.caller.profile") ), ), callee=AgentIdentity( - uri=_require_str(callee["uri"], field="inputs.callee.uri"), - profile=UriProfile.parse( + ura=_require_str(callee["ura"], field="inputs.callee.ura"), + profile=UraProfile.parse( _require_str(callee["profile"], field="inputs.callee.profile") ), ), subject=SubjectIdentity( - uri=_require_str(subject["uri"], field="inputs.subject.uri"), - profile=UriProfile.parse( + ura=_require_str(subject["ura"], field="inputs.subject.ura"), + profile=UraProfile.parse( _require_str(subject["profile"], field="inputs.subject.profile") ), ), diff --git a/sdk/python/tests/test_capability_request.py b/sdk/python/tests/test_capability_request.py index bf0d415b..b6e0932b 100644 --- a/sdk/python/tests/test_capability_request.py +++ b/sdk/python/tests/test_capability_request.py @@ -120,7 +120,7 @@ def test_missing_tenant_id_raises(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) with self.assertRaises(AxonConfigError) as ctx: req.validate() @@ -133,7 +133,7 @@ def test_missing_package_id_raises(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) with self.assertRaises(AxonConfigError) as ctx: req.validate() @@ -146,7 +146,7 @@ def test_missing_capability_name_raises(self) -> None: capability_name="", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) with self.assertRaises(AxonConfigError) as ctx: req.validate() @@ -159,7 +159,7 @@ def test_missing_version_raises(self) -> None: capability_name="cap-a", version=None, signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) with self.assertRaises(AxonConfigError) as ctx: req.validate() @@ -172,7 +172,7 @@ def test_missing_signature_raises(self) -> None: capability_name="cap-a", version="1.0.0", signature=None, - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) with self.assertRaises(AxonConfigError) as ctx: req.validate() @@ -181,7 +181,7 @@ def test_missing_signature_raises(self) -> None: # -- validation: payload source requirement -- def test_validate_requires_payload_source(self) -> None: - """Neither payload_uri nor package_bytes_base64 set.""" + """Neither payload_ura nor package_bytes_base64 set.""" req = PublishCapabilityRequest( tenant_id="tenant-a", package_id="pkg-a", @@ -191,16 +191,16 @@ def test_validate_requires_payload_source(self) -> None: ) with self.assertRaises(AxonConfigError) as ctx: req.validate() - self.assertIn("payload_uri", str(ctx.exception)) + self.assertIn("payload_ura", str(ctx.exception)) - def test_payload_uri_satisfies_payload_source(self) -> None: + def test_payload_ura_satisfies_payload_source(self) -> None: req = PublishCapabilityRequest( tenant_id="tenant-a", package_id="pkg-a", capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/payload.gz", + payload_ura="https://example.com/payload.gz", ) req.validate() # should not raise @@ -224,7 +224,7 @@ def test_validate_rejects_digest_only_without_payload_source(self) -> None: version="1.0.0", digest="sha256:abc", signature="c2ln", - payload_uri="", + payload_ura="", ) with self.assertRaises(AxonConfigError): req.validate() @@ -238,7 +238,7 @@ def test_validate_rejects_negative_payload_size(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", payload_size_bytes=-1, ) with self.assertRaises(AxonConfigError) as ctx: @@ -253,7 +253,7 @@ def test_validate_rejects_digest_without_sha256_prefix(self) -> None: version="1.0.0", digest="abc123", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) with self.assertRaises(AxonConfigError) as ctx: req.validate() @@ -267,7 +267,7 @@ def test_to_payload_runs_validation(self) -> None: version="1.0.0", digest="abc123", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) with self.assertRaises(AxonConfigError) as ctx: req.to_payload() @@ -283,7 +283,7 @@ def test_valid_request_produces_correct_payload(self) -> None: version="1.0.0", digest="sha256:abc", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", payload_size_bytes=42, signature_fingerprint="sig:abc", package_fingerprint="pkg:abc", @@ -298,7 +298,7 @@ def test_valid_request_produces_correct_payload(self) -> None: self.assertEqual("1.0.0", payload["version"]) self.assertEqual("sha256:abc", payload["digest"]) self.assertEqual("c2ln", payload["signature_base64"]) - self.assertEqual("https://example.com/p.gz", payload["payload_uri"]) + self.assertEqual("https://example.com/p.gz", payload["payload_ura"]) self.assertEqual(42, payload["payload_size_bytes"]) self.assertEqual("sig:abc", payload["signature_fingerprint"]) self.assertEqual("pkg:abc", payload["package_fingerprint"]) @@ -314,7 +314,7 @@ def test_digest_omitted_when_none(self) -> None: version="1.0.0", signature="c2ln", digest=None, - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) req.validate() payload = req.to_payload() @@ -328,7 +328,7 @@ def test_digest_omitted_when_blank(self) -> None: version="1.0.0", signature="c2ln", digest=" ", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", ) req.validate() payload = req.to_payload() @@ -344,7 +344,7 @@ def test_payload_omits_unset_optional_fields(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri=" ", # blank + payload_ura=" ", # blank package_bytes_base64="cGF5bG9hZA==", payload_size_bytes=0, publisher_key_version=0, @@ -354,7 +354,7 @@ def test_payload_omits_unset_optional_fields(self) -> None: req.validate() payload = req.to_payload() - self.assertNotIn("payload_uri", payload, "blank payload_uri must be omitted") + self.assertNotIn("payload_ura", payload, "blank payload_ura must be omitted") self.assertNotIn("payload_size_bytes", payload, "zero payload_size_bytes must be omitted") self.assertNotIn("publisher_key_version", payload, "zero publisher_key_version must be omitted") self.assertNotIn("signature_fingerprint", payload, "None signature_fingerprint must be omitted") @@ -369,7 +369,7 @@ def test_payload_size_bytes_included_when_positive(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", payload_size_bytes=42, ) req.validate() @@ -383,7 +383,7 @@ def test_payload_size_bytes_omitted_when_zero(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", payload_size_bytes=0, ) req.validate() @@ -399,7 +399,7 @@ def test_publisher_key_version_included_when_positive(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", publisher_key_version=3, ) req.validate() @@ -413,7 +413,7 @@ def test_publisher_key_version_omitted_when_zero(self) -> None: capability_name="cap-a", version="1.0.0", signature="c2ln", - payload_uri="https://example.com/p.gz", + payload_ura="https://example.com/p.gz", publisher_key_version=0, ) req.validate() @@ -430,7 +430,7 @@ def test_payload_trims_strings(self) -> None: capability_name=" cap-a ", version=" 1.0.0 ", signature=" c2ln ", - payload_uri=" https://example.com/p.gz ", + payload_ura=" https://example.com/p.gz ", ) req.validate() payload = req.to_payload() @@ -441,7 +441,7 @@ def test_payload_trims_strings(self) -> None: self.assertEqual("cap-a", payload["capability_name"]) self.assertEqual("1.0.0", payload["version"]) self.assertEqual("c2ln", payload["signature_base64"]) - self.assertEqual("https://example.com/p.gz", payload["payload_uri"]) + self.assertEqual("https://example.com/p.gz", payload["payload_ura"]) # --------------------------------------------------------------- diff --git a/sdk/python/tests/test_cross_language_verify.py b/sdk/python/tests/test_cross_language_verify.py index 41fe240b..8e6a71ca 100644 --- a/sdk/python/tests/test_cross_language_verify.py +++ b/sdk/python/tests/test_cross_language_verify.py @@ -35,7 +35,7 @@ ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, canonical_receipt_bytes, sha256, sign_invocation, @@ -149,9 +149,9 @@ def _build_bundle(tmp_path: Path) -> Path: _write_key(bundle, "silan", sk_silan) _write_key(bundle, "openai", sk_openai) - silan = AgentIdentity("easynet:///r/silan/agents/writer@1", UriProfile.EASYNET_STRICT_V2) - openai = AgentIdentity("easynet:///r/openai/agents/reviewer@1", UriProfile.EASYNET_STRICT_V2) - paper = SubjectIdentity("easynet:///r/silan/papers/p@draft-1", UriProfile.EASYNET_STRICT_V2) + silan = AgentIdentity("easynet:///r/silan/agents/writer@1", UraProfile.EASYNET_STRICT_V2) + openai = AgentIdentity("easynet:///r/openai/agents/reviewer@1", UraProfile.EASYNET_STRICT_V2) + paper = SubjectIdentity("easynet:///r/silan/papers/p@draft-1", UraProfile.EASYNET_STRICT_V2) # Invocation A: root. env_a = InvocationEnvelope( @@ -178,7 +178,7 @@ def _build_bundle(tmp_path: Path) -> Path: causal_context=CausalContext.scalar( ReceiptRef( receipt_hash=a_terminal_hash, - receipt_uri="bundle:///receipts/inv-a/1", + receipt_ura="bundle:///receipts/inv-a/1", ) ), ) diff --git a/sdk/python/tests/test_federation_conformance.py b/sdk/python/tests/test_federation_conformance.py index b7de42b8..c1b17b88 100644 --- a/sdk/python/tests/test_federation_conformance.py +++ b/sdk/python/tests/test_federation_conformance.py @@ -12,14 +12,14 @@ class _CapturingBridge(DendriteBridge): - """Subclass that captures the (resource_uri, payload) of the most recent + """Subclass that captures the (resource_ura, payload) of the most recent `ability_call_raw` invocation without doing FFI. Used so federation_* helpers can be exercised without a live runtime. """ def __init__(self) -> None: # noqa: D401 — minimal stub # Skip the parent __init__ entirely; we never touch the FFI handle. - self.last_resource_uri: str | None = None + self.last_resource_ura: str | None = None self.last_payload: dict | None = None self.last_timeout_ms: int | None = None @@ -27,13 +27,13 @@ def ability_call_raw( # type: ignore[override] self, *, tenant_id: str, - resource_uri: str, + resource_ura: str, payload_json, subject_id=None, metadata=None, timeout_ms: int = 30000, ) -> dict: - self.last_resource_uri = resource_uri + self.last_resource_ura = resource_ura self.last_payload = payload_json self.last_timeout_ms = timeout_ms return {} @@ -41,21 +41,21 @@ def ability_call_raw( # type: ignore[override] def test_v1_advertise_agent_minimal() -> None: b = _CapturingBridge() - b.federation_advertise_agent("t", "axon://realm/foo") - assert b.last_resource_uri == "federation.advertise_agent" - assert b.last_payload == {"agent_uri": "axon://realm/foo"} + b.federation_advertise_agent("t", "easynet:///r/realm/agent/foo") + assert b.last_resource_ura == "federation.advertise_agent" + assert b.last_payload == {"agent_ura": "easynet:///r/realm/agent/foo"} def test_v2_advertise_agent_full() -> None: b = _CapturingBridge() b.federation_advertise_agent( "t", - "axon://realm/foo", + "easynet:///r/realm/agent/foo", public_key_hex="deadbeef", signing_authority={"kind": "self_signed"}, ) assert b.last_payload == { - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "public_key_hex": "deadbeef", "signing_authority": {"kind": "self_signed"}, } @@ -65,37 +65,37 @@ def test_v3_advertise_agent_omit_empty() -> None: b = _CapturingBridge() b.federation_advertise_agent( "t", - "axon://realm/foo", + "easynet:///r/realm/agent/foo", public_key_hex="", signing_authority={}, ) - assert b.last_payload == {"agent_uri": "axon://realm/foo"} + assert b.last_payload == {"agent_ura": "easynet:///r/realm/agent/foo"} def test_v4_heartbeat_empty_body() -> None: b = _CapturingBridge() b.federation_heartbeat("t") - assert b.last_resource_uri == "federation.heartbeat" + assert b.last_resource_ura == "federation.heartbeat" assert b.last_payload == {} def test_v5_revoke_no_reason() -> None: b = _CapturingBridge() - b.federation_revoke("t", "axon://realm/foo") - assert b.last_payload == {"agent_uri": "axon://realm/foo"} + b.federation_revoke("t", "easynet:///r/realm/agent/foo") + assert b.last_payload == {"agent_ura": "easynet:///r/realm/agent/foo"} def test_v5b_revoke_blank_reason_omitted() -> None: b = _CapturingBridge() - b.federation_revoke("t", "axon://realm/foo", reason="") - assert b.last_payload == {"agent_uri": "axon://realm/foo"} + b.federation_revoke("t", "easynet:///r/realm/agent/foo", reason="") + assert b.last_payload == {"agent_ura": "easynet:///r/realm/agent/foo"} def test_v6_revoke_with_reason() -> None: b = _CapturingBridge() - b.federation_revoke("t", "axon://realm/foo", reason="operator: maintenance") + b.federation_revoke("t", "easynet:///r/realm/agent/foo", reason="operator: maintenance") assert b.last_payload == { - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "reason": "operator: maintenance", } @@ -103,7 +103,7 @@ def test_v6_revoke_with_reason() -> None: def test_v7_resolve_no_filter() -> None: b = _CapturingBridge() b.federation_resolve("t") - assert b.last_resource_uri == "federation.resolve" + assert b.last_resource_ura == "federation.resolve" assert b.last_payload == {} @@ -111,12 +111,12 @@ def test_v8_resolve_with_filter() -> None: b = _CapturingBridge() b.federation_resolve( "t", - agent_uri_prefix="axon://realm/edge-", + agent_ura_prefix="easynet:///r/realm/agent/edge-", include_abilities=True, ) assert b.last_payload == { "filter": { - "agent_uri_prefix": "axon://realm/edge-", + "agent_ura_prefix": "easynet:///r/realm/agent/edge-", "include_abilities": True, } } @@ -124,9 +124,9 @@ def test_v8_resolve_with_filter() -> None: def test_v9_advertise_abilities() -> None: b = _CapturingBridge() - b.federation_advertise_abilities("t", "axon://realm/foo", [{"name": "echo"}]) + b.federation_advertise_abilities("t", "easynet:///r/realm/agent/foo", [{"name": "echo"}]) assert b.last_payload == { - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "abilities": [{"name": "echo"}], } @@ -134,7 +134,7 @@ def test_v9_advertise_abilities() -> None: def test_v10_join_minimal() -> None: b = _CapturingBridge() b.federation_join("t", "easynet", "deadbeef") - assert b.last_resource_uri == "federation.join" + assert b.last_resource_ura == "federation.join" assert b.last_payload == {"realm": "easynet", "public_key_hex": "deadbeef"} @@ -164,5 +164,5 @@ def test_heartbeat_default_timeout_is_5s() -> None: def test_other_helpers_default_timeout_is_30s() -> None: b = _CapturingBridge() - b.federation_advertise_agent("t", "axon://realm/foo") + b.federation_advertise_agent("t", "easynet:///r/realm/agent/foo") assert b.last_timeout_ms == 30_000 diff --git a/sdk/python/tests/test_invoke_signed.py b/sdk/python/tests/test_invoke_signed.py index 3980daa8..98853786 100644 --- a/sdk/python/tests/test_invoke_signed.py +++ b/sdk/python/tests/test_invoke_signed.py @@ -20,7 +20,7 @@ CausalContext, KeyResolver, SubjectIdentity, - UriProfile, + UraProfile, canonical_invocation_bytes, signing_key_from_bytes, verify_invocation_signature, @@ -30,11 +30,11 @@ def _silan() -> AgentIdentity: - return AgentIdentity("easynet:///r/silan/agents/t@1", UriProfile.EASYNET_STRICT_V2) + return AgentIdentity("easynet:///r/silan/agents/t@1", UraProfile.EASYNET_STRICT_V2) def _openai() -> AgentIdentity: - return AgentIdentity("easynet:///r/openai/agents/t@1", UriProfile.EASYNET_STRICT_V2) + return AgentIdentity("easynet:///r/openai/agents/t@1", UraProfile.EASYNET_STRICT_V2) async def _echo(ctx): @@ -45,7 +45,7 @@ class _FixedResolver(KeyResolver): def __init__(self, key): self._key = key - def resolve(self, agent_uri: str): + def resolve(self, agent_ura: str): return self._key @@ -59,7 +59,7 @@ def test_invoke_signed_with_explicit_subject_and_nonce_verifies() -> None: async def run() -> None: rt = _echo_runtime() sk = signing_key_from_bytes(bytes([7] * 32)) - subject = SubjectIdentity("easynet:///r/silan/papers/p@d1", UriProfile.EASYNET_STRICT_V2) + subject = SubjectIdentity("easynet:///r/silan/papers/p@d1", UraProfile.EASYNET_STRICT_V2) handle, signed = await rt.invoke_signed_async( caller=_silan(), callee=_openai(), @@ -73,7 +73,7 @@ async def run() -> None: stored = await rt.axiom_envelope_of(handle.invocation_id) assert stored is not None - assert stored.envelope.subject.uri == subject.uri + assert stored.envelope.subject.ura == subject.ura assert stored.envelope.invocation_nonce == b"\xAB" * 16 verify_invocation_signature(signed.envelope, signed.signature, _FixedResolver(sk.public_key())) @@ -95,7 +95,7 @@ async def run() -> None: signing_key=sk, nonce=b"\x11" * 16, ) - assert signed.envelope.subject.uri == signed.envelope.callee.uri + assert signed.envelope.subject.ura == signed.envelope.callee.ura assert signed.envelope.subject.profile == signed.envelope.callee.profile asyncio.run(run()) @@ -140,7 +140,7 @@ async def run() -> None: def _receipt_ref(hash_byte: int = 0x99) -> object: from easynet_axon.invocation.axiom import ReceiptRef - return ReceiptRef(receipt_hash=bytes([hash_byte] * 32), receipt_uri="evil") + return ReceiptRef(receipt_hash=bytes([hash_byte] * 32), receipt_ura="evil") def test_payload_enters_args_digest() -> None: @@ -173,11 +173,11 @@ async def run() -> None: _, signed = await rt.invoke_signed_async( caller=_silan(), callee=_openai(), ability="echo", payload=b"", signing_key=sk, nonce=b"\x11" * 16, - subject=SubjectIdentity("easynet:///r/silan/papers/p@1", UriProfile.EASYNET_STRICT_V2), + subject=SubjectIdentity("easynet:///r/silan/papers/p@1", UraProfile.EASYNET_STRICT_V2), ) import dataclasses tampered_subject = SubjectIdentity( - "easynet:///r/mallory/papers/evil@1", UriProfile.EASYNET_STRICT_V2 + "easynet:///r/mallory/papers/evil@1", UraProfile.EASYNET_STRICT_V2 ) tampered = dataclasses.replace(signed.envelope, subject=tampered_subject) with pytest.raises(AxonError) as ex: @@ -232,7 +232,7 @@ async def run() -> None: handle, signed = await rt.invoke_signed_async( caller=_silan(), callee=_openai(), ability="echo", payload=b"stable", signing_key=sk, nonce=b"\x44" * 16, - subject=SubjectIdentity("easynet:///r/silan/papers/p@stable", UriProfile.EASYNET_STRICT_V2), + subject=SubjectIdentity("easynet:///r/silan/papers/p@stable", UraProfile.EASYNET_STRICT_V2), ) await handle.wait() stored = await rt.axiom_envelope_of(handle.invocation_id) diff --git a/sdk/python/tests/test_stream_resume.py b/sdk/python/tests/test_stream_resume.py index 7d6ccf71..f828d7ef 100644 --- a/sdk/python/tests/test_stream_resume.py +++ b/sdk/python/tests/test_stream_resume.py @@ -158,7 +158,7 @@ def always_fails() -> _Script: def test_factory_application_error_propagates_without_retry() -> None: """A factory failure that is NOT transport-classified must propagate on the first call; no retry attempts are consumed. This keeps - misconfigurations (invalid resource_uri, missing tenant, etc.) + misconfigurations (invalid resource_ura, missing tenant, etc.) surfacing loudly instead of getting masked by the retry loop.""" call_log: List[int] = [] diff --git a/sdk/react/src/ability_lifecycle.js b/sdk/react/src/ability_lifecycle.js index 960bf1e4..9096fc4c 100644 --- a/sdk/react/src/ability_lifecycle.js +++ b/sdk/react/src/ability_lifecycle.js @@ -6,7 +6,7 @@ // // Protocol Responsibility: // - Defines typed ability descriptors, export targets, and deployment helpers exposed to SDK users. -// - Keeps cross-language ability naming, resource-uri, and tool-spec semantics aligned. +// - Keeps cross-language ability naming, resource-ura, and tool-spec semantics aligned. // // Implementation Approach: // - Separates pure descriptor/export helpers from bridge-backed deployment and invocation flows. @@ -64,7 +64,7 @@ export function buildAbilityDescriptor({ outputSchema, version, tags, - resourceUri, + resourceUra, }) { if (!name?.trim()) throw new AxonConfigError("ability name cannot be empty"); if (!commandTemplate?.trim()) @@ -79,7 +79,7 @@ export function buildAbilityDescriptor({ outputSchema: outputSchema ?? { type: "object", properties: {} }, version: version ?? "1.0.0", tags: tags ?? [], - resourceUri: resourceUri ?? `easynet:///r/org/${token}`, + resourceUra: resourceUra ?? `easynet:///r/org/${token}`, }; } @@ -90,7 +90,7 @@ export function buildAbilityDescriptor({ export function exportAbility(descriptor, target = "agent_skills", axonEndpoint) { const token = descriptor.toolName; const endpoint = axonEndpoint ?? `http://127.0.0.1:${DEFAULT_AXON_PORT}`; - const invokeScript = generateInvokeScript(descriptor.resourceUri, endpoint); + const invokeScript = generateInvokeScript(descriptor.resourceUra, endpoint); const abilityMd = generateAbilityMd(descriptor, target, token); return { abilityMd, invokeScript, abilityName: token }; } @@ -421,7 +421,7 @@ export function useAbilityLifecycle() { return { name: token, description: descriptor.description, - resourceUri: descriptor.resourceUri, + resourceUra: descriptor.resourceUra, parameters: descriptor.inputSchema, }; }, [descriptor]); @@ -433,24 +433,24 @@ export function useAbilityLifecycle() { // Internal generators // --------------------------------------------------------------------------- -function generateInvokeScript(resourceUri, endpoint) { +function generateInvokeScript(resourceUra, endpoint) { return `#!/usr/bin/env bash set -euo pipefail AXON_ENDPOINT="\${AXON_ENDPOINT:-${endpoint}}" TENANT="\${AXON_TENANT:-default}" -RESOURCE_URI="${resourceUri}" +RESOURCE_URA="${resourceUra}" ARGS="\${1:-{}}" curl -sS -X POST "\${AXON_ENDPOINT}/v1/invoke" \\ -H "Content-Type: application/json" \\ - -d "{\\"tenant_id\\":\\"\${TENANT}\\",\\"resource_uri\\":\\"\${RESOURCE_URI}\\",\\"payload\\":\${ARGS}}" + -d "{\\"tenant_id\\":\\"\${TENANT}\\",\\"resource_ura\\":\\"\${RESOURCE_URA}\\",\\"payload\\":\${ARGS}}" `; } -function pushMetadata(lines, version, resourceUri) { +function pushMetadata(lines, version, resourceUra) { lines.push("metadata:"); lines.push(" author: easynet-axon"); lines.push(` version: "${version}"`); - lines.push(` axon-resource-uri: "${resourceUri}"`); + lines.push(` axon-resource-ura: "${resourceUra}"`); } function generateAbilityMd(descriptor, target, token) { @@ -460,7 +460,7 @@ function generateAbilityMd(descriptor, target, token) { lines.push(`description: ${descriptor.description}`); lines.push("compatibility: Requires network access to Axon runtime"); - pushMetadata(lines, descriptor.version, descriptor.resourceUri); + pushMetadata(lines, descriptor.version, descriptor.resourceUra); if (target === "claude") { lines.push("allowed-tools: Bash(*)"); } else if (target === "openclaw") { @@ -505,7 +505,7 @@ function generateAbilityMd(descriptor, target, token) { lines.push(""); lines.push("## Axon Resource"); lines.push(""); - lines.push(`- **URI**: \`${descriptor.resourceUri}\``); + lines.push(`- **URA**: \`${descriptor.resourceUra}\``); lines.push(`- **Version**: ${descriptor.version}`); lines.push(""); diff --git a/sdk/react/src/index.d.ts b/sdk/react/src/index.d.ts index 300e21c0..a12e691a 100644 --- a/sdk/react/src/index.d.ts +++ b/sdk/react/src/index.d.ts @@ -33,7 +33,7 @@ export interface AbilityHook { } export function useAbility( - resourceUri: string, + resourceUra: string, options: { tenant: string; principal?: string; transport?: Transport } ): AbilityHook; export { useAbilityTools } from "./tool_adapter.js"; diff --git a/sdk/react/src/index.js b/sdk/react/src/index.js index 9abf3cb4..db9d675a 100644 --- a/sdk/react/src/index.js +++ b/sdk/react/src/index.js @@ -29,7 +29,7 @@ import { client as createClient } from "@easynet-run/node"; export { useAbilityTools } from "./tool_adapter.js"; -export function useAbility(resourceUri, options) { +export function useAbility(resourceUra, options) { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const inflight = useRef(0); @@ -39,8 +39,8 @@ export function useAbility(resourceUri, options) { if (options.principal) { c = c.principal(options.principal); } - return c.ability(resourceUri); - }, [options.transport, options.tenant, options.principal, resourceUri]); + return c.ability(resourceUra); + }, [options.transport, options.tenant, options.principal, resourceUra]); return { loading, diff --git a/sdk/react/src/index.ts b/sdk/react/src/index.ts index eebe90f8..7c620e7a 100644 --- a/sdk/react/src/index.ts +++ b/sdk/react/src/index.ts @@ -41,7 +41,7 @@ export interface AbilityHook { } export function useAbility( - resourceUri: string, + resourceUra: string, options: { tenant: string; principal?: string; transport?: Transport } ): AbilityHook { const [loading, setLoading] = useState(false); @@ -53,8 +53,8 @@ export function useAbility( if (options.principal) { c = c.principal(options.principal); } - return c.ability(resourceUri); - }, [options.transport, options.tenant, options.principal, resourceUri]); + return c.ability(resourceUra); + }, [options.transport, options.tenant, options.principal, resourceUra]); return { loading, diff --git a/sdk/react/src/tool_adapter.d.ts b/sdk/react/src/tool_adapter.d.ts index e2fde73f..1517711a 100644 --- a/sdk/react/src/tool_adapter.d.ts +++ b/sdk/react/src/tool_adapter.d.ts @@ -30,7 +30,7 @@ import type { JsonValue, Transport } from "@easynet-run/node"; export interface ToolRegistration { name: string; handler?: (args: Record) => JsonValue | Promise; - resourceUri?: string; + resourceUra?: string; description?: string; parameters?: Record; } diff --git a/sdk/react/src/tool_adapter.js b/sdk/react/src/tool_adapter.js index fc6d7fab..0377e147 100644 --- a/sdk/react/src/tool_adapter.js +++ b/sdk/react/src/tool_adapter.js @@ -35,7 +35,7 @@ import { AbilityToolAdapter } from "@easynet-run/node/tool-adapter"; * @param {object} [options.transport] - Optional custom transport. * @param {string} [options.principalId] - Optional principal context for remote tool execution. * @param {"openai"|"anthropic"|"dict"} [options.format="openai"] - Output format for tool definitions. - * @param {Array<{name: string, handler?: Function, resourceUri?: string, description?: string, parameters?: object}>} [options.tools] - Tool registrations. + * @param {Array<{name: string, handler?: Function, resourceUra?: string, description?: string, parameters?: object}>} [options.tools] - Tool registrations. * * @returns {{ tools: Array, execute: Function, executing: boolean, error: Error|null }} * @@ -53,7 +53,7 @@ import { AbilityToolAdapter } from "@easynet-run/node/tool-adapter"; * }, * { * name: "photo_capture", - * resourceUri: "easynet:///r/org/photo_capture", + * resourceUra: "easynet:///r/org/photo_capture", * description: "Capture a photo.", * }, * ], @@ -75,7 +75,7 @@ export function useAbilityTools(options) { // If dynamic parameters are needed, wrap the tools array in useMemo at the // call site. const toolsKey = useMemo( - () => (options.tools ? JSON.stringify(options.tools.map((t) => [t.name, t.resourceUri, t.description])) : ""), + () => (options.tools ? JSON.stringify(options.tools.map((t) => [t.name, t.resourceUra, t.description])) : ""), [options.tools] ); @@ -88,11 +88,11 @@ export function useAbilityTools(options) { if (tool.handler) { a.register(tool.name, tool.handler, { description: tool.description, - resourceUri: tool.resourceUri, + resourceUra: tool.resourceUra, parameters: tool.parameters, }); - } else if (tool.resourceUri) { - a.registerAbility(tool.name, tool.resourceUri, { + } else if (tool.resourceUra) { + a.registerAbility(tool.name, tool.resourceUra, { description: tool.description, parameters: tool.parameters, }); diff --git a/sdk/react/src/tool_adapter.ts b/sdk/react/src/tool_adapter.ts index a3273bdf..d79085f7 100644 --- a/sdk/react/src/tool_adapter.ts +++ b/sdk/react/src/tool_adapter.ts @@ -36,7 +36,7 @@ import type { JsonValue, Transport } from "@easynet-run/node"; export interface ToolRegistration { name: string; handler?: (args: Record) => JsonValue | Promise; - resourceUri?: string; + resourceUra?: string; description?: string; parameters?: Record; } @@ -69,11 +69,11 @@ export function useAbilityTools(options: UseAbilityToolsOptions): AbilityToolsHo if (tool.handler) { next.register(tool.name, tool.handler, { description: tool.description, - resourceUri: tool.resourceUri, + resourceUra: tool.resourceUra, parameters: tool.parameters as never, }); - } else if (tool.resourceUri) { - next.registerAbility(tool.name, tool.resourceUri, { + } else if (tool.resourceUra) { + next.registerAbility(tool.name, tool.resourceUra, { description: tool.description, parameters: tool.parameters as never, }); diff --git a/sdk/rust/Cargo.lock b/sdk/rust/Cargo.lock index 65ee54f5..88a28100 100644 --- a/sdk/rust/Cargo.lock +++ b/sdk/rust/Cargo.lock @@ -8,6 +8,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -165,6 +175,30 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "ciborium" version = "0.2.2" @@ -192,6 +226,17 @@ dependencies = [ "half", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + [[package]] name = "clang-sys" version = "1.8.1" @@ -387,6 +432,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -448,6 +494,7 @@ name = "easynet-axon" version = "0.55.2" dependencies = [ "base64", + "chacha20poly1305", "cpal", "criterion", "ed25519-dalek", @@ -458,16 +505,19 @@ dependencies = [ "libc", "libloading", "rand", + "redb", "serde", "serde_jcs", "serde_json", "sha2", "tar", + "tempfile", "thiserror 2.0.18", "tokio", "tracing", "uuid", "webrtc-vad", + "x25519-dalek", ] [[package]] @@ -517,6 +567,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -764,6 +820,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "is-terminal" version = "0.4.17" @@ -1069,6 +1134,12 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1125,6 +1196,17 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1233,6 +1315,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "redb" +version = "2.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eca1e9d98d5a7e9002d0013e18d5a9b000aee942eb134883a82f06ebffb6c01" +dependencies = [ + "libc", +] + [[package]] name = "redox_syscall" version = "0.7.4" @@ -1466,6 +1557,19 @@ dependencies = [ "xattr", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -1621,6 +1725,16 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "uuid" version = "1.23.1" @@ -2066,6 +2180,18 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core", + "serde", + "zeroize", +] + [[package]] name = "xattr" version = "1.6.1" @@ -2101,6 +2227,20 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "zmij" diff --git a/sdk/rust/Cargo.toml b/sdk/rust/Cargo.toml index 5743357a..05f511a9 100644 --- a/sdk/rust/Cargo.toml +++ b/sdk/rust/Cargo.toml @@ -32,6 +32,9 @@ tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros", "sync", futures = "0.3" hex = "0.4" uuid = { version = "1", features = ["v4"] } +chacha20poly1305 = "0.10" +redb = "2" +x25519-dalek = { version = "2.0", features = ["static_secrets"] } # Audio (optional; gated by the `audio` feature). # cpal provides cross-platform audio I/O (CoreAudio / ALSA / WASAPI). # webrtc-vad is a pure-Rust port of Google's WebRTC VAD. @@ -70,6 +73,7 @@ path = "src/bin/verify.rs" [dev-dependencies] criterion = { version = "0.5", features = ["async_tokio"] } +tempfile = "3" [[bench]] name = "invocation_core" diff --git a/sdk/rust/README.md b/sdk/rust/README.md index 964b174a..9442b4ed 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -56,7 +56,7 @@ For strict multi-target CI parity, use the matching release pack: use easynet_axon::AbilityDescriptor; let descriptor = AbilityDescriptor::builder() - .resource_uri("easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1") + .resource_ura("easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1") .build()?; // Convert to LLM tool spec for MCP/OpenAI/Anthropic interop diff --git a/sdk/rust/benches/admission_replay.rs b/sdk/rust/benches/admission_replay.rs index 50e63a94..d4466c75 100644 --- a/sdk/rust/benches/admission_replay.rs +++ b/sdk/rust/benches/admission_replay.rs @@ -30,7 +30,7 @@ use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criteri use easynet_axon::invocation::admission::NonceReplayStore; use tokio::sync::Barrier; -fn caller_uri() -> &'static str { +fn caller_ura() -> &'static str { "easynet:///r/silan/agents/alice" } fn ability() -> &'static str { @@ -48,7 +48,7 @@ fn bench_clean_store(c: &mut Criterion) { // growth". let mut s = NonceReplayStore::new(); s.check_and_record( - black_box(caller_uri()), + black_box(caller_ura()), black_box(ability()), black_box(nonce(0)), 1_700_000_000_000, @@ -112,7 +112,7 @@ fn bench_store_size_scaling(c: &mut Criterion) { // Reset prune state every call so none fires. s.set_prune_state_for_bench(1_700_000_000_000); s.check_and_record( - black_box(caller_uri()), + black_box(caller_ura()), black_box(ability()), black_box(*nb), 1_700_000_000_000, @@ -147,7 +147,7 @@ fn bench_store_size_scaling(c: &mut Criterion) { let mut nb = [0u8; 16]; nb[0..4].copy_from_slice(&(j as u32).to_be_bytes()); let ts = bucket_width * (j as i64 % 128); - s.insert_raw_for_bench(caller_uri(), ability(), nb, ts); + s.insert_raw_for_bench(caller_ura(), ability(), nb, ts); } // Position cursor so the next call advances 4 // buckets forward, crossing into previously- @@ -157,7 +157,7 @@ fn bench_store_size_scaling(c: &mut Criterion) { nb[8..16].copy_from_slice(&i.to_be_bytes()); let call_start = std::time::Instant::now(); s.check_and_record( - black_box(caller_uri()), + black_box(caller_ura()), black_box(ability()), black_box(nb), bucket_width * (128 + 4) + 1, @@ -183,7 +183,7 @@ fn build_steady_state_store(n: usize) -> NonceReplayStore { for i in 0..n { let mut nb = [0u8; 16]; nb[0..4].copy_from_slice(&(i as u32).to_be_bytes()); - s.insert_raw_for_bench(caller_uri(), ability(), nb, now); + s.insert_raw_for_bench(caller_ura(), ability(), nb, now); } s.set_prune_state_for_bench(now); s @@ -215,7 +215,7 @@ fn bench_contention(c: &mut Criterion) { // is measured separately below.) let mut nb = [0u8; 16]; nb[0] = i as u8; - g.check_and_record(caller_uri(), ability(), nb, 1_700_000_000_000) + g.check_and_record(caller_ura(), ability(), nb, 1_700_000_000_000) .unwrap(); })); } @@ -235,13 +235,13 @@ fn bench_replay_hit(c: &mut Criterion) { // Store with the key pre-inserted so the next call // hits the dedup window. let mut s = NonceReplayStore::new(); - s.check_and_record(caller_uri(), ability(), nonce(0xAA), 1_700_000_000_000) + s.check_and_record(caller_ura(), ability(), nonce(0xAA), 1_700_000_000_000) .unwrap(); s }, |mut s| { let r = s.check_and_record( - black_box(caller_uri()), + black_box(caller_ura()), black_box(ability()), black_box(nonce(0xAA)), 1_700_000_000_000, diff --git a/sdk/rust/benches/invocation_core.rs b/sdk/rust/benches/invocation_core.rs index 39e4123a..d549f169 100644 --- a/sdk/rust/benches/invocation_core.rs +++ b/sdk/rust/benches/invocation_core.rs @@ -27,18 +27,18 @@ use std::sync::Arc; use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput}; use easynet_axon::invocation::audit::AxiomBinding; -use easynet_axon::invocation::axiom::{AgentIdentity, CausalContext, SubjectIdentity, UriProfile}; +use easynet_axon::invocation::axiom::{AgentIdentity, CausalContext, SubjectIdentity, UraProfile}; use easynet_axon::invocation::handle::{EmitExtras, InvocationCore, InvocationState}; use tokio::sync::Barrier; fn sample_binding() -> AxiomBinding { AxiomBinding { - caller: AgentIdentity::new("easynet:///r/silan/agents/a@1", UriProfile::EasynetStrictV2), + caller: AgentIdentity::new("easynet:///r/silan/agents/a@1", UraProfile::EasynetStrictV2), callee: AgentIdentity::new( "easynet:///r/openai/agents/b@1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ), - subject: SubjectIdentity::new("easynet:///r/silan/papers/p@1", UriProfile::EasynetStrictV2), + subject: SubjectIdentity::new("easynet:///r/silan/papers/p@1", UraProfile::EasynetStrictV2), invocation_nonce: [0x42u8; 16], causal: CausalContext::None, payload_digest: [0u8; 32], diff --git a/sdk/rust/examples/emit_worked_example.rs b/sdk/rust/examples/emit_worked_example.rs index 90788dda..7278b1aa 100644 --- a/sdk/rust/examples/emit_worked_example.rs +++ b/sdk/rust/examples/emit_worked_example.rs @@ -11,7 +11,7 @@ use easynet_axon::invocation::axiom::{ canonical_invocation_bytes, sha256, sign_invocation, signing_key_from_bytes, AgentIdentity, - CausalContext, InvocationEnvelope, SubjectIdentity, UriProfile, + CausalContext, InvocationEnvelope, SubjectIdentity, UraProfile, }; fn main() { @@ -19,15 +19,15 @@ fn main() { let seed: [u8; 32] = [0x01; 32]; let caller = AgentIdentity::new( "easynet:///r/silan/agents/alice", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let callee = AgentIdentity::new( "easynet:///r/openai/agents/reviewer@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let subject = SubjectIdentity::new( "easynet:///r/silan/papers/paper@draft-1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let ability = "review"; let payload = b"{}"; diff --git a/sdk/rust/src/ability.rs b/sdk/rust/src/ability.rs index 0a4287f4..eda45d30 100644 --- a/sdk/rust/src/ability.rs +++ b/sdk/rust/src/ability.rs @@ -6,7 +6,7 @@ //! //! Protocol Responsibility: //! - Defines typed ability descriptors, export targets, and deployment helpers exposed to SDK users. -//! - Keeps cross-language ability naming, resource-uri, and tool-spec semantics aligned. +//! - Keeps cross-language ability naming, resource-ura, and tool-spec semantics aligned. //! //! Implementation Approach: //! - Separates pure descriptor/export helpers from bridge-backed deployment and invocation flows. @@ -40,6 +40,7 @@ use crate::dendrite_bridge::DendriteBridge; use crate::error::{AxonError, Result}; use crate::presets::remote_control::DeployResult; use crate::tool_adapter::ToolSpec; +use crate::ura; use crate::utils::{normalize_id, str_from_value}; /// Placeholder signature used for ephemeral / temporary skill deployments @@ -61,7 +62,7 @@ pub struct AbilityDescriptor { pub output_schema: Value, pub version: String, pub tags: Vec, - pub resource_uri: String, + pub resource_ura: String, // Agent ecosystem extensions (SKILL.md / MCP / CLI) pub instructions: String, /// Example input objects as JSON strings. Each entry is a serialized JSON @@ -105,7 +106,7 @@ impl AbilityDescriptor { output_schema: None, version: None, tags: None, - resource_uri: None, + resource_ura: None, read_only: None, destructive: None, idempotent: None, @@ -126,7 +127,7 @@ impl AbilityDescriptor { output_schema: Option, version: Option, tags: Option>, - resource_uri: Option, + resource_ura: Option, ) -> Result { let name = name.into(); if name.trim().is_empty() { @@ -139,7 +140,8 @@ impl AbilityDescriptor { )); } let tool_name = normalize_ability_name(&name)?; - let resource_uri = resource_uri.unwrap_or_else(|| format!("easynet:///r/org/{tool_name}")); + let resource_ura = + resource_ura.unwrap_or_else(|| ura::resource_dot_ura("org", &tool_name, "")); Ok(Self { name, tool_name, @@ -151,7 +153,7 @@ impl AbilityDescriptor { .unwrap_or_else(|| json!({"type": "object", "properties": {}})), version: version.unwrap_or_else(|| "1.0.0".into()), tags: tags.unwrap_or_default(), - resource_uri, + resource_ura, instructions: String::new(), input_examples: Vec::new(), prerequisites: Vec::new(), @@ -173,7 +175,7 @@ impl AbilityDescriptor { ToolSpec { name: self.tool_name.clone(), description: self.description.clone(), - resource_uri: self.resource_uri.clone(), + resource_ura: self.resource_ura.clone(), parameters: self.input_schema.clone(), } } @@ -221,7 +223,7 @@ pub struct AbilityDescriptorBuilder { output_schema: Option, version: Option, tags: Option>, - resource_uri: Option, + resource_ura: Option, // MCP safety hints (overrides for fail-closed defaults) read_only: Option, destructive: Option, @@ -249,8 +251,8 @@ impl AbilityDescriptorBuilder { self.tags = Some(tags); self } - pub fn resource_uri(mut self, uri: impl Into) -> Self { - self.resource_uri = Some(uri.into()); + pub fn resource_ura(mut self, uri: impl Into) -> Self { + self.resource_ura = Some(uri.into()); self } /// Mark as read-only (does not modify state). Default: `false`. @@ -294,7 +296,7 @@ impl AbilityDescriptorBuilder { self.output_schema, self.version, self.tags, - self.resource_uri, + self.resource_ura, )?; if let Some(v) = self.read_only { desc.read_only = v; @@ -327,7 +329,7 @@ pub fn parse_descriptor_from_args(args: &Map) -> Result> = args.get("tags").and_then(|v| v.as_array()).map(|arr| { arr.iter() .filter_map(|v| v.as_str().map(String::from)) @@ -342,7 +344,7 @@ pub fn parse_descriptor_from_args(args: &Map) -> Result(value: &'a str, label: &str) -> Result<&'a str> { Ok(value) } -fn generate_invoke_script(resource_uri: &str, endpoint: &str) -> Result { +fn generate_invoke_script(resource_ura: &str, endpoint: &str) -> Result { let safe_ep = sanitize_shell_value(endpoint, "endpoint")?; - let safe_uri = sanitize_shell_value(resource_uri, "resource_uri")?; + let safe_uri = sanitize_shell_value(resource_ura, "resource_ura")?; Ok(format!( r#"#!/usr/bin/env bash set -euo pipefail AXON_ENDPOINT="${{AXON_ENDPOINT:-{safe_ep}}}" TENANT="${{AXON_TENANT:-default}}" -RESOURCE_URI="{safe_uri}" +RESOURCE_URA="{safe_uri}" ARGS="${{1:-{{}}}}" curl -sS -X POST "${{AXON_ENDPOINT}}/v1/invoke" \ -H "Content-Type: application/json" \ - -d "{{\\"tenant_id\\":\\"${{TENANT}}\\",\\"resource_uri\\":\\"${{RESOURCE_URI}}\\",\\"payload\\":${{ARGS}}}}" + -d "{{\\"tenant_id\\":\\"${{TENANT}}\\",\\"resource_ura\\":\\"${{RESOURCE_URA}}\\",\\"payload\\":${{ARGS}}}}" "# )) } -fn push_metadata(md: &mut String, version: &str, resource_uri: &str) { +fn push_metadata(md: &mut String, version: &str, resource_ura: &str) { md.push_str("metadata:\n"); md.push_str(" author: easynet-axon\n"); md.push_str(&format!(" version: \"{version}\"\n")); - md.push_str(&format!(" axon-resource-uri: \"{resource_uri}\"\n")); + md.push_str(&format!(" axon-resource-ura: \"{resource_ura}\"\n")); } fn generate_ability_md( @@ -795,11 +797,11 @@ fn generate_ability_md( match target { AbilityTarget::Claude => { - push_metadata(&mut md, &descriptor.version, &descriptor.resource_uri); + push_metadata(&mut md, &descriptor.version, &descriptor.resource_ura); md.push_str("allowed-tools: Bash(*)\n"); } AbilityTarget::OpenClaw => { - push_metadata(&mut md, &descriptor.version, &descriptor.resource_uri); + push_metadata(&mut md, &descriptor.version, &descriptor.resource_ura); md.push_str(" openclaw:\n"); md.push_str(" emoji: \"⚡\"\n"); md.push_str(" requires:\n"); @@ -807,7 +809,7 @@ fn generate_ability_md( md.push_str(" command-dispatch: tool\n"); } AbilityTarget::Codex | AbilityTarget::AgentSkills => { - push_metadata(&mut md, &descriptor.version, &descriptor.resource_uri); + push_metadata(&mut md, &descriptor.version, &descriptor.resource_ura); } } @@ -909,7 +911,7 @@ fn generate_ability_md( // Axon Resource section md.push_str("## Axon Resource\n\n"); - md.push_str(&format!("- **URI**: `{}`\n", descriptor.resource_uri)); + md.push_str(&format!("- **URA**: `{}`\n", descriptor.resource_ura)); md.push_str(&format!("- **Version**: {}\n", descriptor.version)); if !descriptor.category.is_empty() { md.push_str(&format!("- **Category**: {}\n", descriptor.category)); @@ -948,7 +950,7 @@ mod tests { ) .unwrap(); assert_eq!(desc.version, "1.0.0"); - assert_eq!(desc.resource_uri, "easynet:///r/org/my-ability"); + assert_eq!(desc.resource_ura, "easynet:///r/org/my-ability"); assert!(desc.tags.is_empty()); } @@ -968,7 +970,7 @@ mod tests { let spec = desc.to_tool_spec(); assert_eq!(spec.name, "test-tool"); assert_eq!(spec.description, "A test"); - assert_eq!(spec.resource_uri, "easynet:///r/org/test-tool"); + assert_eq!(spec.resource_ura, "easynet:///r/org/test-tool"); } #[test] diff --git a/sdk/rust/src/bin/verify.rs b/sdk/rust/src/bin/verify.rs index e65fce55..60a01c3a 100644 --- a/sdk/rust/src/bin/verify.rs +++ b/sdk/rust/src/bin/verify.rs @@ -87,7 +87,7 @@ const USAGE: &str = concat!( "ARGS:\n", " Directory containing receipts/, invocations/, keys/\n", " --against-pubkeys Comma-separated alias=path for third-party pubkeys.\n", - " Aliases are tried as URI substring matches.\n", + " Aliases are tried as URA substring matches.\n", " --help Show this help\n", "\n", "EXIT CODES:\n", @@ -189,7 +189,7 @@ impl From for VerifyExit { // ── Key resolver ────────────────────────────────────────────────────── // -// Matches an agent URI against alias substrings (e.g. "silan" matches +// Matches an agent URA against alias substrings (e.g. "silan" matches // "easynet:///r/silan/..."). Also accepts a direct URI→path binding when // a keyfile in the bundle's keys/ directory is named after the URI. struct AliasResolver { @@ -242,17 +242,17 @@ impl AliasResolver { } impl KeyResolver for AliasResolver { - fn resolve(&self, agent_uri: &str) -> Result { - if let Some(k) = self.by_uri.get(agent_uri) { + fn resolve(&self, agent_ura: &str) -> Result { + if let Some(k) = self.by_uri.get(agent_ura) { return Ok(*k); } for (alias, k) in &self.by_alias { - if agent_uri.contains(alias) { + if agent_ura.contains(alias) { return Ok(*k); } } Err(AxonError::invalid_argument(format!( - "no_pubkey_for_agent:{agent_uri}" + "no_pubkey_for_agent:{agent_ura}" ))) } } diff --git a/sdk/rust/src/dendrite_bridge.rs b/sdk/rust/src/dendrite_bridge.rs index c00b0591..bfeb9aef 100644 --- a/sdk/rust/src/dendrite_bridge.rs +++ b/sdk/rust/src/dendrite_bridge.rs @@ -104,7 +104,7 @@ pub struct PublishCapabilityRequest<'a> { pub signature_base64: Option<&'a str>, pub tags: &'a [&'a str], pub metadata: Value, - pub payload_uri: Option<&'a str>, + pub payload_ura: Option<&'a str>, pub payload_size_bytes: Option, pub package_bytes_base64: Option<&'a str>, pub signature_fingerprint: Option<&'a str>, @@ -173,7 +173,7 @@ pub struct DendriteBridge { /// Mirrors `axon_dendrite_bridge::SigningConfigRequest` field-for-field /// because the SDK loads the bridge dynamically via `libloading` — /// there is no Rust-level dep coupling. The bridge accepts the JSON -/// shape `{algorithm, seed_base64, caller_uri, caller_profile}` on +/// shape `{algorithm, seed_base64, caller_ura, caller_profile}` on /// the open verb; this struct serialises to that shape exactly. /// /// Construct via `from_seed` (typical) or by hand for tests with @@ -182,7 +182,7 @@ pub struct DendriteBridge { pub struct SigningConfigRequest { pub algorithm: String, pub seed_base64: String, - pub caller_uri: String, + pub caller_ura: String, pub caller_profile: String, } @@ -190,11 +190,11 @@ impl SigningConfigRequest { /// Build a signing request from a 32-byte Ed25519 seed and a /// caller URA. Profile is pinned to `"easynet-strict-v2"` per /// RFC 001 §3.1 — the only currently-accepted URA profile. - pub fn from_seed(seed: [u8; 32], caller_uri: impl Into) -> Self { + pub fn from_seed(seed: [u8; 32], caller_ura: impl Into) -> Self { Self { algorithm: "ed25519".to_string(), seed_base64: BASE64.encode(seed), - caller_uri: caller_uri.into(), + caller_ura: caller_ura.into(), caller_profile: "easynet-strict-v2".to_string(), } } @@ -225,9 +225,9 @@ pub struct ConnectOptions<'a> { pub struct AbilitySignedCallOptions<'a> { pub tenant_id: &'a str, pub ability: &'a str, - pub callee_uri: &'a str, + pub callee_ura: &'a str, pub callee_profile: &'a str, - pub subject_uri: Option<&'a str>, + pub subject_ura: Option<&'a str>, pub subject_profile: Option<&'a str>, pub payload: &'a [u8], pub nonce_base64: Option<&'a str>, @@ -250,9 +250,9 @@ pub struct McpSignedCallOptions<'a> { pub tenant_id: &'a str, pub tool_name: &'a str, pub target_node_id: Option<&'a str>, - pub callee_uri: &'a str, + pub callee_ura: &'a str, pub callee_profile: &'a str, - pub subject_uri: Option<&'a str>, + pub subject_ura: Option<&'a str>, pub subject_profile: Option<&'a str>, pub arguments: &'a [u8], pub nonce_base64: Option<&'a str>, @@ -266,13 +266,13 @@ fn build_ability_signed_request(opts: &AbilitySignedCallOptions<'_>) -> Value { "tenant_id": opts.tenant_id, "ability": opts.ability, "callee": { - "uri": opts.callee_uri, + "ura": opts.callee_ura, "profile": opts.callee_profile, }, "payload_base64": BASE64.encode(opts.payload), }); - if let (Some(uri), Some(profile)) = (opts.subject_uri, opts.subject_profile) { - req["subject"] = json!({ "uri": uri, "profile": profile }); + if let (Some(uri), Some(profile)) = (opts.subject_ura, opts.subject_profile) { + req["subject"] = json!({ "ura": uri, "profile": profile }); } if let Some(nonce) = opts.nonce_base64 { req["nonce_base64"] = json!(nonce); @@ -451,7 +451,7 @@ impl DendriteBridge { if let Some(signing_cfg) = signing { // SigningConfigRequest derives Serialize, so serde_json // produces the exact JSON shape the bridge expects: - // {algorithm, seed_base64, caller_uri, caller_profile}. + // {algorithm, seed_base64, caller_ura, caller_profile}. let signing_value = serde_json::to_value(&signing_cfg).map_err(|e| { AxonError::Bridge(format!("failed to serialize signing config: {e}")) })?; @@ -508,7 +508,7 @@ impl DendriteBridge { pub fn ability_call( &self, tenant_id: &str, - resource_uri: &str, + resource_ura: &str, payload_json: Value, subject_id: Option<&str>, metadata: Option<&HashMap>, @@ -516,7 +516,7 @@ impl DendriteBridge { ) -> Result { self.ability_call_raw( tenant_id, - resource_uri, + resource_ura, payload_json, subject_id, metadata, @@ -528,7 +528,7 @@ impl DendriteBridge { pub fn ability_call_raw( &self, tenant_id: &str, - resource_uri: &str, + resource_ura: &str, payload_json: Value, subject_id: Option<&str>, metadata: Option<&HashMap>, @@ -536,7 +536,7 @@ impl DendriteBridge { ) -> Result { let mut request = json!({ "tenant_id": tenant_id, - "resource_uri": resource_uri, + "resource_ura": resource_ura, "payload_json": payload_json, "metadata": metadata.cloned().unwrap_or_default(), "timeout_ms": timeout_ms.max(1), @@ -567,7 +567,7 @@ impl DendriteBridge { pub fn federation_advertise_agent( &self, tenant_id: &str, - agent_uri: &str, + agent_ura: &str, public_key_hex: Option<&str>, signing_authority: Option, timeout_ms: u64, @@ -575,7 +575,7 @@ impl DendriteBridge { self.ability_call_raw( tenant_id, "federation.advertise_agent", - build_advertise_agent_body(agent_uri, public_key_hex, signing_authority), + build_advertise_agent_body(agent_ura, public_key_hex, signing_authority), None, None, resolve_federation_timeout(timeout_ms), @@ -586,14 +586,14 @@ impl DendriteBridge { pub fn federation_advertise_abilities( &self, tenant_id: &str, - agent_uri: &str, + agent_ura: &str, abilities: Vec, timeout_ms: u64, ) -> Result { self.ability_call_raw( tenant_id, "federation.advertise_abilities", - build_advertise_abilities_body(agent_uri, abilities), + build_advertise_abilities_body(agent_ura, abilities), None, None, resolve_federation_timeout(timeout_ms), @@ -621,14 +621,14 @@ impl DendriteBridge { pub fn federation_revoke( &self, tenant_id: &str, - agent_uri: &str, + agent_ura: &str, reason: Option<&str>, timeout_ms: u64, ) -> Result { self.ability_call_raw( tenant_id, "federation.revoke", - build_revoke_body(agent_uri, reason), + build_revoke_body(agent_ura, reason), None, None, resolve_federation_timeout(timeout_ms), @@ -640,14 +640,14 @@ impl DendriteBridge { pub fn federation_resolve( &self, tenant_id: &str, - agent_uri_prefix: Option<&str>, + agent_ura_prefix: Option<&str>, include_abilities: bool, timeout_ms: u64, ) -> Result { self.ability_call_raw( tenant_id, "federation.resolve", - build_resolve_body(agent_uri_prefix, include_abilities), + build_resolve_body(agent_ura_prefix, include_abilities), None, None, resolve_federation_timeout(timeout_ms), @@ -685,7 +685,7 @@ impl DendriteBridge { "signature_base64": req.signature_base64.unwrap_or(""), "tags": req.tags, "metadata": req.metadata, - "payload_uri": req.payload_uri.unwrap_or(""), + "payload_ura": req.payload_ura.unwrap_or(""), "payload_size_bytes": req.payload_size_bytes, "package_bytes_base64": req.package_bytes_base64, "signature_fingerprint": req.signature_fingerprint, @@ -706,7 +706,7 @@ impl DendriteBridge { signature_base64: Option<&str>, tags: &[&str], metadata: Value, - payload_uri: Option<&str>, + payload_ura: Option<&str>, payload_size_bytes: Option, package_bytes_base64: Option<&str>, signature_fingerprint: Option<&str>, @@ -721,7 +721,7 @@ impl DendriteBridge { signature_base64, tags, metadata, - payload_uri, + payload_ura, payload_size_bytes, package_bytes_base64, signature_fingerprint, @@ -1843,11 +1843,11 @@ fn use_local_source() -> bool { // sdk/FEDERATION_INVOKE_SCHEMAS.md §9 for the cross-language anchor set. fn build_advertise_agent_body( - agent_uri: &str, + agent_ura: &str, public_key_hex: Option<&str>, signing_authority: Option, ) -> Value { - let mut body = json!({ "agent_uri": agent_uri }); + let mut body = json!({ "agent_ura": agent_ura }); if let Some(hex) = public_key_hex.filter(|v| !v.is_empty()) { body["public_key_hex"] = Value::String(hex.to_string()); } @@ -1859,22 +1859,22 @@ fn build_advertise_agent_body( body } -fn build_advertise_abilities_body(agent_uri: &str, abilities: Vec) -> Value { - json!({ "agent_uri": agent_uri, "abilities": abilities }) +fn build_advertise_abilities_body(agent_ura: &str, abilities: Vec) -> Value { + json!({ "agent_ura": agent_ura, "abilities": abilities }) } -fn build_revoke_body(agent_uri: &str, reason: Option<&str>) -> Value { - let mut body = json!({ "agent_uri": agent_uri }); +fn build_revoke_body(agent_ura: &str, reason: Option<&str>) -> Value { + let mut body = json!({ "agent_ura": agent_ura }); if let Some(reason) = reason.filter(|v| !v.is_empty()) { body["reason"] = Value::String(reason.to_string()); } body } -fn build_resolve_body(agent_uri_prefix: Option<&str>, include_abilities: bool) -> Value { +fn build_resolve_body(agent_ura_prefix: Option<&str>, include_abilities: bool) -> Value { let mut filter = serde_json::Map::new(); - if let Some(prefix) = agent_uri_prefix.filter(|v| !v.is_empty()) { - filter.insert("agent_uri_prefix".into(), Value::String(prefix.to_string())); + if let Some(prefix) = agent_ura_prefix.filter(|v| !v.is_empty()) { + filter.insert("agent_ura_prefix".into(), Value::String(prefix.to_string())); } if include_abilities { filter.insert("include_abilities".into(), Value::Bool(true)); @@ -1917,8 +1917,8 @@ mod federation_conformance_tests { #[test] fn v1_advertise_agent_minimal() { assert_eq!( - build_advertise_agent_body("axon://realm/foo", None, None), - json!({"agent_uri": "axon://realm/foo"}) + build_advertise_agent_body("easynet:///r/realm/agent/foo", None, None), + json!({"agent_ura": "easynet:///r/realm/agent/foo"}) ); } @@ -1926,12 +1926,12 @@ mod federation_conformance_tests { fn v2_advertise_agent_full() { assert_eq!( build_advertise_agent_body( - "axon://realm/foo", + "easynet:///r/realm/agent/foo", Some("deadbeef"), Some(json!({"kind": "self_signed"})) ), json!({ - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "public_key_hex": "deadbeef", "signing_authority": {"kind": "self_signed"} }) @@ -1941,33 +1941,36 @@ mod federation_conformance_tests { #[test] fn v3_advertise_agent_omit_empty() { assert_eq!( - build_advertise_agent_body("axon://realm/foo", Some(""), Some(json!({}))), - json!({"agent_uri": "axon://realm/foo"}) + build_advertise_agent_body("easynet:///r/realm/agent/foo", Some(""), Some(json!({}))), + json!({"agent_ura": "easynet:///r/realm/agent/foo"}) ); } #[test] fn v5_revoke_no_reason() { assert_eq!( - build_revoke_body("axon://realm/foo", None), - json!({"agent_uri": "axon://realm/foo"}) + build_revoke_body("easynet:///r/realm/agent/foo", None), + json!({"agent_ura": "easynet:///r/realm/agent/foo"}) ); } #[test] fn v5b_revoke_blank_reason_omitted() { assert_eq!( - build_revoke_body("axon://realm/foo", Some("")), - json!({"agent_uri": "axon://realm/foo"}) + build_revoke_body("easynet:///r/realm/agent/foo", Some("")), + json!({"agent_ura": "easynet:///r/realm/agent/foo"}) ); } #[test] fn v6_revoke_with_reason() { assert_eq!( - build_revoke_body("axon://realm/foo", Some("operator: maintenance")), + build_revoke_body( + "easynet:///r/realm/agent/foo", + Some("operator: maintenance") + ), json!({ - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "reason": "operator: maintenance" }) ); @@ -1981,10 +1984,10 @@ mod federation_conformance_tests { #[test] fn v8_resolve_with_filter() { assert_eq!( - build_resolve_body(Some("axon://realm/edge-"), true), + build_resolve_body(Some("easynet:///r/realm/agent/edge-"), true), json!({ "filter": { - "agent_uri_prefix": "axon://realm/edge-", + "agent_ura_prefix": "easynet:///r/realm/agent/edge-", "include_abilities": true } }) @@ -1994,9 +1997,12 @@ mod federation_conformance_tests { #[test] fn v9_advertise_abilities() { assert_eq!( - build_advertise_abilities_body("axon://realm/foo", vec![json!({"name": "echo"})]), + build_advertise_abilities_body( + "easynet:///r/realm/agent/foo", + vec![json!({"name": "echo"})] + ), json!({ - "agent_uri": "axon://realm/foo", + "agent_ura": "easynet:///r/realm/agent/foo", "abilities": [{"name": "echo"}] }) ); diff --git a/sdk/rust/src/invocation/admission.rs b/sdk/rust/src/invocation/admission.rs index 62410cd7..96073fc7 100644 --- a/sdk/rust/src/invocation/admission.rs +++ b/sdk/rust/src/invocation/admission.rs @@ -13,7 +13,7 @@ //! a resolver we run in Local-fast mode where identity is //! self-asserted — documented trust model, not a gap. //! 4. [`NonceReplayStore::check_and_record`] — always on. Dedup key is -//! `(caller.uri, ability, invocation_nonce)`; `ability` guards +//! `(caller.ura, ability, invocation_nonce)`; `ability` guards //! against cross-ability false-positives per review. //! //! All rejections map to @@ -65,7 +65,7 @@ pub const DEFAULT_DEDUP_WINDOW_MS: i64 = 7 * 86_400_000; /// /// Checks applied (RFC 001 §5.2 step 1, strengthened per review): /// - ability non-empty -/// - caller.uri / callee.uri / subject.uri non-empty +/// - caller.ura / callee.ura / subject.ura non-empty /// - invocation_nonce is not the all-zero sentinel (a CSPRNG-generated /// nonce being all-zero has probability ≈ 2⁻¹²⁸; we reject it as a /// probable uninitialised-field mistake rather than accepting a @@ -74,7 +74,7 @@ pub const DEFAULT_DEDUP_WINDOW_MS: i64 = 7 * 86_400_000; /// already enforces it via type, but we re-check defensively so /// admission is self-contained) /// -/// Left intentionally cheap: no URI-scheme parsing here. That's URA +/// Left intentionally cheap: no URA-scheme parsing here. That's URA /// §3's job and belongs to a profile-level validator, not admission. pub fn validate_envelope(env: &InvocationEnvelope) -> Result<(), AxonError> { fn reject(msg: &str) -> AxonError { @@ -83,14 +83,14 @@ pub fn validate_envelope(env: &InvocationEnvelope) -> Result<(), AxonError> { if env.ability.is_empty() { return Err(reject("ability_empty")); } - if env.caller.uri.is_empty() { - return Err(reject("caller_uri_empty")); + if env.caller.ura.is_empty() { + return Err(reject("caller_ura_empty")); } - if env.callee.uri.is_empty() { - return Err(reject("callee_uri_empty")); + if env.callee.ura.is_empty() { + return Err(reject("callee_ura_empty")); } - if env.subject.uri.is_empty() { - return Err(reject("subject_uri_empty")); + if env.subject.ura.is_empty() { + return Err(reject("subject_ura_empty")); } if env.args_digest.len() != 32 { return Err(reject("args_digest_wrong_length")); @@ -364,7 +364,7 @@ impl NonceReplayStore { } } - /// Register a `(caller.uri, ability, nonce)` observation as of + /// Register a `(caller.ura, ability, nonce)` observation as of /// `now_ms`. Returns [`REASON_NONCE_REPLAY`] on collision inside /// the current window. /// @@ -377,7 +377,7 @@ impl NonceReplayStore { /// malformed or unverified caller's nonce never enters the store. pub fn check_and_record( &mut self, - caller_uri: &str, + caller_ura: &str, ability: &str, nonce: [u8; 16], now_ms: i64, @@ -394,7 +394,7 @@ impl NonceReplayStore { // Advance wheel cursor — bounded by MAX_ADVANCE_PER_CALL. self.advance_wheel(now_ms); - let key: ReplayKey = (caller_uri.to_string(), ability.to_string(), nonce); + let key: ReplayKey = (caller_ura.to_string(), ability.to_string(), nonce); if let Some(meta) = self.seen.get(&key) { if meta.ts >= cutoff { return Err( @@ -572,12 +572,12 @@ impl NonceReplayStore { #[doc(hidden)] pub fn insert_raw_for_bench( &mut self, - caller_uri: &str, + caller_ura: &str, ability: &str, nonce: [u8; 16], ts: i64, ) { - let key: ReplayKey = (caller_uri.to_string(), ability.to_string(), nonce); + let key: ReplayKey = (caller_ura.to_string(), ability.to_string(), nonce); let bucket_gen = self.bucket_gen_for(ts); let bucket_idx = Self::bucket_idx_from_gen(bucket_gen); self.seen.insert(key.clone(), EntryMeta { ts, bucket_gen }); @@ -629,7 +629,7 @@ pub fn run_admission( if let Some(r) = resolver { verify_signature(env, sig, r)?; } - replay.check_and_record(&env.caller.uri, &env.ability, env.invocation_nonce, now_ms)?; + replay.check_and_record(&env.caller.ura, &env.ability, env.invocation_nonce, now_ms)?; Ok(()) } @@ -646,7 +646,7 @@ mod tests { use super::*; use crate::invocation::axiom::{ sha256, sign_invocation, signing_key_from_bytes, AgentIdentity, CausalContext, - SubjectIdentity, UriProfile, + SubjectIdentity, UraProfile, }; use ed25519_dalek::VerifyingKey; @@ -660,16 +660,16 @@ mod tests { fn sample_env() -> InvocationEnvelope { InvocationEnvelope { caller: AgentIdentity::new( - "easynet:///r/silan/agents/r@1", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/agent/silan.r", + UraProfile::EasynetStrictV2, ), callee: AgentIdentity::new( - "easynet:///r/openai/agents/r@1", - UriProfile::EasynetStrictV2, + "easynet:///r/openai/agent/openai.r", + UraProfile::EasynetStrictV2, ), subject: SubjectIdentity::new( - "easynet:///r/silan/papers/p@d1", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/resource/silan.papers/p", + UraProfile::EasynetStrictV2, ), ability: "review".to_string(), args_digest: sha256(b""), @@ -702,17 +702,17 @@ mod tests { } #[test] - fn validate_envelope_rejects_empty_uri() { + fn validate_envelope_rejects_empty_ura() { for (mutator, detail) in [ - (0u8, "caller_uri_empty"), - (1u8, "callee_uri_empty"), - (2u8, "subject_uri_empty"), + (0u8, "caller_ura_empty"), + (1u8, "callee_ura_empty"), + (2u8, "subject_ura_empty"), ] { let mut env = sample_env(); match mutator { - 0 => env.caller.uri = String::new(), - 1 => env.callee.uri = String::new(), - _ => env.subject.uri = String::new(), + 0 => env.caller.ura = String::new(), + 1 => env.callee.ura = String::new(), + _ => env.subject.ura = String::new(), } let err = validate_envelope(&env).unwrap_err(); assert_eq!(err.reason, REASON_ENVELOPE_INCOMPLETE); @@ -863,7 +863,7 @@ mod tests { // Review invariant: malformed envelopes MUST NOT pollute the // replay store. let mut env = sample_env(); - env.caller.uri = String::new(); + env.caller.ura = String::new(); let (sig, _) = sample_sig(&env); let mut s = NonceReplayStore::new(); let err = run_admission(&env, &sig, None, &mut s, 1_000).unwrap_err(); diff --git a/sdk/rust/src/invocation/audit.rs b/sdk/rust/src/invocation/audit.rs index 135a4bc3..d0dd6d3d 100644 --- a/sdk/rust/src/invocation/audit.rs +++ b/sdk/rust/src/invocation/audit.rs @@ -252,23 +252,23 @@ pub fn verify_receipt_chain(receipts: &[InvocationReceipt]) -> ChainCheckResult #[cfg(test)] mod tests { use super::super::axiom::{ - AgentIdentity, CalleeSignature, CausalContext, ReceiptRef, SubjectIdentity, UriProfile, + AgentIdentity, CalleeSignature, CausalContext, ReceiptRef, SubjectIdentity, UraProfile, }; use super::*; fn sample_binding() -> AxiomBinding { AxiomBinding { caller: AgentIdentity::new( - "easynet:///r/silan/agents/a@1", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/agent/silan.a", + UraProfile::EasynetStrictV2, ), callee: AgentIdentity::new( - "easynet:///r/openai/agents/b@1", - UriProfile::EasynetStrictV2, + "easynet:///r/openai/agent/openai.b", + UraProfile::EasynetStrictV2, ), subject: SubjectIdentity::new( - "easynet:///r/silan/papers/p@1", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/resource/silan.papers/p", + UraProfile::EasynetStrictV2, ), invocation_nonce: [0x42u8; 16], causal: CausalContext::None, @@ -357,14 +357,14 @@ mod tests { let r = sample_receipt(0, ZERO_HASH); let mut t = r.clone(); match mutation { - 0 => t.axiom_binding.caller.uri = "evil".to_string(), - 1 => t.axiom_binding.callee.uri = "evil".to_string(), - 2 => t.axiom_binding.subject.uri = "evil".to_string(), + 0 => t.axiom_binding.caller.ura = "evil".to_string(), + 1 => t.axiom_binding.callee.ura = "evil".to_string(), + 2 => t.axiom_binding.subject.ura = "evil".to_string(), 3 => t.axiom_binding.invocation_nonce = [0xFF; 16], 4 => { t.axiom_binding.causal = CausalContext::Scalar(ReceiptRef { receipt_hash: [0xAA; 32], - receipt_uri: "r".to_string(), + receipt_ura: "r".to_string(), }) } _ => unreachable!(), diff --git a/sdk/rust/src/invocation/axiom.rs b/sdk/rust/src/invocation/axiom.rs index e264b294..60fbb14e 100644 --- a/sdk/rust/src/invocation/axiom.rs +++ b/sdk/rust/src/invocation/axiom.rs @@ -11,7 +11,7 @@ //! Normative references: //! document/concepts/AXIOM.tex //! document/rfcs/001-envelope-axiom-alignment.md -//! ~/Documents/GitHub/URA/README.md (URA v2 §3 canonicalisation) +//! ~/Documents/GitHub/URA/README.md (current URA §3 canonicalisation) use ed25519_dalek::{ Signature, Signer, SigningKey, Verifier, VerifyingKey, SECRET_KEY_LENGTH, SIGNATURE_LENGTH, @@ -20,65 +20,65 @@ use sha2::{Digest, Sha256}; use super::error::AxonError; -/// URA profile selector. Bound structurally to the URI it profiles +/// URA profile selector. Bound structurally to the URA it profiles /// (AXIOM §5.4 Axis B, RFC 001 INV-4). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum UriProfile { - /// RFC 001 default. Strict URA v2 canonicalisation. +pub enum UraProfile { + /// RFC 001 default. Strict current URA canonicalisation. EasynetStrictV2, /// RFC 3986-compatible subset for interop with legacy HTTP tooling. WebSafeV2, } -impl UriProfile { +impl UraProfile { pub fn as_str(&self) -> &'static str { match self { - UriProfile::EasynetStrictV2 => "easynet-strict-v2", - UriProfile::WebSafeV2 => "web-safe-v2", + UraProfile::EasynetStrictV2 => "easynet-strict-v2", + UraProfile::WebSafeV2 => "web-safe-v2", } } pub fn parse(s: &str) -> Result { match s { - "easynet-strict-v2" => Ok(UriProfile::EasynetStrictV2), - "web-safe-v2" => Ok(UriProfile::WebSafeV2), + "easynet-strict-v2" => Ok(UraProfile::EasynetStrictV2), + "web-safe-v2" => Ok(UraProfile::WebSafeV2), other => Err(AxonError::invalid_argument(format!( - "unknown_uri_profile:{other}" + "unknown_ura_profile:{other}" ))), } } } -/// URA v2 composite identity for an agent. `profile` is bound structurally -/// to `uri` per RFC 001 §3.1. +/// current URA composite identity for an agent. `profile` is bound structurally +/// to `ura` per RFC 001 §3.1. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct AgentIdentity { - pub uri: String, - pub profile: UriProfile, + pub ura: String, + pub profile: UraProfile, } impl AgentIdentity { - pub fn new(uri: impl Into, profile: UriProfile) -> Self { + pub fn new(ura: impl Into, profile: UraProfile) -> Self { Self { - uri: uri.into(), + ura: ura.into(), profile, } } } -/// URA v2 composite identity for a subject. Distinct type from +/// current URA composite identity for a subject. Distinct type from /// [`AgentIdentity`] so the compiler can enforce RFC 001 INV-7 — a subject -/// URI can differ in namespace/scope/subject-type from the callee URI. +/// URA can differ in namespace/scope/subject-type from the callee URA. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct SubjectIdentity { - pub uri: String, - pub profile: UriProfile, + pub ura: String, + pub profile: UraProfile, } impl SubjectIdentity { - pub fn new(uri: impl Into, profile: UriProfile) -> Self { + pub fn new(ura: impl Into, profile: UraProfile) -> Self { Self { - uri: uri.into(), + ura: ura.into(), profile, } } @@ -89,7 +89,7 @@ impl SubjectIdentity { /// always populated per INV-1. pub fn from_callee(callee: &AgentIdentity) -> Self { Self { - uri: callee.uri.clone(), + ura: callee.ura.clone(), profile: callee.profile, } } @@ -100,9 +100,9 @@ impl SubjectIdentity { pub struct ReceiptRef { /// SHA-256 over the referenced receipt's canonical bytes. pub receipt_hash: [u8; 32], - /// URA locator. Auditors fetch by this URI; the SDK never follows it + /// URA locator. Auditors fetch by this URA; the SDK never follows it /// at admission time. - pub receipt_uri: String, + pub receipt_ura: String, } /// Causal context per RFC 001 §3.3. One of four canonical forms. @@ -119,7 +119,7 @@ pub enum CausalContext { /// Fan-in join with a bounded number of predecessors. Caller-ordered. List(Vec), /// Large-fan-in join via Merkle root. Auditor-behaviour deferred. - Merkle { root: [u8; 32], proof_uri: String }, + Merkle { root: [u8; 32], proof_ura: String }, } impl CausalContext { @@ -185,9 +185,9 @@ fn put_bytes(out: &mut Vec, b: &[u8]) { out.extend_from_slice(b); } -/// Append a canonical identity block (URI + profile) per §4.1. -fn put_identity_uri_profile(out: &mut Vec, uri: &str, profile: UriProfile) { - put_str(out, uri); +/// Append a canonical identity block (URA + profile) per §4.1. +fn put_identity_ura_profile(out: &mut Vec, ura: &str, profile: UraProfile) { + put_str(out, ura); put_str(out, profile.as_str()); } @@ -203,20 +203,20 @@ pub fn canonical_causal_context(ctx: &CausalContext) -> Vec { CausalContext::Scalar(r) => { out.push(0x01); out.extend_from_slice(&r.receipt_hash); - put_str(&mut out, &r.receipt_uri); + put_str(&mut out, &r.receipt_ura); } CausalContext::List(refs) => { out.push(0x02); out.extend_from_slice(&(refs.len() as u32).to_be_bytes()); for r in refs { out.extend_from_slice(&r.receipt_hash); - put_str(&mut out, &r.receipt_uri); + put_str(&mut out, &r.receipt_ura); } } - CausalContext::Merkle { root, proof_uri } => { + CausalContext::Merkle { root, proof_ura } => { out.push(0x03); out.extend_from_slice(root); - put_str(&mut out, proof_uri); + put_str(&mut out, proof_ura); } } out @@ -228,9 +228,9 @@ pub fn canonical_causal_context(ctx: &CausalContext) -> Vec { /// length-prefixed so no two valid envelopes collide under concatenation. pub fn canonical_invocation_bytes(env: &InvocationEnvelope) -> Vec { let mut out = Vec::with_capacity(512); - put_identity_uri_profile(&mut out, &env.caller.uri, env.caller.profile); - put_identity_uri_profile(&mut out, &env.callee.uri, env.callee.profile); - put_identity_uri_profile(&mut out, &env.subject.uri, env.subject.profile); + put_identity_ura_profile(&mut out, &env.caller.ura, env.caller.profile); + put_identity_ura_profile(&mut out, &env.callee.ura, env.callee.profile); + put_identity_ura_profile(&mut out, &env.subject.ura, env.subject.profile); put_str(&mut out, &env.ability); out.extend_from_slice(&env.args_digest); out.extend_from_slice(&env.invocation_nonce); @@ -272,9 +272,9 @@ pub fn canonical_receipt_bytes(r: &ReceiptBody) -> Vec { put_str(&mut out, &r.state); out.extend_from_slice(&r.timestamp_unix_ms.to_be_bytes()); out.extend_from_slice(&r.prev_receipt_hash); - put_identity_uri_profile(&mut out, &r.caller_binding.uri, r.caller_binding.profile); - put_identity_uri_profile(&mut out, &r.callee_binding.uri, r.callee_binding.profile); - put_identity_uri_profile(&mut out, &r.subject_binding.uri, r.subject_binding.profile); + put_identity_ura_profile(&mut out, &r.caller_binding.ura, r.caller_binding.profile); + put_identity_ura_profile(&mut out, &r.callee_binding.ura, r.callee_binding.profile); + put_identity_ura_profile(&mut out, &r.subject_binding.ura, r.subject_binding.profile); out.extend_from_slice(&r.invocation_nonce); let causal = canonical_causal_context(&r.causal_binding); put_bytes(&mut out, &causal); @@ -299,12 +299,12 @@ pub fn sha256(bytes: &[u8]) -> [u8; 32] { // resolver. A file path embedded inside the verifier is a conformance bug. pub trait KeyResolver: Send + Sync { - /// Resolve an agent's verifying (public) key by its URI. - fn resolve(&self, agent_uri: &str) -> Result; + /// Resolve an agent's verifying (public) key by its URA. + fn resolve(&self, agent_ura: &str) -> Result; } /// File-based resolver — RFC 001's only shipped implementation. -/// Maps `agent_uri → file path containing the 32-byte Ed25519 public key`. +/// Maps `agent_ura → file path containing the 32-byte Ed25519 public key`. pub struct FileKeyResolver { mapping: std::collections::HashMap, } @@ -316,8 +316,8 @@ impl FileKeyResolver { } } - pub fn insert(&mut self, agent_uri: impl Into, path: impl Into) { - self.mapping.insert(agent_uri.into(), path.into()); + pub fn insert(&mut self, agent_ura: impl Into, path: impl Into) { + self.mapping.insert(agent_ura.into(), path.into()); } } @@ -328,11 +328,11 @@ impl Default for FileKeyResolver { } impl KeyResolver for FileKeyResolver { - fn resolve(&self, agent_uri: &str) -> Result { + fn resolve(&self, agent_ura: &str) -> Result { let path = self .mapping - .get(agent_uri) - .ok_or_else(|| AxonError::invalid_argument(format!("unknown_agent_key:{agent_uri}")))?; + .get(agent_ura) + .ok_or_else(|| AxonError::invalid_argument(format!("unknown_agent_key:{agent_ura}")))?; let bytes = std::fs::read(path).map_err(|e| { AxonError::internal(format!("key_file_read_failed:{}:{e}", path.display())) })?; @@ -389,7 +389,7 @@ pub fn verify_invocation_signature( sig.algorithm ))); } - let key = resolver.resolve(&env.caller.uri)?; + let key = resolver.resolve(&env.caller.ura)?; let bytes = canonical_invocation_bytes(env); if sig.signature.len() != SIGNATURE_LENGTH { return Err(AxonError::invalid_argument(format!( @@ -434,7 +434,7 @@ pub fn verify_receipt_signature( sig.algorithm ))); } - let key = resolver.resolve(&r.callee_binding.uri)?; + let key = resolver.resolve(&r.callee_binding.ura)?; let bytes = canonical_receipt_bytes(r); if sig.signature.len() != SIGNATURE_LENGTH { return Err(AxonError::invalid_argument(format!( @@ -471,16 +471,16 @@ mod tests { fn sample_envelope() -> InvocationEnvelope { InvocationEnvelope { caller: AgentIdentity::new( - "easynet:///r/silan/agents/quote-bot@1.0", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/agent/silan.quote-bot", + UraProfile::EasynetStrictV2, ), callee: AgentIdentity::new( - "easynet:///r/openai/agents/reviewer@1.0", - UriProfile::EasynetStrictV2, + "easynet:///r/openai/agent/openai.reviewer", + UraProfile::EasynetStrictV2, ), subject: SubjectIdentity::new( - "easynet:///r/silan/papers/paper@draft-1", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/resource/silan.papers/paper", + UraProfile::EasynetStrictV2, ), ability: "review".to_string(), args_digest: sha256(b"{}"), @@ -543,8 +543,8 @@ mod tests { fn subject_is_part_of_signed_bytes() { let mut a = sample_envelope(); let mut b = sample_envelope(); - a.subject = SubjectIdentity::new("easynet:///r/a/x", UriProfile::EasynetStrictV2); - b.subject = SubjectIdentity::new("easynet:///r/b/y", UriProfile::EasynetStrictV2); + a.subject = SubjectIdentity::new("easynet:///r/a/x", UraProfile::EasynetStrictV2); + b.subject = SubjectIdentity::new("easynet:///r/b/y", UraProfile::EasynetStrictV2); assert_ne!( canonical_invocation_bytes(&a), canonical_invocation_bytes(&b) @@ -555,8 +555,8 @@ mod tests { fn profile_is_part_of_signed_bytes() { let mut a = sample_envelope(); let mut b = sample_envelope(); - a.caller.profile = UriProfile::EasynetStrictV2; - b.caller.profile = UriProfile::WebSafeV2; + a.caller.profile = UraProfile::EasynetStrictV2; + b.caller.profile = UraProfile::WebSafeV2; assert_ne!( canonical_invocation_bytes(&a), canonical_invocation_bytes(&b) @@ -569,14 +569,14 @@ mod tests { fn causal_forms_are_distinct() { let r = ReceiptRef { receipt_hash: [0xAA; 32], - receipt_uri: "easynet:///r/x/receipts/1".to_string(), + receipt_ura: "easynet:///r/x/receipts/1".to_string(), }; let none_b = canonical_causal_context(&CausalContext::None); let scalar_b = canonical_causal_context(&CausalContext::Scalar(r.clone())); let list_b = canonical_causal_context(&CausalContext::List(vec![r.clone()])); let merkle_b = canonical_causal_context(&CausalContext::Merkle { root: [0xBB; 32], - proof_uri: "easynet:///r/x/proofs/1".to_string(), + proof_ura: "easynet:///r/x/proofs/1".to_string(), }); assert_eq!(none_b, vec![0x00]); assert_eq!(scalar_b[0], 0x01); @@ -598,10 +598,10 @@ mod tests { // ── 3. Merkle form full structure (filling a gap called out in review) ── #[test] - fn merkle_form_has_root_and_length_prefixed_proof_uri() { + fn merkle_form_has_root_and_length_prefixed_proof_ura() { let ctx = CausalContext::Merkle { root: [0xCC; 32], - proof_uri: "abc".to_string(), + proof_ura: "abc".to_string(), }; let bytes = canonical_causal_context(&ctx); assert_eq!(bytes[0], 0x03); @@ -618,11 +618,11 @@ mod tests { fn list_form_preserves_order() { let r1 = ReceiptRef { receipt_hash: [0x01; 32], - receipt_uri: "u1".to_string(), + receipt_ura: "u1".to_string(), }; let r2 = ReceiptRef { receipt_hash: [0x02; 32], - receipt_uri: "u2".to_string(), + receipt_ura: "u2".to_string(), }; let ab = canonical_causal_context(&CausalContext::List(vec![r1.clone(), r2.clone()])); let ba = canonical_causal_context(&CausalContext::List(vec![r2, r1])); @@ -656,13 +656,13 @@ mod tests { } #[test] - fn tamper_caller_uri_breaks_signature() { + fn tamper_caller_ura_breaks_signature() { let sk = SigningKey::generate(&mut OsRng {}); let vk = sk.verifying_key(); let env = sample_envelope(); let sig = sign_invocation(&sk, &env, ""); let mut t = env.clone(); - t.caller.uri = "easynet:///r/mallory/x@1".to_string(); + t.caller.ura = "easynet:///r/mallory/x@1".to_string(); let err = verify_invocation_signature(&t, &sig, &FixedResolver(vk)).unwrap_err(); assert!(format!("{err}").contains("caller_signature_invalid")); } @@ -674,7 +674,7 @@ mod tests { let env = sample_envelope(); let sig = sign_invocation(&sk, &env, ""); let mut t = env.clone(); - t.subject = SubjectIdentity::new("easynet:///r/other/x", UriProfile::EasynetStrictV2); + t.subject = SubjectIdentity::new("easynet:///r/other/x", UraProfile::EasynetStrictV2); let err = verify_invocation_signature(&t, &sig, &FixedResolver(vk)).unwrap_err(); assert!(format!("{err}").contains("caller_signature_invalid")); } @@ -688,7 +688,7 @@ mod tests { let mut t = env.clone(); t.causal_context = CausalContext::Scalar(ReceiptRef { receipt_hash: [0xAA; 32], - receipt_uri: "r".to_string(), + receipt_ura: "r".to_string(), }); let err = verify_invocation_signature(&t, &sig, &FixedResolver(vk)).unwrap_err(); assert!(format!("{err}").contains("caller_signature_invalid")); @@ -748,7 +748,7 @@ mod tests { let mut t = r.clone(); t.causal_binding = CausalContext::Scalar(ReceiptRef { receipt_hash: [0x99; 32], - receipt_uri: "evil".to_string(), + receipt_ura: "evil".to_string(), }); let err = verify_receipt_signature(&t, &sig, &FixedResolver(vk)).unwrap_err(); assert!(format!("{err}").contains("callee_signature_invalid")); @@ -757,24 +757,24 @@ mod tests { // ── 7. SubjectIdentity is a newtype, distinct from AgentIdentity ────── // // We cannot test "compile-time rejection of swap" with assert!; but we - // can test that their canonical bytes diverge for identical (uri, + // can test that their canonical bytes diverge for identical (ura, // profile) because the two enter different field positions in §4.1. #[test] fn agent_and_subject_are_distinct_types() { // Compile-time proof: this assignment would not type-check. - // let s: SubjectIdentity = AgentIdentity::new("x", UriProfile::EasynetStrictV2); + // let s: SubjectIdentity = AgentIdentity::new("x", UraProfile::EasynetStrictV2); // // Runtime proof of positional distinction: building two envelopes - // where we "swap" the callee and subject URIs still produces + // where we "swap" the callee and subject URAs still produces // different canonical bytes because the callee slot comes before // the subject slot. let mut a = sample_envelope(); let mut b = sample_envelope(); - a.callee = AgentIdentity::new("easynet:///r/X/a", UriProfile::EasynetStrictV2); - a.subject = SubjectIdentity::new("easynet:///r/Y/b", UriProfile::EasynetStrictV2); - b.callee = AgentIdentity::new("easynet:///r/Y/b", UriProfile::EasynetStrictV2); - b.subject = SubjectIdentity::new("easynet:///r/X/a", UriProfile::EasynetStrictV2); + a.callee = AgentIdentity::new("easynet:///r/X/a", UraProfile::EasynetStrictV2); + a.subject = SubjectIdentity::new("easynet:///r/Y/b", UraProfile::EasynetStrictV2); + b.callee = AgentIdentity::new("easynet:///r/Y/b", UraProfile::EasynetStrictV2); + b.subject = SubjectIdentity::new("easynet:///r/X/a", UraProfile::EasynetStrictV2); assert_ne!( canonical_invocation_bytes(&a), canonical_invocation_bytes(&b) @@ -785,30 +785,30 @@ mod tests { fn subject_from_callee_convention_round_trips() { // RFC 001 §5.1 subject defaulting: SDK synthesises subject=callee // at the boundary; wire field is always populated. - let callee = AgentIdentity::new("easynet:///r/silan/self@1", UriProfile::EasynetStrictV2); + let callee = AgentIdentity::new("easynet:///r/silan/self@1", UraProfile::EasynetStrictV2); let subj = SubjectIdentity::from_callee(&callee); - assert_eq!(subj.uri, callee.uri); + assert_eq!(subj.ura, callee.ura); assert_eq!(subj.profile, callee.profile); } // ── 8. Empty-field GIGO contract (runtime-check boundary) ───────────── // - // Canonical encoder is GIGO on empty URI — it will emit a 4-byte zero + // Canonical encoder is GIGO on empty URA — it will emit a 4-byte zero // length prefix plus nothing. Rejection is admission-layer responsibility, // not the encoder's. This test pins the contract so the boundary is // explicit rather than accidental. #[test] - fn empty_uri_produces_length_zero_not_panic() { + fn empty_ura_produces_length_zero_not_panic() { let env = InvocationEnvelope { - caller: AgentIdentity::new("", UriProfile::EasynetStrictV2), + caller: AgentIdentity::new("", UraProfile::EasynetStrictV2), ..sample_envelope() }; let bytes = canonical_invocation_bytes(&env); - // First 4 bytes = caller.uri length = 0. + // First 4 bytes = caller.ura length = 0. assert_eq!(&bytes[0..4], &0u32.to_be_bytes()); // Then caller.profile length + bytes. - let profile = UriProfile::EasynetStrictV2.as_str(); + let profile = UraProfile::EasynetStrictV2.as_str(); assert_eq!(&bytes[4..8], &(profile.len() as u32).to_be_bytes()); } @@ -841,16 +841,16 @@ mod tests { #[test] fn profile_string_round_trip() { - for p in [UriProfile::EasynetStrictV2, UriProfile::WebSafeV2] { + for p in [UraProfile::EasynetStrictV2, UraProfile::WebSafeV2] { let s = p.as_str(); - assert_eq!(UriProfile::parse(s).unwrap(), p); + assert_eq!(UraProfile::parse(s).unwrap(), p); } - assert!(UriProfile::parse("not-a-profile").is_err()); + assert!(UraProfile::parse("not-a-profile").is_err()); // Unknown profile strings MUST be rejected; this guards against // silently accepting a profile that a future runtime might // interpret differently. - assert!(UriProfile::parse("easynet-v1-compat").is_err()); - assert!(UriProfile::parse("easynet-strict-v3").is_err()); + assert!(UraProfile::parse("easynet-v1-compat").is_err()); + assert!(UraProfile::parse("easynet-strict-v3").is_err()); } // ── Frozen worked example ──────────────────────────────────────── @@ -869,16 +869,16 @@ mod tests { fn worked_example_envelope() -> InvocationEnvelope { InvocationEnvelope { caller: AgentIdentity::new( - "easynet:///r/silan/agents/alice", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/agent/silan.alice", + UraProfile::EasynetStrictV2, ), callee: AgentIdentity::new( - "easynet:///r/openai/agents/reviewer@1.0", - UriProfile::EasynetStrictV2, + "easynet:///r/openai/agent/openai.reviewer", + UraProfile::EasynetStrictV2, ), subject: SubjectIdentity::new( - "easynet:///r/silan/papers/paper@draft-1", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/resource/silan.papers/paper", + UraProfile::EasynetStrictV2, ), ability: "review".to_string(), args_digest: sha256(b"{}"), @@ -917,7 +917,7 @@ mod tests { let canon = canonical_invocation_bytes(&env); let h = hex::encode(sha256(&canon)); assert_eq!( - h, "132aacb0e21a0159a187fc7d71f204f58ecf12feab06eec9f61d3769321820f7", + h, "68464c0da3500e842ece4d3e6e539ec74d12b741160bd5174b13234b02b1eb28", "canonical_invocation_sha256 changed — the §4.1 byte \ layout has drifted; update AUTHENTICATED_INVOCATION.md \ §4.1.3 and axiom-worked-example-authenticated.json in \ @@ -934,7 +934,7 @@ mod tests { let b64 = base64::engine::general_purpose::STANDARD.encode(&sig.signature); assert_eq!( b64, - "onZ3dvtXDf66nw+I5xe1QPDH5Vm8uqxzELiuX79mNV5uPvvnoddClhFiDemXlF4gS5zWPXhZ4QGQ45FVuhdjBQ==", + "N78HErlFC7s7NiUumMf7s7mpaBiH+yV8rYo0m0YDxIzZf0d9i/7lMb0mTxMNVwHpP61mN5swqnPH/2WQUsO/AQ==", "Ed25519 signature output changed for the frozen worked \ example. This is deterministic (same seed, same message, \ same library) — divergence means either the canonical \ diff --git a/sdk/rust/src/invocation/bundle.rs b/sdk/rust/src/invocation/bundle.rs index f8fab7d5..57721cf1 100644 --- a/sdk/rust/src/invocation/bundle.rs +++ b/sdk/rust/src/invocation/bundle.rs @@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize}; use super::axiom::{ AgentIdentity, CausalContext, InvocationEnvelope, ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, }; use super::error::AxonError; @@ -28,33 +28,33 @@ use super::error::AxonError; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IdentityJson { - pub uri: String, + pub ura: String, pub profile: String, } impl IdentityJson { pub fn from_agent(a: &AgentIdentity) -> Self { Self { - uri: a.uri.clone(), + ura: a.ura.clone(), profile: a.profile.as_str().to_string(), } } pub fn from_subject(s: &SubjectIdentity) -> Self { Self { - uri: s.uri.clone(), + ura: s.ura.clone(), profile: s.profile.as_str().to_string(), } } pub fn to_agent(&self) -> Result { Ok(AgentIdentity::new( - self.uri.clone(), - UriProfile::parse(&self.profile)?, + self.ura.clone(), + UraProfile::parse(&self.profile)?, )) } pub fn to_subject(&self) -> Result { Ok(SubjectIdentity::new( - self.uri.clone(), - UriProfile::parse(&self.profile)?, + self.ura.clone(), + UraProfile::parse(&self.profile)?, )) } } @@ -67,21 +67,21 @@ pub enum CausalJson { None, Scalar { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, }, List { prior: Vec, }, Merkle { root_hex: String, - proof_uri: String, + proof_ura: String, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReceiptRefJson { pub receipt_hash_hex: String, - pub receipt_uri: String, + pub receipt_ura: String, } impl CausalJson { @@ -90,20 +90,20 @@ impl CausalJson { CausalContext::None => CausalJson::None, CausalContext::Scalar(r) => CausalJson::Scalar { receipt_hash_hex: hex::encode(r.receipt_hash), - receipt_uri: r.receipt_uri.clone(), + receipt_ura: r.receipt_ura.clone(), }, CausalContext::List(refs) => CausalJson::List { prior: refs .iter() .map(|r| ReceiptRefJson { receipt_hash_hex: hex::encode(r.receipt_hash), - receipt_uri: r.receipt_uri.clone(), + receipt_ura: r.receipt_ura.clone(), }) .collect(), }, - CausalContext::Merkle { root, proof_uri } => CausalJson::Merkle { + CausalContext::Merkle { root, proof_ura } => CausalJson::Merkle { root_hex: hex::encode(root), - proof_uri: proof_uri.clone(), + proof_ura: proof_ura.clone(), }, } } @@ -112,10 +112,10 @@ impl CausalJson { CausalJson::None => Ok(CausalContext::None), CausalJson::Scalar { receipt_hash_hex, - receipt_uri, + receipt_ura, } => Ok(CausalContext::Scalar(ReceiptRef { receipt_hash: hex_to_32(receipt_hash_hex)?, - receipt_uri: receipt_uri.clone(), + receipt_ura: receipt_ura.clone(), })), CausalJson::List { prior } => Ok(CausalContext::List( prior @@ -123,17 +123,17 @@ impl CausalJson { .map(|p| { Ok::<_, AxonError>(ReceiptRef { receipt_hash: hex_to_32(&p.receipt_hash_hex)?, - receipt_uri: p.receipt_uri.clone(), + receipt_ura: p.receipt_ura.clone(), }) }) .collect::>()?, )), CausalJson::Merkle { root_hex, - proof_uri, + proof_ura, } => Ok(CausalContext::Merkle { root: hex_to_32(root_hex)?, - proof_uri: proof_uri.clone(), + proof_ura: proof_ura.clone(), }), } } @@ -226,7 +226,7 @@ impl ReceiptJson { // ── Key bundle ──────────────────────────────────────────────────────── /// A `--against-pubkeys silan=path,openai=path` mapping resolved into -/// agent_uri-prefix → path pairs the verifier will match on. +/// agent_ura-prefix → path pairs the verifier will match on. #[derive(Debug, Clone, Default)] pub struct PubkeyMap { pub by_alias: BTreeMap, @@ -290,16 +290,16 @@ mod tests { fn make_env() -> InvocationEnvelope { InvocationEnvelope { caller: AgentIdentity::new( - "easynet:///r/silan/agents/r@1.0", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/agent/silan.r", + UraProfile::EasynetStrictV2, ), callee: AgentIdentity::new( - "easynet:///r/openai/agents/r@1.0", - UriProfile::EasynetStrictV2, + "easynet:///r/openai/agent/openai.r", + UraProfile::EasynetStrictV2, ), subject: SubjectIdentity::new( - "easynet:///r/silan/papers/p@draft-1", - UriProfile::EasynetStrictV2, + "easynet:///r/silan/resource/silan.papers/p", + UraProfile::EasynetStrictV2, ), ability: "review".to_string(), args_digest: sha256(b"{}"), diff --git a/sdk/rust/src/invocation/ledger.rs b/sdk/rust/src/invocation/ledger.rs new file mode 100644 index 00000000..f5b3c216 --- /dev/null +++ b/sdk/rust/src/invocation/ledger.rs @@ -0,0 +1,1328 @@ +//! EasyNet Axon for AgentNet +//! ========================= +//! +//! File: sdk/rust/src/invocation/ledger.rs +//! Description: Invocation ledger records, encrypted event payloads, +//! and the embedded database used by hosts to persist +//! auditable invocation history. +//! +//! Protocol Responsibility: +//! - Defines the durable invocation-history record shape used by +//! CLI, daemon, and future Axon runtime surfaces. +//! - Keeps plaintext payloads optional. Event bodies are represented +//! either as digests or as sealed bytes encrypted for explicit +//! recipient public keys. The normal private invocation policy is a +//! multi-recipient sealed payload for exactly the caller and callee +//! of that event. +//! - Preserves full URAs from the caller/callee/subject/ability +//! envelope instead of letting applications reconstruct identity. +//! - Projects invocation traces as a DAG from causal receipt links. +//! CLI and UI consumers read that graph; they do not infer edges. +//! +//! Implementation Approach: +//! - Uses `redb`, a pure Rust embedded database, so each workspace can +//! hold one native database file at `billing/invocations.redb`. +//! - Stores records as canonical JSON values inside typed database +//! tables. The database is native; JSON is the stable value codec +//! that keeps future language bindings straightforward. +//! - Uses X25519 + ChaCha20-Poly1305 for event payload sealing. Ed25519 +//! signing keys remain signing-only; encryption has its own key type. +//! - Stores receipt-chain anchors as hashes/URAs so auditors can locate +//! and verify terminal receipts without reading private payloads. +//! +//! Usage Contract: +//! - Callers must pass complete URAs and should use the URA builder +//! module before constructing records. +//! - Do not store raw logs or arguments in `LedgerEventPayload::Digest`; +//! use `Sealed` when content must be recoverable by a participant. +//! - AAD must be the canonical envelope or a stable hash of it. This +//! binds ciphertext to the invocation edge and prevents replay under +//! another caller/callee/ability tuple. +//! +//! Architectural Position: +//! - SDK protocol object shared by application hosts. Runtime services +//! call through this object rather than hand-writing ledger keys. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use chacha20poly1305::aead::{Aead, Payload}; +use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce}; +use rand::RngCore; +use redb::{Database, ReadableTable, TableDefinition, TableError}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use thiserror::Error; +use x25519_dalek::{PublicKey, StaticSecret}; + +const RECORDS: TableDefinition<&str, &[u8]> = TableDefinition::new("invocation_records_v2"); +const REQUEST_INDEX: TableDefinition<&str, &str> = TableDefinition::new("invocation_by_request_v2"); +const TRACE_INDEX: TableDefinition<&str, &str> = TableDefinition::new("invocation_by_trace_v2"); + +const LEDGER_ALGORITHM: &str = "x25519-chacha20poly1305-sha256-aad-v1"; + +#[derive(Debug, Error)] +pub enum InvocationLedgerError { + #[error("ledger database error: {0}")] + Database(String), + #[error("ledger codec error: {0}")] + Codec(#[from] serde_json::Error), + #[error("missing required ledger field: {0}")] + MissingField(&'static str), + #[error("ledger record not found: {0}")] + NotFound(String), + #[error("invalid encryption public key length: expected 32, got {0}")] + InvalidPublicKeyLen(usize), + #[error("payload encryption failed")] + EncryptionFailed, + #[error("payload decryption failed")] + DecryptionFailed, +} + +impl From for InvocationLedgerError { + fn from(value: redb::DatabaseError) -> Self { + Self::Database(value.to_string()) + } +} + +impl From for InvocationLedgerError { + fn from(value: redb::TransactionError) -> Self { + Self::Database(value.to_string()) + } +} + +impl From for InvocationLedgerError { + fn from(value: redb::TableError) -> Self { + Self::Database(value.to_string()) + } +} + +impl From for InvocationLedgerError { + fn from(value: redb::StorageError) -> Self { + Self::Database(value.to_string()) + } +} + +impl From for InvocationLedgerError { + fn from(value: redb::CommitError) -> Self { + Self::Database(value.to_string()) + } +} + +#[derive(Clone)] +pub struct InvocationEventPayloadKeypair { + secret: StaticSecret, + public: [u8; 32], +} + +impl InvocationEventPayloadKeypair { + pub fn generate() -> Self { + let secret = StaticSecret::random_from_rng(rand::rngs::OsRng); + let public = PublicKey::from(&secret).to_bytes(); + Self { secret, public } + } + + pub fn from_secret_bytes(secret_bytes: [u8; 32]) -> Self { + let secret = StaticSecret::from(secret_bytes); + let public = PublicKey::from(&secret).to_bytes(); + Self { secret, public } + } + + pub fn public_key(&self) -> [u8; 32] { + self.public + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct SealedLedgerEventPayload { + pub algorithm: String, + pub recipient_public_key: Vec, + pub ephemeral_public_key: Vec, + pub nonce: Vec, + pub aad_sha256: String, + pub plaintext_sha256: String, + pub ciphertext: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct LedgerRecipientPublicKey { + pub recipient_ura: String, + pub public_key: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct RecipientSealedLedgerEventPayload { + pub recipient_ura: String, + pub payload: SealedLedgerEventPayload, +} + +impl SealedLedgerEventPayload { + pub fn seal( + recipient_public_key: &[u8], + aad: &[u8], + plaintext: &[u8], + ) -> Result { + let recipient_public_key = public_key_from_slice(recipient_public_key)?; + let ephemeral_secret = StaticSecret::random_from_rng(rand::rngs::OsRng); + let ephemeral_public_key = PublicKey::from(&ephemeral_secret); + let shared = ephemeral_secret.diffie_hellman(&recipient_public_key); + let key = derive_payload_key(shared.as_bytes(), aad); + let cipher = ChaCha20Poly1305::new_from_slice(&key) + .map_err(|_| InvocationLedgerError::EncryptionFailed)?; + let mut nonce = [0_u8; 12]; + rand::rngs::OsRng.fill_bytes(&mut nonce); + let ciphertext = cipher + .encrypt( + Nonce::from_slice(&nonce), + Payload { + msg: plaintext, + aad, + }, + ) + .map_err(|_| InvocationLedgerError::EncryptionFailed)?; + + Ok(Self { + algorithm: LEDGER_ALGORITHM.to_string(), + recipient_public_key: recipient_public_key.to_bytes().to_vec(), + ephemeral_public_key: ephemeral_public_key.to_bytes().to_vec(), + nonce: nonce.to_vec(), + aad_sha256: sha256_hex(aad), + plaintext_sha256: sha256_hex(plaintext), + ciphertext, + }) + } + + pub fn open( + &self, + recipient: &InvocationEventPayloadKeypair, + aad: &[u8], + ) -> Result, InvocationLedgerError> { + if self.algorithm != LEDGER_ALGORITHM { + return Err(InvocationLedgerError::DecryptionFailed); + } + if self.recipient_public_key.as_slice() != recipient.public_key() { + return Err(InvocationLedgerError::DecryptionFailed); + } + if self.aad_sha256 != sha256_hex(aad) { + return Err(InvocationLedgerError::DecryptionFailed); + } + let ephemeral = public_key_from_slice(&self.ephemeral_public_key)?; + let shared = recipient.secret.diffie_hellman(&ephemeral); + let key = derive_payload_key(shared.as_bytes(), aad); + let cipher = ChaCha20Poly1305::new_from_slice(&key) + .map_err(|_| InvocationLedgerError::DecryptionFailed)?; + let plaintext = cipher + .decrypt( + Nonce::from_slice(&self.nonce), + Payload { + msg: self.ciphertext.as_slice(), + aad, + }, + ) + .map_err(|_| InvocationLedgerError::DecryptionFailed)?; + if sha256_hex(&plaintext) != self.plaintext_sha256 { + return Err(InvocationLedgerError::DecryptionFailed); + } + Ok(plaintext) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum LedgerEventPayloadKind { + Digest, + Sealed, + MultiSealed, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum LedgerEventPayload { + Digest { + content_type: String, + sha256: String, + size_bytes: u64, + }, + Sealed { + content_type: String, + payload: SealedLedgerEventPayload, + }, + MultiSealed { + content_type: String, + recipients: Vec, + }, +} + +impl LedgerEventPayload { + pub fn digest(content_type: impl Into, bytes: &[u8]) -> Self { + Self::Digest { + content_type: content_type.into(), + sha256: sha256_hex(bytes), + size_bytes: bytes.len() as u64, + } + } + + pub fn sealed( + content_type: impl Into, + recipient_public_key: &[u8], + aad: &[u8], + plaintext: &[u8], + ) -> Result { + Ok(Self::Sealed { + content_type: content_type.into(), + payload: SealedLedgerEventPayload::seal(recipient_public_key, aad, plaintext)?, + }) + } + + pub fn sealed_for_recipients( + content_type: impl Into, + recipients: &[LedgerRecipientPublicKey], + aad: &[u8], + plaintext: &[u8], + ) -> Result { + if recipients.is_empty() { + return Err(InvocationLedgerError::MissingField("recipients")); + } + let mut sealed = Vec::with_capacity(recipients.len()); + for recipient in recipients { + sealed.push(RecipientSealedLedgerEventPayload { + recipient_ura: recipient.recipient_ura.clone(), + payload: SealedLedgerEventPayload::seal(&recipient.public_key, aad, plaintext)?, + }); + } + Ok(Self::MultiSealed { + content_type: content_type.into(), + recipients: sealed, + }) + } + + pub fn open_for_recipient( + &self, + recipient_ura: &str, + recipient: &InvocationEventPayloadKeypair, + aad: &[u8], + ) -> Result, InvocationLedgerError> { + match self { + Self::Digest { .. } => Err(InvocationLedgerError::DecryptionFailed), + Self::Sealed { payload, .. } => payload.open(recipient, aad), + Self::MultiSealed { recipients, .. } => { + let Some(payload) = recipients + .iter() + .find(|candidate| candidate.recipient_ura == recipient_ura) + else { + return Err(InvocationLedgerError::DecryptionFailed); + }; + payload.payload.open(recipient, aad) + } + } + } + + pub fn kind(&self) -> LedgerEventPayloadKind { + match self { + Self::Digest { .. } => LedgerEventPayloadKind::Digest, + Self::Sealed { .. } => LedgerEventPayloadKind::Sealed, + Self::MultiSealed { .. } => LedgerEventPayloadKind::MultiSealed, + } + } + + pub fn visibility_summary(&self) -> LedgerPayloadVisibility { + match self { + Self::Digest { + content_type, + size_bytes, + .. + } => LedgerPayloadVisibility { + policy: "digest_only".to_string(), + content_type: content_type.clone(), + encrypted: false, + recoverable: false, + recipient_uras: Vec::new(), + size_bytes: Some(*size_bytes), + }, + Self::Sealed { + content_type, + payload, + } => LedgerPayloadVisibility { + policy: "sealed_single_recipient".to_string(), + content_type: content_type.clone(), + encrypted: true, + recoverable: true, + recipient_uras: vec![format!( + "public-key-sha256:{}", + sha256_hex(&payload.recipient_public_key) + )], + size_bytes: Some(payload.ciphertext.len() as u64), + }, + Self::MultiSealed { + content_type, + recipients, + } => LedgerPayloadVisibility { + policy: "sealed_explicit_recipients".to_string(), + content_type: content_type.clone(), + encrypted: true, + recoverable: true, + recipient_uras: recipients + .iter() + .map(|recipient| recipient.recipient_ura.clone()) + .collect(), + size_bytes: Some( + recipients + .iter() + .map(|r| r.payload.ciphertext.len() as u64) + .sum(), + ), + }, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct LedgerErrorRecord { + pub source: String, + pub code: String, + pub message: String, + pub retryable: bool, + pub context: BTreeMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct LedgerPayloadVisibility { + pub policy: String, + pub content_type: String, + pub encrypted: bool, + pub recoverable: bool, + pub recipient_uras: Vec, + pub size_bytes: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct LedgerVisibilitySummary { + pub args: LedgerPayloadVisibility, + pub result: Option, + pub diagnostics: Vec, +} + +impl LedgerVisibilitySummary { + pub fn from_payloads( + args: &LedgerEventPayload, + result: Option<&LedgerEventPayload>, + diagnostics: &[LedgerDiagnosticRecord], + ) -> Self { + Self { + args: args.visibility_summary(), + result: result.map(LedgerEventPayload::visibility_summary), + diagnostics: diagnostics + .iter() + .filter_map(|diagnostic| diagnostic.payload.as_ref()) + .map(LedgerEventPayload::visibility_summary) + .collect(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct LedgerDiagnosticRecord { + pub timestamp_unix_ms: i64, + pub level: String, + pub source: String, + pub code: String, + pub message: String, + pub retryable: bool, + pub payload: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct InvocationReceiptAnchor { + pub receipt_ura: String, + pub receipt_hash: String, + pub receipt_type: String, + pub state: String, + pub timestamp_unix_ms: i64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct InvocationReceiptChainSummary { + pub anchors: Vec, + pub verified: bool, + pub head_receipt_hash: Option, + pub verification_detail: String, +} + +impl InvocationReceiptChainSummary { + pub fn from_receipts( + receipt_ura_prefix: &str, + receipts: &[super::audit::InvocationReceipt], + ) -> Self { + let check = super::audit::verify_receipt_chain(receipts); + let anchors = receipts + .iter() + .map(|receipt| InvocationReceiptAnchor { + receipt_ura: format!( + "{}/receipt/{}", + receipt_ura_prefix.trim_end_matches('/'), + receipt.index + ), + receipt_hash: hex::encode(receipt.self_hash), + receipt_type: receipt.receipt_type.clone(), + state: receipt.state.clone(), + timestamp_unix_ms: receipt.timestamp_unix_ms, + }) + .collect::>(); + let head_receipt_hash = anchors.last().map(|anchor| anchor.receipt_hash.clone()); + Self { + anchors, + verified: check.ok, + head_receipt_hash, + verification_detail: check.detail, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct InvocationCausalLink { + pub source_invocation_ura: Option, + pub source_receipt_ura: String, + pub source_receipt_hash: String, + pub relation: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct InvocationTraceEdge { + pub from_invocation_ura: Option, + pub from_receipt_ura: String, + pub from_receipt_hash: String, + pub to_invocation_ura: String, + pub relation: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub struct InvocationTraceGraph { + pub trace_id: String, + pub records: Vec, + pub edges: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum InvocationLedgerFetchKey { + InvocationUra(String), + RequestId(String), + TraceId(String), +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct InvocationLedgerQuery { + pub key: Option, + pub limit: usize, + pub caller_ura: Option, + pub callee_ura: Option, + pub subject_uras: BTreeSet, + pub ability_ura: Option, + pub ability_name: Option, + pub trace_id: Option, + pub state: Option, +} + +impl InvocationLedgerQuery { + pub fn new() -> Self { + Self::default() + } + + pub fn key(mut self, key: InvocationLedgerFetchKey) -> Self { + self.key = Some(key); + self + } + + pub fn limit(mut self, limit: usize) -> Self { + self.limit = limit; + self + } + + pub fn caller_ura(mut self, value: impl Into) -> Self { + self.caller_ura = non_empty_string(value.into()); + self + } + + pub fn callee_ura(mut self, value: impl Into) -> Self { + self.callee_ura = non_empty_string(value.into()); + self + } + + pub fn subject_ura(mut self, value: impl Into) -> Self { + self.subject_uras.clear(); + if let Some(value) = non_empty_string(value.into()) { + self.subject_uras.insert(value); + } + self + } + + pub fn subject_uras(mut self, values: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.subject_uras.clear(); + self.subject_uras.extend( + values + .into_iter() + .filter_map(|value| non_empty_string(value.into())), + ); + self + } + + pub fn ability_ura(mut self, value: impl Into) -> Self { + self.ability_ura = non_empty_string(value.into()); + self + } + + pub fn ability_name(mut self, value: impl Into) -> Self { + self.ability_name = non_empty_string(value.into()); + self + } + + pub fn trace_id(mut self, value: impl Into) -> Self { + self.trace_id = non_empty_string(value.into()); + self + } + + pub fn state(mut self, value: impl Into) -> Self { + self.state = non_empty_string(value.into()); + self + } + + fn matches(&self, record: &InvocationLedgerRecord) -> bool { + matches_opt(&self.caller_ura, &record.caller_ura) + && matches_opt(&self.callee_ura, &record.callee_ura) + && matches_any(&self.subject_uras, &record.subject_ura) + && matches_opt(&self.ability_ura, &record.ability_ura) + && matches_opt(&self.ability_name, &record.ability_name) + && matches_opt(&self.trace_id, &record.trace_id) + && matches_opt(&self.state, &record.state) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct InvocationLedgerRecord { + pub invocation_ura: String, + pub request_id: String, + pub trace_id: String, + pub span_id: String, + pub caller_ura: String, + pub callee_ura: String, + pub subject_ura: String, + pub ability_ura: String, + pub ability_name: String, + pub state: String, + pub started_unix_ms: i64, + pub completed_unix_ms: Option, + pub elapsed_ms: Option, + pub args: LedgerEventPayload, + pub result: Option, + pub error: Option, + #[serde(default)] + pub diagnostics: Vec, + #[serde(default)] + pub causal_links: Vec, + #[serde(default)] + pub receipt_chain: InvocationReceiptChainSummary, + #[serde(default)] + pub visibility: LedgerVisibilitySummary, +} + +#[derive(Debug, Default)] +pub struct InvocationLedgerRecordBuilder { + invocation_ura: Option, + request_id: Option, + trace_id: Option, + span_id: Option, + caller_ura: Option, + callee_ura: Option, + subject_ura: Option, + ability_ura: Option, + ability_name: Option, + state: Option, + started_unix_ms: Option, + completed_unix_ms: Option, + elapsed_ms: Option, + args: Option, + result: Option, + error: Option, + diagnostics: Option>, + causal_links: Option>, + receipt_chain: Option, + visibility: Option, +} + +macro_rules! builder_setter { + ($name:ident, $ty:ty) => { + pub fn $name(mut self, value: impl Into<$ty>) -> Self { + self.$name = Some(value.into()); + self + } + }; +} + +impl InvocationLedgerRecordBuilder { + pub fn new() -> Self { + Self::default() + } + + builder_setter!(invocation_ura, String); + builder_setter!(request_id, String); + builder_setter!(trace_id, String); + builder_setter!(span_id, String); + builder_setter!(caller_ura, String); + builder_setter!(callee_ura, String); + builder_setter!(subject_ura, String); + builder_setter!(ability_ura, String); + builder_setter!(ability_name, String); + builder_setter!(state, String); + builder_setter!(started_unix_ms, i64); + builder_setter!(completed_unix_ms, i64); + builder_setter!(elapsed_ms, u64); + builder_setter!(args, LedgerEventPayload); + builder_setter!(result, LedgerEventPayload); + builder_setter!(error, LedgerErrorRecord); + builder_setter!(diagnostics, Vec); + builder_setter!(causal_links, Vec); + builder_setter!(receipt_chain, InvocationReceiptChainSummary); + builder_setter!(visibility, LedgerVisibilitySummary); + + pub fn build(self) -> Result { + let args = required(self.args, "args")?; + let result = self.result; + let diagnostics = self.diagnostics.unwrap_or_default(); + let visibility = self.visibility.unwrap_or_else(|| { + LedgerVisibilitySummary::from_payloads(&args, result.as_ref(), &diagnostics) + }); + Ok(InvocationLedgerRecord { + invocation_ura: required(self.invocation_ura, "invocation_ura")?, + request_id: required(self.request_id, "request_id")?, + trace_id: self.trace_id.unwrap_or_default(), + span_id: self.span_id.unwrap_or_default(), + caller_ura: required(self.caller_ura, "caller_ura")?, + callee_ura: required(self.callee_ura, "callee_ura")?, + subject_ura: required(self.subject_ura, "subject_ura")?, + ability_ura: required(self.ability_ura, "ability_ura")?, + ability_name: required(self.ability_name, "ability_name")?, + state: required(self.state, "state")?, + started_unix_ms: required(self.started_unix_ms, "started_unix_ms")?, + completed_unix_ms: self.completed_unix_ms, + elapsed_ms: self.elapsed_ms, + args, + result, + error: self.error, + diagnostics, + causal_links: self.causal_links.unwrap_or_default(), + receipt_chain: self.receipt_chain.unwrap_or_default(), + visibility, + }) + } +} + +pub struct InvocationLedger { + db: Database, +} + +impl InvocationLedger { + pub fn open(path: impl AsRef) -> Result { + let path = path.as_ref(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| InvocationLedgerError::Database(e.to_string()))?; + } + Ok(Self { + db: Database::create(path)?, + }) + } + + pub fn put(&self, record: &InvocationLedgerRecord) -> Result<(), InvocationLedgerError> { + let encoded = serde_json::to_vec(record)?; + let trace_key = trace_index_key(record); + let txn = self.db.begin_write()?; + { + let mut records = txn.open_table(RECORDS)?; + records.insert(record.invocation_ura.as_str(), encoded.as_slice())?; + } + { + let mut by_request = txn.open_table(REQUEST_INDEX)?; + by_request.insert(record.request_id.as_str(), record.invocation_ura.as_str())?; + } + { + let mut by_trace = txn.open_table(TRACE_INDEX)?; + by_trace.insert(trace_key.as_str(), record.invocation_ura.as_str())?; + } + txn.commit()?; + Ok(()) + } + + pub fn get( + &self, + invocation_ura: &str, + ) -> Result, InvocationLedgerError> { + let txn = self.db.begin_read()?; + let table = match txn.open_table(RECORDS) { + Ok(table) => table, + Err(err) if is_missing_table(&err) => return Ok(None), + Err(err) => return Err(err.into()), + }; + let Some(value) = table.get(invocation_ura)? else { + return Ok(None); + }; + Ok(Some(serde_json::from_slice(value.value())?)) + } + + pub fn get_by_request( + &self, + request_id: &str, + ) -> Result, InvocationLedgerError> { + let txn = self.db.begin_read()?; + let table = match txn.open_table(REQUEST_INDEX) { + Ok(table) => table, + Err(err) if is_missing_table(&err) => return Ok(None), + Err(err) => return Err(err.into()), + }; + let Some(invocation_ura) = table.get(request_id)? else { + return Ok(None); + }; + drop(table); + let records = match txn.open_table(RECORDS) { + Ok(table) => table, + Err(err) if is_missing_table(&err) => return Ok(None), + Err(err) => return Err(err.into()), + }; + let Some(value) = records.get(invocation_ura.value())? else { + return Ok(None); + }; + Ok(Some(serde_json::from_slice(value.value())?)) + } + + pub fn list_all(&self) -> Result, InvocationLedgerError> { + let txn = self.db.begin_read()?; + let table = match txn.open_table(RECORDS) { + Ok(table) => table, + Err(err) if is_missing_table(&err) => return Ok(Vec::new()), + Err(err) => return Err(err.into()), + }; + let mut out: Vec = Vec::new(); + for row in table.iter()? { + let (_, value) = row?; + out.push(serde_json::from_slice(value.value())?); + } + out.sort_by(|a, b| { + a.started_unix_ms + .cmp(&b.started_unix_ms) + .then_with(|| a.invocation_ura.cmp(&b.invocation_ura)) + }); + Ok(out) + } + + pub fn list_recent( + &self, + limit: usize, + ) -> Result, InvocationLedgerError> { + let mut records = self.list_all()?; + records.reverse(); + if limit > 0 && records.len() > limit { + records.truncate(limit); + } + Ok(records) + } + + pub fn fetch( + &self, + query: InvocationLedgerQuery, + ) -> Result, InvocationLedgerError> { + let mut records = match query.key.as_ref() { + Some(InvocationLedgerFetchKey::InvocationUra(ura)) => { + self.get(ura)?.into_iter().collect::>() + } + Some(InvocationLedgerFetchKey::RequestId(request_id)) => self + .get_by_request(request_id)? + .into_iter() + .collect::>(), + Some(InvocationLedgerFetchKey::TraceId(trace_id)) => self.list_by_trace(trace_id)?, + None => self.list_all()?, + }; + records.retain(|record| query.matches(record)); + records.sort_by(|a, b| { + b.started_unix_ms + .cmp(&a.started_unix_ms) + .then_with(|| b.invocation_ura.cmp(&a.invocation_ura)) + }); + if query.limit > 0 && records.len() > query.limit { + records.truncate(query.limit); + } + Ok(records) + } + + pub fn fetch_one( + &self, + query: InvocationLedgerQuery, + ) -> Result, InvocationLedgerError> { + Ok(self.fetch(query.limit(1))?.into_iter().next()) + } + + pub fn list_by_trace( + &self, + trace_id: &str, + ) -> Result, InvocationLedgerError> { + let txn = self.db.begin_read()?; + let trace_index = match txn.open_table(TRACE_INDEX) { + Ok(table) => table, + Err(err) if is_missing_table(&err) => return Ok(Vec::new()), + Err(err) => return Err(err.into()), + }; + let start = format!("{trace_id}\u{1f}"); + let end = format!("{trace_id}\u{20}"); + let mut invocation_uras = Vec::new(); + for row in trace_index.range(start.as_str()..end.as_str())? { + let (_, invocation_ura) = row?; + invocation_uras.push(invocation_ura.value().to_string()); + } + drop(trace_index); + + let records_table = match txn.open_table(RECORDS) { + Ok(table) => table, + Err(err) if is_missing_table(&err) => return Ok(Vec::new()), + Err(err) => return Err(err.into()), + }; + let mut records: Vec = Vec::new(); + for invocation_ura in invocation_uras { + if let Some(value) = records_table.get(invocation_ura.as_str())? { + records.push(serde_json::from_slice(value.value())?); + } + } + records.sort_by(|a, b| { + a.started_unix_ms + .cmp(&b.started_unix_ms) + .then_with(|| a.invocation_ura.cmp(&b.invocation_ura)) + }); + Ok(records) + } + + pub fn trace_graph( + &self, + trace_id: &str, + ) -> Result { + let records = self.list_by_trace(trace_id)?; + let known_invocations = records + .iter() + .map(|record| record.invocation_ura.as_str()) + .collect::>(); + let mut edges = Vec::new(); + for record in &records { + for link in &record.causal_links { + let from_invocation_ura = link + .source_invocation_ura + .as_ref() + .filter(|candidate| known_invocations.contains(candidate.as_str())) + .cloned(); + edges.push(InvocationTraceEdge { + from_invocation_ura, + from_receipt_ura: link.source_receipt_ura.clone(), + from_receipt_hash: link.source_receipt_hash.clone(), + to_invocation_ura: record.invocation_ura.clone(), + relation: if link.relation.is_empty() { + "causal".to_string() + } else { + link.relation.clone() + }, + }); + } + } + Ok(InvocationTraceGraph { + trace_id: trace_id.to_string(), + records, + edges, + }) + } +} + +fn is_missing_table(err: &TableError) -> bool { + matches!(err, TableError::TableDoesNotExist(_)) +} + +fn required(value: Option, field: &'static str) -> Result { + value.ok_or(InvocationLedgerError::MissingField(field)) +} + +fn public_key_from_slice(value: &[u8]) -> Result { + if value.len() != 32 { + return Err(InvocationLedgerError::InvalidPublicKeyLen(value.len())); + } + let mut bytes = [0_u8; 32]; + bytes.copy_from_slice(value); + Ok(PublicKey::from(bytes)) +} + +fn derive_payload_key(shared_secret: &[u8; 32], aad: &[u8]) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(b"easynet-axon-invocation-ledger-payload-v1"); + hasher.update(shared_secret); + hasher.update((aad.len() as u64).to_be_bytes()); + hasher.update(aad); + hasher.finalize().into() +} + +fn sha256_hex(bytes: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(bytes); + hex::encode(hasher.finalize()) +} + +fn trace_index_key(record: &InvocationLedgerRecord) -> String { + format!( + "{}\u{1f}{:020}\u{1f}{}", + record.trace_id, record.started_unix_ms, record.invocation_ura + ) +} + +fn non_empty_string(value: String) -> Option { + let trimmed = value.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } +} + +fn matches_opt(expected: &Option, actual: &str) -> bool { + expected + .as_deref() + .map(|value| value == actual) + .unwrap_or(true) +} + +fn matches_any(expected: &BTreeSet, actual: &str) -> bool { + expected.is_empty() || expected.contains(actual) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sealed_payload_opens_only_for_recipient_and_matching_aad() { + let recipient = InvocationEventPayloadKeypair::from_secret_bytes([7_u8; 32]); + let other = InvocationEventPayloadKeypair::from_secret_bytes([9_u8; 32]); + let aad = b"caller|callee|ability|nonce"; + let sealed = + SealedLedgerEventPayload::seal(&recipient.public_key(), aad, b"private log line") + .expect("seal"); + + assert_ne!(sealed.ciphertext, b"private log line"); + let opened = sealed.open(&recipient, aad).expect("open"); + assert_eq!(opened, b"private log line"); + assert!(sealed.open(&other, aad).is_err()); + assert!(sealed.open(&recipient, b"wrong aad").is_err()); + } + + #[test] + fn multi_recipient_payload_opens_only_for_named_participants() { + let caller = InvocationEventPayloadKeypair::from_secret_bytes([1_u8; 32]); + let callee = InvocationEventPayloadKeypair::from_secret_bytes([2_u8; 32]); + let unrelated = InvocationEventPayloadKeypair::from_secret_bytes([3_u8; 32]); + let caller_ura = "easynet:///r/acme/agent/alice.caller"; + let callee_ura = "easynet:///r/acme/agent/bob.callee"; + let aad = b"canonical invocation edge"; + let payload = LedgerEventPayload::sealed_for_recipients( + "application/json", + &[ + LedgerRecipientPublicKey { + recipient_ura: caller_ura.to_string(), + public_key: caller.public_key().to_vec(), + }, + LedgerRecipientPublicKey { + recipient_ura: callee_ura.to_string(), + public_key: callee.public_key().to_vec(), + }, + ], + aad, + br#"{"secret":true}"#, + ) + .expect("sealed"); + + assert_eq!( + payload + .open_for_recipient(caller_ura, &caller, aad) + .expect("caller open"), + br#"{"secret":true}"# + ); + assert_eq!( + payload + .open_for_recipient(callee_ura, &callee, aad) + .expect("callee open"), + br#"{"secret":true}"# + ); + assert!(payload + .open_for_recipient(caller_ura, &unrelated, aad) + .is_err()); + assert!(payload + .open_for_recipient("easynet:///r/acme/agent/charlie.other", &unrelated, aad) + .is_err()); + assert_eq!( + payload.visibility_summary().recipient_uras, + vec![caller_ura.to_string(), callee_ura.to_string()] + ); + } + + #[test] + fn ledger_persists_records_by_ura_and_request_id() { + let temp = tempfile::tempdir().expect("tempdir"); + let path = temp.path().join("billing").join("invocations.redb"); + let ledger = InvocationLedger::open(&path).expect("open"); + let record = sample_record("completed"); + ledger.put(&record).expect("put"); + drop(ledger); + + let reopened = InvocationLedger::open(&path).expect("reopen"); + let by_ura = reopened + .get(&record.invocation_ura) + .expect("get") + .expect("record"); + assert_eq!(by_ura, record); + let by_request = reopened + .get_by_request("req-1") + .expect("get by request") + .expect("record"); + assert_eq!(by_request.invocation_ura, record.invocation_ura); + assert_eq!(reopened.list_all().expect("list").len(), 1); + assert_eq!(reopened.list_recent(1).expect("recent").len(), 1); + } + + #[test] + fn empty_existing_ledger_file_reads_as_empty_history() { + let temp = tempfile::tempdir().expect("tempdir"); + let path = temp.path().join("billing").join("invocations.redb"); + let ledger = InvocationLedger::open(&path).expect("open"); + + assert!(path.exists(), "open should create the native redb file"); + assert_eq!(ledger.list_all().expect("list all"), Vec::new()); + assert_eq!(ledger.list_recent(10).expect("recent"), Vec::new()); + assert_eq!( + ledger + .fetch(InvocationLedgerQuery::new().limit(10)) + .expect("fetch"), + Vec::new() + ); + assert!(ledger + .get("easynet:///r/acme/resource/alice.invocations/missing") + .expect("get") + .is_none()); + assert!(ledger + .get_by_request("missing-request") + .expect("get by request") + .is_none()); + assert!(ledger + .fetch_one( + InvocationLedgerQuery::new().key(InvocationLedgerFetchKey::RequestId( + "missing-request".to_string() + )), + ) + .expect("fetch one") + .is_none()); + let graph = ledger.trace_graph("missing-trace").expect("trace graph"); + assert_eq!(graph.trace_id, "missing-trace"); + assert!(graph.records.is_empty()); + assert!(graph.edges.is_empty()); + } + + #[test] + fn trace_graph_projects_causal_edges_from_records() { + let temp = tempfile::tempdir().expect("tempdir"); + let ledger = InvocationLedger::open(temp.path().join("billing").join("invocations.redb")) + .expect("open"); + let parent = sample_record("completed"); + let child_ura = crate::ura::resource_dot_ura("acme", "alice.invocations", "req-2"); + let child = InvocationLedgerRecordBuilder::new() + .invocation_ura(child_ura.clone()) + .request_id("req-2".to_string()) + .trace_id(parent.trace_id.clone()) + .span_id("span-2".to_string()) + .caller_ura(parent.caller_ura.clone()) + .callee_ura("easynet:///r/acme/agent/worker".to_string()) + .subject_ura(parent.subject_ura.clone()) + .ability_ura("easynet:///r/acme/ability/worker.step".to_string()) + .ability_name("worker.step".to_string()) + .state("completed".to_string()) + .started_unix_ms(43_i64) + .completed_unix_ms(46_i64) + .elapsed_ms(3_u64) + .args(LedgerEventPayload::digest("application/json", b"{}")) + .causal_links(vec![InvocationCausalLink { + source_invocation_ura: Some(parent.invocation_ura.clone()), + source_receipt_ura: format!("{}/receipt/1", parent.invocation_ura), + source_receipt_hash: "ab".repeat(32), + relation: "child_spawned".to_string(), + }]) + .build() + .expect("child"); + ledger.put(&parent).expect("put parent"); + ledger.put(&child).expect("put child"); + + let graph = ledger.trace_graph(&parent.trace_id).expect("graph"); + assert_eq!(graph.records.len(), 2); + assert_eq!(graph.edges.len(), 1); + assert_eq!( + graph.edges[0].from_invocation_ura.as_deref(), + Some(parent.invocation_ura.as_str()) + ); + assert_eq!(graph.edges[0].to_invocation_ura, child_ura); + assert_eq!(graph.edges[0].relation, "child_spawned"); + } + + #[test] + fn fetch_filters_by_protocol_identity_fields() { + let temp = tempfile::tempdir().expect("tempdir"); + let ledger = InvocationLedger::open(temp.path().join("billing").join("invocations.redb")) + .expect("open"); + let first = sample_record("completed"); + let second = InvocationLedgerRecordBuilder::new() + .invocation_ura(crate::ura::resource_dot_ura( + "acme", + "alice.invocations", + "req-2", + )) + .request_id("req-2".to_string()) + .trace_id("trace-2".to_string()) + .span_id("span-2".to_string()) + .caller_ura("easynet:///r/acme/device/dev-b".to_string()) + .callee_ura(first.callee_ura.clone()) + .subject_ura(first.subject_ura.clone()) + .ability_ura(first.ability_ura.clone()) + .ability_name(first.ability_name.clone()) + .state("failed".to_string()) + .started_unix_ms(50_i64) + .args(LedgerEventPayload::digest("application/json", b"{}")) + .build() + .expect("record"); + ledger.put(&first).expect("put first"); + ledger.put(&second).expect("put second"); + + let records = ledger + .fetch( + InvocationLedgerQuery::new() + .ability_name("federation.resolve") + .subject_ura("easynet:///r/acme/user/alice") + .state("completed"), + ) + .expect("fetch"); + assert_eq!(records.len(), 1); + assert_eq!(records[0].request_id, "req-1"); + + let subject_matches = ledger + .fetch( + InvocationLedgerQuery::new() + .subject_uras([ + "easynet:///r/acme/device/dev-missing", + "easynet:///r/acme/user/alice", + ]) + .limit(10), + ) + .expect("fetch subject set"); + assert_eq!(subject_matches.len(), 2); + + let by_request = ledger + .fetch_one( + InvocationLedgerQuery::new() + .key(InvocationLedgerFetchKey::RequestId("req-2".to_string())) + .callee_ura(first.callee_ura), + ) + .expect("fetch one") + .expect("record"); + assert_eq!(by_request.request_id, "req-2"); + } + + #[test] + fn receipt_chain_summary_verifies_and_exposes_head_hash() { + let r0 = sample_receipt(0, super::super::audit::ZERO_HASH); + let r1 = sample_receipt(1, r0.self_hash); + let expected_head = hex::encode(r1.self_hash); + let summary = InvocationReceiptChainSummary::from_receipts( + "easynet:///r/acme/resource/alice.invocations/req-1", + &[r0, r1], + ); + assert!(summary.verified, "{}", summary.verification_detail); + assert_eq!(summary.anchors.len(), 2); + assert_eq!( + summary.head_receipt_hash.as_deref(), + Some(expected_head.as_str()) + ); + } + + #[test] + fn builder_requires_complete_protocol_identity() { + let err = InvocationLedgerRecordBuilder::new() + .request_id("req-1".to_string()) + .args(LedgerEventPayload::digest("application/json", b"{}")) + .build() + .unwrap_err(); + assert!(format!("{err}").contains("invocation_ura")); + } + + fn sample_record(state: &str) -> InvocationLedgerRecord { + InvocationLedgerRecordBuilder::new() + .invocation_ura(crate::ura::resource_dot_ura( + "acme", + "alice.invocations", + "req-1", + )) + .request_id("req-1".to_string()) + .trace_id("trace-1".to_string()) + .span_id("span-1".to_string()) + .caller_ura("easynet:///r/acme/device/dev-a".to_string()) + .callee_ura("easynet:///r/acme/hub".to_string()) + .subject_ura("easynet:///r/acme/user/alice".to_string()) + .ability_ura("easynet:///r/acme/ability/hub.federation.resolve".to_string()) + .ability_name("federation.resolve".to_string()) + .state(state.to_string()) + .started_unix_ms(42_i64) + .completed_unix_ms(45_i64) + .elapsed_ms(3_u64) + .args(LedgerEventPayload::digest("application/json", b"{}")) + .result(LedgerEventPayload::digest( + "application/json", + b"{\"ok\":true}", + )) + .build() + .expect("record") + } + + fn sample_binding() -> super::super::audit::AxiomBinding { + super::super::audit::AxiomBinding { + caller: super::super::axiom::AgentIdentity::new( + "easynet:///r/acme/agent/alice.caller", + super::super::axiom::UraProfile::EasynetStrictV2, + ), + callee: super::super::axiom::AgentIdentity::new( + "easynet:///r/acme/agent/bob.callee", + super::super::axiom::UraProfile::EasynetStrictV2, + ), + subject: super::super::axiom::SubjectIdentity::new( + "easynet:///r/acme/resource/alice.invocations/req-1", + super::super::axiom::UraProfile::EasynetStrictV2, + ), + invocation_nonce: [0x42; 16], + causal: super::super::axiom::CausalContext::None, + payload_digest: super::super::axiom::sha256(b"{}"), + callee_signature: None, + } + } + + fn sample_receipt(index: u64, prev: [u8; 32]) -> super::super::audit::InvocationReceipt { + super::super::audit::new_receipt( + index, + "req-1", + if index == 0 { "admitted" } else { "completed" }, + if index == 0 { "ADMITTED" } else { "COMPLETED" }, + 1_700_000_000_000 + index as i64, + prev, + Vec::new(), + "application/json", + index > 0, + "", + "", + sample_binding(), + ) + } +} diff --git a/sdk/rust/src/invocation/local_runtime.rs b/sdk/rust/src/invocation/local_runtime.rs index f74ff237..83fea3a4 100644 --- a/sdk/rust/src/invocation/local_runtime.rs +++ b/sdk/rust/src/invocation/local_runtime.rs @@ -613,11 +613,11 @@ impl LocalRuntime { } } -/// Well-known local-runtime SystemAgent URI used when no caller identity +/// Well-known local-runtime SystemAgent URA used when no caller identity /// is provided. AXIOM.tex §3.2 permits this: infrastructure-initiated /// invocations carry a SystemAgent identity and are still axiom-bound. -const SYSTEM_CALLER_URI: &str = "easynet:///r/_system/agents/local@1"; -const SYSTEM_CALLEE_URI: &str = "easynet:///r/_system/agents/local@1"; +const SYSTEM_CALLER_URA: &str = "easynet:///r/_system/agent/_system.local"; +const SYSTEM_CALLEE_URA: &str = "easynet:///r/_system/agent/_system.local"; /// Build an axiom binding for a plain `invoke_async` caller. /// @@ -628,12 +628,12 @@ const SYSTEM_CALLEE_URI: &str = "easynet:///r/_system/agents/local@1"; /// rely on this path. fn system_local_binding(_ability: &str, payload: &[u8]) -> AxiomBinding { let system = AgentIdentity::new( - SYSTEM_CALLER_URI, - crate::invocation::UriProfile::EasynetStrictV2, + SYSTEM_CALLER_URA, + crate::invocation::UraProfile::EasynetStrictV2, ); let callee = AgentIdentity::new( - SYSTEM_CALLEE_URI, - crate::invocation::UriProfile::EasynetStrictV2, + SYSTEM_CALLEE_URA, + crate::invocation::UraProfile::EasynetStrictV2, ); let subject = SubjectIdentity::from_callee(&callee); AxiomBinding { diff --git a/sdk/rust/src/invocation/mod.rs b/sdk/rust/src/invocation/mod.rs index 2d5804fe..6b528977 100644 --- a/sdk/rust/src/invocation/mod.rs +++ b/sdk/rust/src/invocation/mod.rs @@ -19,6 +19,7 @@ pub mod bundle; pub mod error; pub mod handle; pub mod invocation_tools; +pub mod ledger; pub mod local_runtime; pub mod messaging; pub mod persistence; @@ -38,7 +39,7 @@ pub use axiom::{ sha256, sign_invocation, sign_receipt, signing_key_from_bytes, verify_invocation_signature, verify_receipt_signature, AgentIdentity, CalleeSignature, CallerSignature, CausalContext, FileKeyResolver, InvocationEnvelope, KeyResolver, ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, }; pub use bundle::{ CausalJson, IdentityJson, InvocationJson, PubkeyMap, ReceiptJson, ReceiptRefJson, @@ -52,6 +53,14 @@ pub use invocation_tools::{ build_invocation_tools, CancelInvocationTool, InvocationListTool, InvocationOutputTool, InvocationToolSet, SendInvocationMessageTool, ToolSchema, }; +pub use ledger::{ + InvocationCausalLink, InvocationEventPayloadKeypair, InvocationLedger, InvocationLedgerError, + InvocationLedgerFetchKey, InvocationLedgerQuery, InvocationLedgerRecord, + InvocationLedgerRecordBuilder, InvocationReceiptAnchor, InvocationReceiptChainSummary, + InvocationTraceEdge, InvocationTraceGraph, LedgerDiagnosticRecord, LedgerErrorRecord, + LedgerEventPayload, LedgerEventPayloadKind, LedgerPayloadVisibility, LedgerRecipientPublicKey, + LedgerVisibilitySummary, RecipientSealedLedgerEventPayload, SealedLedgerEventPayload, +}; pub use local_runtime::{make_ability, AbilityContext, AbilityFn, LocalRuntime, SignedEnvelope}; pub use messaging::{InboundMessage, InboxFull, MessageAck, MessageInbox}; pub use persistence::{default_log_dir, InvocationIndex, PersistentLog}; diff --git a/sdk/rust/src/lib.rs b/sdk/rust/src/lib.rs index ad161975..bb22e8db 100644 --- a/sdk/rust/src/lib.rs +++ b/sdk/rust/src/lib.rs @@ -25,6 +25,7 @@ pub mod stream_resume; pub mod streaming; pub mod streams; pub mod tool_adapter; +pub mod ura; pub mod utils; pub use ability::{ diff --git a/sdk/rust/src/server.rs b/sdk/rust/src/server.rs index a4ba6c8e..85f275aa 100644 --- a/sdk/rust/src/server.rs +++ b/sdk/rust/src/server.rs @@ -102,7 +102,7 @@ impl Drop for ServerHandle { /// ``` #[derive(Debug, Clone)] pub struct ServerConfig { - /// Axon transport URI (`axon://host`) or HTTP URL. If `None`, + /// Axon transport URA (`axon://host`) or HTTP URL. If `None`, /// checks `EASYNET_AXON_ENDPOINT` env var, then auto-starts locally. pub endpoint: Option, /// Path to write runtime logs. Default: `~/.easynet/logs/axon-runtime.log`. diff --git a/sdk/rust/src/tool_adapter.rs b/sdk/rust/src/tool_adapter.rs index 11b5e601..1f9e8245 100644 --- a/sdk/rust/src/tool_adapter.rs +++ b/sdk/rust/src/tool_adapter.rs @@ -16,6 +16,7 @@ use crate::{ dendrite_bridge::DendriteBridge, error::{AxonError, Result}, presets::remote_control::DEFAULT_AXON_PORT, + ura, }; // --------------------------------------------------------------------------- @@ -27,7 +28,7 @@ use crate::{ pub struct ToolSpec { pub name: String, pub description: String, - pub resource_uri: String, + pub resource_ura: String, pub parameters: Value, } @@ -68,7 +69,7 @@ impl ToolSpec { json!({ "name": self.name, "description": self.description, - "resource_uri": self.resource_uri, + "resource_ura": self.resource_ura, "parameters": self.parameters, }) } @@ -124,12 +125,12 @@ impl Default for ToolAdapterRemoteConfig { } } -/// Parse the visibility segment from an Axon resource URI. +/// Parse the visibility segment from an Axon resource URA. /// -/// URI format: `easynet:///r/{visibility}/{token}` +/// URA format: `easynet:///r/{visibility}/{token}` /// Returns the visibility string, defaulting to `"org"`. -fn parse_resource_visibility(resource_uri: &str) -> &'static str { - let normalized = resource_uri.trim().to_ascii_lowercase(); +fn parse_resource_visibility(resource_ura: &str) -> &'static str { + let normalized = resource_ura.trim().to_ascii_lowercase(); // Format: easynet:///r/{visibility}/... if let Some(after) = normalized.strip_prefix("easynet:///r/") { match after.split('/').next() { @@ -142,7 +143,7 @@ fn parse_resource_visibility(resource_uri: &str) -> &'static str { "org" } -fn principal_to_subject_id(principal_id: &str, resource_uri: &str) -> Result { +fn principal_to_subject_id(principal_id: &str, resource_ura: &str) -> Result { let normalized = principal_id.trim(); if normalized.is_empty() { return Err(AxonError::Invocation( @@ -163,7 +164,7 @@ fn principal_to_subject_id(principal_id: &str, resource_uri: &str) -> Result Result Result { let subject_id = config .principal_id .as_deref() .filter(|value| !value.trim().is_empty()) - .map(|value| principal_to_subject_id(value, resource_uri)) + .map(|value| principal_to_subject_id(value, resource_ura)) .transpose()?; let bridge = DendriteBridge::connect(&config.endpoint, config.connect_timeout_ms)?; bridge.ability_call( tenant_id, - resource_uri, + resource_ura, arguments, subject_id.as_deref(), None, @@ -211,7 +212,7 @@ fn default_remote_execute( /// }, ToolSpec { /// name: "get_horoscope".into(), /// description: "Get today's horoscope.".into(), -/// resource_uri: "easynet:///r/org/get_horoscope".into(), +/// resource_ura: "easynet:///r/org/get_horoscope".into(), /// parameters: json!({ /// "type": "object", /// "properties": {"sign": {"type": "string"}}, @@ -322,14 +323,15 @@ impl AbilityToolAdapter { name: impl Into, handler: impl ToolHandler + 'static, description: impl Into, - resource_uri: Option, + resource_ura: Option, parameters: Option, ) -> &mut Self { let name_str = name.into(); let spec = ToolSpec { name: name_str.clone(), description: description.into(), - resource_uri: resource_uri.unwrap_or_else(|| format!("easynet:///r/org/{name_str}")), + resource_ura: resource_ura + .unwrap_or_else(|| ura::resource_dot_ura("org", &name_str, "")), parameters: parameters.unwrap_or_else(|| json!({"type": "object", "properties": {}})), }; self.register(name_str, handler, spec) @@ -420,7 +422,7 @@ impl AbilityToolAdapter { (self.remote_executor)( &self.remote_config, &self.tenant_id, - &self.specs[idx].resource_uri, + &self.specs[idx].resource_ura, arguments, ) } @@ -448,7 +450,7 @@ mod tests { ToolSpec { name: "ignored".into(), description: "first".into(), - resource_uri: "easynet:///r/org/shared".into(), + resource_ura: "easynet:///r/org/shared".into(), parameters: json!({"type": "object", "properties": {"v": {"type": "number"}}}), }, ); @@ -458,7 +460,7 @@ mod tests { ToolSpec { name: "ignored-again".into(), description: "second".into(), - resource_uri: "easynet:///r/org/shared-v2".into(), + resource_ura: "easynet:///r/org/shared-v2".into(), parameters: json!({"type": "object", "properties": {"name": {"type": "string"}}}), }, ); @@ -467,7 +469,7 @@ mod tests { assert_eq!(adapter.specs()[0].name, "shared"); assert_eq!(adapter.specs()[0].description, "second"); assert_eq!( - adapter.specs()[0].resource_uri, + adapter.specs()[0].resource_ura, "easynet:///r/org/shared-v2" ); assert_eq!( @@ -490,16 +492,16 @@ mod tests { }); adapter.set_remote_executor({ let calls = Arc::clone(&calls); - move |config, tenant_id, resource_uri, arguments| { + move |config, tenant_id, resource_ura, arguments| { calls.lock().unwrap().push(( tenant_id.to_string(), - resource_uri.to_string(), + resource_ura.to_string(), arguments.clone(), config.endpoint.clone(), )); Ok(json!({ "source": "remote", - "resource_uri": resource_uri, + "resource_ura": resource_ura, })) } }); @@ -509,14 +511,14 @@ mod tests { ToolSpec { name: "shared".into(), description: "local".into(), - resource_uri: "easynet:///r/org/shared-local".into(), + resource_ura: "easynet:///r/org/shared-local".into(), parameters: json!({"type": "object", "properties": {}}), }, ); adapter.register_ability(ToolSpec { name: "shared".into(), description: "remote".into(), - resource_uri: "easynet:///r/org/shared-remote".into(), + resource_ura: "easynet:///r/org/shared-remote".into(), parameters: json!({"type": "object", "properties": {}}), }); @@ -542,7 +544,7 @@ mod tests { ToolSpec { name: "stringify".into(), description: "returns string".into(), - resource_uri: "easynet:///r/org/stringify".into(), + resource_ura: "easynet:///r/org/stringify".into(), parameters: json!({"type": "object", "properties": {}}), }, ); diff --git a/sdk/rust/src/ura.rs b/sdk/rust/src/ura.rs new file mode 100644 index 00000000..6af7729d --- /dev/null +++ b/sdk/rust/src/ura.rs @@ -0,0 +1,729 @@ +//! Current EasyNet URA grammar and builders. +//! +//! URA is an Axon protocol primitive, not a string helper. It is the +//! stable identity/address form carried by envelopes, receipts, trace +//! records, directory entries, resource dialogs, and invocation targets. +//! Higher layers should receive and forward full URAs; they should not +//! reconstruct URAs from fragments. +//! +//! ## Canonical shapes +//! +//! ```text +//! user easynet:///r//user/ +//! device easynet:///r//device/ +//! agent easynet:///r//agent/. +//! ability easynet:///r//ability/.. +//! hub easynet:///r//hub +//! resource easynet:///r//resource// +//! ``` +//! +//! ## Examples +//! +//! ```text +//! easynet:///r/localhost/user/u-9f4 +//! easynet:///r/localhost/device/8315ea5c-7cfd-473e-8fef-95340af6d971 +//! easynet:///r/localhost/agent/u-9f4.frontend-engineer +//! easynet:///r/localhost/ability/u-9f4.frontend-engineer.chat +//! easynet:///r/localhost/ability/hub.federation.resolve +//! easynet:///r/localhost/hub +//! easynet:///r/localhost/resource/agent.u-9f4.frontend-engineer/skill/alive-video +//! easynet:///r/localhost/resource/device.8315ea5c-7cfd-473e-8fef-95340af6d971/ability/device.skill.tree +//! ``` +//! +//! ## Semantics +//! +//! - `realm` names the federation authority, such as `localhost` or +//! `easynet.run`. +//! - `user` is ownership identity. A user owns agents and user-scoped +//! resources. +//! - `device` is runtime placement identity. A device hosts sessions, +//! local abilities, terminal/PTY operations, and file substrate access. +//! - `agent` is user-owned logical execution identity. Device placement +//! is directory metadata, not part of the agent URA. +//! - `ability` is the callable identity. Hub-owned abilities use owner +//! token `hub`, for example `hub.federation.resolve`. +//! - `hub` is a realm singleton and never has a tail. +//! - `resource` is the concrete substrate or inspectable object. Its +//! first tail segment is an owner id such as `device.`, +//! `agent..`, `api_key.`, or `.files`; the +//! remaining slash path is interpreted by that owner namespace. +//! +//! ## Ownership boundary +//! +//! This Rust SDK module is the source API for Rust callers. CLI imports +//! it through its local `src/ura.rs` façade. Frontend and backend code +//! should treat URAs as opaque protocol values returned by the CLI/Axon +//! boundary, displaying or forwarding them rather than assembling them. + +use std::fmt; + +pub const REALM_EASYNET: &str = "easynet.run"; +pub const URA_SCHEME: &str = "easynet:///r/"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum URAKind { + Hub, + Device, + User, + Agent, + Ability, + Resource, + #[default] + Unknown, +} + +impl fmt::Display for URAKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + URAKind::Hub => "hub", + URAKind::Device => "device", + URAKind::User => "user", + URAKind::Agent => "agent", + URAKind::Ability => "ability", + URAKind::Resource => "resource", + URAKind::Unknown => "unknown", + }) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResourceNamespace { + Fs, + Process, + Pty, + Shell, + Http, +} + +impl ResourceNamespace { + pub fn as_str(self) -> &'static str { + match self { + ResourceNamespace::Fs => "fs", + ResourceNamespace::Process => "process", + ResourceNamespace::Pty => "pty", + ResourceNamespace::Shell => "shell", + ResourceNamespace::Http => "http", + } + } +} + +impl fmt::Display for ResourceNamespace { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ParsedURA { + pub realm: String, + pub kind: URAKind, + pub user_id: String, + pub device_id: String, + pub agent_id: String, + pub ability_id: String, + pub namespace: Option, + pub path: String, + pub raw: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ParseError { + BadScheme, + EmptyRealm, + EmptyRole, + UserMissingTail, + UserBadShape, + DeviceMissingTail, + DeviceBadShape, + AgentMissingTail, + AgentBadShape, + AbilityMissingTail, + AbilityBadShape, + HubUnexpectedTail(String), + ResourceMissingTail, + ResourceEmptyOwner, + UnknownRole(String), +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ParseError::BadScheme => f.write_str("URA must start with easynet:///r/"), + ParseError::EmptyRealm => f.write_str("URA missing segment"), + ParseError::EmptyRole => f.write_str("URA missing segment"), + ParseError::UserMissingTail => f.write_str("user URA requires tail"), + ParseError::UserBadShape => f.write_str("user-id must be a single path segment"), + ParseError::DeviceMissingTail => f.write_str("device URA requires tail"), + ParseError::DeviceBadShape => f.write_str("device-id must be a single path segment"), + ParseError::AgentMissingTail => { + f.write_str("agent URA requires . tail") + } + ParseError::AgentBadShape => f.write_str("agent tail must be ."), + ParseError::AbilityMissingTail => { + f.write_str("ability URA requires .. tail") + } + ParseError::AbilityBadShape => { + f.write_str("ability tail must have three non-empty dot-separated parts") + } + ParseError::HubUnexpectedTail(tail) => { + write!(f, "hub is a realm singleton; unexpected tail {tail:?}") + } + ParseError::ResourceMissingTail => f.write_str("resource URA requires tail"), + ParseError::ResourceEmptyOwner => f.write_str("resource owner segment is empty"), + ParseError::UnknownRole(role) => write!( + f, + "unknown URA role {role:?} (allowed: user/device/agent/ability/hub/resource)" + ), + } + } +} + +impl std::error::Error for ParseError {} + +/// Canonical EasyNet URA value object. +/// +/// `Ura` is the OOP boundary for URA construction and validation inside +/// Axon-owned Rust code. It stores only a parsed, full +/// `easynet:///r/...` address. Callers that need a raw string can borrow it +/// through [`Ura::as_str`] or format it with `Display`; callers that need +/// role details use [`Ura::parsed`] instead of slicing strings. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Ura(String); + +impl Ura { + pub fn parse(raw: impl AsRef) -> Result { + let raw = raw.as_ref(); + parse_ura(raw)?; + Ok(Self(raw.to_string())) + } + + pub fn user(realm: &str, user_id: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/user/{user_id}")) + } + + pub fn device(realm: &str, device_id: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/device/{device_id}")) + } + + pub fn agent(realm: &str, user_id: &str, agent_id: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/agent/{user_id}.{agent_id}")) + } + + pub fn ability(realm: &str, user_id: &str, agent_id: &str, ability_id: &str) -> Self { + Self(format!( + "{URA_SCHEME}{realm}/ability/{user_id}.{agent_id}.{ability_id}" + )) + } + + pub fn hub_ability(realm: &str, full_ability_name: &str) -> Self { + let (namespace, tail) = full_ability_name + .split_once('.') + .expect("hub-owned ability names must include a namespace prefix"); + Self::ability(realm, "hub", namespace, tail) + } + + pub fn hub(realm: &str) -> Self { + Self(format!("{URA_SCHEME}{realm}/hub")) + } + + pub fn resource(realm: &str, owner_id: &str, ns: ResourceNamespace, path: &str) -> Self { + let owner = if owner_id.contains('.') { + owner_id.to_string() + } else { + format!("{owner_id}.{}", ns.as_str()) + }; + Self::resource_dot(realm, &owner, path) + } + + pub fn resource_dot(realm: &str, owner_id: &str, path: &str) -> Self { + let clean = path.strip_prefix('/').unwrap_or(path); + if clean.is_empty() { + return Self(format!("{URA_SCHEME}{realm}/resource/{owner_id}")); + } + Self(format!("{URA_SCHEME}{realm}/resource/{owner_id}/{clean}")) + } + + pub fn device_ability_resource(realm: &str, device_id: &str, ability_id: &str) -> Self { + Self::resource_dot( + realm, + &format!("device.{device_id}"), + &format!("ability/{ability_id}"), + ) + } + + pub fn payload_resource(realm: &str, owner_id: &str, payload_id: &str) -> Self { + Self::resource_dot(realm, owner_id, &format!("payload/{payload_id}")) + } + + pub fn invocation_history_resource(realm: &str, owner_id: &str, invocation_id: &str) -> Self { + Self::resource_dot( + realm, + owner_id, + &format!("invocation/{invocation_id}/history"), + ) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn into_string(self) -> String { + self.0 + } + + pub fn parsed(&self) -> ParsedURA { + parse_ura(&self.0).expect("Ura stores only validated canonical addresses") + } + + pub fn kind(&self) -> URAKind { + self.parsed().kind + } + + pub fn realm(&self) -> String { + self.parsed().realm + } + + pub fn display_id(&self) -> String { + display_id(&self.0) + } + + pub fn ability_name(&self) -> Option { + ability_name_from_parts(&self.parsed()) + } + + pub fn public_ability_name_for_owner(&self, owner_ura: &str) -> Option { + public_ability_name_from_ability_ura(owner_ura, self.as_str()) + } +} + +impl fmt::Display for Ura { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl AsRef for Ura { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl TryFrom<&str> for Ura { + type Error = ParseError; + + fn try_from(value: &str) -> Result { + Self::parse(value) + } +} + +impl From for String { + fn from(value: Ura) -> Self { + value.into_string() + } +} + +pub fn user_ura(realm: &str, user_id: &str) -> String { + Ura::user(realm, user_id).into_string() +} + +pub fn device_ura(realm: &str, device_id: &str) -> String { + Ura::device(realm, device_id).into_string() +} + +pub fn agent_ura(realm: &str, user_id: &str, agent_id: &str) -> String { + Ura::agent(realm, user_id, agent_id).into_string() +} + +pub fn ability_ura(realm: &str, user_id: &str, agent_id: &str, ability_id: &str) -> String { + Ura::ability(realm, user_id, agent_id, ability_id).into_string() +} + +pub fn hub_ability_ura(realm: &str, full_ability_name: &str) -> String { + Ura::hub_ability(realm, full_ability_name).into_string() +} + +pub fn hub_ura(realm: &str) -> String { + Ura::hub(realm).into_string() +} + +pub fn resource_ura(realm: &str, owner_id: &str, ns: ResourceNamespace, path: &str) -> String { + Ura::resource(realm, owner_id, ns, path).into_string() +} + +pub fn resource_dot_ura(realm: &str, owner_id: &str, path: &str) -> String { + Ura::resource_dot(realm, owner_id, path).into_string() +} + +pub fn device_ability_resource_ura(realm: &str, device_id: &str, ability_id: &str) -> String { + Ura::device_ability_resource(realm, device_id, ability_id).into_string() +} + +pub fn payload_resource_ura(realm: &str, owner_id: &str, payload_id: &str) -> String { + Ura::payload_resource(realm, owner_id, payload_id).into_string() +} + +pub fn invocation_history_resource_ura(realm: &str, owner_id: &str, invocation_id: &str) -> String { + Ura::invocation_history_resource(realm, owner_id, invocation_id).into_string() +} + +pub fn realm_user_prefix(realm: &str) -> String { + format!("{URA_SCHEME}{realm}/user/") +} + +pub fn realm_device_prefix(realm: &str) -> String { + format!("{URA_SCHEME}{realm}/device/") +} + +pub fn realm_agent_prefix(realm: &str) -> String { + format!("{URA_SCHEME}{realm}/agent/") +} + +pub fn realm_ability_prefix(realm: &str) -> String { + format!("{URA_SCHEME}{realm}/ability/") +} + +pub fn realm_resource_prefix(realm: &str) -> String { + format!("{URA_SCHEME}{realm}/resource/") +} + +pub fn parse_ura(ura: &str) -> Result { + let rest = ura.strip_prefix(URA_SCHEME).ok_or(ParseError::BadScheme)?; + let (realm, after_realm) = rest.split_once('/').ok_or(ParseError::EmptyRealm)?; + if realm.is_empty() { + return Err(ParseError::EmptyRealm); + } + let (role, tail) = match after_realm.split_once('/') { + Some((role, tail)) => (role, tail), + None => (after_realm, ""), + }; + if role.is_empty() { + return Err(ParseError::EmptyRole); + } + + let mut parsed = ParsedURA { + realm: realm.to_string(), + raw: ura.to_string(), + ..Default::default() + }; + + match role { + "user" => { + if tail.is_empty() { + return Err(ParseError::UserMissingTail); + } + if tail.contains('/') || tail.contains('.') { + return Err(ParseError::UserBadShape); + } + parsed.kind = URAKind::User; + parsed.user_id = tail.to_string(); + } + "device" => { + if tail.is_empty() { + return Err(ParseError::DeviceMissingTail); + } + if tail.contains('/') || tail.contains('.') { + return Err(ParseError::DeviceBadShape); + } + parsed.kind = URAKind::Device; + parsed.device_id = tail.to_string(); + } + "agent" => { + if tail.is_empty() { + return Err(ParseError::AgentMissingTail); + } + let (user_id, agent_id) = tail.split_once('.').ok_or(ParseError::AgentBadShape)?; + if user_id.is_empty() + || agent_id.is_empty() + || user_id.contains('/') + || agent_id.contains('/') + || agent_id.contains('.') + { + return Err(ParseError::AgentBadShape); + } + parsed.kind = URAKind::Agent; + parsed.user_id = user_id.to_string(); + parsed.agent_id = agent_id.to_string(); + } + "ability" => { + if tail.is_empty() { + return Err(ParseError::AbilityMissingTail); + } + let mut parts = tail.splitn(3, '.'); + let user_id = parts.next().unwrap_or(""); + let agent_id = parts.next().unwrap_or(""); + let ability_id = parts.next().unwrap_or(""); + if user_id.is_empty() + || agent_id.is_empty() + || ability_id.is_empty() + || user_id.contains('/') + || agent_id.contains('/') + || agent_id.contains('.') + { + return Err(ParseError::AbilityBadShape); + } + parsed.kind = URAKind::Ability; + parsed.user_id = user_id.to_string(); + parsed.agent_id = agent_id.to_string(); + parsed.ability_id = ability_id.to_string(); + } + "hub" => { + if !tail.is_empty() { + return Err(ParseError::HubUnexpectedTail(tail.to_string())); + } + parsed.kind = URAKind::Hub; + } + "resource" => { + if tail.is_empty() { + return Err(ParseError::ResourceMissingTail); + } + let (owner, path) = match tail.split_once('/') { + Some((owner, path)) => (owner, path), + None => (tail, ""), + }; + if owner.is_empty() { + return Err(ParseError::ResourceEmptyOwner); + } + parsed.kind = URAKind::Resource; + parsed.user_id = owner.to_string(); + parsed.path = path.to_string(); + } + other => return Err(ParseError::UnknownRole(other.to_string())), + } + + Ok(parsed) +} + +pub fn kind_from_ura(ura: &str) -> URAKind { + parse_ura(ura).map(|parsed| parsed.kind).unwrap_or_default() +} + +pub fn realm_from_ura(ura: &str) -> String { + parse_ura(ura) + .map(|parsed| parsed.realm) + .unwrap_or_default() +} + +pub fn display_id(ura: &str) -> String { + match parse_ura(ura) { + Err(_) => ura.to_string(), + Ok(parsed) => match parsed.kind { + URAKind::Device => parsed.device_id, + URAKind::User => parsed.user_id, + URAKind::Agent => format!("{}.{}", parsed.user_id, parsed.agent_id), + URAKind::Ability => { + format!( + "{}.{}.{}", + parsed.user_id, parsed.agent_id, parsed.ability_id + ) + } + URAKind::Hub => "hub".to_string(), + URAKind::Resource if parsed.path.is_empty() => parsed.user_id, + URAKind::Resource => format!("{}/{}", parsed.user_id, parsed.path), + URAKind::Unknown => ura.to_string(), + }, + } +} + +pub fn qualified_ability_name(ura: &str) -> Option { + let parsed = parse_ura(ura).ok()?; + ability_name_from_parts(&parsed) +} + +pub fn ability_name_from_parts(parsed: &ParsedURA) -> Option { + if parsed.kind != URAKind::Ability { + return None; + } + if parsed.user_id == "hub" { + return Some(format!("{}.{}", parsed.agent_id, parsed.ability_id)); + } + Some(parsed.ability_id.clone()) +} + +pub fn public_ability_name_for_owner(owner_ura: &str, registered_name: &str) -> String { + match parse_ura(owner_ura) { + Ok(parsed) if parsed.kind == URAKind::Agent && !parsed.agent_id.is_empty() => { + registered_name + .strip_prefix(&format!("{}.", parsed.agent_id)) + .unwrap_or(registered_name) + .to_string() + } + _ => registered_name.to_string(), + } +} + +pub fn public_ability_name_from_ability_ura(owner_ura: &str, ability_ura: &str) -> Option { + let owner = parse_ura(owner_ura).ok()?; + let ability = parse_ura(ability_ura).ok()?; + if ability.kind != URAKind::Ability { + return None; + } + match owner.kind { + URAKind::Agent + if owner.realm == ability.realm + && owner.user_id == ability.user_id + && owner.agent_id == ability.agent_id => + { + Some(ability.ability_id) + } + URAKind::Hub if owner.realm == ability.realm && ability.user_id == "hub" => { + ability_name_from_parts(&ability) + } + _ => None, + } +} + +pub fn agent_scoped_registry_ability(target_ura: &str, ability_name: &str) -> String { + if ability_name.contains('.') { + return ability_name.to_string(); + } + match parse_ura(target_ura) { + Ok(parsed) if parsed.kind == URAKind::Agent && !parsed.agent_id.is_empty() => { + format!("{}.{}", parsed.agent_id, ability_name) + } + _ => ability_name.to_string(), + } +} + +pub fn canonicalize_presence_key(ura: &str) -> String { + if parse_ura(ura).is_ok() { + return ura.to_string(); + } + match bare_device_agent_alias_parts(ura) { + Some((realm, device_id)) => device_ura(&realm, &device_id), + None => ura.to_string(), + } +} + +pub fn strip_agent_alias_prefix(ura: &str) -> String { + bare_device_agent_alias_parts(ura) + .map(|(_, device_id)| device_id) + .unwrap_or_else(|| ura.to_string()) +} + +pub fn bare_device_agent_alias_parts(ura: &str) -> Option<(String, String)> { + let rest = ura.strip_prefix(URA_SCHEME)?; + let (realm, after_realm) = rest.split_once('/')?; + let device_id = after_realm.strip_prefix("agent/")?; + if realm.is_empty() + || device_id.is_empty() + || device_id.contains('/') + || device_id.contains('.') + { + return None; + } + Some((realm.to_string(), device_id.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_current_roles_and_rejects_unknown_role() { + assert_eq!( + parse_ura("easynet:///r/localhost/device/dev-1") + .unwrap() + .kind, + URAKind::Device + ); + assert_eq!( + parse_ura("easynet:///r/localhost/agent/user-1.frontend-engineer") + .unwrap() + .agent_id, + "frontend-engineer" + ); + assert_eq!( + parse_ura("easynet:///r/localhost/ability/hub.federation.resolve") + .unwrap() + .ability_id, + "resolve" + ); + assert!(matches!( + parse_ura("easynet:///r/localhost/widget/frontend-engineer"), + Err(ParseError::UnknownRole(role)) if role == "widget" + )); + } + + #[test] + fn ura_value_object_is_the_builder_and_parser_boundary() { + let ability = Ura::ability("localhost", "dev", "frontend-engineer", "chat"); + assert_eq!( + ability.as_str(), + "easynet:///r/localhost/ability/dev.frontend-engineer.chat" + ); + assert_eq!(ability.kind(), URAKind::Ability); + assert_eq!(ability.realm(), "localhost"); + assert_eq!(ability.display_id(), "dev.frontend-engineer.chat"); + + let parsed = Ura::parse(ability.as_str()).unwrap(); + assert_eq!(parsed, ability); + assert!(Ura::parse("axon://localhost:50051").is_err()); + } + + #[test] + fn resource_ura_carries_owner_and_path_verbatim() { + let ura = resource_dot_ura( + "localhost", + "agent.dev.frontend-engineer", + "skill/alive-video", + ); + assert_eq!( + ura, + "easynet:///r/localhost/resource/agent.dev.frontend-engineer/skill/alive-video" + ); + let parsed = parse_ura(&ura).unwrap(); + assert_eq!(parsed.kind, URAKind::Resource); + assert_eq!(parsed.user_id, "agent.dev.frontend-engineer"); + assert_eq!(parsed.path, "skill/alive-video"); + } + + #[test] + fn hub_is_singleton_and_hub_abilities_are_ability_uras() { + assert_eq!(hub_ura("localhost"), "easynet:///r/localhost/hub"); + assert!(parse_ura("easynet:///r/localhost/hub/01HUB").is_err()); + assert_eq!( + hub_ability_ura("localhost", "federation.resolve"), + "easynet:///r/localhost/ability/hub.federation.resolve" + ); + assert_eq!( + qualified_ability_name("easynet:///r/localhost/ability/hub.federation.resolve"), + Some("federation.resolve".to_string()) + ); + assert_eq!( + qualified_ability_name("easynet:///r/localhost/ability/dev.frontend-engineer.chat"), + Some("chat".to_string()) + ); + assert_eq!( + public_ability_name_for_owner( + "easynet:///r/localhost/agent/dev.frontend-engineer", + "frontend-engineer.chat" + ), + "chat" + ); + assert_eq!( + public_ability_name_from_ability_ura( + "easynet:///r/localhost/agent/dev.frontend-engineer", + "easynet:///r/localhost/ability/dev.frontend-engineer.chat", + ), + Some("chat".to_string()) + ); + assert_eq!( + agent_scoped_registry_ability( + "easynet:///r/localhost/agent/dev.frontend-engineer", + "chat" + ), + "frontend-engineer.chat" + ); + } + + #[test] + fn only_named_ingress_repair_accepts_bare_device_agent_alias() { + let alias = "easynet:///r/localhost/agent/dev-1"; + assert!(parse_ura(alias).is_err()); + assert_eq!( + canonicalize_presence_key(alias), + "easynet:///r/localhost/device/dev-1" + ); + assert_eq!(strip_agent_alias_prefix(alias), "dev-1"); + } +} diff --git a/sdk/rust/tests/admission.rs b/sdk/rust/tests/admission.rs index 43747705..dfb4b76e 100644 --- a/sdk/rust/tests/admission.rs +++ b/sdk/rust/tests/admission.rs @@ -10,19 +10,19 @@ use easynet_axon::invocation::axiom::{signing_key_from_bytes, verify_invocation_signature}; use easynet_axon::invocation::{ make_ability, AgentIdentity, AxonErrorKind, CausalContext, KeyResolver, LocalRuntime, - UriProfile, REASON_CALLER_SIGNATURE_INVALID, REASON_ENVELOPE_INCOMPLETE, REASON_NONCE_REPLAY, + UraProfile, REASON_CALLER_SIGNATURE_INVALID, REASON_ENVELOPE_INCOMPLETE, REASON_NONCE_REPLAY, }; use ed25519_dalek::VerifyingKey; use std::sync::Arc; fn silan() -> AgentIdentity { - AgentIdentity::new("easynet:///r/silan/agents/t@1", UriProfile::EasynetStrictV2) + AgentIdentity::new("easynet:///r/silan/agents/t@1", UraProfile::EasynetStrictV2) } fn openai() -> AgentIdentity { AgentIdentity::new( "easynet:///r/openai/agents/t@1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ) } diff --git a/sdk/rust/tests/axiom_vectors.rs b/sdk/rust/tests/axiom_vectors.rs index d0dd9945..dcada22f 100644 --- a/sdk/rust/tests/axiom_vectors.rs +++ b/sdk/rust/tests/axiom_vectors.rs @@ -23,7 +23,7 @@ use easynet_axon::invocation::axiom::{ }; use easynet_axon::invocation::{ AgentIdentity, CallerSignature, CausalContext, InvocationEnvelope, KeyResolver, ReceiptRef, - SubjectIdentity, UriProfile, + SubjectIdentity, UraProfile, }; use ed25519_dalek::VerifyingKey; use serde::Deserialize; @@ -42,16 +42,16 @@ fn vectors_dir() -> PathBuf { #[derive(Debug, Deserialize)] struct IdentityJ { - uri: String, + ura: String, profile: String, } impl IdentityJ { fn to_agent(&self) -> AgentIdentity { - AgentIdentity::new(self.uri.clone(), UriProfile::parse(&self.profile).unwrap()) + AgentIdentity::new(self.ura.clone(), UraProfile::parse(&self.profile).unwrap()) } fn to_subject(&self) -> SubjectIdentity { - SubjectIdentity::new(self.uri.clone(), UriProfile::parse(&self.profile).unwrap()) + SubjectIdentity::new(self.ura.clone(), UraProfile::parse(&self.profile).unwrap()) } } @@ -61,21 +61,21 @@ enum CausalJ { None, Scalar { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, }, List { prior: Vec, }, Merkle { root_hex: String, - proof_uri: String, + proof_ura: String, }, } #[derive(Debug, Deserialize)] struct ReceiptRefJ { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, } impl CausalJ { @@ -84,26 +84,26 @@ impl CausalJ { CausalJ::None => CausalContext::None, CausalJ::Scalar { receipt_hash_hex, - receipt_uri, + receipt_ura, } => CausalContext::Scalar(ReceiptRef { receipt_hash: hex32(receipt_hash_hex), - receipt_uri: receipt_uri.clone(), + receipt_ura: receipt_ura.clone(), }), CausalJ::List { prior } => CausalContext::List( prior .iter() .map(|r| ReceiptRef { receipt_hash: hex32(&r.receipt_hash_hex), - receipt_uri: r.receipt_uri.clone(), + receipt_ura: r.receipt_ura.clone(), }) .collect(), ), CausalJ::Merkle { root_hex, - proof_uri, + proof_ura, } => CausalContext::Merkle { root: hex32(root_hex), - proof_uri: proof_uri.clone(), + proof_ura: proof_ura.clone(), }, } } @@ -242,12 +242,12 @@ fn run_e1(v: &Value) { assert!(!bytes.is_empty(), "e1: canonical bytes must be non-empty"); // Check all seven components can be located structurally (lengths present). - // The first four bytes are caller.uri length prefix. + // The first four bytes are caller.ura length prefix. let caller_len = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize; assert_eq!( &bytes[4..4 + caller_len], - env.caller.uri.as_bytes(), - "e1: caller.uri not at expected offset" + env.caller.ura.as_bytes(), + "e1: caller.ura not at expected offset" ); // Enforce canonical-bytes sha256 pin for cross-language parity. @@ -318,7 +318,7 @@ fn run_e4(v: &Value) { let inputs: InputsJ = serde_json::from_value(v["inputs"].clone()).unwrap(); let env = inputs.to_envelope(); assert_ne!( - env.callee.uri, env.subject.uri, + env.callee.ura, env.subject.ura, "e4: subject must differ from callee in this vector" ); let secret = hex32(inputs.caller_secret_hex.as_deref().unwrap()); @@ -389,7 +389,7 @@ fn run_profile_binding(v: &Value) { let new_profile_s = v["inputs"]["profile_swap_on_verify"]["caller"] .as_str() .unwrap(); - let new_profile = UriProfile::parse(new_profile_s).unwrap(); + let new_profile = UraProfile::parse(new_profile_s).unwrap(); let mut tampered = env.clone(); tampered.caller.profile = new_profile; @@ -409,11 +409,11 @@ fn run_subject_survives(v: &Value) { let eb = b.to_envelope(); // subject bytes identical (URI + profile both match). - assert_eq!(ea.subject.uri, eb.subject.uri); + assert_eq!(ea.subject.ura, eb.subject.ura); assert_eq!(ea.subject.profile, eb.subject.profile); // callee bytes differ. - assert_ne!(ea.callee.uri, eb.callee.uri); + assert_ne!(ea.callee.ura, eb.callee.ura); // canonical overall differs. assert_ne!( @@ -527,9 +527,9 @@ fn print_canonical_pins() { #[test] fn inputsj_full_surface_compiles() { let s = r#"{ - "caller": {"uri":"a","profile":"easynet-strict-v2"}, - "callee": {"uri":"b","profile":"easynet-strict-v2"}, - "subject": {"uri":"c","profile":"easynet-strict-v2"}, + "caller": {"ura":"a","profile":"easynet-strict-v2"}, + "callee": {"ura":"b","profile":"easynet-strict-v2"}, + "subject": {"ura":"c","profile":"easynet-strict-v2"}, "ability": "x", "args_digest_hex": "0000000000000000000000000000000000000000000000000000000000000000", "invocation_nonce_hex": "00000000000000000000000000000000", diff --git a/sdk/rust/tests/axiom_worked_example.rs b/sdk/rust/tests/axiom_worked_example.rs index 02943c9c..744e1ca4 100644 --- a/sdk/rust/tests/axiom_worked_example.rs +++ b/sdk/rust/tests/axiom_worked_example.rs @@ -30,7 +30,7 @@ use std::path::PathBuf; use base64::Engine; use easynet_axon::invocation::axiom::{ canonical_invocation_bytes, sha256, sign_invocation, signing_key_from_bytes, AgentIdentity, - CausalContext, InvocationEnvelope, ReceiptRef, SubjectIdentity, UriProfile, + CausalContext, InvocationEnvelope, ReceiptRef, SubjectIdentity, UraProfile, }; use ed25519_dalek::VerifyingKey; use serde::Deserialize; @@ -81,7 +81,7 @@ struct MetadataExcluded { #[derive(Debug, Deserialize)] struct IdentityJson { - uri: String, + ura: String, profile: String, } @@ -91,7 +91,7 @@ enum CausalJson { None, Scalar { receipt_hash_hex: String, - receipt_uri: String, + receipt_ura: String, }, } @@ -130,16 +130,16 @@ fn parse_hex_fixed(s: &str) -> [u8; N] { fn build_envelope(inputs: &Inputs) -> InvocationEnvelope { let caller = AgentIdentity::new( - inputs.caller.uri.clone(), - UriProfile::parse(&inputs.caller.profile).expect("caller profile"), + inputs.caller.ura.clone(), + UraProfile::parse(&inputs.caller.profile).expect("caller profile"), ); let callee = AgentIdentity::new( - inputs.callee.uri.clone(), - UriProfile::parse(&inputs.callee.profile).expect("callee profile"), + inputs.callee.ura.clone(), + UraProfile::parse(&inputs.callee.profile).expect("callee profile"), ); let subject = SubjectIdentity::new( - inputs.subject.uri.clone(), - UriProfile::parse(&inputs.subject.profile).expect("subject profile"), + inputs.subject.ura.clone(), + UraProfile::parse(&inputs.subject.profile).expect("subject profile"), ); let payload = base64::engine::general_purpose::STANDARD .decode(inputs.payload_base64.as_bytes()) @@ -150,10 +150,10 @@ fn build_envelope(inputs: &Inputs) -> InvocationEnvelope { CausalJson::None => CausalContext::None, CausalJson::Scalar { receipt_hash_hex, - receipt_uri, + receipt_ura, } => CausalContext::Scalar(ReceiptRef { receipt_hash: parse_hex_fixed::<32>(receipt_hash_hex), - receipt_uri: receipt_uri.clone(), + receipt_ura: receipt_ura.clone(), }), }; InvocationEnvelope { diff --git a/sdk/rust/tests/concurrency/admission_replay_concurrent.rs b/sdk/rust/tests/concurrency/admission_replay_concurrent.rs index 69672b09..e73bb0f9 100644 --- a/sdk/rust/tests/concurrency/admission_replay_concurrent.rs +++ b/sdk/rust/tests/concurrency/admission_replay_concurrent.rs @@ -4,14 +4,14 @@ //! //! The replay store is the single authority that prevents an attacker //! from replaying a captured signed envelope. A race that admits two -//! observations of the same `(caller_uri, ability, nonce)` breaks +//! observations of the same `(caller_ura, ability, nonce)` breaks //! RFC 001 §5.2's replay-protection contract: the "admission is //! fact" guarantee downstream of it is only as strong as the //! exactly-once property here. //! //! # Invariants //! -//! R1. **Exactly-one winner per (caller_uri, ability, nonce).** For +//! R1. **Exactly-one winner per (caller_ura, ability, nonce).** For //! N concurrent `check_and_record` calls with identical keys, //! exactly one returns `Ok`. The other N-1 return //! `REASON_NONCE_REPLAY`. diff --git a/sdk/rust/tests/concurrency/invocation_core_concurrent.rs b/sdk/rust/tests/concurrency/invocation_core_concurrent.rs index db4bd48a..cc7ab255 100644 --- a/sdk/rust/tests/concurrency/invocation_core_concurrent.rs +++ b/sdk/rust/tests/concurrency/invocation_core_concurrent.rs @@ -35,19 +35,19 @@ use std::collections::HashSet; use std::sync::Arc; use easynet_axon::invocation::audit::AxiomBinding; -use easynet_axon::invocation::axiom::{AgentIdentity, CausalContext, SubjectIdentity, UriProfile}; +use easynet_axon::invocation::axiom::{AgentIdentity, CausalContext, SubjectIdentity, UraProfile}; use easynet_axon::invocation::handle::{EmitExtras, InvocationCore, InvocationState}; use sha2::{Digest, Sha256}; use tokio::sync::Barrier; fn sample_binding() -> AxiomBinding { AxiomBinding { - caller: AgentIdentity::new("easynet:///r/silan/agents/a@1", UriProfile::EasynetStrictV2), + caller: AgentIdentity::new("easynet:///r/silan/agents/a@1", UraProfile::EasynetStrictV2), callee: AgentIdentity::new( "easynet:///r/openai/agents/b@1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ), - subject: SubjectIdentity::new("easynet:///r/silan/papers/p@1", UriProfile::EasynetStrictV2), + subject: SubjectIdentity::new("easynet:///r/silan/papers/p@1", UraProfile::EasynetStrictV2), invocation_nonce: [0x42u8; 16], causal: CausalContext::None, payload_digest: [0u8; 32], diff --git a/sdk/rust/tests/connect_then_signed_mcp.rs b/sdk/rust/tests/connect_then_signed_mcp.rs index ec0e5093..54249ec0 100644 --- a/sdk/rust/tests/connect_then_signed_mcp.rs +++ b/sdk/rust/tests/connect_then_signed_mcp.rs @@ -66,7 +66,7 @@ fn signing_config_from_seed_has_documented_shape() { let req = SigningConfigRequest::from_seed(seed, "easynet:///r/silan/agents/alice"); assert_eq!(req.algorithm, "ed25519"); assert_eq!(req.caller_profile, "easynet-strict-v2"); - assert_eq!(req.caller_uri, "easynet:///r/silan/agents/alice"); + assert_eq!(req.caller_ura, "easynet:///r/silan/agents/alice"); // base64 of [0x01; 32] = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=" — // matches the §1 worked-example anchor used across the // tests/admission.rs fixtures. @@ -120,9 +120,9 @@ fn jcs_bytes_feed_directly_into_signed_options() { tenant_id: "silan", tool_name: "search_web", target_node_id: None, - callee_uri: "easynet:///r/silan/agents/reviewer", + callee_ura: "easynet:///r/silan/agents/reviewer", callee_profile: "easynet-strict-v2", - subject_uri: None, + subject_ura: None, subject_profile: None, arguments: &canonical_bytes, nonce_base64: None, @@ -134,9 +134,9 @@ fn jcs_bytes_feed_directly_into_signed_options() { let _ability_opts = AbilitySignedCallOptions { tenant_id: "silan", ability: "review", - callee_uri: "easynet:///r/silan/agents/reviewer", + callee_ura: "easynet:///r/silan/agents/reviewer", callee_profile: "easynet-strict-v2", - subject_uri: None, + subject_ura: None, subject_profile: None, payload: &canonical_bytes, nonce_base64: None, diff --git a/sdk/rust/tests/invoke_signed.rs b/sdk/rust/tests/invoke_signed.rs index 20f6efb0..ce4923d4 100644 --- a/sdk/rust/tests/invoke_signed.rs +++ b/sdk/rust/tests/invoke_signed.rs @@ -14,7 +14,7 @@ use easynet_axon::invocation::axiom::{ }; use easynet_axon::invocation::{ make_ability, AgentIdentity, CausalContext, KeyResolver, LocalRuntime, SubjectIdentity, - UriProfile, + UraProfile, }; use ed25519_dalek::VerifyingKey; @@ -26,13 +26,13 @@ impl KeyResolver for Fixed { } fn silan() -> AgentIdentity { - AgentIdentity::new("easynet:///r/silan/agents/t@1", UriProfile::EasynetStrictV2) + AgentIdentity::new("easynet:///r/silan/agents/t@1", UraProfile::EasynetStrictV2) } fn openai() -> AgentIdentity { AgentIdentity::new( "easynet:///r/openai/agents/t@1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ) } @@ -55,7 +55,7 @@ async fn invoke_signed_with_explicit_subject_and_nonce_verifies() { let sk = signing_key_from_bytes(&[7u8; 32]); let subject = SubjectIdentity::new( "easynet:///r/silan/papers/p@d1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let (handle, signed) = rt .invoke_signed_async( @@ -78,7 +78,7 @@ async fn invoke_signed_with_explicit_subject_and_nonce_verifies() { // Envelope stored for later retrieval. let stored = rt.axiom_envelope_of(handle.invocation_id()).await.unwrap(); - assert_eq!(stored.envelope.subject.uri, subject.uri); + assert_eq!(stored.envelope.subject.ura, subject.ura); assert_eq!(stored.envelope.invocation_nonce, [0xABu8; 16]); // Signature verifies under a fresh Fixed resolver (no runtime contact). @@ -110,7 +110,7 @@ async fn invoke_signed_defaults_subject_to_callee_when_none() { ) .await .unwrap(); - assert_eq!(signed.envelope.subject.uri, signed.envelope.callee.uri); + assert_eq!(signed.envelope.subject.ura, signed.envelope.callee.ura); assert_eq!( signed.envelope.subject.profile, signed.envelope.callee.profile @@ -255,7 +255,7 @@ async fn tampered_subject_breaks_verification() { vec![], Some(SubjectIdentity::new( "easynet:///r/silan/papers/p@1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, )), CausalContext::None, Some([0x11; 16]), @@ -269,7 +269,7 @@ async fn tampered_subject_breaks_verification() { let mut tampered = signed.envelope.clone(); tampered.subject = SubjectIdentity::new( "easynet:///r/mallory/papers/evil@1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let vk = sk.verifying_key(); let err = verify_invocation_signature(&tampered, &signed.signature, &Fixed(vk)) @@ -300,7 +300,7 @@ async fn tampered_causal_context_breaks_verification() { let mut tampered = signed.envelope.clone(); tampered.causal_context = CausalContext::Scalar(easynet_axon::invocation::ReceiptRef { receipt_hash: [0x99; 32], - receipt_uri: "evil".to_string(), + receipt_ura: "evil".to_string(), }); let vk = sk.verifying_key(); let err = verify_invocation_signature(&tampered, &signed.signature, &Fixed(vk)) @@ -349,7 +349,7 @@ async fn stored_envelope_canonical_bytes_are_stable() { b"stable".to_vec(), Some(SubjectIdentity::new( "easynet:///r/silan/papers/p@stable", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, )), CausalContext::None, Some([0x44; 16]), diff --git a/sdk/rust/tests/options_symmetry.rs b/sdk/rust/tests/options_symmetry.rs index df3dc1b2..7dfd5387 100644 --- a/sdk/rust/tests/options_symmetry.rs +++ b/sdk/rust/tests/options_symmetry.rs @@ -38,9 +38,9 @@ use easynet_axon::{AbilitySignedCallOptions, McpSignedCallOptions}; /// SignedInvokeRequest). const SHARED_FIELDS: &[&str] = &[ "tenant_id", - "callee_uri", + "callee_ura", "callee_profile", - "subject_uri", + "subject_ura", "subject_profile", "nonce_base64", "timeout_ms", @@ -59,9 +59,9 @@ fn ability_options_fields() -> BTreeSet { let opts = AbilitySignedCallOptions { tenant_id: "t", ability: "a", - callee_uri: "c", + callee_ura: "c", callee_profile: "p", - subject_uri: Some("s"), + subject_ura: Some("s"), subject_profile: Some("sp"), payload: &payload, nonce_base64: Some("n"), @@ -77,9 +77,9 @@ fn ability_options_fields() -> BTreeSet { let fields = &[ "tenant_id", "ability", - "callee_uri", + "callee_ura", "callee_profile", - "subject_uri", + "subject_ura", "subject_profile", "payload", "nonce_base64", @@ -91,9 +91,9 @@ fn ability_options_fields() -> BTreeSet { let _ = ( opts.tenant_id, opts.ability, - opts.callee_uri, + opts.callee_ura, opts.callee_profile, - opts.subject_uri, + opts.subject_ura, opts.subject_profile, opts.payload, opts.nonce_base64, @@ -108,9 +108,9 @@ fn mcp_options_fields() -> BTreeSet { tenant_id: "t", tool_name: "tool", target_node_id: Some("node"), - callee_uri: "c", + callee_ura: "c", callee_profile: "p", - subject_uri: Some("s"), + subject_ura: Some("s"), subject_profile: Some("sp"), arguments: &arguments, nonce_base64: Some("n"), @@ -121,9 +121,9 @@ fn mcp_options_fields() -> BTreeSet { "tenant_id", "tool_name", "target_node_id", - "callee_uri", + "callee_ura", "callee_profile", - "subject_uri", + "subject_ura", "subject_profile", "arguments", "nonce_base64", @@ -133,9 +133,9 @@ fn mcp_options_fields() -> BTreeSet { opts.tenant_id, opts.tool_name, opts.target_node_id, - opts.callee_uri, + opts.callee_ura, opts.callee_profile, - opts.subject_uri, + opts.subject_ura, opts.subject_profile, opts.arguments, opts.nonce_base64, diff --git a/sdk/rust/tests/verify_binary.rs b/sdk/rust/tests/verify_binary.rs index 2bda87aa..3e7ab7b5 100644 --- a/sdk/rust/tests/verify_binary.rs +++ b/sdk/rust/tests/verify_binary.rs @@ -17,7 +17,7 @@ use easynet_axon::invocation::axiom::{ use easynet_axon::invocation::bundle::{CausalJson, IdentityJson, InvocationJson, ReceiptJson}; use easynet_axon::invocation::{ AgentIdentity, CausalContext, InvocationEnvelope, ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, }; use ed25519_dalek::SigningKey; @@ -141,15 +141,15 @@ fn verify_single_invocation_chain_passes() { let caller = AgentIdentity::new( "easynet:///r/silan/agents/r@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let callee = AgentIdentity::new( "easynet:///r/openai/agents/r@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let subject = SubjectIdentity::new( "easynet:///r/silan/papers/p@draft-1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let env = InvocationEnvelope { @@ -232,19 +232,19 @@ fn verify_fan_in_dag_passes() { let silan = AgentIdentity::new( "easynet:///r/silan/agents/writer@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let openai = AgentIdentity::new( "easynet:///r/openai/agents/reviewer@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let google = AgentIdentity::new( "easynet:///r/google/agents/reviewer@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let paper = SubjectIdentity::new( "easynet:///r/silan/papers/paper@draft-1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let invocations: Vec<(String, InvocationEnvelope, &SigningKey, &SigningKey)> = Vec::new(); @@ -351,11 +351,11 @@ fn verify_fan_in_dag_passes() { causal_context: CausalContext::List(vec![ ReceiptRef { receipt_hash: h_oa1, - receipt_uri: format!("bundle:///receipts/{openai_id}/1"), + receipt_ura: format!("bundle:///receipts/{openai_id}/1"), }, ReceiptRef { receipt_hash: h_ga1, - receipt_uri: format!("bundle:///receipts/{google_id}/1"), + receipt_ura: format!("bundle:///receipts/{google_id}/1"), }, ]), }; @@ -419,11 +419,11 @@ fn verify_tampered_receipt_fails_non_zero() { let caller = AgentIdentity::new( "easynet:///r/silan/agents/t@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let callee = AgentIdentity::new( "easynet:///r/openai/agents/t@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let subject = SubjectIdentity::from_callee(&callee); @@ -476,8 +476,8 @@ fn verify_wrong_pubkey_fails_non_zero() { let sk_caller_fake = signing_key_from_bytes(&[4u8; 32]); let sk_callee = signing_key_from_bytes(&[5u8; 32]); - let caller = AgentIdentity::new("easynet:///r/silan/x@1.0", UriProfile::EasynetStrictV2); - let callee = AgentIdentity::new("easynet:///r/openai/x@1.0", UriProfile::EasynetStrictV2); + let caller = AgentIdentity::new("easynet:///r/silan/x@1.0", UraProfile::EasynetStrictV2); + let callee = AgentIdentity::new("easynet:///r/openai/x@1.0", UraProfile::EasynetStrictV2); let subject = SubjectIdentity::from_callee(&callee); let env = InvocationEnvelope { @@ -521,8 +521,8 @@ fn verify_wrong_pubkey_fails_non_zero() { fn verify_canonical_bytes_size_is_reasonable() { // Sanity on canonical encoder size — two fixed sample envelopes // produce distinct but bounded bytes. - let caller = AgentIdentity::new("easynet:///r/a/b@1", UriProfile::EasynetStrictV2); - let callee = AgentIdentity::new("easynet:///r/c/d@1", UriProfile::EasynetStrictV2); + let caller = AgentIdentity::new("easynet:///r/a/b@1", UraProfile::EasynetStrictV2); + let callee = AgentIdentity::new("easynet:///r/c/d@1", UraProfile::EasynetStrictV2); let subject = SubjectIdentity::from_callee(&callee); let env = InvocationEnvelope { caller, diff --git a/sdk/rust/tests/verify_end_to_end.rs b/sdk/rust/tests/verify_end_to_end.rs index f906eb69..6c59ec09 100644 --- a/sdk/rust/tests/verify_end_to_end.rs +++ b/sdk/rust/tests/verify_end_to_end.rs @@ -17,7 +17,7 @@ use std::process::Command; use easynet_axon::invocation::axiom::{ canonical_invocation_bytes, canonical_receipt_bytes, sha256, sign_invocation, sign_receipt, AgentIdentity, CausalContext, InvocationEnvelope, ReceiptBody, ReceiptRef, SubjectIdentity, - UriProfile, + UraProfile, }; use easynet_axon::invocation::bundle::{CausalJson, IdentityJson, InvocationJson, ReceiptJson}; use ed25519_dalek::SigningKey; @@ -86,15 +86,15 @@ fn make_signed_invocation( ) -> (InvocationJson, Vec, [u8; 32]) { let caller = AgentIdentity::new( "easynet:///r/silan/agents/r@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let callee = AgentIdentity::new( "easynet:///r/openai/agents/r@1.0", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let subject = SubjectIdentity::new( "easynet:///r/silan/papers/p@draft-1", - UriProfile::EasynetStrictV2, + UraProfile::EasynetStrictV2, ); let env = InvocationEnvelope { caller: caller.clone(), @@ -324,7 +324,7 @@ fn verify_accepts_scalar_causal_chain() { let scalar = CausalContext::Scalar(ReceiptRef { receipt_hash: a_terminal_hash, - receipt_uri: "easynet:///r/silan/receipts/inv-A/1".to_string(), + receipt_ura: "easynet:///r/silan/receipts/inv-A/1".to_string(), }); let (inv_b, receipts_b, _) = make_signed_invocation("inv-B", &caller, &callee, scalar); b.write_invocation(&inv_b); @@ -353,7 +353,7 @@ fn verify_rejects_dangling_causal_pointer() { let fake = CausalContext::Scalar(ReceiptRef { receipt_hash: [0xFFu8; 32], - receipt_uri: "easynet:///r/nowhere".to_string(), + receipt_ura: "easynet:///r/nowhere".to_string(), }); let (inv, receipts, _) = make_signed_invocation("inv-dangle", &caller, &callee, fake); b.write_invocation(&inv); @@ -443,12 +443,12 @@ fn flush(dir: &Path, inv: &InvocationJson, receipts: &[ReceiptJson]) { } } -// ── P0-2: per-field envelope tamper — caller.uri ──────────────────────── +// ── P0-2: per-field envelope tamper — caller.ura ──────────────────────── #[test] -fn verify_rejects_tampered_caller_uri() { +fn verify_rejects_tampered_caller_ura() { let (dir, _c, _e, mut inv, receipts) = golden_bundle("tcu"); - inv.caller.uri = "easynet:///r/mallory/agents/x@1".to_string(); + inv.caller.ura = "easynet:///r/mallory/agents/x@1".to_string(); flush(&dir, &inv, &receipts); let (code, _stdout, stderr) = run_verify(&dir); assert_eq!(code, 1, "stderr={stderr}"); @@ -458,12 +458,12 @@ fn verify_rejects_tampered_caller_uri() { ); } -// ── P0-2: per-field envelope tamper — callee.uri ──────────────────────── +// ── P0-2: per-field envelope tamper — callee.ura ──────────────────────── #[test] -fn verify_rejects_tampered_callee_uri() { +fn verify_rejects_tampered_callee_ura() { let (dir, _c, _e, mut inv, receipts) = golden_bundle("tceu"); - inv.callee.uri = "easynet:///r/otherorg/agents/x@1".to_string(); + inv.callee.ura = "easynet:///r/otherorg/agents/x@1".to_string(); flush(&dir, &inv, &receipts); let (code, _stdout, stderr) = run_verify(&dir); assert_eq!(code, 1, "stderr={stderr}"); @@ -473,12 +473,12 @@ fn verify_rejects_tampered_callee_uri() { ); } -// ── P0-2: per-field envelope tamper — subject.uri ─────────────────────── +// ── P0-2: per-field envelope tamper — subject.ura ─────────────────────── #[test] -fn verify_rejects_tampered_subject_uri() { +fn verify_rejects_tampered_subject_ura() { let (dir, _c, _e, mut inv, receipts) = golden_bundle("tsu"); - inv.subject.uri = "easynet:///r/silan/papers/other@draft-1".to_string(); + inv.subject.ura = "easynet:///r/silan/papers/other@draft-1".to_string(); flush(&dir, &inv, &receipts); let (code, _stdout, stderr) = run_verify(&dir); assert_eq!(code, 1, "stderr={stderr}"); @@ -556,7 +556,7 @@ fn verify_rejects_tampered_envelope_causal_context() { // Was None; set to a scalar pointing at a fake hash. inv.causal_context = CausalJson::Scalar { receipt_hash_hex: hex::encode([0xAAu8; 32]), - receipt_uri: "easynet:///r/unknown".to_string(), + receipt_ura: "easynet:///r/unknown".to_string(), }; flush(&dir, &inv, &receipts); let (code, _stdout, stderr) = run_verify(&dir); @@ -605,11 +605,11 @@ fn verify_rejects_reordered_causal_list() { let causal_ordered = CausalContext::List(vec![ ReceiptRef { receipt_hash: a_hash, - receipt_uri: "easynet:///r/silan/receipts/A/1".to_string(), + receipt_ura: "easynet:///r/silan/receipts/A/1".to_string(), }, ReceiptRef { receipt_hash: b_hash, - receipt_uri: "easynet:///r/silan/receipts/B/1".to_string(), + receipt_ura: "easynet:///r/silan/receipts/B/1".to_string(), }, ]); let (mut inv_pw, mut rec_pw, _) = @@ -667,7 +667,7 @@ fn verify_rejects_causal_binding_mismatch() { let scalar = CausalContext::Scalar(ReceiptRef { receipt_hash: pred_hash, - receipt_uri: "easynet:///r/silan/receipts/pred/1".to_string(), + receipt_ura: "easynet:///r/silan/receipts/pred/1".to_string(), }); let (inv_sig_valid_but_inconsistent, mut receipts, _) = make_signed_invocation("inv-cbm", &caller, &callee, scalar); @@ -896,7 +896,7 @@ fn verify_rejects_causal_self_reference() { let self_cycle = CausalContext::Scalar(ReceiptRef { receipt_hash: a_terminal_hash, - receipt_uri: "easynet:///r/silan/receipts/inv-self/1".to_string(), + receipt_ura: "easynet:///r/silan/receipts/inv-self/1".to_string(), }); let (inv_a, rec_a, _) = make_signed_invocation("inv-self", &caller, &callee, self_cycle); diff --git a/sdk/swift/Sources/EasyNetAxon/AbilityLifecycle.swift b/sdk/swift/Sources/EasyNetAxon/AbilityLifecycle.swift index 7d59ac70..48298d07 100644 --- a/sdk/swift/Sources/EasyNetAxon/AbilityLifecycle.swift +++ b/sdk/swift/Sources/EasyNetAxon/AbilityLifecycle.swift @@ -6,7 +6,7 @@ // // Protocol Responsibility: // - Defines typed ability descriptors, export targets, and deployment helpers exposed to SDK users. -// - Keeps cross-language ability naming, resource-uri, and tool-spec semantics aligned. +// - Keeps cross-language ability naming, resource-ura, and tool-spec semantics aligned. // // Implementation Approach: // - Separates pure descriptor/export helpers from bridge-backed deployment and invocation flows. @@ -98,7 +98,7 @@ public struct AbilityDescriptor: Equatable, Sendable { public let outputSchema: JSONObject public let version: String public let tags: [String] - public let resourceURI: String + public let resourceURA: String // Agent ecosystem extensions (SKILL.md / MCP / CLI) public let instructions: String public let inputExamples: [JSONValue] @@ -125,7 +125,7 @@ public struct AbilityDescriptor: Equatable, Sendable { outputSchema: JSONObject = ["type": .string("object"), "properties": .object([:])], version: String = "1.0.0", tags: [String] = [], - resourceURI: String = "", + resourceURA: String = "", instructions: String = "", inputExamples: [JSONValue] = [], prerequisites: [String] = [], @@ -156,7 +156,7 @@ public struct AbilityDescriptor: Equatable, Sendable { self.outputSchema = outputSchema self.version = version self.tags = tags - self.resourceURI = resourceURI.isEmpty ? "easynet:///r/org/\(token)" : resourceURI + self.resourceURA = resourceURA.isEmpty ? "easynet:///r/org/\(token)" : resourceURA self.instructions = instructions self.inputExamples = inputExamples self.prerequisites = prerequisites @@ -175,7 +175,7 @@ public struct AbilityDescriptor: Equatable, Sendable { ToolSpec( name: toolName, description: description, - resourceURI: resourceURI, + resourceURA: resourceURA, parameters: inputSchema, readOnlyHint: readOnly, destructiveHint: destructive, @@ -205,7 +205,7 @@ public func buildAbilityDescriptor( outputSchema: JSONObject = ["type": .string("object"), "properties": .object([:])], version: String = "1.0.0", tags: [String] = [], - resourceURI: String = "", + resourceURA: String = "", instructions: String = "", inputExamples: [JSONValue] = [], prerequisites: [String] = [], @@ -227,7 +227,7 @@ public func buildAbilityDescriptor( outputSchema: outputSchema, version: version, tags: tags, - resourceURI: resourceURI, + resourceURA: resourceURA, instructions: instructions, inputExamples: inputExamples, prerequisites: prerequisites, @@ -252,7 +252,7 @@ public func exportAbility( let endpoint = axonEndpoint ?? "http://127.0.0.1:50051" return AbilityExportResult( abilityMD: generateAbilityMD(descriptor: descriptor, target: target, token: token), - invokeScript: try generateInvokeScript(resourceURI: descriptor.resourceURI, endpoint: endpoint), + invokeScript: try generateInvokeScript(resourceURA: descriptor.resourceURA, endpoint: endpoint), abilityName: token ) } @@ -283,19 +283,19 @@ private func sanitizeShellValue(_ value: String, label: String) throws -> String return value } -private func generateInvokeScript(resourceURI: String, endpoint: String) throws -> String { +private func generateInvokeScript(resourceURA: String, endpoint: String) throws -> String { let safeEP = try sanitizeShellValue(endpoint, label: "endpoint") - let safeURI = try sanitizeShellValue(resourceURI, label: "resource_uri") + let safeURA = try sanitizeShellValue(resourceURA, label: "resource_ura") return """ #!/usr/bin/env bash set -euo pipefail AXON_ENDPOINT="${AXON_ENDPOINT:-\(safeEP)}" TENANT="${AXON_TENANT:-default}" - RESOURCE_URI="\(safeURI)" + RESOURCE_URA="\(safeURA)" ARGS="${1:-{}}" curl -sS -X POST "${AXON_ENDPOINT}/v1/invoke" \ -H "Content-Type: application/json" \ - -d "{\"tenant_id\":\"${TENANT}\",\"resource_uri\":\"${RESOURCE_URI}\",\"payload\":${ARGS}}" + -d "{\"tenant_id\":\"${TENANT}\",\"resource_ura\":\"${RESOURCE_URA}\",\"payload\":${ARGS}}" """ } @@ -312,7 +312,7 @@ private func generateAbilityMD( "metadata:", " author: easynet-axon", " version: \"\(descriptor.version)\"", - " axon-resource-uri: \"\(descriptor.resourceURI)\"", + " axon-resource-ura: \"\(descriptor.resourceURA)\"", ] switch target { @@ -415,7 +415,7 @@ private func generateAbilityMD( lines.append("") lines.append("## Axon Resource") lines.append("") - lines.append("- **URI**: `\(descriptor.resourceURI)`") + lines.append("- **URA**: `\(descriptor.resourceURA)`") lines.append("- **Version**: \(descriptor.version)") if !descriptor.category.isEmpty { lines.append("- **Category**: \(descriptor.category)") @@ -530,7 +530,7 @@ public func deployToNode( // Per-device ability catalog (`listAbilities`) and tool-name-keyed invocation // (`invokeAbility`) were removed by RFC-001 §A1 — the directory is now // federation-scoped (`federation.resolve`) and invocation is target-typed -// (`Invoke(callee=, ability=...)`) rather than node-id + tool-name. +// (`Invoke(callee=, ability=...)`) rather than node-id + tool-name. // Use `bridge.federationResolve(...)` and `bridge.abilityCallRaw(...)` directly. // MARK: - Uninstall ability @@ -580,17 +580,17 @@ public func discoverNodes( // MARK: - Disconnect device /// Withdraws an Agent via `federation.revoke`. RFC-001 §A1 collapsed -/// drain-then-deregister into a single revoke; `agentURI` replaces the +/// drain-then-deregister into a single revoke; `agentURA` replaces the /// earlier `nodeId` parameter. public func disconnectDevice( bridge: DendriteBridge, tenant: String, - agentURI: String, + agentURA: String, reason: String? = nil ) throws -> JSONObject { try bridge.federationRevoke( tenantID: tenant, - agentURI: agentURI, + agentURA: agentURA, reason: reason ?? "sdk: disconnect_device" ) } @@ -602,13 +602,13 @@ public func disconnectDevice( public func drainDevice( bridge: DendriteBridge, tenant: String, - agentURI: String, + agentURA: String, reason: String? = nil ) throws -> JSONObject { try disconnectDevice( bridge: bridge, tenant: tenant, - agentURI: agentURI, + agentURA: agentURA, reason: reason ?? "sdk: drain_device" ) } diff --git a/sdk/swift/Sources/EasyNetAxon/Client.swift b/sdk/swift/Sources/EasyNetAxon/Client.swift index 521c31fc..0f3efd8c 100644 --- a/sdk/swift/Sources/EasyNetAxon/Client.swift +++ b/sdk/swift/Sources/EasyNetAxon/Client.swift @@ -11,14 +11,14 @@ import Foundation public protocol Transport { func call( tenantID: String, - resourceURI: String, + resourceURA: String, payload: JSONObject, principalID: String? ) throws -> JSONObject func callRaw( tenantID: String, - resourceURI: String, + resourceURA: String, payload: JSONObject, principalID: String? ) throws -> JSONObject @@ -28,8 +28,8 @@ func defaultAxonEndpoint() -> String { ProcessInfo.processInfo.environment["EASYNET_AXON_ENDPOINT"] ?? "http://127.0.0.1:50051" } -func subjectVisibility(from resourceURI: String) -> String { - let normalized = resourceURI.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() +func subjectVisibility(from resourceURA: String) -> String { + let normalized = resourceURA.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() if normalized.hasPrefix("easynet:///r/pub/") { return "pub" } @@ -39,7 +39,7 @@ func subjectVisibility(from resourceURI: String) -> String { return "org" } -func principalToSubjectID(_ principalID: String, resourceURI: String) throws -> String { +func principalToSubjectID(_ principalID: String, resourceURA: String) throws -> String { let normalized = principalID.trimmingCharacters(in: .whitespacesAndNewlines) guard !normalized.isEmpty else { throw DendriteError("principal(...) cannot be blank") @@ -47,7 +47,7 @@ func principalToSubjectID(_ principalID: String, resourceURI: String) throws -> if normalized.hasPrefix("easynet:") { return normalized } - return "easynet:\(subjectVisibility(from: resourceURI)):reg:agent.\(normalized)" + return "easynet:\(subjectVisibility(from: resourceURA)):reg:agent.\(normalized)" } public final class SidecarTransport: Transport { @@ -116,14 +116,14 @@ public final class SidecarTransport: Transport { public func call( tenantID: String, - resourceURI: String, + resourceURA: String, payload: JSONObject, principalID: String? ) throws -> JSONObject { - let subjectID = try principalID.map { try principalToSubjectID($0, resourceURI: resourceURI) } + let subjectID = try principalID.map { try principalToSubjectID($0, resourceURA: resourceURA) } return try ensureBridge().abilityCallRaw( tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, payloadJSON: .object(payload), subjectID: subjectID, timeoutMs: timeoutMs @@ -136,14 +136,14 @@ public final class SidecarTransport: Transport { /// once structured envelope unwrapping is added to `call`. public func callRaw( tenantID: String, - resourceURI: String, + resourceURA: String, payload: JSONObject, principalID: String? ) throws -> JSONObject { - let subjectID = try principalID.map { try principalToSubjectID($0, resourceURI: resourceURI) } + let subjectID = try principalID.map { try principalToSubjectID($0, resourceURA: resourceURA) } return try ensureBridge().abilityCallRaw( tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, payloadJSON: .object(payload), subjectID: subjectID, timeoutMs: timeoutMs @@ -158,18 +158,18 @@ public final class SidecarTransport: Transport { public struct Client { private let transport: Transport private let tenantID: String? - private let resourceURI: String? + private let resourceURA: String? private let principalID: String? public init( transport: Transport = SidecarTransport(), tenantID: String? = nil, - resourceURI: String? = nil, + resourceURA: String? = nil, principalID: String? = nil ) { self.transport = transport self.tenantID = tenantID - self.resourceURI = resourceURI + self.resourceURA = resourceURA self.principalID = principalID } @@ -177,16 +177,16 @@ public struct Client { Client( transport: transport, tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, principalID: principalID ) } - public func ability(_ resourceURI: String) -> Client { + public func ability(_ resourceURA: String) -> Client { Client( transport: transport, tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, principalID: principalID ) } @@ -194,12 +194,12 @@ public struct Client { public func principal(_ principalID: String) throws -> Client { _ = try principalToSubjectID( principalID, - resourceURI: resourceURI ?? "easynet:///r/org/reg/agent.placeholder/abilities/placeholder@1" + resourceURA: resourceURA ?? "easynet:///r/org/reg/agent.placeholder/abilities/placeholder@1" ) return Client( transport: transport, tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, principalID: principalID ) } @@ -208,12 +208,12 @@ public struct Client { guard let tenantID, !tenantID.isEmpty else { throw DendriteError("tenant(...) is required before call(...)") } - guard let resourceURI, !resourceURI.isEmpty else { + guard let resourceURA, !resourceURA.isEmpty else { throw DendriteError("ability(...) is required before call(...)") } return try transport.call( tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, payload: payload, principalID: principalID ) @@ -223,12 +223,12 @@ public struct Client { guard let tenantID, !tenantID.isEmpty else { throw DendriteError("tenant(...) is required before callRaw(...)") } - guard let resourceURI, !resourceURI.isEmpty else { + guard let resourceURA, !resourceURA.isEmpty else { throw DendriteError("ability(...) is required before callRaw(...)") } return try transport.callRaw( tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, payload: payload, principalID: principalID ) diff --git a/sdk/swift/Sources/EasyNetAxon/DendriteBridge.swift b/sdk/swift/Sources/EasyNetAxon/DendriteBridge.swift index 09a3821a..58289f5d 100644 --- a/sdk/swift/Sources/EasyNetAxon/DendriteBridge.swift +++ b/sdk/swift/Sources/EasyNetAxon/DendriteBridge.swift @@ -713,7 +713,7 @@ public final class DendriteBridge { public func abilityCall( tenantID: String, - resourceURI: String, + resourceURA: String, payloadJSON: JSONValue, subjectID: String? = nil, metadata: [String: String] = [:], @@ -721,7 +721,7 @@ public final class DendriteBridge { ) throws -> JSONObject { try abilityCallRaw( tenantID: tenantID, - resourceURI: resourceURI, + resourceURA: resourceURA, payloadJSON: payloadJSON, subjectID: subjectID, metadata: metadata, @@ -731,7 +731,7 @@ public final class DendriteBridge { public func abilityCallRaw( tenantID: String, - resourceURI: String, + resourceURA: String, payloadJSON: JSONValue, subjectID: String? = nil, metadata: [String: String] = [:], @@ -739,7 +739,7 @@ public final class DendriteBridge { ) throws -> JSONObject { var request: JSONObject = [ "tenant_id": .string(tenantID), - "resource_uri": .string(resourceURI), + "resource_ura": .string(resourceURA), "payload_json": payloadJSON, "metadata": .object(metadata.mapValues(JSONValue.string)), "timeout_ms": .number(Double(max(timeoutMs, 1))), @@ -837,19 +837,19 @@ public final class DendriteBridge { /// `federation.advertise_agent`. Replaces the legacy `registerNode` RPC. public func federationAdvertiseAgent( tenantID: String, - agentURI: String, + agentURA: String, publicKeyHex: String? = nil, signingAuthority: JSONObject? = nil, timeoutMs: Int = federationDefaultTimeoutMs ) throws -> JSONObject { let body = FederationBody.advertiseAgent( - agentURI: agentURI, + agentURA: agentURA, publicKeyHex: publicKeyHex, signingAuthority: signingAuthority ) return try abilityCallRaw( tenantID: tenantID, - resourceURI: "federation.advertise_agent", + resourceURA: "federation.advertise_agent", payloadJSON: .object(body), timeoutMs: timeoutMs ) @@ -862,17 +862,17 @@ public final class DendriteBridge { /// (Python `list[dict]`, Go `[]map[string]any`, Java `List>`). public func federationAdvertiseAbilities( tenantID: String, - agentURI: String, + agentURA: String, abilities: [JSONObject], timeoutMs: Int = federationDefaultTimeoutMs ) throws -> JSONObject { let body = FederationBody.advertiseAbilities( - agentURI: agentURI, + agentURA: agentURA, abilities: abilities ) return try abilityCallRaw( tenantID: tenantID, - resourceURI: "federation.advertise_abilities", + resourceURA: "federation.advertise_abilities", payloadJSON: .object(body), timeoutMs: timeoutMs ) @@ -885,7 +885,7 @@ public final class DendriteBridge { ) throws -> JSONObject { try abilityCallRaw( tenantID: tenantID, - resourceURI: "federation.heartbeat", + resourceURA: "federation.heartbeat", payloadJSON: .object([:]), timeoutMs: timeoutMs ) @@ -896,14 +896,14 @@ public final class DendriteBridge { /// runtime substitutes a canonical default in that case. public func federationRevoke( tenantID: String, - agentURI: String, + agentURA: String, reason: String? = nil, timeoutMs: Int = federationDefaultTimeoutMs ) throws -> JSONObject { - let body = FederationBody.revoke(agentURI: agentURI, reason: reason) + let body = FederationBody.revoke(agentURA: agentURA, reason: reason) return try abilityCallRaw( tenantID: tenantID, - resourceURI: "federation.revoke", + resourceURA: "federation.revoke", payloadJSON: .object(body), timeoutMs: timeoutMs ) @@ -912,17 +912,17 @@ public final class DendriteBridge { /// `federation.resolve` — directory query. public func federationResolve( tenantID: String, - agentURIPrefix: String? = nil, + agentURAPrefix: String? = nil, includeAbilities: Bool = false, timeoutMs: Int = federationDefaultTimeoutMs ) throws -> JSONObject { let body = FederationBody.resolve( - agentURIPrefix: agentURIPrefix, + agentURAPrefix: agentURAPrefix, includeAbilities: includeAbilities ) return try abilityCallRaw( tenantID: tenantID, - resourceURI: "federation.resolve", + resourceURA: "federation.resolve", payloadJSON: .object(body), timeoutMs: timeoutMs ) @@ -945,7 +945,7 @@ public final class DendriteBridge { ) return try abilityCallRaw( tenantID: tenantID, - resourceURI: "federation.join", + resourceURA: "federation.join", payloadJSON: .object(body), timeoutMs: timeoutMs ) @@ -961,7 +961,7 @@ public final class DendriteBridge { tags: [String] = [], requirements: JSONObject = [:], metadata: [String: String] = [:], - payloadURI: String? = nil, + payloadURA: String? = nil, payloadSizeBytes: Int? = nil, packageBytesBase64: String? = nil, signatureFingerprint: String? = nil, @@ -985,8 +985,8 @@ public final class DendriteBridge { if let resolvedSignature = resolvedDeploySignature(signatureBase64) { payload["signature_base64"] = .string(resolvedSignature) } - if let payloadURI, !payloadURI.isEmpty { - payload["payload_uri"] = .string(payloadURI) + if let payloadURA, !payloadURA.isEmpty { + payload["payload_ura"] = .string(payloadURA) } if let payloadSizeBytes { payload["payload_size_bytes"] = .number(Double(max(payloadSizeBytes, 0))) diff --git a/sdk/swift/Sources/EasyNetAxon/FederationBody.swift b/sdk/swift/Sources/EasyNetAxon/FederationBody.swift index 7f33671c..17ee9c73 100644 --- a/sdk/swift/Sources/EasyNetAxon/FederationBody.swift +++ b/sdk/swift/Sources/EasyNetAxon/FederationBody.swift @@ -25,11 +25,11 @@ import Foundation enum FederationBody { static func advertiseAgent( - agentURI: String, + agentURA: String, publicKeyHex: String?, signingAuthority: JSONObject? ) -> JSONObject { - var body: JSONObject = ["agent_uri": .string(agentURI)] + var body: JSONObject = ["agent_ura": .string(agentURA)] if let publicKeyHex, !publicKeyHex.isEmpty { body["public_key_hex"] = .string(publicKeyHex) } @@ -40,17 +40,17 @@ enum FederationBody { } static func advertiseAbilities( - agentURI: String, + agentURA: String, abilities: [JSONObject] ) -> JSONObject { [ - "agent_uri": .string(agentURI), + "agent_ura": .string(agentURA), "abilities": .array(abilities.map(JSONValue.object)), ] } - static func revoke(agentURI: String, reason: String?) -> JSONObject { - var body: JSONObject = ["agent_uri": .string(agentURI)] + static func revoke(agentURA: String, reason: String?) -> JSONObject { + var body: JSONObject = ["agent_ura": .string(agentURA)] if let reason, !reason.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { body["reason"] = .string(reason) } @@ -58,12 +58,12 @@ enum FederationBody { } static func resolve( - agentURIPrefix: String?, + agentURAPrefix: String?, includeAbilities: Bool ) -> JSONObject { var filter: JSONObject = [:] - if let agentURIPrefix, !agentURIPrefix.isEmpty { - filter["agent_uri_prefix"] = .string(agentURIPrefix) + if let agentURAPrefix, !agentURAPrefix.isEmpty { + filter["agent_ura_prefix"] = .string(agentURAPrefix) } if includeAbilities { filter["include_abilities"] = .bool(true) diff --git a/sdk/swift/Sources/EasyNetAxon/Invocation/Admission.swift b/sdk/swift/Sources/EasyNetAxon/Invocation/Admission.swift index 088ae2f1..c017f669 100644 --- a/sdk/swift/Sources/EasyNetAxon/Invocation/Admission.swift +++ b/sdk/swift/Sources/EasyNetAxon/Invocation/Admission.swift @@ -14,7 +14,7 @@ // Local-fast mode where identity is // self-asserted. // 4. NonceReplayStore.checkAndRecord — always on. Dedup key is -// `(caller.uri, ability, invocation_nonce)`; `ability` guards +// `(caller.ura, ability, invocation_nonce)`; `ability` guards // against cross-ability false-positives per review. // // All rejections throw `AxonInvocationError` with @@ -55,21 +55,21 @@ private func rejectEnvelope(_ detail: String) -> AxonInvocationError { /// /// Checks applied (RFC 001 §5.2 step 1, strengthened per review): /// * `ability` non-empty -/// * `caller.uri` / `callee.uri` / `subject.uri` non-empty +/// * `caller.ura` / `callee.ura` / `subject.ura` non-empty /// * `invocationNonce` is not the all-zero sentinel /// * `argsDigest` length is 32 bytes (defensive) public func validateEnvelope(_ env: InvocationEnvelope) throws { if env.ability.isEmpty { throw rejectEnvelope("ability_empty") } - if env.caller.uri.isEmpty { - throw rejectEnvelope("caller_uri_empty") + if env.caller.ura.isEmpty { + throw rejectEnvelope("caller_ura_empty") } - if env.callee.uri.isEmpty { - throw rejectEnvelope("callee_uri_empty") + if env.callee.ura.isEmpty { + throw rejectEnvelope("callee_ura_empty") } - if env.subject.uri.isEmpty { - throw rejectEnvelope("subject_uri_empty") + if env.subject.ura.isEmpty { + throw rejectEnvelope("subject_ura_empty") } if env.argsDigest.count != 32 { throw rejectEnvelope("args_digest_wrong_length") @@ -159,7 +159,7 @@ public final class NonceReplayStore: @unchecked Sendable { self.windowMs = windowMs } - /// Register a `(caller.uri, ability, nonce)` observation as of + /// Register a `(caller.ura, ability, nonce)` observation as of /// `nowMs`. Throws `AxonInvocationError` with reason /// `REASON_NONCE_REPLAY` on collision inside the current window. /// Out-of-window entries are pruned before the check. @@ -167,7 +167,7 @@ public final class NonceReplayStore: @unchecked Sendable { /// Admission calls this *after* structure/verify, so a malformed /// or unverified caller's nonce never enters the store. public func checkAndRecord( - callerUri: String, + callerUra: String, ability: String, nonce: Data, nowMs: Int64 @@ -181,9 +181,9 @@ public final class NonceReplayStore: @unchecked Sendable { seen.removeValue(forKey: k) } - // Key = callerUri + "\0" + ability + "\0" + nonce-hex, matching + // Key = callerUra + "\0" + ability + "\0" + nonce-hex, matching // Node's Map-keying approach and giving deterministic equality. - let key = "\(callerUri)\u{0}\(ability)\u{0}\(nonce.map { String(format: "%02x", $0) }.joined())" + let key = "\(callerUra)\u{0}\(ability)\u{0}\(nonce.map { String(format: "%02x", $0) }.joined())" if let prev = seen[key], prev >= cutoff { throw AxonInvocationError( @@ -264,7 +264,7 @@ public func runAdmission( try verifySignature(env, sig, r) } try replay.checkAndRecord( - callerUri: env.caller.uri, + callerUra: env.caller.ura, ability: env.ability, nonce: env.invocationNonce, nowMs: nowMs diff --git a/sdk/swift/Sources/EasyNetAxon/Invocation/Axiom.swift b/sdk/swift/Sources/EasyNetAxon/Invocation/Axiom.swift index 23333589..c48d5a3a 100644 --- a/sdk/swift/Sources/EasyNetAxon/Invocation/Axiom.swift +++ b/sdk/swift/Sources/EasyNetAxon/Invocation/Axiom.swift @@ -15,48 +15,48 @@ import CryptoKit // ── Types ──────────────────────────────────────────────────────────── -public enum UriProfile: String, Sendable, CaseIterable { +public enum UraProfile: String, Sendable, CaseIterable { case easynetStrictV2 = "easynet-strict-v2" case webSafeV2 = "web-safe-v2" - public static func parse(_ s: String) throws -> UriProfile { - guard let p = UriProfile(rawValue: s) else { - throw AxiomError.invalidArgument("unknown_uri_profile:\(s)") + public static func parse(_ s: String) throws -> UraProfile { + guard let p = UraProfile(rawValue: s) else { + throw AxiomError.invalidArgument("unknown_ura_profile:\(s)") } return p } } public struct AgentIdentity: Sendable, Hashable { - public let uri: String - public let profile: UriProfile - public init(uri: String, profile: UriProfile) { - self.uri = uri + public let ura: String + public let profile: UraProfile + public init(ura: String, profile: UraProfile) { + self.ura = ura self.profile = profile } } public struct SubjectIdentity: Sendable, Hashable { - public let uri: String - public let profile: UriProfile - public init(uri: String, profile: UriProfile) { - self.uri = uri + public let ura: String + public let profile: UraProfile + public init(ura: String, profile: UraProfile) { + self.ura = ura self.profile = profile } public static func fromCallee(_ callee: AgentIdentity) -> SubjectIdentity { - SubjectIdentity(uri: callee.uri, profile: callee.profile) + SubjectIdentity(ura: callee.ura, profile: callee.profile) } } public struct ReceiptRef: Sendable, Hashable { public let receiptHash: Data // 32 bytes - public let receiptUri: String - public init(receiptHash: Data, receiptUri: String) throws { + public let receiptUra: String + public init(receiptHash: Data, receiptUra: String) throws { guard receiptHash.count == 32 else { throw AxiomError.invalidArgument("receipt_hash_wrong_length:\(receiptHash.count)") } self.receiptHash = receiptHash - self.receiptUri = receiptUri + self.receiptUra = receiptUra } } @@ -64,13 +64,13 @@ public enum CausalContext: Sendable, Hashable { case none case scalar(ReceiptRef) case list([ReceiptRef]) - case merkle(root: Data, proofUri: String) + case merkle(root: Data, proofUra: String) - public static func merkleChecked(root: Data, proofUri: String) throws -> CausalContext { + public static func merkleChecked(root: Data, proofUra: String) throws -> CausalContext { guard root.count == 32 else { throw AxiomError.invalidArgument("merkle_root_wrong_length:\(root.count)") } - return .merkle(root: root, proofUri: proofUri) + return .merkle(root: root, proofUra: proofUra) } } @@ -164,8 +164,8 @@ public struct CalleeSignature: Sendable { } public protocol KeyResolver: Sendable { - /// Return raw 32-byte Ed25519 public key for the given agent URI. - func resolve(_ agentUri: String) throws -> Data + /// Return raw 32-byte Ed25519 public key for the given agent URA. + func resolve(_ agentUra: String) throws -> Data } public enum AxiomError: Error, CustomStringConvertible { @@ -218,8 +218,8 @@ func putBytes(_ b: Data, into out: inout Data) { } @inlinable -func putIdentityUriProfile(_ uri: String, _ profile: UriProfile, into out: inout Data) { - putStr(uri, into: &out) +func putIdentityUraProfile(_ ura: String, _ profile: UraProfile, into out: inout Data) { + putStr(ura, into: &out) putStr(profile.rawValue, into: &out) } @@ -231,27 +231,27 @@ public func canonicalCausalContext(_ ctx: CausalContext) -> Data { case .scalar(let r): out.append(0x01) out.append(r.receiptHash) - putStr(r.receiptUri, into: &out) + putStr(r.receiptUra, into: &out) case .list(let refs): out.append(0x02) putU32BE(UInt32(refs.count), into: &out) for r in refs { out.append(r.receiptHash) - putStr(r.receiptUri, into: &out) + putStr(r.receiptUra, into: &out) } - case .merkle(let root, let proofUri): + case .merkle(let root, let proofUra): out.append(0x03) out.append(root) - putStr(proofUri, into: &out) + putStr(proofUra, into: &out) } return out } public func canonicalInvocationBytes(_ env: InvocationEnvelope) -> Data { var out = Data() - putIdentityUriProfile(env.caller.uri, env.caller.profile, into: &out) - putIdentityUriProfile(env.callee.uri, env.callee.profile, into: &out) - putIdentityUriProfile(env.subject.uri, env.subject.profile, into: &out) + putIdentityUraProfile(env.caller.ura, env.caller.profile, into: &out) + putIdentityUraProfile(env.callee.ura, env.callee.profile, into: &out) + putIdentityUraProfile(env.subject.ura, env.subject.profile, into: &out) putStr(env.ability, into: &out) out.append(env.argsDigest) out.append(env.invocationNonce) @@ -268,9 +268,9 @@ public func canonicalReceiptBytes(_ r: ReceiptBody) -> Data { putStr(r.state, into: &out) putI64BE(r.timestampUnixMs, into: &out) out.append(r.prevReceiptHash) - putIdentityUriProfile(r.callerBinding.uri, r.callerBinding.profile, into: &out) - putIdentityUriProfile(r.calleeBinding.uri, r.calleeBinding.profile, into: &out) - putIdentityUriProfile(r.subjectBinding.uri, r.subjectBinding.profile, into: &out) + putIdentityUraProfile(r.callerBinding.ura, r.callerBinding.profile, into: &out) + putIdentityUraProfile(r.calleeBinding.ura, r.calleeBinding.profile, into: &out) + putIdentityUraProfile(r.subjectBinding.ura, r.subjectBinding.profile, into: &out) out.append(r.invocationNonce) let causal = canonicalCausalContext(r.causalBinding) putBytes(causal, into: &out) @@ -325,7 +325,7 @@ public func verifyInvocationSignature(envelope: InvocationEnvelope, guard signature.signature.count == 64 else { throw AxiomError.invalidArgument("signature_wrong_length:expected_64_got_\(signature.signature.count)") } - let raw = try resolver.resolve(envelope.caller.uri) + let raw = try resolver.resolve(envelope.caller.ura) let pk = try Curve25519.Signing.PublicKey(rawRepresentation: raw) let bytes = canonicalInvocationBytes(envelope) guard pk.isValidSignature(signature.signature, for: bytes) else { @@ -356,7 +356,7 @@ public func verifyReceiptSignature(body: ReceiptBody, guard signature.signature.count == 64 else { throw AxiomError.invalidArgument("signature_wrong_length:expected_64_got_\(signature.signature.count)") } - let raw = try resolver.resolve(body.calleeBinding.uri) + let raw = try resolver.resolve(body.calleeBinding.ura) let pk = try Curve25519.Signing.PublicKey(rawRepresentation: raw) let bytes = canonicalReceiptBytes(body) guard pk.isValidSignature(signature.signature, for: bytes) else { diff --git a/sdk/swift/Sources/EasyNetAxon/Invocation/Bundle.swift b/sdk/swift/Sources/EasyNetAxon/Invocation/Bundle.swift index 1e6a7413..03ce262c 100644 --- a/sdk/swift/Sources/EasyNetAxon/Invocation/Bundle.swift +++ b/sdk/swift/Sources/EasyNetAxon/Invocation/Bundle.swift @@ -16,25 +16,25 @@ import Foundation public enum BundleJSON { public static func identityFromAgent(_ a: AgentIdentity) -> [String: Any] { - ["uri": a.uri, "profile": a.profile.rawValue] + ["ura": a.ura, "profile": a.profile.rawValue] } public static func identityFromSubject(_ s: SubjectIdentity) -> [String: Any] { - ["uri": s.uri, "profile": s.profile.rawValue] + ["ura": s.ura, "profile": s.profile.rawValue] } public static func identityToAgent(_ d: [String: Any]) throws -> AgentIdentity { - guard let uri = d["uri"] as? String, let profile = d["profile"] as? String else { + guard let ura = d["ura"] as? String, let profile = d["profile"] as? String else { throw AxiomError.invalidArgument("bad_identity_json") } - return AgentIdentity(uri: uri, profile: try UriProfile.parse(profile)) + return AgentIdentity(ura: ura, profile: try UraProfile.parse(profile)) } public static func identityToSubject(_ d: [String: Any]) throws -> SubjectIdentity { - guard let uri = d["uri"] as? String, let profile = d["profile"] as? String else { + guard let ura = d["ura"] as? String, let profile = d["profile"] as? String else { throw AxiomError.invalidArgument("bad_identity_json") } - return SubjectIdentity(uri: uri, profile: try UriProfile.parse(profile)) + return SubjectIdentity(ura: ura, profile: try UraProfile.parse(profile)) } // ── Causal context JSON ────────────────────────────────────────── @@ -47,18 +47,18 @@ public enum BundleJSON { return [ "form": "scalar", "receipt_hash_hex": r.receiptHash.hexString, - "receipt_uri": r.receiptUri, + "receipt_ura": r.receiptUra, ] case .list(let refs): let prior: [[String: Any]] = refs.map { - ["receipt_hash_hex": $0.receiptHash.hexString, "receipt_uri": $0.receiptUri] + ["receipt_hash_hex": $0.receiptHash.hexString, "receipt_ura": $0.receiptUra] } return ["form": "list", "prior": prior] - case .merkle(let root, let proofUri): + case .merkle(let root, let proofUra): return [ "form": "merkle", "root_hex": root.hexString, - "proof_uri": proofUri, + "proof_ura": proofUra, ] } } @@ -72,28 +72,28 @@ public enum BundleJSON { return .none case "scalar": guard let h = d["receipt_hash_hex"] as? String, - let uri = d["receipt_uri"] as? String else { + let ura = d["receipt_ura"] as? String else { throw AxiomError.invalidArgument("bad_scalar_causal") } - return try .scalar(ReceiptRef(receiptHash: try hexToData(h, 32), receiptUri: uri)) + return try .scalar(ReceiptRef(receiptHash: try hexToData(h, 32), receiptUra: ura)) case "list": guard let arr = d["prior"] as? [[String: Any]] else { throw AxiomError.invalidArgument("bad_list_causal") } let refs: [ReceiptRef] = try arr.map { guard let h = $0["receipt_hash_hex"] as? String, - let uri = $0["receipt_uri"] as? String else { + let ura = $0["receipt_ura"] as? String else { throw AxiomError.invalidArgument("bad_list_entry") } - return try ReceiptRef(receiptHash: try hexToData(h, 32), receiptUri: uri) + return try ReceiptRef(receiptHash: try hexToData(h, 32), receiptUra: ura) } return .list(refs) case "merkle": guard let root = d["root_hex"] as? String, - let proofUri = d["proof_uri"] as? String else { + let proofUra = d["proof_ura"] as? String else { throw AxiomError.invalidArgument("bad_merkle_causal") } - return try CausalContext.merkleChecked(root: try hexToData(root, 32), proofUri: proofUri) + return try CausalContext.merkleChecked(root: try hexToData(root, 32), proofUra: proofUra) default: throw AxiomError.invalidArgument("unknown_causal_form:\(form)") } diff --git a/sdk/swift/Sources/EasyNetAxon/Invocation/LocalRuntime.swift b/sdk/swift/Sources/EasyNetAxon/Invocation/LocalRuntime.swift index ed9f12a1..28f0f8c1 100644 --- a/sdk/swift/Sources/EasyNetAxon/Invocation/LocalRuntime.swift +++ b/sdk/swift/Sources/EasyNetAxon/Invocation/LocalRuntime.swift @@ -277,15 +277,15 @@ fileprivate extension NSLock { } } -// Well-known local-runtime SystemAgent URI used when no caller identity +// Well-known local-runtime SystemAgent URA used when no caller identity // is provided. AXIOM.tex §3.2 permits this: infrastructure-initiated // invocations carry a SystemAgent identity and are still axiom-bound. private let SYSTEM_URI = "easynet:///r/_system/agents/local@1" internal func systemLocalBinding(payload: Data) -> AxiomBinding { - let system = AgentIdentity(uri: SYSTEM_URI, profile: .easynetStrictV2) - let callee = AgentIdentity(uri: SYSTEM_URI, profile: .easynetStrictV2) - let subject = SubjectIdentity(uri: SYSTEM_URI, profile: .easynetStrictV2) + let system = AgentIdentity(ura: SYSTEM_URI, profile: .easynetStrictV2) + let callee = AgentIdentity(ura: SYSTEM_URI, profile: .easynetStrictV2) + let subject = SubjectIdentity(ura: SYSTEM_URI, profile: .easynetStrictV2) return AxiomBinding( caller: system, callee: callee, diff --git a/sdk/swift/Sources/EasyNetAxon/ToolAdapter.swift b/sdk/swift/Sources/EasyNetAxon/ToolAdapter.swift index 63995179..cf4a9904 100644 --- a/sdk/swift/Sources/EasyNetAxon/ToolAdapter.swift +++ b/sdk/swift/Sources/EasyNetAxon/ToolAdapter.swift @@ -11,7 +11,7 @@ import Foundation public struct ToolSpec: Equatable, Sendable { public let name: String public let description: String - public let resourceURI: String + public let resourceURA: String public let parameters: JSONObject // MCP safety hints (mirrors types.proto ability hints). Defaults are // fail-closed: assume writes, assume destructive, assume non-idempotent, @@ -24,7 +24,7 @@ public struct ToolSpec: Equatable, Sendable { public init( name: String, description: String, - resourceURI: String, + resourceURA: String, parameters: JSONObject = ["type": .string("object"), "properties": .object([:])], readOnlyHint: Bool = false, destructiveHint: Bool = true, @@ -33,7 +33,7 @@ public struct ToolSpec: Equatable, Sendable { ) { self.name = name self.description = description - self.resourceURI = resourceURI + self.resourceURA = resourceURA self.parameters = parameters self.readOnlyHint = readOnlyHint self.destructiveHint = destructiveHint @@ -73,7 +73,7 @@ public struct ToolSpec: Equatable, Sendable { [ "name": .string(name), "description": .string(description), - "resource_uri": .string(resourceURI), + "resource_ura": .string(resourceURA), "parameters": .object(parameters), "read_only_hint": .bool(readOnlyHint), "destructive_hint": .bool(destructiveHint), @@ -110,14 +110,14 @@ public final class AbilityToolAdapter { public func register( _ name: String, description: String = "", - resourceURI: String? = nil, + resourceURA: String? = nil, parameters: JSONObject = ["type": .string("object"), "properties": .object([:])], handler: @escaping LocalToolHandler ) -> AbilityToolAdapter { let spec = ToolSpec( name: name, description: description, - resourceURI: resourceURI ?? "easynet:///r/org/\(name)", + resourceURA: resourceURA ?? "easynet:///r/org/\(name)", parameters: parameters ) specsByName[name] = spec @@ -128,14 +128,14 @@ public final class AbilityToolAdapter { @discardableResult public func registerAbility( _ name: String, - resourceURI: String, + resourceURA: String, description: String = "", parameters: JSONObject = ["type": .string("object"), "properties": .object([:])] ) -> AbilityToolAdapter { specsByName[name] = ToolSpec( name: name, description: description, - resourceURI: resourceURI, + resourceURA: resourceURA, parameters: parameters ) localHandlers.removeValue(forKey: name) @@ -175,7 +175,7 @@ public final class AbilityToolAdapter { var abilityClient = Client( transport: clientTransport, tenantID: tenantID, - resourceURI: spec.resourceURI, + resourceURA: spec.resourceURA, principalID: nil ) if let principalID, !principalID.isEmpty { diff --git a/sdk/swift/Tests/EasyNetAxonTests/AdmissionTests.swift b/sdk/swift/Tests/EasyNetAxonTests/AdmissionTests.swift index 0b4b9144..7fd424b1 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/AdmissionTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/AdmissionTests.swift @@ -9,11 +9,11 @@ import Foundation @testable import EasyNetAxon private let silan = AgentIdentity( - uri: "easynet:///r/silan/agents/t@1", + ura: "easynet:///r/silan/agents/t@1", profile: .easynetStrictV2 ) private let openai = AgentIdentity( - uri: "easynet:///r/openai/agents/t@1", + ura: "easynet:///r/openai/agents/t@1", profile: .easynetStrictV2 ) @@ -25,7 +25,7 @@ private func echoRuntime() -> LocalRuntime { private struct FixedResolver: KeyResolver { let raw: Data - func resolve(_ agentUri: String) throws -> Data { raw } + func resolve(_ agentUra: String) throws -> Data { raw } } private func sampleEnv() throws -> InvocationEnvelope { @@ -33,7 +33,7 @@ private func sampleEnv() throws -> InvocationEnvelope { caller: silan, callee: openai, subject: SubjectIdentity( - uri: "easynet:///r/silan/papers/p@d1", profile: .easynetStrictV2), + ura: "easynet:///r/silan/papers/p@d1", profile: .easynetStrictV2), ability: "echo", argsDigest: sha256Bytes(Data()), invocationNonce: Data(repeating: 0x11, count: 16), @@ -135,7 +135,7 @@ final class AdmissionTests: XCTestCase { func testReplayAcceptsFirstObservation() throws { let s = NonceReplayStore() try s.checkAndRecord( - callerUri: "caller", ability: "echo", + callerUra: "caller", ability: "echo", nonce: Data(repeating: 0x01, count: 16), nowMs: 1000 ) XCTAssertEqual(s.size, 1) @@ -144,12 +144,12 @@ final class AdmissionTests: XCTestCase { func testReplayRejectsSecondInsideWindow() throws { let s = NonceReplayStore() try s.checkAndRecord( - callerUri: "caller", ability: "echo", + callerUra: "caller", ability: "echo", nonce: Data(repeating: 0x01, count: 16), nowMs: 1000 ) do { try s.checkAndRecord( - callerUri: "caller", ability: "echo", + callerUra: "caller", ability: "echo", nonce: Data(repeating: 0x01, count: 16), nowMs: 2000 ) XCTFail("expected replay reject") @@ -161,17 +161,17 @@ final class AdmissionTests: XCTestCase { func testReplayDedupKeyIncludesAbility() throws { let s = NonceReplayStore() let n = Data(repeating: 0x01, count: 16) - try s.checkAndRecord(callerUri: "caller", ability: "ability-a", nonce: n, nowMs: 1000) + try s.checkAndRecord(callerUra: "caller", ability: "ability-a", nonce: n, nowMs: 1000) // Same caller + nonce on different ability — must pass. - try s.checkAndRecord(callerUri: "caller", ability: "ability-b", nonce: n, nowMs: 2000) + try s.checkAndRecord(callerUra: "caller", ability: "ability-b", nonce: n, nowMs: 2000) XCTAssertEqual(s.size, 2) } func testReplayPrunesOutOfWindowEntries() throws { let s = NonceReplayStore(windowMs: 1) let n = Data(repeating: 0x01, count: 16) - try s.checkAndRecord(callerUri: "c", ability: "a", nonce: n, nowMs: 0) - try s.checkAndRecord(callerUri: "c", ability: "a", nonce: n, nowMs: 10_000) + try s.checkAndRecord(callerUra: "c", ability: "a", nonce: n, nowMs: 0) + try s.checkAndRecord(callerUra: "c", ability: "a", nonce: n, nowMs: 10_000) XCTAssertEqual(s.size, 1) } @@ -209,7 +209,7 @@ final class AdmissionTests: XCTestCase { func testRunAdmissionRejectsEnvelopeBeforeReplayStore() throws { let env = try InvocationEnvelope( - caller: AgentIdentity(uri: "", profile: .easynetStrictV2), + caller: AgentIdentity(ura: "", profile: .easynetStrictV2), callee: openai, subject: SubjectIdentity.fromCallee(openai), ability: "echo", diff --git a/sdk/swift/Tests/EasyNetAxonTests/AxiomVectorsTests.swift b/sdk/swift/Tests/EasyNetAxonTests/AxiomVectorsTests.swift index fb09cf78..584c9a10 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/AxiomVectorsTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/AxiomVectorsTests.swift @@ -123,15 +123,15 @@ final class AxiomVectorsTests: XCTestCase { } private func parseAgent(_ o: [String: Any]) throws -> AgentIdentity { - let uri = o["uri"] as? String ?? "" + let ura = o["ura"] as? String ?? "" let profStr = o["profile"] as? String ?? "" - return AgentIdentity(uri: uri, profile: try UriProfile.parse(profStr)) + return AgentIdentity(ura: ura, profile: try UraProfile.parse(profStr)) } private func parseSubject(_ o: [String: Any]) throws -> SubjectIdentity { - let uri = o["uri"] as? String ?? "" + let ura = o["ura"] as? String ?? "" let profStr = o["profile"] as? String ?? "" - return SubjectIdentity(uri: uri, profile: try UriProfile.parse(profStr)) + return SubjectIdentity(ura: ura, profile: try UraProfile.parse(profStr)) } private func parseCausal(_ o: [String: Any]) throws -> CausalContext { @@ -142,7 +142,7 @@ final class AxiomVectorsTests: XCTestCase { case "scalar": let ref = try ReceiptRef( receiptHash: hexToData(o["receipt_hash_hex"] as? String ?? ""), - receiptUri: o["receipt_uri"] as? String ?? "") + receiptUra: o["receipt_ura"] as? String ?? "") return .scalar(ref) case "list": let prior = (o["prior"] as? [[String: Any]]) ?? [] @@ -150,13 +150,13 @@ final class AxiomVectorsTests: XCTestCase { for p in prior { refs.append(try ReceiptRef( receiptHash: hexToData(p["receipt_hash_hex"] as? String ?? ""), - receiptUri: p["receipt_uri"] as? String ?? "")) + receiptUra: p["receipt_ura"] as? String ?? "")) } return .list(refs) case "merkle": return try .merkleChecked( root: hexToData(o["root_hex"] as? String ?? ""), - proofUri: o["proof_uri"] as? String ?? "") + proofUra: o["proof_ura"] as? String ?? "") default: throw NSError(domain: "AxiomVectors", code: 2, userInfo: [NSLocalizedDescriptionKey: "unknown_causal_form:\(form)"]) @@ -183,5 +183,5 @@ final class AxiomVectorsTests: XCTestCase { private struct FixedResolver: KeyResolver { let pub: Data - func resolve(_ agentUri: String) throws -> Data { pub } + func resolve(_ agentUra: String) throws -> Data { pub } } diff --git a/sdk/swift/Tests/EasyNetAxonTests/AxiomWorkedExampleTests.swift b/sdk/swift/Tests/EasyNetAxonTests/AxiomWorkedExampleTests.swift index 24b2fe07..4df4118f 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/AxiomWorkedExampleTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/AxiomWorkedExampleTests.swift @@ -136,14 +136,14 @@ final class AxiomWorkedExampleTests: XCTestCase { XCTAssertEqual(nonce.count, 16, "invocation_nonce must decode to 16 bytes") let caller = AgentIdentity( - uri: callerRaw["uri"] as? String ?? "", - profile: try UriProfile.parse(callerRaw["profile"] as? String ?? "")) + ura: callerRaw["ura"] as? String ?? "", + profile: try UraProfile.parse(callerRaw["profile"] as? String ?? "")) let callee = AgentIdentity( - uri: calleeRaw["uri"] as? String ?? "", - profile: try UriProfile.parse(calleeRaw["profile"] as? String ?? "")) + ura: calleeRaw["ura"] as? String ?? "", + profile: try UraProfile.parse(calleeRaw["profile"] as? String ?? "")) let subject = SubjectIdentity( - uri: subjectRaw["uri"] as? String ?? "", - profile: try UriProfile.parse(subjectRaw["profile"] as? String ?? "")) + ura: subjectRaw["ura"] as? String ?? "", + profile: try UraProfile.parse(subjectRaw["profile"] as? String ?? "")) return try InvocationEnvelope( caller: caller, callee: callee, subject: subject, diff --git a/sdk/swift/Tests/EasyNetAxonTests/ClientTests.swift b/sdk/swift/Tests/EasyNetAxonTests/ClientTests.swift index 153996ca..ddcde184 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/ClientTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/ClientTests.swift @@ -7,21 +7,21 @@ private struct CaptureTransport: Transport { func call( tenantID: String, - resourceURI: String, + resourceURA: String, payload: JSONObject, principalID: String? ) throws -> JSONObject { - onCall(tenantID, resourceURI, payload, principalID) + onCall(tenantID, resourceURA, payload, principalID) return response } func callRaw( tenantID: String, - resourceURI: String, + resourceURA: String, payload: JSONObject, principalID: String? ) throws -> JSONObject { - onCall(tenantID, resourceURI, payload, principalID) + onCall(tenantID, resourceURA, payload, principalID) return response } } @@ -31,10 +31,10 @@ final class ClientTests: XCTestCase { let expectation = expectation(description: "transport called") let transport = CaptureTransport( response: ["ok": .bool(true)], - onCall: { tenantID, resourceURI, payload, _ in + onCall: { tenantID, resourceURA, payload, _ in XCTAssertEqual(tenantID, "tenant-test") XCTAssertEqual( - resourceURI, + resourceURA, "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test" ) XCTAssertEqual(payload["sku"], .string("A1")) @@ -80,28 +80,28 @@ final class ClientTests: XCTestCase { XCTAssertEqual( try principalToSubjectID( "alice", - resourceURI: "easynet:///r/pub/reg/agent.alice/abilities/voice.stream@1" + resourceURA: "easynet:///r/pub/reg/agent.alice/abilities/voice.stream@1" ), "easynet:pub:reg:agent.alice" ) XCTAssertEqual( try principalToSubjectID( "alice", - resourceURI: "easynet:///r/prv/reg/agent.alice/abilities/voice.stream@1" + resourceURA: "easynet:///r/prv/reg/agent.alice/abilities/voice.stream@1" ), "easynet:prv:reg:agent.alice" ) XCTAssertEqual( try principalToSubjectID( "alice", - resourceURI: "easynet:///r/org/reg/agent.alice/abilities/order.quote@1?tenant_id=tenant-test" + resourceURA: "easynet:///r/org/reg/agent.alice/abilities/order.quote@1?tenant_id=tenant-test" ), "easynet:org:reg:agent.alice" ) XCTAssertEqual( try principalToSubjectID( "easynet:pub:reg:agent.alice", - resourceURI: "easynet:///r/org/reg/agent.alice/abilities/order.quote@1?tenant_id=tenant-test" + resourceURA: "easynet:///r/org/reg/agent.alice/abilities/order.quote@1?tenant_id=tenant-test" ), "easynet:pub:reg:agent.alice" ) diff --git a/sdk/swift/Tests/EasyNetAxonTests/CrossLanguageVerifyTests.swift b/sdk/swift/Tests/EasyNetAxonTests/CrossLanguageVerifyTests.swift index da781197..f1d94886 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/CrossLanguageVerifyTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/CrossLanguageVerifyTests.swift @@ -128,11 +128,11 @@ final class CrossLanguageVerifyTests: XCTestCase { try writeKey(bundle, alias: "silan", seed: silanSeed) try writeKey(bundle, alias: "openai", seed: openaiSeed) - let silan = AgentIdentity(uri: "easynet:///r/silan/agents/writer@1", + let silan = AgentIdentity(ura: "easynet:///r/silan/agents/writer@1", profile: .easynetStrictV2) - let openai = AgentIdentity(uri: "easynet:///r/openai/agents/reviewer@1", + let openai = AgentIdentity(ura: "easynet:///r/openai/agents/reviewer@1", profile: .easynetStrictV2) - let paper = SubjectIdentity(uri: "easynet:///r/silan/papers/p@draft-1", + let paper = SubjectIdentity(ura: "easynet:///r/silan/papers/p@draft-1", profile: .easynetStrictV2) let envA = try InvocationEnvelope( @@ -154,7 +154,7 @@ final class CrossLanguageVerifyTests: XCTestCase { invocationNonce: Data(repeating: 0xBB, count: 16), causalContext: .scalar(try ReceiptRef( receiptHash: aTerminalHash, - receiptUri: "bundle:///receipts/inv-a/1" + receiptUra: "bundle:///receipts/inv-a/1" )) ) _ = try emitTwoReceiptChain( diff --git a/sdk/swift/Tests/EasyNetAxonTests/DendriteBridgeTests.swift b/sdk/swift/Tests/EasyNetAxonTests/DendriteBridgeTests.swift index cfe86bcc..71523fc1 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/DendriteBridgeTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/DendriteBridgeTests.swift @@ -65,7 +65,7 @@ final class DendriteBridgeTests: XCTestCase { let response = try bridge.abilityCallRaw( tenantID: "tenant-test", - resourceURI: "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", + resourceURA: "easynet:///r/org/reg/agent.quote-bot/abilities/order.quote@1?tenant_id=tenant-test", payloadJSON: .object(["sku": .string("A1")]), subjectID: "easynet:org:reg:agent.quote-bot" ) diff --git a/sdk/swift/Tests/EasyNetAxonTests/FederationConformanceTests.swift b/sdk/swift/Tests/EasyNetAxonTests/FederationConformanceTests.swift index 65b265f3..4c5fd0c3 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/FederationConformanceTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/FederationConformanceTests.swift @@ -24,23 +24,23 @@ final class FederationConformanceTests: XCTestCase { func testV1AdvertiseAgentMinimal() { let body = FederationBody.advertiseAgent( - agentURI: "axon://realm/foo", + agentURA: "easynet:///r/realm/agent/foo", publicKeyHex: nil, signingAuthority: nil ) - XCTAssertEqual(body, ["agent_uri": .string("axon://realm/foo")]) + XCTAssertEqual(body, ["agent_ura": .string("easynet:///r/realm/agent/foo")]) } // MARK: V2 — federation.advertise_agent, full func testV2AdvertiseAgentFull() { let body = FederationBody.advertiseAgent( - agentURI: "axon://realm/foo", + agentURA: "easynet:///r/realm/agent/foo", publicKeyHex: "deadbeef", signingAuthority: ["kind": .string("self_signed")] ) XCTAssertEqual(body, [ - "agent_uri": .string("axon://realm/foo"), + "agent_ura": .string("easynet:///r/realm/agent/foo"), "public_key_hex": .string("deadbeef"), "signing_authority": .object(["kind": .string("self_signed")]), ]) @@ -50,35 +50,35 @@ final class FederationConformanceTests: XCTestCase { func testV3AdvertiseAgentOmitEmpty() { let body = FederationBody.advertiseAgent( - agentURI: "axon://realm/foo", + agentURA: "easynet:///r/realm/agent/foo", publicKeyHex: "", signingAuthority: [:] ) - XCTAssertEqual(body, ["agent_uri": .string("axon://realm/foo")]) + XCTAssertEqual(body, ["agent_ura": .string("easynet:///r/realm/agent/foo")]) } // MARK: V5 — federation.revoke, no reason func testV5RevokeNoReason() { - let body = FederationBody.revoke(agentURI: "axon://realm/foo", reason: nil) - XCTAssertEqual(body, ["agent_uri": .string("axon://realm/foo")]) + let body = FederationBody.revoke(agentURA: "easynet:///r/realm/agent/foo", reason: nil) + XCTAssertEqual(body, ["agent_ura": .string("easynet:///r/realm/agent/foo")]) } // V5 also covers blank reasons being omitted. func testV5RevokeBlankReason() { - let body = FederationBody.revoke(agentURI: "axon://realm/foo", reason: " ") - XCTAssertEqual(body, ["agent_uri": .string("axon://realm/foo")]) + let body = FederationBody.revoke(agentURA: "easynet:///r/realm/agent/foo", reason: " ") + XCTAssertEqual(body, ["agent_ura": .string("easynet:///r/realm/agent/foo")]) } // MARK: V6 — federation.revoke, with reason func testV6RevokeWithReason() { let body = FederationBody.revoke( - agentURI: "axon://realm/foo", + agentURA: "easynet:///r/realm/agent/foo", reason: "operator: maintenance" ) XCTAssertEqual(body, [ - "agent_uri": .string("axon://realm/foo"), + "agent_ura": .string("easynet:///r/realm/agent/foo"), "reason": .string("operator: maintenance"), ]) } @@ -86,7 +86,7 @@ final class FederationConformanceTests: XCTestCase { // MARK: V7 — federation.resolve, no filter func testV7ResolveNoFilter() { - let body = FederationBody.resolve(agentURIPrefix: nil, includeAbilities: false) + let body = FederationBody.resolve(agentURAPrefix: nil, includeAbilities: false) XCTAssertEqual(body, [:]) } @@ -94,12 +94,12 @@ final class FederationConformanceTests: XCTestCase { func testV8ResolveWithFilter() { let body = FederationBody.resolve( - agentURIPrefix: "axon://realm/edge-", + agentURAPrefix: "easynet:///r/realm/agent/edge-", includeAbilities: true ) XCTAssertEqual(body, [ "filter": .object([ - "agent_uri_prefix": .string("axon://realm/edge-"), + "agent_ura_prefix": .string("easynet:///r/realm/agent/edge-"), "include_abilities": .bool(true), ]), ]) @@ -109,11 +109,11 @@ final class FederationConformanceTests: XCTestCase { func testV9AdvertiseAbilities() { let body = FederationBody.advertiseAbilities( - agentURI: "axon://realm/foo", + agentURA: "easynet:///r/realm/agent/foo", abilities: [["name": .string("echo")]] ) XCTAssertEqual(body, [ - "agent_uri": .string("axon://realm/foo"), + "agent_ura": .string("easynet:///r/realm/agent/foo"), "abilities": .array([.object(["name": .string("echo")])]), ]) } diff --git a/sdk/swift/Tests/EasyNetAxonTests/InvokeSignedTests.swift b/sdk/swift/Tests/EasyNetAxonTests/InvokeSignedTests.swift index ba24119a..0b426bec 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/InvokeSignedTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/InvokeSignedTests.swift @@ -9,11 +9,11 @@ import Foundation @testable import EasyNetAxon private let silan = AgentIdentity( - uri: "easynet:///r/silan/agents/t@1", + ura: "easynet:///r/silan/agents/t@1", profile: .easynetStrictV2 ) private let openai = AgentIdentity( - uri: "easynet:///r/openai/agents/t@1", + ura: "easynet:///r/openai/agents/t@1", profile: .easynetStrictV2 ) @@ -27,7 +27,7 @@ private func echoRuntime() -> LocalRuntime { private struct FixedResolver: KeyResolver { let raw: Data - func resolve(_ agentUri: String) throws -> Data { raw } + func resolve(_ agentUra: String) throws -> Data { raw } } final class InvokeSignedTests: XCTestCase { @@ -36,7 +36,7 @@ final class InvokeSignedTests: XCTestCase { let rt = echoRuntime() let seed = Data(repeating: 7, count: 32) let subject = SubjectIdentity( - uri: "easynet:///r/silan/papers/p@d1", + ura: "easynet:///r/silan/papers/p@d1", profile: .easynetStrictV2 ) let nonce = Data(repeating: 0xAB, count: 16) @@ -54,7 +54,7 @@ final class InvokeSignedTests: XCTestCase { let stored = rt.axiomEnvelopeOf(handle.invocationId) XCTAssertNotNil(stored, "envelope must be stored") - XCTAssertEqual(stored?.envelope.subject.uri, subject.uri) + XCTAssertEqual(stored?.envelope.subject.ura, subject.ura) XCTAssertEqual(stored?.envelope.invocationNonce, nonce) // Independent verification via the same seed → pubkey derivation. @@ -82,7 +82,7 @@ final class InvokeSignedTests: XCTestCase { signingSeed: Data(repeating: 8, count: 32), nonce: Data(repeating: 0x11, count: 16) ) - XCTAssertEqual(signed.envelope.subject.uri, signed.envelope.callee.uri) + XCTAssertEqual(signed.envelope.subject.ura, signed.envelope.callee.ura) XCTAssertEqual(signed.envelope.subject.profile, signed.envelope.callee.profile) } @@ -161,7 +161,7 @@ final class InvokeSignedTests: XCTestCase { let rt = echoRuntime() let seed = Data(repeating: 21, count: 32) let nonce = Data(repeating: 0x11, count: 16) - let subj = SubjectIdentity(uri: "easynet:///r/silan/papers/p@1", profile: .easynetStrictV2) + let subj = SubjectIdentity(ura: "easynet:///r/silan/papers/p@1", profile: .easynetStrictV2) let (_, signed) = try await rt.invokeSignedAsync( caller: silan, callee: openai, ability: "echo", payload: Data(), signingSeed: seed, subject: subj, nonce: nonce @@ -170,7 +170,7 @@ final class InvokeSignedTests: XCTestCase { caller: signed.envelope.caller, callee: signed.envelope.callee, subject: SubjectIdentity( - uri: "easynet:///r/mallory/papers/evil@1", profile: .easynetStrictV2), + ura: "easynet:///r/mallory/papers/evil@1", profile: .easynetStrictV2), ability: signed.envelope.ability, argsDigest: signed.envelope.argsDigest, invocationNonce: signed.envelope.invocationNonce, @@ -197,7 +197,7 @@ final class InvokeSignedTests: XCTestCase { signingSeed: seed, nonce: nonce ) let fakeRef = try ReceiptRef(receiptHash: Data(repeating: 0x99, count: 32), - receiptUri: "evil") + receiptUra: "evil") let tampered = try InvocationEnvelope( caller: signed.envelope.caller, callee: signed.envelope.callee, @@ -245,7 +245,7 @@ final class InvokeSignedTests: XCTestCase { let seed = Data(repeating: 25, count: 32) let nonce = Data(repeating: 0x44, count: 16) let subj = SubjectIdentity( - uri: "easynet:///r/silan/papers/p@stable", profile: .easynetStrictV2) + ura: "easynet:///r/silan/papers/p@stable", profile: .easynetStrictV2) let (handle, signed) = try await rt.invokeSignedAsync( caller: silan, callee: openai, ability: "echo", payload: Data("stable".utf8), diff --git a/sdk/swift/Tests/EasyNetAxonTests/ToolAdapterTests.swift b/sdk/swift/Tests/EasyNetAxonTests/ToolAdapterTests.swift index 45b3cc51..66d18a80 100644 --- a/sdk/swift/Tests/EasyNetAxonTests/ToolAdapterTests.swift +++ b/sdk/swift/Tests/EasyNetAxonTests/ToolAdapterTests.swift @@ -93,7 +93,7 @@ final class ToolAdapterTests: XCTestCase { XCTAssertTrue(export.abilityMD.contains("allowed-tools: Bash(*)")) XCTAssertTrue(export.invokeScript.contains("curl -sS -X POST")) XCTAssertEqual(spec.name, "screenshot-capture") - XCTAssertEqual(spec.resourceURI, "easynet:///r/org/screenshot-capture") + XCTAssertEqual(spec.resourceURA, "easynet:///r/org/screenshot-capture") } func testBuildDeployPackagePreservesAgentExtensions() throws {