diff --git a/crates/app/ironclaw_architecture_tests/tests/reborn_extension_specificity.rs b/crates/app/ironclaw_architecture_tests/tests/reborn_extension_specificity.rs index f1ce138dba5..42964d07bc8 100644 --- a/crates/app/ironclaw_architecture_tests/tests/reborn_extension_specificity.rs +++ b/crates/app/ironclaw_architecture_tests/tests/reborn_extension_specificity.rs @@ -1287,15 +1287,10 @@ const ALLOWLIST: &[(&str, &str)] = &[ "github", ), ("crates/ironclaw_assistant/src/workflow.rs", "slack"), - ("crates/ironclaw_host_api/src/dispatch.rs", "slack"), ( "crates/ironclaw_host_runtime/src/first_party_tools/schemas.rs", "slack", ), - ( - "crates/ironclaw_host_runtime/src/services/wasm_execution.rs", - "slack", - ), ("crates/ironclaw_loop_host/src/tool_disclosure.rs", "google"), ( "crates/ironclaw_loop_host/src/tool_disclosure.rs", @@ -1694,7 +1689,13 @@ const ALLOWLIST: &[(&str, &str)] = &[ // `loop_driver_host.rs`/"slack" carve-out was retired when the channel-context // forwarding it described was reworked, so its now-stale allowlist entry was // deleted — the ratchet only ever shrinks. -const WS0_EXTENSION_SPECIFICITY_ALLOWLIST_BASELINE: usize = 112; +// 112 -> 110 (retire lane-named DispatchError variants, PR 4 stage 1): the +// `ironclaw_host_api/src/dispatch.rs`/"slack" and +// `ironclaw_host_runtime/src/services/wasm_execution.rs`/"slack" carve-outs +// named doc-comment examples on the retired `DispatchError::Wasm` variant; +// deleting the variant deleted the examples, so the now-stale allowlist +// entries were deleted too. +const WS0_EXTENSION_SPECIFICITY_ALLOWLIST_BASELINE: usize = 110; /// §11.2.8 vendor-scope shrink, armed at the WS0 baseline. /// diff --git a/crates/app/ironclaw_architecture_tests/tests/reborn_retired_failure_vocabulary.rs b/crates/app/ironclaw_architecture_tests/tests/reborn_retired_failure_vocabulary.rs index bc9dd0a4b62..c033cddf6e2 100644 --- a/crates/app/ironclaw_architecture_tests/tests/reborn_retired_failure_vocabulary.rs +++ b/crates/app/ironclaw_architecture_tests/tests/reborn_retired_failure_vocabulary.rs @@ -45,13 +45,20 @@ const RETIRED_TYPES: &[&str] = &[ // retried), not free text that lets a producer skip classifying. "CapabilityFailureKindValue", "FailureKindValue", + "DispatchError::Mcp", + "DispatchError::Script", + "DispatchError::Wasm", + "DispatchError::FirstParty", + "DispatchErrorLane", + "dispatch_error_lane", + "ToolError::Failed", ]; // Crate paths are spelled flat (`crates/ironclaw_x/...`) and RESOLVED through // the crate inventory, so the family move (PROPOSAL section 5) repoints them // without editing the literals. Identity on today's tree - pinned by // `reborn_crate_inventory.rs` (CHECKLIST WS10). -use ratchet_support::{crate_path, workspace_root}; +use ratchet_support::{crate_path, strip_comments_and_strings, workspace_root}; /// Conversion helpers that existed only to move a value between two spellings /// of the same domain. Their absence is what proves the collapse is real @@ -79,55 +86,6 @@ const RETIRED_MAPPERS: &[&str] = &[ /// invent one. A retired type name inside a string literal would be /// stringly-typed handling of the exact domain this collapse made typed, so /// the blind spot is not worth a real parser. -fn strip_comments(source: &str) -> String { - let bytes = source.as_bytes(); - let mut out = String::with_capacity(source.len()); - let mut index = 0usize; - // Depth, not a bool: Rust block comments nest (`/* /* … */ still comment */`), - // so a bool would exit at the first `*/` and scan the tail as code. - let mut depth = 0usize; - while index < bytes.len() { - let byte = bytes[index]; - if depth > 0 { - if byte == b'/' && bytes.get(index + 1) == Some(&b'*') { - depth += 1; - out.push(' '); - out.push(' '); - index += 2; - continue; - } - if byte == b'*' && bytes.get(index + 1) == Some(&b'/') { - depth -= 1; - out.push(' '); - out.push(' '); - index += 2; - continue; - } - // Keep newlines so reported line numbers stay accurate. - out.push(if byte == b'\n' { '\n' } else { ' ' }); - index += 1; - continue; - } - if byte == b'/' && bytes.get(index + 1) == Some(&b'*') { - depth = 1; - out.push(' '); - out.push(' '); - index += 2; - continue; - } - if byte == b'/' && bytes.get(index + 1) == Some(&b'/') { - while index < bytes.len() && bytes[index] != b'\n' { - out.push(' '); - index += 1; - } - continue; - } - out.push(byte as char); - index += 1; - } - out -} - /// Scan one directory tree, failing loudly on anything unreadable. /// /// A gate that silently skips a path it cannot read is a gate that passes @@ -164,7 +122,7 @@ fn scan_dir(root: &Path, dir: &Path, hits: &mut Vec) -> std::io::Result< } let contents = std::fs::read_to_string(&path) .map_err(|error| std::io::Error::other(format!("read {relative}: {error}")))?; - for (number, line) in strip_comments(&contents).lines().enumerate() { + for (number, line) in strip_comments_and_strings(&contents).lines().enumerate() { if line.trim().is_empty() { continue; } @@ -207,7 +165,7 @@ fn the_surviving_failure_vocabulary_stays_closed() { .unwrap_or_else(|error| panic!("read {}: {error}", result_meta.display())); // Same rule as the scan above: prose explaining the retired open set is // worth keeping, so only code is policed. - let contents = strip_comments(&raw); + let contents = strip_comments_and_strings(&raw); assert!( contents.contains("Unclassified"), @@ -228,15 +186,65 @@ fn the_surviving_failure_vocabulary_stays_closed() { ); } +fn assert_tool_error_rejected_uses_runtime_kind(contents: &str) { + let rejected = contents + .split("pub enum ToolError") + .nth(1) + .expect("pub enum ToolError") + .split("Rejected {") + .nth(1) + .and_then(|tail| tail.split('}').next()) + .expect("ToolError::Rejected variant"); + + assert!( + rejected.contains("kind: RuntimeDispatchErrorKind"), + "extension adapters may report runtime failures only; trusted dispatch owns control-plane kinds" + ); + assert!( + !rejected.contains("DispatchFailureKind"), + "ToolError::Rejected must not accept the host's control-plane failure taxonomy" + ); +} + +#[test] +fn extension_tool_errors_cannot_mint_control_plane_failure_kinds() { + let root = workspace_root(); + let tool_adapter = crate_path( + &root, + "crates/ironclaw_extension_contracts/src/tool_adapter.rs", + ); + let raw = std::fs::read_to_string(&tool_adapter) + .unwrap_or_else(|error| panic!("read {}: {error}", tool_adapter.display())); + let contents = strip_comments_and_strings(&raw); + + assert_tool_error_rejected_uses_runtime_kind(&contents); +} + +#[test] +#[should_panic(expected = "extension adapters may report runtime failures only")] +fn extension_tool_error_scope_ratchet_rejects_malformed_source() { + let malformed = r#" + enum UnrelatedError { + Rejected { kind: RuntimeDispatchErrorKind }, + } + + pub enum ToolError { + Rejected { kind: DispatchFailureKind }, + } + "#; + + assert_tool_error_rejected_uses_runtime_kind(malformed); +} + /// The comment contract is a promise this gate makes to every file it scans, /// so it gets its own coverage rather than being trusted. A guardrail whose /// exemption rule is untested is a guardrail that silently changes meaning. #[cfg(test)] mod strip_comments_tests { - use super::strip_comments; + use super::strip_comments_and_strings; fn scans_as_code(source: &str, term: &str) -> bool { - strip_comments(source).contains(term) + strip_comments_and_strings(source).contains(term) } #[test] @@ -285,7 +293,8 @@ mod strip_comments_tests { #[test] fn line_numbers_survive_stripping() { // Hits are reported by line, so blanking must preserve newlines. - let stripped = strip_comments("/* one\ntwo\nthree */\npub enum CapabilityErrorClass {}"); + let stripped = + strip_comments_and_strings("/* one\ntwo\nthree */\npub enum CapabilityErrorClass {}"); let line = stripped .lines() .position(|line| line.contains("CapabilityErrorClass")) diff --git a/crates/contracts/ironclaw_extension_contracts/src/tool_adapter.rs b/crates/contracts/ironclaw_extension_contracts/src/tool_adapter.rs index 04c5efe2652..490897d02f1 100644 --- a/crates/contracts/ironclaw_extension_contracts/src/tool_adapter.rs +++ b/crates/contracts/ironclaw_extension_contracts/src/tool_adapter.rs @@ -12,6 +12,8 @@ //! in-process envelope the dispatcher builds per invocation; nothing here //! serializes. +use std::fmt; + use async_trait::async_trait; use ironclaw_host_api::{ @@ -20,12 +22,11 @@ use ironclaw_host_api::{ decision::RuntimeCredentialAuthRequirement, dispatch::{ CapabilityDisplayOutputPreview, DispatchAuthRequirement, DispatchFailureDetail, - DispatchFailureKind, ProviderDiagnostic, RuntimeDispatchErrorKind, + ProviderDiagnostic, RuntimeDispatchErrorKind, }, ids::{CapabilityId, SecretHandle}, mount::MountView, resource::{ResourceEstimate, ResourceReservation, ResourceScope}, - runtime::RuntimeKind, }; /// One invocation of one declared capability. @@ -67,8 +68,10 @@ pub struct ToolResult { /// Typed invocation failures. The host maps these onto the dispatch port's /// redacted failure categories; `AuthRequired` maps to the generic re-auth -/// gate and resumes through the standard blocked-turn flow. -#[derive(Debug, Clone, thiserror::Error)] +/// gate and resumes through the standard blocked-turn flow. All non-auth +/// failures use `Rejected`, preserving the runtime kind, provider diagnostic, +/// and any fixed host summary in one payload. +#[derive(Clone, thiserror::Error)] pub enum ToolError { #[error("tool invocation requires authorization")] AuthRequired { @@ -76,73 +79,82 @@ pub enum ToolError { }, #[error("tool provider rejected invocation ({kind})")] Rejected { - runtime: Option, - kind: DispatchFailureKind, + kind: RuntimeDispatchErrorKind, /// Provider-authored metadata remains typed so its `Debug` output is /// redacted until the host's model-diagnostic scrub/fence seam. diagnostic: Option>, + /// Structured failure detail carried across the adapter boundary. detail: Option, }, - #[error("tool invocation failed ({kind:?})")] - Failed { - kind: RuntimeDispatchErrorKind, - /// Fixed, host-authored text only — never interpolated payload data. - safe_summary: Option, - /// Raw-or-better failure cause for the model-visible Diagnostic seam - /// (#5965). Carried across the tool ABI verbatim and scrubbed - /// downstream (`scrub_model_visible_detail`) — NOT display-safe here; - /// never log or render it directly. - model_visible_cause: Option, - }, +} + +fn debug_redacted_option(value: &Option) -> &'static str { + if value.is_some() { + "" + } else { + "" + } +} + +impl fmt::Debug for ToolError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AuthRequired { requirement } => { + let required_secrets = format!( + "[{} handle(s) redacted]", + requirement.required_secrets.len() + ); + let credential_requirements = format!( + "[{} requirement(s) redacted]", + requirement.credential_requirements.len() + ); + formatter + .debug_struct("AuthRequired") + .field("required_secrets", &required_secrets) + .field("credential_requirements", &credential_requirements) + .field( + "model_visible_cause", + &debug_redacted_option(&requirement.model_visible_cause), + ) + .finish() + } + Self::Rejected { + kind, + diagnostic, + detail, + } => formatter + .debug_struct("Rejected") + .field("kind", kind) + .field("diagnostic", &debug_redacted_option(diagnostic)) + .field("detail", &debug_redacted_option(detail)) + .finish(), + } + } } impl PartialEq for ToolError { fn eq(&self, other: &Self) -> bool { match (self, other) { ( - Self::AuthRequired { - requirement: left_requirement, - }, - Self::AuthRequired { - requirement: right_requirement, - }, - ) => { - left_requirement.required_secrets == right_requirement.required_secrets - && left_requirement.credential_requirements - == right_requirement.credential_requirements - } - ( - Self::Failed { - kind: left_kind, - safe_summary: left_summary, - model_visible_cause: left_cause, - }, - Self::Failed { - kind: right_kind, - safe_summary: right_summary, - model_visible_cause: right_cause, - }, + Self::AuthRequired { requirement: left }, + Self::AuthRequired { requirement: right }, ) => { - left_kind == right_kind - && left_summary == right_summary - && left_cause == right_cause + left.required_secrets == right.required_secrets + && left.credential_requirements == right.credential_requirements } ( Self::Rejected { - runtime: left_runtime, kind: left_kind, diagnostic: left_diagnostic, detail: left_detail, }, Self::Rejected { - runtime: right_runtime, kind: right_kind, diagnostic: right_diagnostic, detail: right_detail, }, ) => { - left_runtime == right_runtime - && left_kind == right_kind + left_kind == right_kind && left_diagnostic == right_diagnostic && left_detail == right_detail } @@ -257,15 +269,26 @@ impl ToolCall { #[cfg(test)] mod tests { + use ironclaw_host_api::dispatch::RuntimeDispatchErrorKind; + use ironclaw_host_api::safe_summary::SafeSummary; + use super::*; - use ironclaw_host_api::dispatch::{DispatchInputIssue, DispatchInputIssueCode}; #[test] fn tool_error_display_stays_redacted() { - let error = ToolError::Failed { + let error = ToolError::Rejected { kind: RuntimeDispatchErrorKind::Backend, - safe_summary: Some("vendor API unavailable".to_string()), - model_visible_cause: None, + diagnostic: Some(Box::new(ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "vendor API unavailable", + )), + retry_after: None, + })), + detail: Some(DispatchFailureDetail::HostSummary { + summary: SafeSummary::new("vendor API unavailable").unwrap(), + detail: None, + }), }; let rendered = error.to_string(); assert!(rendered.contains("Backend"), "{rendered}"); @@ -273,48 +296,44 @@ mod tests { } #[test] - fn rejected_debug_redacts_nested_diagnostic_detail_but_keeps_input_detail() { - let marker = "TOOL_DIAGNOSTIC_SECRET_MARKER"; - let error = ToolError::Rejected { - runtime: Some(RuntimeKind::Wasm), - kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest), - diagnostic: None, + fn tool_error_debug_never_exposes_untrusted_failure_text() { + let rejected = ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Backend, + diagnostic: Some(Box::new(ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "provider-secret-message", + )), + retry_after: None, + })), detail: Some(DispatchFailureDetail::Diagnostic { - text: marker.to_string(), + text: "raw-detail-secret".to_string(), }), }; - let debug = format!("{error:?}"); - assert!(!debug.contains(marker), "diagnostic text leaked: {debug}"); - assert!( - debug.contains("Diagnostic"), - "detail kind was lost: {debug}" - ); - assert!( - debug.contains(""), - "redaction is not visible: {debug}" - ); + let rejected_debug = format!("{rejected:?}"); + assert!(rejected_debug.contains("Rejected"), "{rejected_debug}"); + assert!(rejected_debug.contains("Backend"), "{rejected_debug}"); + assert!(rejected_debug.contains("diagnostic"), "{rejected_debug}"); + assert!(rejected_debug.contains("detail"), "{rejected_debug}"); + assert!(!rejected_debug.contains("provider-secret-message")); + assert!(!rejected_debug.contains("raw-detail-secret")); - let useful = ToolError::Rejected { - runtime: Some(RuntimeKind::Wasm), - kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest), - diagnostic: None, - detail: Some(DispatchFailureDetail::InvalidInput { - issues: vec![ - DispatchInputIssue::new("/title", DispatchInputIssueCode::TypeMismatch) - .expected("string") - .received("integer"), - ], + let auth_required = ToolError::AuthRequired { + requirement: Box::new(DispatchAuthRequirement { + required_secrets: Vec::new(), + credential_requirements: Vec::new(), + model_visible_cause: Some(ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "auth-secret-message", + )), + retry_after: None, + }), }), }; - let useful_debug = format!("{useful:?}"); - assert!( - useful_debug.contains("/title"), - "input path was lost: {useful_debug}" - ); - assert!( - useful_debug.contains("string"), - "input detail was lost: {useful_debug}" - ); + let auth_debug = format!("{auth_required:?}"); + assert!(auth_debug.contains("AuthRequired"), "{auth_debug}"); + assert!(!auth_debug.contains("auth-secret-message")); } #[test] @@ -371,21 +390,20 @@ mod tests { } fn rejected( - kind: DispatchFailureKind, - diagnostic: Option>, + kind: RuntimeDispatchErrorKind, + diagnostic: Option, ) -> ToolError { ToolError::Rejected { - runtime: Some(RuntimeKind::FirstParty), kind, - diagnostic, + diagnostic: diagnostic.map(Box::new), detail: None, } } #[test] fn rejected_equality_compares_kind_and_diagnostic() { - let denied = DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::PolicyDenied); - let network_denied = DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied); + let denied = RuntimeDispatchErrorKind::PolicyDenied; + let network_denied = RuntimeDispatchErrorKind::NetworkDenied; assert_eq!( rejected(denied, None), @@ -400,11 +418,11 @@ mod tests { assert_ne!( rejected( denied, - Some(Box::new(ProviderDiagnostic { + Some(ProviderDiagnostic { code: None, message: None, retry_after: None, - })) + }) ), rejected(denied, None), "differing diagnostic presence must break equality" @@ -420,18 +438,12 @@ mod tests { model_visible_cause: None, }), }; - let failed = ToolError::Failed { + let rejected = ToolError::Rejected { kind: RuntimeDispatchErrorKind::Backend, - safe_summary: None, - model_visible_cause: None, + diagnostic: None, + detail: None, }; - assert_ne!(auth_required, failed); - } - - #[cfg(target_pointer_width = "64")] - #[test] - fn tool_error_stays_within_stack_budget() { - assert!(std::mem::size_of::() <= 56); + assert_ne!(auth_required, rejected); } } diff --git a/crates/contracts/ironclaw_host_api/src/dispatch.rs b/crates/contracts/ironclaw_host_api/src/dispatch.rs index b44fb61591f..294db7c62ee 100644 --- a/crates/contracts/ironclaw_host_api/src/dispatch.rs +++ b/crates/contracts/ironclaw_host_api/src/dispatch.rs @@ -22,6 +22,7 @@ use crate::{ ResourceEstimate, ResourceReceipt, ResourceReservation, ResourceScope, ResourceUsage, }, runtime::RuntimeKind, + safe_summary::SafeSummary, }; /// Stable provider error code supplied by a protocol decoder. @@ -68,9 +69,9 @@ pub struct ProviderDiagnostic { pub retry_after: Option, } -/// Authentication requirements carried across the dispatch and capability -/// error boundaries. The outer error variants box this aggregate so their -/// common vector payloads do not inflate every future that returns them. +/// Authentication requirements carried across dispatch and capability error +/// boundaries. The outer variants box this aggregate to keep error futures +/// compact as credential metadata grows. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DispatchAuthRequirement { pub required_secrets: Vec, @@ -200,7 +201,7 @@ pub enum DispatchInputIssueCode { } /// Stable input issue for dispatch validation failures. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct DispatchInputIssue { pub path: String, pub code: DispatchInputIssueCode, @@ -209,6 +210,19 @@ pub struct DispatchInputIssue { pub schema_path: Option, } +impl fmt::Debug for DispatchInputIssue { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("DispatchInputIssue") + .field("path", &self.path) + .field("code", &self.code) + .field("expected", &self.expected) + .field("received", &self.received.as_ref().map(|_| "")) + .field("schema_path", &self.schema_path) + .finish() + } +} + impl DispatchInputIssue { pub fn new(path: impl Into, code: DispatchInputIssueCode) -> Self { Self { @@ -264,6 +278,30 @@ pub enum DispatchFailureDetail { HostRemediation { text: HostRemediation, }, + /// Host-authored public label carried alongside a vendor/provider cause + /// riding [`DispatchError::Rejected`]'s `diagnostic` field — e.g. a + /// first-party capability's fixed rejection summary. + /// + /// Distinct from [`Self::Diagnostic`] (an internal-only raw cause) and + /// [`Self::HostRemediation`] (an operator remediation instruction): this + /// is the plain host-authored text that `ironclaw_capabilities`'s + /// `CapabilityInvocationError::from(DispatchError)` maps into the public + /// `safe_summary` field as its highest-precedence source. When present, + /// it wins over the vendor/provider cause riding `diagnostic` — the two + /// are never merged — so a caller with its own trusted label (e.g. a + /// first-party capability's fixed rejection summary) is guaranteed that + /// label reaches the user, not whatever vendor text happens to also be + /// attached. When this variant is absent, `safe_summary` falls back to + /// the vendor/provider diagnostic text (still validation-gated + /// downstream), and only then to the kind's fixed sentence — see + /// `CapabilityInvocationError::Dispatch`'s `safe_summary` field doc for + /// the full three-tier precedence. Carries no separate model-visible + /// representation; the loop projection drops it rather than duplicating + /// the safe-summary text into the diagnostic detail seam. + HostSummary { + summary: SafeSummary, + detail: Option>, + }, } impl fmt::Debug for DispatchFailureDetail { @@ -281,6 +319,11 @@ impl fmt::Debug for DispatchFailureDetail { .debug_struct("HostRemediation") .field("text", text) .finish(), + Self::HostSummary { summary, detail } => formatter + .debug_struct("HostSummary") + .field("summary", summary) + .field("detail", detail) + .finish(), } } } @@ -558,9 +601,9 @@ pub enum DispatchError { MissingProcessAuthorization { capability: CapabilityId }, /// Authentication is required to dispatch this capability. /// - /// `requirement.required_secrets` names the credentials the caller must - /// stage. The aggregate is intentionally redacted from `Debug` output to - /// avoid leaking secret-handle identifiers into logs. + /// `required_secrets` names the credentials the caller must stage. The + /// field is intentionally absent from the `Debug` output to avoid leaking + /// secret-handle identifiers into logs. #[error("capability {capability} dispatch requires authentication")] AuthRequired { capability: CapabilityId, @@ -575,40 +618,6 @@ pub enum DispatchError { diagnostic: Option>, detail: Option, }, - /// MCP dispatch failure. `model_visible_cause` carries the raw backend cause — - /// it is NOT yet display/model-safe: secret VALUES are scrubbed downstream - /// at the model-visible Diagnostic seam (`scrub_model_visible_detail`), - /// and display surfaces run their own redaction. Do not log or surface it - /// directly. - #[error("MCP dispatch failed: {kind}")] - Mcp { - kind: RuntimeDispatchErrorKind, - model_visible_cause: Option, - }, - /// Script dispatch failure. Same `model_visible_cause` contract as [`Self::Mcp`]: - /// raw cause, scrubbed downstream — not directly displayable. - #[error("script dispatch failed: {kind}")] - Script { - kind: RuntimeDispatchErrorKind, - model_visible_cause: Option, - }, - /// WASM guest dispatch failure. `model_visible_cause` carries the best available - /// cause: the stable, host-sanitized error code a structured guest error - /// declared (e.g. a Slack `channel_not_found`) when present, otherwise the - /// raw error text (secret VALUES are scrubbed downstream at the - /// model-visible Diagnostic seam), so the failure keeps its actionable - /// cause instead of collapsing to the kind's generic sentence. - #[error("WASM dispatch failed: {kind}")] - Wasm { - kind: RuntimeDispatchErrorKind, - model_visible_cause: Option, - }, - #[error("first-party dispatch failed: {kind}")] - FirstParty { - kind: RuntimeDispatchErrorKind, - safe_summary: Option, - detail: Option, - }, } impl fmt::Debug for DispatchError { @@ -683,6 +692,9 @@ impl fmt::Debug for DispatchError { ), ) .finish(), + // `DispatchFailureDetail`'s Debug implementation selectively + // preserves structured input issues while redacting raw + // provider/backend causes. Self::Rejected { runtime, kind, @@ -695,12 +707,6 @@ impl fmt::Debug for DispatchError { .field("detail", detail) .field("diagnostic", &"") .finish(), - Self::Mcp { kind, .. } => f.debug_struct("Mcp").field("kind", kind).finish(), - Self::Script { kind, .. } => f.debug_struct("Script").field("kind", kind).finish(), - Self::Wasm { kind, .. } => f.debug_struct("Wasm").field("kind", kind).finish(), - Self::FirstParty { kind, .. } => { - f.debug_struct("FirstParty").field("kind", kind).finish() - } } } } @@ -733,10 +739,6 @@ impl DispatchError { } Self::AuthRequired { .. } => DispatchFailureKind::AuthRequired, Self::Rejected { kind, .. } => *kind, - Self::Mcp { kind, .. } - | Self::Script { kind, .. } - | Self::Wasm { kind, .. } - | Self::FirstParty { kind, .. } => DispatchFailureKind::Runtime(*kind), } } @@ -759,10 +761,35 @@ impl DispatchError { DispatchFailureKind::Runtime(kind) => kind.event_kind(), _ => "provider_rejected", }, - Self::Mcp { kind, .. } - | Self::Script { kind, .. } - | Self::Wasm { kind, .. } - | Self::FirstParty { kind, .. } => kind.event_kind(), + } + } + + /// Builds a provider-rejection [`Self::Rejected`] from an optional cause + /// string. `cause` rides the typed diagnostic channel (#5965): + /// raw-or-better cause text, scrubbed downstream at the model-visible + /// Diagnostic seam. `detail` carries an optional structured + /// [`DispatchFailureDetail`] when the caller has one. + /// + /// This is the single construction site for cause-only provider + /// rejections; runtime-lane callers wrap it with a thin constant-runtime + /// helper rather than repeating the struct literal. + pub fn provider_rejected( + runtime: Option, + kind: DispatchFailureKind, + cause: Option, + detail: Option, + ) -> Self { + Self::Rejected { + runtime, + kind, + diagnostic: cause.map(|text| { + Box::new(ProviderDiagnostic { + code: None, + message: Some(UntrustedProviderMessage::new(text)), + retry_after: None, + }) + }), + detail, } } } @@ -840,9 +867,49 @@ mod tests { assert!(!format!("{diagnostic:?}").contains('é')); } - #[cfg(target_pointer_width = "64")] #[test] - fn dispatch_error_stays_within_stack_budget() { - assert!(std::mem::size_of::() <= 72); + fn dispatch_error_rejected_debug_redacts_diagnostic_detail_text() { + // `DispatchFailureDetail::Diagnostic { text }` carries an untrusted + // raw provider/backend cause (never-log content); the folded + // `Rejected` variant's Debug must not print it, matching the retired + // `FirstParty` variant's omission of the same content. + let error = DispatchError::Rejected { + runtime: Some(RuntimeKind::FirstParty), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::OperationFailed), + diagnostic: None, + detail: Some(DispatchFailureDetail::Diagnostic { + text: "leak-me-not: /secret/path token=abc123".to_string(), + }), + }; + + let debug_output = format!("{error:?}"); + assert!(!debug_output.contains("leak-me-not")); + assert!(!debug_output.contains("/secret/path")); + assert!(!debug_output.contains("abc123")); + } + + #[test] + fn dispatch_error_rejected_debug_keeps_structured_input_detail_visible() { + let error = DispatchError::Rejected { + runtime: Some(RuntimeKind::FirstParty), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::InputEncode), + diagnostic: None, + detail: Some(DispatchFailureDetail::InvalidInput { + issues: vec![ + DispatchInputIssue::new("schedule.kind", DispatchInputIssueCode::TypeMismatch) + .expected("string") + .received("secret-attacker-controlled-value") + .schema_path("/properties/schedule/kind"), + ], + }), + }; + + let debug_output = format!("{error:?}"); + assert!(debug_output.contains("InvalidInput")); + assert!(debug_output.contains("schedule.kind")); + assert!(debug_output.contains("TypeMismatch")); + assert!(debug_output.contains("string")); + assert!(debug_output.contains("/properties/schedule/kind")); + assert!(!debug_output.contains("secret-attacker-controlled-value")); } } diff --git a/crates/contracts/ironclaw_host_api/src/messaging.rs b/crates/contracts/ironclaw_host_api/src/messaging.rs index f81e02d44ee..c05722763be 100644 --- a/crates/contracts/ironclaw_host_api/src/messaging.rs +++ b/crates/contracts/ironclaw_host_api/src/messaging.rs @@ -584,9 +584,9 @@ impl StandardMessagingErrorCode { Self::VendorError, ]; - /// The `messaging.*`-namespaced wire code carried on the structured WASM - /// guest error channel (`{code, kind}`) or a first-party `ToolError::Failed` - /// safe summary. + /// The `messaging.*`-namespaced wire code carried by the structured WASM + /// guest failure or a first-party `ToolError::Rejected` provider + /// diagnostic. The host recognizes only exact members of [`Self::ALL`]. pub fn as_str(&self) -> &'static str { match self { Self::UnknownConversation => "messaging.unknown_conversation", diff --git a/crates/contracts/ironclaw_host_api/src/runtime.rs b/crates/contracts/ironclaw_host_api/src/runtime.rs index 87562ee3a01..bb3337c3760 100644 --- a/crates/contracts/ironclaw_host_api/src/runtime.rs +++ b/crates/contracts/ironclaw_host_api/src/runtime.rs @@ -61,41 +61,6 @@ impl std::fmt::Display for RuntimeKind { } } -/// Which `DispatchError` variant family a [`RuntimeKind`]'s failures route -/// to. -/// -/// Several crates each classify a `RuntimeKind` into the matching -/// `DispatchError` shape and were independently hand-editing four copies of -/// this match every time a `RuntimeKind` variant was added (see the -/// `Sandbox` addition). This type centralizes the *classification* only — -/// each call site still builds its own `DispatchError` value (different -/// payload fields, different fallback logic), because `DispatchError` -/// construction genuinely differs by call site. Living beside `RuntimeKind` -/// means a new variant here is a single compile error, not four silent -/// misses. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DispatchErrorLane { - Wasm, - Mcp, - Script, - FirstParty, -} - -impl RuntimeKind { - /// Classify this runtime into its `DispatchError` lane. Exhaustive over - /// `RuntimeKind` with no catch-all: adding a new variant forces this - /// match to be updated here, not silently misclassified at four call - /// sites. - pub const fn dispatch_error_lane(self) -> DispatchErrorLane { - match self { - Self::Wasm => DispatchErrorLane::Wasm, - Self::Mcp => DispatchErrorLane::Mcp, - Self::Script | Self::Sandbox => DispatchErrorLane::Script, - Self::FirstParty | Self::System => DispatchErrorLane::FirstParty, - } - } -} - /// Trusted deserialization for [`RuntimeKind`] on **durable host-written /// records** (e.g. the process store's `ProcessRecord`). It accepts **every** /// variant — including the host-assigned `FirstParty` / `System` that the @@ -234,29 +199,4 @@ mod tests { assert!(serde_json::from_str::("\"mcp\"").is_ok()); assert!(serde_json::from_str::("\"script\"").is_ok()); } - - // Regression: this canonical mapping replaced four independently - // hand-maintained `RuntimeKind` -> `DispatchError` match arms - // (ironclaw_capabilities::dispatch/registry, - // ironclaw_extension_host::resolver, ironclaw_host_runtime's - // runtime_adapters) that all had to be hand-edited when `Sandbox` was - // added. Pin the classification for every `RuntimeKind` variant here so - // the next variant is a compile error in exactly one place. - #[test] - fn dispatch_error_lane_covers_every_runtime_kind() { - for (kind, expected) in [ - (RuntimeKind::Wasm, DispatchErrorLane::Wasm), - (RuntimeKind::Mcp, DispatchErrorLane::Mcp), - (RuntimeKind::Script, DispatchErrorLane::Script), - (RuntimeKind::Sandbox, DispatchErrorLane::Script), - (RuntimeKind::FirstParty, DispatchErrorLane::FirstParty), - (RuntimeKind::System, DispatchErrorLane::FirstParty), - ] { - assert_eq!( - kind.dispatch_error_lane(), - expected, - "{kind} classified into the wrong DispatchError lane" - ); - } - } } diff --git a/crates/contracts/ironclaw_host_api/tests/host_api_contract.rs b/crates/contracts/ironclaw_host_api/tests/host_api_contract.rs index 0ecf4b63448..59e0eb9c10f 100644 --- a/crates/contracts/ironclaw_host_api/tests/host_api_contract.rs +++ b/crates/contracts/ironclaw_host_api/tests/host_api_contract.rs @@ -15,8 +15,8 @@ use ironclaw_host_api::{ RuntimeCredentialAuthRequirement, }, dispatch::{ - DispatchAuthRequirement, DispatchError, DispatchFailureDetail, DispatchFailureKind, - DispatchInputIssue, DispatchInputIssueCode, RuntimeDispatchErrorKind, + DispatchAuthRequirement, DispatchError, DispatchFailureKind, DispatchInputIssueCode, + RuntimeDispatchErrorKind, }, error::HostApiError, host_port::{ @@ -436,9 +436,11 @@ fn dispatch_errors_preserve_typed_failure_kind() { DispatchFailureKind::UnsupportedRuntime ); assert_eq!( - DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Guest, - model_visible_cause: None, + DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest), + diagnostic: None, + detail: None, } .failure_kind(), DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest) @@ -1933,48 +1935,3 @@ fn dispatch_error_auth_required_debug_redacts_required_secrets() { "provider id must not appear in Debug output; got: {debug_with_requirement}" ); } - -#[test] -fn dispatch_error_rejected_debug_redacts_only_diagnostic_detail() { - let marker = "DISPATCH_DIAGNOSTIC_SECRET_MARKER"; - let error = DispatchError::Rejected { - runtime: Some(RuntimeKind::Wasm), - kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest), - diagnostic: None, - detail: Some(DispatchFailureDetail::Diagnostic { - text: marker.to_string(), - }), - }; - let debug = format!("{error:?}"); - assert!(!debug.contains(marker), "diagnostic text leaked: {debug}"); - assert!( - debug.contains("Diagnostic"), - "detail kind was lost: {debug}" - ); - assert!( - debug.contains(""), - "redaction is not visible: {debug}" - ); - - let useful = DispatchError::Rejected { - runtime: Some(RuntimeKind::Wasm), - kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest), - diagnostic: None, - detail: Some(DispatchFailureDetail::InvalidInput { - issues: vec![ - DispatchInputIssue::new("/title", DispatchInputIssueCode::TypeMismatch) - .expected("string") - .received("integer"), - ], - }), - }; - let useful_debug = format!("{useful:?}"); - assert!( - useful_debug.contains("/title"), - "input path was lost: {useful_debug}" - ); - assert!( - useful_debug.contains("string"), - "input detail was lost: {useful_debug}" - ); -} diff --git a/crates/extensions/ironclaw_extension_host/src/generic_host.rs b/crates/extensions/ironclaw_extension_host/src/generic_host.rs index deab91be51b..febaf6056b5 100644 --- a/crates/extensions/ironclaw_extension_host/src/generic_host.rs +++ b/crates/extensions/ironclaw_extension_host/src/generic_host.rs @@ -40,8 +40,8 @@ use ironclaw_extension_registry::{ ExtensionInstallationError, ExtensionInstallationStorePort, ExtensionManifest, ExtensionPackage, ResolvedExtensionManifest, }; -use ironclaw_host_api::ids::ExtensionId; use ironclaw_host_api::path::VirtualPath; +use ironclaw_host_api::{dispatch::RuntimeDispatchErrorKind, ids::ExtensionId}; use ironclaw_host_runtime::{ExtensionLaneToolBinder, ExtensionToolBindError}; use ironclaw_resources::ResourceGovernor; @@ -660,14 +660,17 @@ impl ToolAdapter for SettlingToolAdapter { let reservation = call.resources.reservation.take(); let reservation = match reservation { Some(reservation) => reservation, - None => self - .governor - .reserve(scope, estimate) - .map_err(|_| ToolError::Failed { - kind: ironclaw_host_api::dispatch::RuntimeDispatchErrorKind::Resource, - safe_summary: None, - model_visible_cause: None, - })?, + None => self.governor.reserve(scope, estimate).map_err(|error| { + // The tool boundary deliberately exposes only the stable + // resource failure class. Keep the governor's cause in the + // host log before it is redacted from the adapter result. + tracing::warn!(%error, "native extension tool resource reservation failed"); + ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Resource, + diagnostic: None, + detail: None, + } + })?, }; match self.inner.invoke(call, ports).await { Ok(result) => { diff --git a/crates/extensions/ironclaw_extension_host/src/resolver.rs b/crates/extensions/ironclaw_extension_host/src/resolver.rs index 1ebdefc4917..7ed87a7a864 100644 --- a/crates/extensions/ironclaw_extension_host/src/resolver.rs +++ b/crates/extensions/ironclaw_extension_host/src/resolver.rs @@ -27,10 +27,12 @@ use ironclaw_extension_contracts::tool_adapter::{ ToolCall, ToolCallResources, ToolError, ToolPorts, }; use ironclaw_host_api::{ - dispatch::{DispatchError, DispatchFailureDetail, RuntimeDispatchErrorKind}, + dispatch::{DispatchError, DispatchFailureDetail, DispatchFailureKind, ProviderDiagnostic}, ids::{CapabilityId, ExtensionId}, + messaging::StandardMessagingErrorCode, resource::{ReservationStatus, ResourceReceipt, ResourceUsage}, - runtime::{DispatchErrorLane, RuntimeKind}, + runtime::RuntimeKind, + safe_summary::SafeSummary, }; use crate::active::ResolvedToolBinding; @@ -142,91 +144,131 @@ fn dispatch_error_for_tool_error( requirement, }, ToolError::Rejected { - runtime, - kind, - diagnostic, - detail, - } => DispatchError::Rejected { - runtime, kind, diagnostic, detail, - }, - ToolError::Failed { - kind, - safe_summary, - model_visible_cause, - } => dispatch_error_for_kind(runtime, kind, safe_summary, model_visible_cause), + .. + } => { + let messaging_code = standard_messaging_code(diagnostic.as_deref()); + DispatchError::Rejected { + // Runtime provenance belongs to the trusted resolved binding, + // not to the extension-supplied error payload. + runtime: Some(runtime), + kind: DispatchFailureKind::Runtime(kind), + diagnostic, + detail: dispatch_detail_for_tool_error(messaging_code, detail), + } + } } } -fn dispatch_error_for_kind( - runtime: RuntimeKind, - kind: RuntimeDispatchErrorKind, - safe_summary: Option, - model_visible_cause: Option, -) -> DispatchError { - match runtime.dispatch_error_lane() { - // The lane variants carry the cause on `model_visible_cause` (#5965): - // raw-or-better cause text, scrubbed downstream at the model-visible - // Diagnostic seam. When an adapter supplied only a fixed host-authored - // summary, that text is trivially cause-safe, so it rides the same - // channel rather than being dropped. - DispatchErrorLane::Wasm => DispatchError::Wasm { - kind, - model_visible_cause: model_visible_cause.or(safe_summary), - }, - DispatchErrorLane::Mcp => DispatchError::Mcp { - kind, - model_visible_cause: model_visible_cause.or(safe_summary), - }, - DispatchErrorLane::Script => DispatchError::Script { - kind, - model_visible_cause: model_visible_cause.or(safe_summary), - }, - // FirstParty/System carry the raw cause on the Diagnostic detail - // channel (untrusted-provenance text, scrubbed downstream) rather than - // dropping it — the lane arms' `model_visible_cause` equivalent for the - // detail-shaped variant. A fixed host-authored summary, if that is all - // the adapter gave, still travels on `safe_summary`. - DispatchErrorLane::FirstParty => DispatchError::FirstParty { - kind, - safe_summary, - detail: model_visible_cause.map(|text| DispatchFailureDetail::Diagnostic { text }), - }, +/// Resolve the only trusted text an extension may select — a closed standard +/// messaging code — after the adapter boundary. Raw host-summary variants are +/// intentionally discarded here because an extension cannot attest to host +/// authorship. Other detail variants retain their existing untrusted/typed +/// semantics and continue through the downstream scrubbers. +fn dispatch_detail_for_tool_error( + messaging_code: Option, + detail: Option, +) -> Option { + messaging_code + .map(trusted_standard_messaging_summary) + .or_else(|| extension_detail_without_host_summary(detail)) +} + +/// Recognize only an exact member of the closed standard-messaging code set. +/// Provider text never undergoes substring or keyword interpretation here. +fn standard_messaging_code( + diagnostic: Option<&ProviderDiagnostic>, +) -> Option { + let code = diagnostic?.code.as_ref()?.as_str(); + StandardMessagingErrorCode::ALL + .iter() + .copied() + .find(|candidate| candidate.as_str() == code) +} + +fn trusted_standard_messaging_summary(code: StandardMessagingErrorCode) -> DispatchFailureDetail { + let summary = match SafeSummary::new(format!("messaging operation failed: {}", code.as_str())) { + Ok(summary) => summary, + Err(_) => SafeSummary::placeholder(), + }; + DispatchFailureDetail::HostSummary { + summary, + detail: None, + } +} + +fn extension_detail_without_host_summary( + detail: Option, +) -> Option { + match detail { + Some(DispatchFailureDetail::HostSummary { .. }) + | Some(DispatchFailureDetail::HostRemediation { .. }) => None, + other => other, } } #[cfg(test)] mod tests { use super::*; + use ironclaw_host_api::{ + dispatch::RuntimeDispatchErrorKind, messaging::StandardMessagingErrorCode, + }; fn cause_of(error: &DispatchError) -> Option<&str> { match error { - DispatchError::Wasm { - model_visible_cause, - .. - } - | DispatchError::Mcp { - model_visible_cause, - .. - } - | DispatchError::Script { - model_visible_cause, - .. - } => model_visible_cause.as_deref(), - DispatchError::FirstParty { - detail: Some(DispatchFailureDetail::Diagnostic { text }), + DispatchError::Rejected { + diagnostic: Some(diagnostic), .. - } => Some(text.as_str()), + } => diagnostic.message.as_ref().map(|message| message.as_str()), _ => None, } } - /// The generic extension lanes must carry a failing adapter's - /// `model_visible_cause` across the tool ABI onto the dispatch error — - /// including the FirstParty/System arm, which routes it to the Diagnostic - /// detail channel rather than dropping it (#5965 on the extension path). + #[test] + fn standard_messaging_code_becomes_a_host_summary_at_the_resolver_boundary() { + let cap = CapabilityId::new("telegram.send_message").unwrap(); + let dispatch = dispatch_error_for_tool_error( + &cap, + RuntimeKind::FirstParty, + ToolError::Rejected { + kind: RuntimeDispatchErrorKind::OperationFailed, + diagnostic: Some(Box::new(ironclaw_host_api::dispatch::ProviderDiagnostic { + code: Some(ironclaw_host_api::dispatch::ProviderErrorCode::new( + StandardMessagingErrorCode::RateLimited.as_str(), + )), + message: None, + retry_after: None, + })), + detail: None, + }, + ); + let DispatchError::Rejected { detail, .. } = dispatch else { + panic!("expected Rejected dispatch error"); + }; + assert!(matches!( + detail, + Some(ironclaw_host_api::dispatch::DispatchFailureDetail::HostSummary { + summary, + detail: None, + }) if summary.as_str().contains(StandardMessagingErrorCode::RateLimited.as_str()) + )); + } + + #[test] + fn extension_host_remediation_is_not_trusted_at_the_resolver_boundary() { + let detail = DispatchFailureDetail::HostRemediation { + text: ironclaw_host_api::host_remediation::HostRemediation::new("connect the account") + .unwrap(), + }; + + assert!(extension_detail_without_host_summary(Some(detail)).is_none()); + } + + /// The generic extension lanes must carry a provider diagnostic across the + /// tool ABI onto the dispatch error — including the FirstParty/System arm, + /// which routes it to the diagnostic channel rather than dropping it. #[test] fn tool_error_cause_survives_every_lane() { let cap = CapabilityId::new("acme.cap").unwrap(); @@ -237,10 +279,16 @@ mod tests { RuntimeKind::FirstParty, RuntimeKind::System, ] { - let error = ToolError::Failed { + let error = ToolError::Rejected { kind: RuntimeDispatchErrorKind::Backend, - safe_summary: None, - model_visible_cause: Some("channel_not_found".to_string()), + diagnostic: Some(Box::new(ironclaw_host_api::dispatch::ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "channel_not_found", + )), + retry_after: None, + })), + detail: None, }; let dispatch = dispatch_error_for_tool_error(&cap, runtime, error); assert_eq!( @@ -251,19 +299,98 @@ mod tests { } } - /// When the adapter supplied only a fixed host-authored `safe_summary` - /// (no raw cause), the lane arms still surface it on the cause channel so - /// the failure keeps an actionable label instead of collapsing to the - /// kind's generic sentence. + /// An adapter cannot attest to host authorship, so a summary supplied in + /// the tool error is discarded when no closed standard code is present. #[test] - fn lane_summary_rides_the_cause_channel_when_no_raw_cause() { + fn lane_summary_is_dropped_when_no_closed_code_is_present() { let cap = CapabilityId::new("acme.cap").unwrap(); - let error = ToolError::Failed { + let error = ToolError::Rejected { kind: RuntimeDispatchErrorKind::Backend, - safe_summary: Some("vendor unavailable".to_string()), - model_visible_cause: None, + diagnostic: None, + detail: Some( + ironclaw_host_api::dispatch::DispatchFailureDetail::HostSummary { + summary: ironclaw_host_api::safe_summary::SafeSummary::new( + "vendor unavailable", + ) + .unwrap(), + detail: None, + }, + ), }; let dispatch = dispatch_error_for_tool_error(&cap, RuntimeKind::Wasm, error); - assert_eq!(cause_of(&dispatch), Some("vendor unavailable")); + let DispatchError::Rejected { + diagnostic, detail, .. + } = dispatch + else { + panic!("expected Rejected dispatch error"); + }; + assert!(diagnostic.is_none()); + assert!(detail.is_none()); + } + + #[test] + fn rejected_tool_error_drops_extension_summary_but_keeps_vendor_cause() { + let cap = CapabilityId::new("acme.cap").unwrap(); + let dispatch = dispatch_error_for_tool_error( + &cap, + RuntimeKind::FirstParty, + ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Backend, + diagnostic: Some(Box::new(ironclaw_host_api::dispatch::ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "vendor backend returned 503", + )), + retry_after: None, + })), + detail: Some( + ironclaw_host_api::dispatch::DispatchFailureDetail::HostSummary { + summary: ironclaw_host_api::safe_summary::SafeSummary::new( + "the tool's backend failed", + ) + .unwrap(), + detail: None, + }, + ), + }, + ); + + let DispatchError::Rejected { + runtime, + diagnostic, + detail, + .. + } = dispatch + else { + panic!("expected Rejected dispatch error"); + }; + assert_eq!(runtime, Some(RuntimeKind::FirstParty)); + assert_eq!( + diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.message.as_ref()) + .map(|message| message.as_str()), + Some("vendor backend returned 503") + ); + assert!(detail.is_none()); + } + + #[test] + fn rejected_tool_error_runtime_comes_from_the_outer_binding() { + let cap = CapabilityId::new("acme.cap").unwrap(); + let dispatch = dispatch_error_for_tool_error( + &cap, + RuntimeKind::FirstParty, + ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Backend, + diagnostic: None, + detail: None, + }, + ); + + let DispatchError::Rejected { runtime, .. } = dispatch else { + panic!("expected Rejected dispatch error"); + }; + assert_eq!(runtime, Some(RuntimeKind::FirstParty)); } } diff --git a/crates/extensions/ironclaw_extension_host/tests/lifecycle_contract.rs b/crates/extensions/ironclaw_extension_host/tests/lifecycle_contract.rs index 501c470652c..74892281075 100644 --- a/crates/extensions/ironclaw_extension_host/tests/lifecycle_contract.rs +++ b/crates/extensions/ironclaw_extension_host/tests/lifecycle_contract.rs @@ -660,7 +660,6 @@ async fn snapshot_resolver_maps_tool_auth_required_to_the_generic_gate() { DispatchError::AuthRequired { capability, requirement, - .. } => { assert_eq!(capability.as_str(), "acme.ping"); assert_eq!(requirement.required_secrets.len(), 1); @@ -687,11 +686,10 @@ async fn snapshot_resolver_preserves_typed_provider_rejection() { }; use ironclaw_host_api::{ dispatch::{ - DispatchError, DispatchFailureKind, ProviderDiagnostic, ProviderErrorCode, - RuntimeDispatchErrorKind, UntrustedProviderMessage, + DispatchError, ProviderDiagnostic, ProviderErrorCode, RuntimeDispatchErrorKind, + UntrustedProviderMessage, }, ids::CapabilityId, - runtime::RuntimeKind, }; struct RejectingAdapter; @@ -704,8 +702,7 @@ async fn snapshot_resolver_preserves_typed_provider_rejection() { _ports: &ToolPorts<'_>, ) -> Result { Err(ToolError::Rejected { - runtime: Some(RuntimeKind::Mcp), - kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Client), + kind: RuntimeDispatchErrorKind::Client, diagnostic: Some(Box::new(ProviderDiagnostic { code: Some(ProviderErrorCode::new("mcp_tool_rejected")), message: Some(UntrustedProviderMessage::new("Bad credentials")), diff --git a/crates/extensions/packages/github/wasm-src/src/lib.rs b/crates/extensions/packages/github/wasm-src/src/lib.rs index 341b5da169e..086b328524d 100644 --- a/crates/extensions/packages/github/wasm-src/src/lib.rs +++ b/crates/extensions/packages/github/wasm-src/src/lib.rs @@ -24,14 +24,17 @@ struct GitHubTool; impl exports::near::agent::tool::Guest for GitHubTool { fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response { match dispatch::execute_inner(&req.params, req.context.as_deref()) { - Ok(result) => exports::near::agent::tool::Response { - output: Some(result), - error: None, - }, - Err(error) => exports::near::agent::tool::Response { - output: None, - error: Some(guest_error_payload(&error)), - }, + Ok(result) => exports::near::agent::tool::Response::Success(result), + Err(error) => { + let message = request::take_last_error_message(); + exports::near::agent::tool::Response::Failure( + exports::near::agent::tool::GuestFailure { + kind: guest_error_kind(&error), + code: Some(error), + message, + }, + ) + } } } @@ -45,36 +48,11 @@ impl exports::near::agent::tool::Guest for GitHubTool { } } -fn guest_error_payload(error: &str) -> String { - if is_structured_error_envelope(error) { - return error.to_string(); - } - serde_json::json!({ - "code": error, - "kind": guest_error_kind(error), - }) - .to_string() -} +fn guest_error_kind(code: &str) -> exports::near::agent::tool::ErrorKind { + use exports::near::agent::tool::ErrorKind; -/// A handful of error origins (currently only the 401 path in -/// `request::unauthorized_error_payload`) pre-build the full `{code, kind, -/// message}` envelope so they can carry a provider `message` alongside the -/// stable code. Detect that shape here and pass it through unchanged instead -/// of re-wrapping it as `{"code": "", "kind": ...}`. -fn is_structured_error_envelope(error: &str) -> bool { - serde_json::from_str::(error) - .ok() - .and_then(|value| { - value - .as_object() - .map(|object| object.contains_key("code") && object.contains_key("kind")) - }) - .unwrap_or(false) -} - -fn guest_error_kind(code: &str) -> &'static str { match code { - "AuthRequired" => "auth_required", + "AuthRequired" => ErrorKind::AuthRequired, "missing_invocation_context" | "invalid_invocation_context" | "unsupported_github_capability" @@ -105,15 +83,15 @@ fn guest_error_kind(code: &str) -> &'static str { | "Invalid path: empty segment not allowed" | "Unsupported from_ref: use a branch or tag ref, not a raw commit SHA" | "Unsupported from_ref: only refs/heads/* and refs/tags/* are supported" - | "Source ref response missing object.sha" => "input", - code if is_string_validation_input_error(code) => "input", - "github_api_body_limit" => "output_too_large", - "github_api_timeout" => "executor", - "github_api_egress_denied" | "github_api_redirect_denied" => "network_denied", - "github_api_error_status_401" => "auth_required", - "github_api_error_status_422_validation" => "input", - "github_api_error_status_403" | "github_api_error_status_429" => "client", - _ => "operation_failed", + | "Source ref response missing object.sha" => ErrorKind::Input, + code if is_string_validation_input_error(code) => ErrorKind::Input, + "github_api_body_limit" => ErrorKind::OutputTooLarge, + "github_api_timeout" => ErrorKind::Executor, + "github_api_egress_denied" | "github_api_redirect_denied" => ErrorKind::NetworkDenied, + "github_api_error_status_401" => ErrorKind::AuthRequired, + "github_api_error_status_422_validation" => ErrorKind::Input, + "github_api_error_status_403" | "github_api_error_status_429" => ErrorKind::Client, + _ => ErrorKind::OperationFailed, } } @@ -128,39 +106,16 @@ export!(GitHubTool); #[cfg(test)] mod tests { use super::guest_error_kind; - use super::guest_error_payload; use super::GitHubTool; use crate::dispatch::{action_from_context, execute_inner}; use crate::exports::near::agent::tool::Guest; - use crate::request::{sanitize_host_error, test_support, unauthorized_error_payload}; + use crate::request::test_support; use crate::types::{GitHubAction, GitHubWebhookRequest}; use crate::validation::{normalize_ref_lookup, validate_repo_path}; use crate::webhook::handle_webhook; use serde_json::json; use std::collections::HashMap; - #[test] - fn guest_error_payload_passes_through_a_structured_401_envelope_with_message() { - let error = unauthorized_error_payload(br#"{"message":"Bad credentials"}"#); - - let payload = guest_error_payload(&error); - - let value: serde_json::Value = serde_json::from_str(&payload).expect("valid json"); - assert_eq!(value["code"], "github_api_error_status_401"); - assert_eq!(value["kind"], "auth_required"); - assert_eq!(value["message"], "Bad credentials"); - } - - #[test] - fn guest_error_payload_wraps_legacy_plain_codes_unchanged() { - let payload = guest_error_payload("github_api_error_status_403"); - - let value: serde_json::Value = serde_json::from_str(&payload).expect("valid json"); - assert_eq!(value["code"], "github_api_error_status_403"); - assert_eq!(value["kind"], "client"); - assert!(value.get("message").is_none()); - } - #[test] fn operation_comes_from_host_context_not_param_shape() { assert_eq!( @@ -313,36 +268,10 @@ mod tests { ); } - #[test] - fn sanitizes_host_egress_errors_without_leaking_details() { - assert_eq!( - sanitize_host_error("missing token ghp_secret_value"), - "AuthRequired" - ); - assert_eq!( - sanitize_host_error("deadline exceeded"), - "github_api_timeout" - ); - assert_eq!( - sanitize_host_error("redirect blocked"), - "github_api_redirect_denied" - ); - assert_eq!( - sanitize_host_error("response body too large"), - "github_api_body_limit" - ); - assert_eq!( - sanitize_host_error("host not allowed"), - "github_api_egress_denied" - ); - assert_eq!( - sanitize_host_error("connection reset with token ghp_secret_value"), - "AuthRequired" - ); - } - #[test] fn guest_error_kind_classifies_string_validation_errors_as_input() { + use crate::exports::near::agent::tool::ErrorKind; + for code in [ "Invalid labels: values cannot be empty", "Invalid assignees: values cannot be empty", @@ -351,15 +280,17 @@ mod tests { "invalid_comments: comments serialization failed", "github_api_error_status_422_validation", ] { - assert_eq!(guest_error_kind(code), "input", "{code}"); + assert_eq!(guest_error_kind(code), ErrorKind::Input, "{code}"); } } #[test] fn guest_error_kind_does_not_classify_generic_422_as_input() { + use crate::exports::near::agent::tool::ErrorKind; + assert_eq!( guest_error_kind("github_api_error_status_422"), - "operation_failed" + ErrorKind::OperationFailed ); } diff --git a/crates/extensions/packages/github/wasm-src/src/request.rs b/crates/extensions/packages/github/wasm-src/src/request.rs index c2eb6ccb917..a052b9bf7ce 100644 --- a/crates/extensions/packages/github/wasm-src/src/request.rs +++ b/crates/extensions/packages/github/wasm-src/src/request.rs @@ -5,6 +5,33 @@ const GITHUB_API_VERSION: &str = "2026-03-10"; #[cfg(not(test))] const HTTP_TIMEOUT_MS: u32 = 10_000; +thread_local! { + /// The provider's bounded `message` field from the most recent `401` + /// GitHub API response body, if any. `github_request` stashes it here + /// immediately before returning its `Err(code)` so `lib.rs::execute` + /// can attach it to the typed `guest-failure.message` alongside the + /// stable `code` for the auth-required diagnostic the host carries onto + /// the auth gate — the host scrubs and bounds it before it becomes + /// guest-visible, so this only needs to carry the raw text out. Scoped + /// to `401` only: other provider error bodies are not validated end to + /// end onto a model-visible surface and echoing them verbatim would + /// widen what a guest-authored response body can put in front of the + /// model without the same scrutiny. + static LAST_ERROR_MESSAGE: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Take (and clear) the provider message captured alongside the most recent +/// `github_request` error, if any. +pub(crate) fn take_last_error_message() -> Option { + LAST_ERROR_MESSAGE.with(|cell| cell.borrow_mut().take()) +} + +fn set_last_error_message(body: &[u8]) { + let message = provider_error_message(body); + LAST_ERROR_MESSAGE.with(|cell| *cell.borrow_mut() = message); +} + #[cfg(not(test))] pub(crate) fn github_request( method: &str, @@ -27,7 +54,7 @@ pub(crate) fn github_request( body_bytes.as_deref(), Some(HTTP_TIMEOUT_MS), ) - .map_err(|error| sanitize_host_error(&error))?; + .map_err(|failure| host_failure_code(&failure))?; if (200..300).contains(&response.status) { if response.body.is_empty() { @@ -38,14 +65,14 @@ pub(crate) fn github_request( return Ok(body); } - if response.status == 401 { - return Err(unauthorized_error_payload(&response.body)); - } - if response.status == 422 && is_github_validation_error_body(&response.body) { return Err("github_api_error_status_422_validation".to_string()); } + if response.status == 401 { + set_last_error_message(&response.body); + } + Err(format!("github_api_error_status_{}", response.status)) } @@ -54,23 +81,6 @@ pub(crate) fn github_request( /// host's own `MAX_WASM_GUEST_MESSAGE_BYTES` backstop. const MAX_PROVIDER_MESSAGE_CHARS: usize = 512; -/// Build the structured guest error envelope for a 401 response, carrying the -/// provider's rejection `message` (when the body has one) alongside the -/// stable `code`/`kind` pair. This is a pre-built envelope -- unlike other -/// error codes in this module, which are plain stable strings wrapped later -/// by `guest_error_payload` -- so `guest_error_payload` recognizes and passes -/// it through unchanged instead of re-wrapping it. -pub(crate) fn unauthorized_error_payload(body: &[u8]) -> String { - let mut payload = serde_json::json!({ - "code": "github_api_error_status_401", - "kind": "auth_required", - }); - if let Some(message) = provider_error_message(body) { - payload["message"] = serde_json::Value::String(message); - } - payload.to_string() -} - fn provider_error_message(body: &[u8]) -> Option { let parsed: serde_json::Value = serde_json::from_slice(body).ok()?; let message = parsed.get("message")?.as_str()?.trim(); @@ -95,28 +105,22 @@ pub(crate) fn github_request( .unwrap_or_else(|| Err("github_test_missing_mock_response".to_string())) } -pub(crate) fn sanitize_host_error(error: &str) -> String { - let lower = error.to_ascii_lowercase(); - if lower.contains("auth") - || lower.contains("credential") - || lower.contains("secret") - || lower.contains("token") - { - return "AuthRequired".to_string(); - } - if lower.contains("timeout") || lower.contains("deadline") { - return "github_api_timeout".to_string(); - } - if lower.contains("redirect") { - return "github_api_redirect_denied".to_string(); - } - if lower.contains("body") || lower.contains("size") || lower.contains("large") { - return "github_api_body_limit".to_string(); - } - if lower.contains("deny") || lower.contains("allow") || lower.contains("host") { - return "github_api_egress_denied".to_string(); - } - "github_api_request_failed".to_string() +fn host_failure_code(failure: &crate::near::agent::host::HttpFailure) -> String { + use crate::near::agent::host::HttpErrorKind; + + match failure.kind { + HttpErrorKind::AuthRequired => "AuthRequired", + HttpErrorKind::Input => "invalid_parameters", + HttpErrorKind::OutputTooLarge => "github_api_body_limit", + HttpErrorKind::Executor => "github_api_executor_failed", + HttpErrorKind::NetworkDenied => "github_api_egress_denied", + HttpErrorKind::Client => "github_api_request_failed", + HttpErrorKind::OperationFailed => failure + .code + .as_deref() + .unwrap_or("github_api_request_failed"), + } + .to_string() } fn is_github_validation_error_body(body: &[u8]) -> bool { @@ -184,50 +188,48 @@ pub(crate) mod test_support { #[cfg(test)] mod tests { - use super::{is_github_validation_error_body, unauthorized_error_payload}; + use super::{ + is_github_validation_error_body, provider_error_message, set_last_error_message, + take_last_error_message, + }; #[test] - fn unauthorized_error_payload_carries_the_provider_message() { - let payload = unauthorized_error_payload(br#"{"message":"Bad credentials"}"#); - let value: serde_json::Value = serde_json::from_str(&payload).expect("valid json"); + fn provider_error_message_carries_the_rejection_text() { + let message = provider_error_message(br#"{"message":"Bad credentials"}"#); - assert_eq!(value["code"], "github_api_error_status_401"); - assert_eq!(value["kind"], "auth_required"); - assert_eq!(value["message"], "Bad credentials"); + assert_eq!(message.as_deref(), Some("Bad credentials")); } #[test] - fn unauthorized_error_payload_degrades_gracefully_without_a_message() { + fn provider_error_message_degrades_gracefully_without_usable_text() { for body in [ &b"{}"[..], b"not json", br#"{"message":""}"#, + br#"{"message":" "}"#, br#"{"message":123}"#, ] { - let payload = unauthorized_error_payload(body); - let value: serde_json::Value = serde_json::from_str(&payload).expect("valid json"); - - assert_eq!(value["code"], "github_api_error_status_401"); - assert_eq!(value["kind"], "auth_required"); assert!( - value.get("message").is_none(), - "no message field expected for body {body:?}, got {value:?}" + provider_error_message(body).is_none(), + "no message expected for body {body:?}" ); } } #[test] - fn unauthorized_error_payload_bounds_the_message_to_512_chars() { - let long_message = "a".repeat(1000); - let body = serde_json::json!({ "message": long_message }).to_string(); + fn provider_error_message_bounds_the_message_to_512_chars() { + let body = serde_json::json!({ "message": "a".repeat(1000) }).to_string(); + + let message = provider_error_message(body.as_bytes()).expect("message present"); - let payload = unauthorized_error_payload(body.as_bytes()); - let value: serde_json::Value = serde_json::from_str(&payload).expect("valid json"); + assert_eq!(message.chars().count(), 512); + } + + #[test] + fn production_capture_uses_the_validated_provider_message_parser() { + set_last_error_message(br#"{"message":" "}"#); - assert_eq!( - value["message"].as_str().expect("message string").len(), - 512 - ); + assert!(take_last_error_message().is_none()); } #[test] diff --git a/crates/extensions/packages/github/wasm/github_tool.wasm b/crates/extensions/packages/github/wasm/github_tool.wasm index 64a674a4dff..220b8f07b92 100644 Binary files a/crates/extensions/packages/github/wasm/github_tool.wasm and b/crates/extensions/packages/github/wasm/github_tool.wasm differ diff --git a/crates/extensions/packages/google-docs/wasm-src/src/api.rs b/crates/extensions/packages/google-docs/wasm-src/src/api.rs index fc353f75385..01ee1b0e5ab 100644 --- a/crates/extensions/packages/google-docs/wasm-src/src/api.rs +++ b/crates/extensions/packages/google-docs/wasm-src/src/api.rs @@ -4,14 +4,70 @@ //! credential injection and rate limiting. The WASM tool never sees //! the actual OAuth token. +use crate::exports::near::agent::tool::{ErrorKind, GuestFailure}; use crate::near::agent::host; use crate::types::*; const DOCS_API_BASE: &str = "https://docs.googleapis.com/v1/documents"; const GOOGLE_API_AUTH_REQUIRED_ERROR: &str = "google_api_error_status_401"; +/// Bound a free-text message to a sane length before it rides in a +/// `guest-failure`; the host re-bounds and scrubs downstream, but the guest +/// should never hand over an unbounded string in the first place. +pub(crate) fn bounded_message(message: &str) -> String { + const MAX_MESSAGE_CHARS: usize = 512; + message.chars().take(MAX_MESSAGE_CHARS).collect() +} + +// ponytail: duplicated across isolated WASM guest packages; consolidate only +// when guests share a supported contracts crate. +fn transport_failure(failure: &host::HttpFailure) -> GuestFailure { + let kind = match failure.kind { + host::HttpErrorKind::AuthRequired => ErrorKind::AuthRequired, + host::HttpErrorKind::Input => ErrorKind::Input, + host::HttpErrorKind::OutputTooLarge => ErrorKind::OutputTooLarge, + host::HttpErrorKind::Executor => ErrorKind::Executor, + host::HttpErrorKind::NetworkDenied => ErrorKind::NetworkDenied, + host::HttpErrorKind::Client => ErrorKind::Client, + host::HttpErrorKind::OperationFailed => ErrorKind::OperationFailed, + }; + GuestFailure { + kind, + code: failure.code.clone().or_else(|| Some("google_api_transport_error".into())), + message: failure.message.as_deref().map(bounded_message), + } +} + +/// A guest-side JSON encode/decode of an already-well-formed payload failed +/// — a tool-side processing failure, not anything the caller did wrong. +pub(crate) fn serialization_failure(error: &serde_json::Error) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Executor, + code: Some("serialization_failed".to_string()), + message: Some(bounded_message(&error.to_string())), + } +} + +/// Build an `input`-kind guest failure for a caller-supplied argument that +/// fails local validation before any egress. +fn input_failure(code: &'static str, message: impl Into) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: Some(bounded_message(&message.into())), + } +} + +fn utf8_decode_failure(error: &std::string::FromUtf8Error) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Executor, + code: Some("invalid_utf8_response".to_string()), + message: Some(bounded_message(&error.to_string())), + } +} + /// Make a Google Docs API call. -fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { +fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { let url = if path.is_empty() { DOCS_API_BASE.to_string() } else { @@ -31,43 +87,54 @@ fn api_call(method: &str, path: &str, body: Option<&str>) -> Result= 300 { - return Err(api_status_error("Google Docs", response.status, &response.body)); + return Err(api_status_error( + "Google Docs", + response.status, + &response.body, + )); } if response.body.is_empty() { return Ok(String::new()); } - String::from_utf8(response.body).map_err(|e| format!("Invalid UTF-8 in response: {}", e)) + String::from_utf8(response.body).map_err(|e| utf8_decode_failure(&e)) } -fn api_status_error(service: &str, status: u16, body: &[u8]) -> String { +fn api_status_error(service: &str, status: u16, body: &[u8]) -> GuestFailure { if status == 401 { - return serde_json::json!({ - "code": GOOGLE_API_AUTH_REQUIRED_ERROR, - "kind": "auth_required", - }) - .to_string(); + return GuestFailure { + kind: ErrorKind::AuthRequired, + code: Some(GOOGLE_API_AUTH_REQUIRED_ERROR.to_string()), + message: None, + }; } let body_text = String::from_utf8_lossy(body); - format!("{service} API returned status {status}: {body_text}") + GuestFailure { + kind: ErrorKind::Client, + code: Some(format!("api_status_{status}")), + message: Some(bounded_message(&format!( + "{service} API returned status {status}: {body_text}" + ))), + } } /// Send a batchUpdate to the document and return the parsed response. fn batch_update_raw( document_id: &str, requests: Vec, -) -> Result { +) -> Result { let path = format!("{}:batchUpdate", url_encode(document_id)); let body = serde_json::json!({ "requests": requests }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("POST", &path, Some(&body_str))?; - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e)) + serde_json::from_str(&response).map_err(|e| serialization_failure(&e)) } /// Extract revision ID from a batchUpdate response. @@ -79,13 +146,13 @@ fn extract_revision_id(parsed: &serde_json::Value) -> String { } /// Create a new document. -pub fn create_document(title: &str) -> Result { +pub fn create_document(title: &str) -> Result { let body = serde_json::json!({ "title": title }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("POST", "", Some(&body_str))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(CreateDocumentResult { document_id: parsed["documentId"].as_str().unwrap_or("").to_string(), @@ -94,12 +161,12 @@ pub fn create_document(title: &str) -> Result { } /// Get document metadata. -pub fn get_document(document_id: &str) -> Result { +pub fn get_document(document_id: &str) -> Result { let path = url_encode(document_id); let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; // Calculate body length from the last element's endIndex let body_length = parsed["body"]["content"] @@ -141,12 +208,12 @@ pub fn get_document(document_id: &str) -> Result { } /// Read the document body as plain text by walking the structural elements. -pub fn read_content(document_id: &str) -> Result { +pub fn read_content(document_id: &str) -> Result { let path = url_encode(document_id); let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; let mut text = String::new(); if let Some(content) = parsed["body"]["content"].as_array() { @@ -203,7 +270,7 @@ pub fn insert_text( text: &str, index: i64, segment_id: &str, -) -> Result { +) -> Result { let request = if index == -1 { // Append at end of segment let mut loc = serde_json::json!({}); @@ -217,8 +284,9 @@ pub fn insert_text( } }) } else if index < 0 { - return Err(format!( - "invalid index {index}: only -1 (append) or non-negative indexes are accepted" + return Err(input_failure( + "invalid_index", + format!("invalid index {index}: only -1 (append) or non-negative indexes are accepted"), )); } else { let mut loc = serde_json::json!({ "index": index }); @@ -247,7 +315,7 @@ pub fn delete_content( start_index: i64, end_index: i64, segment_id: &str, -) -> Result { +) -> Result { let mut range = serde_json::json!({ "startIndex": start_index, "endIndex": end_index, @@ -274,7 +342,7 @@ pub fn replace_text( find: &str, replace: &str, match_case: bool, -) -> Result { +) -> Result { let request = serde_json::json!({ "replaceAllText": { "containsText": { @@ -339,7 +407,7 @@ pub struct FormatTextOptions<'a> { } /// Format text in a range. -pub fn format_text(opts: FormatTextOptions<'_>) -> Result { +pub fn format_text(opts: FormatTextOptions<'_>) -> Result { let mut style = serde_json::json!({}); let mut fields = Vec::new(); @@ -369,21 +437,30 @@ pub fn format_text(opts: FormatTextOptions<'_>) -> Result } if let Some(color) = opts.foreground_color { let Some(c) = parse_hex_color(color) else { - return Err(format!("invalid foreground_color hex: {color}")); + return Err(input_failure( + "invalid_color", + format!("invalid foreground_color hex: {color}"), + )); }; style["foregroundColor"] = c; fields.push("foregroundColor"); } if let Some(color) = opts.background_color { let Some(c) = parse_hex_color(color) else { - return Err(format!("invalid background_color hex: {color}")); + return Err(input_failure( + "invalid_color", + format!("invalid background_color hex: {color}"), + )); }; style["backgroundColor"] = c; fields.push("backgroundColor"); } if fields.is_empty() { - return Err("No formatting options specified".to_string()); + return Err(input_failure( + "no_formatting_options", + "No formatting options specified", + )); } let request = serde_json::json!({ @@ -413,7 +490,7 @@ pub fn format_paragraph( named_style: Option<&str>, alignment: Option<&str>, line_spacing: Option, -) -> Result { +) -> Result { let mut para_style = serde_json::json!({}); let mut fields = Vec::new(); @@ -431,7 +508,10 @@ pub fn format_paragraph( } if fields.is_empty() { - return Err("No paragraph style options specified".to_string()); + return Err(input_failure( + "no_paragraph_style_options", + "No paragraph style options specified", + )); } let request = serde_json::json!({ @@ -459,7 +539,7 @@ pub fn insert_table( rows: i64, columns: i64, index: i64, -) -> Result { +) -> Result { let request = serde_json::json!({ "insertTable": { "rows": rows, @@ -482,7 +562,7 @@ pub fn create_list( start_index: i64, end_index: i64, bullet_preset: &str, -) -> Result { +) -> Result { let request = serde_json::json!({ "createParagraphBullets": { "range": { @@ -505,7 +585,7 @@ pub fn create_list( pub fn batch_update( document_id: &str, requests: Vec, -) -> Result { +) -> Result { let parsed = batch_update_raw(document_id, requests)?; let replies = parsed["replies"] @@ -550,11 +630,40 @@ mod tests { assert_eq!(text, "Heading 1\n"); } + #[test] + fn api_status_error_401_maps_to_auth_required() { + let err = api_status_error("Google Docs", 401, b"{\"error\":\"invalid_token\"}"); + + assert_eq!(err.kind, ErrorKind::AuthRequired); + assert_eq!(err.code.as_deref(), Some(GOOGLE_API_AUTH_REQUIRED_ERROR)); + } + + #[test] + fn api_status_error_non_401_maps_to_client() { + let err = api_status_error("Google Docs", 429, b"rate limited"); + + assert_eq!(err.kind, ErrorKind::Client); + assert_eq!(err.code.as_deref(), Some("api_status_429")); + assert!( + err.message + .as_deref() + .is_some_and(|message| message.contains("rate limited")), + "{err:?}" + ); + } + #[test] fn insert_text_rejects_negative_indexes_other_than_append() { let err = insert_text("doc-1", "text", -2, "").unwrap_err(); - assert!(err.contains("invalid index -2"), "{err}"); + assert_eq!(err.kind, ErrorKind::Input); + assert_eq!(err.code.as_deref(), Some("invalid_index")); + assert!( + err.message + .as_deref() + .is_some_and(|message| message.contains("invalid index -2")), + "{err:?}" + ); } #[test] @@ -574,6 +683,11 @@ mod tests { }) .unwrap_err(); - assert_eq!(err, "invalid foreground_color hex: #GG0000"); + assert_eq!(err.kind, ErrorKind::Input); + assert_eq!(err.code.as_deref(), Some("invalid_color")); + assert_eq!( + err.message.as_deref(), + Some("invalid foreground_color hex: #GG0000") + ); } } diff --git a/crates/extensions/packages/google-docs/wasm-src/src/lib.rs b/crates/extensions/packages/google-docs/wasm-src/src/lib.rs index ab95fc05680..b3642eda996 100644 --- a/crates/extensions/packages/google-docs/wasm-src/src/lib.rs +++ b/crates/extensions/packages/google-docs/wasm-src/src/lib.rs @@ -54,19 +54,15 @@ wit_bindgen::generate!({ path: "../../../../lanes/ironclaw_wasm/wit/tool.wit", }); +use exports::near::agent::tool::{ErrorKind, GuestFailure, Response}; + struct GoogleDocsTool; impl exports::near::agent::tool::Guest for GoogleDocsTool { fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response { match execute_inner(&req.params, req.context.as_deref()) { - Ok(result) => exports::near::agent::tool::Response { - output: Some(result), - error: None, - }, - Err(e) => exports::near::agent::tool::Response { - output: None, - error: Some(e), - }, + Ok(result) => Response::Success(result), + Err(failure) => Response::Failure(failure), } } @@ -91,11 +87,25 @@ impl exports::near::agent::tool::Guest for GoogleDocsTool { } } -fn execute_inner(params: &str, context: Option<&str>) -> Result { +/// Build an `input`-kind guest failure with a stable code and no free-text +/// message (the code alone is the actionable signal for these host-plumbing +/// failures). +fn input_failure(code: &'static str) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: None, + } +} + +fn execute_inner(params: &str, context: Option<&str>) -> Result { let action_name = action_from_context(context)?; let params = params_with_action(params, action_name)?; - let action: GoogleDocsAction = - serde_json::from_value(params).map_err(|e| format!("Invalid parameters: {}", e))?; + let action: GoogleDocsAction = serde_json::from_value(params).map_err(|e| GuestFailure { + kind: ErrorKind::Input, + code: Some("invalid_parameters".to_string()), + message: Some(api::bounded_message(&e.to_string())), + })?; crate::near::agent::host::log( crate::near::agent::host::LogLevel::Debug, @@ -105,17 +115,17 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result let result = match action { GoogleDocsAction::CreateDocument { title } => { let result = api::create_document(&title)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::GetDocument { document_id } => { let result = api::get_document(&document_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::ReadContent { document_id } => { let result = api::read_content(&document_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::InsertText { @@ -125,7 +135,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result segment_id, } => { let result = api::insert_text(&document_id, &text, index, &segment_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::DeleteContent { @@ -135,7 +145,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result segment_id, } => { let result = api::delete_content(&document_id, start_index, end_index, &segment_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::ReplaceText { @@ -145,7 +155,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result match_case, } => { let result = api::replace_text(&document_id, &find, &replace, match_case)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::FormatText { @@ -174,7 +184,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result foreground_color: foreground_color.as_deref(), background_color: background_color.as_deref(), })?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::FormatParagraph { @@ -193,7 +203,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result alignment.as_deref(), line_spacing, )?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::InsertTable { @@ -203,7 +213,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result index, } => { let result = api::insert_table(&document_id, rows, columns, index)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::CreateList { @@ -213,7 +223,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result bullet_preset, } => { let result = api::create_list(&document_id, start_index, end_index, &bullet_preset)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDocsAction::BatchUpdate { @@ -221,17 +231,17 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result requests, } => { let result = api::batch_update(&document_id, requests)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } }; Ok(result) } -fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { - let context = context.ok_or_else(|| "missing_invocation_context".to_string())?; +fn action_from_context(context: Option<&str>) -> Result<&'static str, GuestFailure> { + let context = context.ok_or_else(|| input_failure("missing_invocation_context"))?; let context: ToolContext = - serde_json::from_str(context).map_err(|_| "invalid_invocation_context".to_string())?; + serde_json::from_str(context).map_err(|_| input_failure("invalid_invocation_context"))?; match context.capability_id.as_str() { "google-docs.create_document" => Ok("create_document"), "google-docs.get_document" => Ok("get_document"), @@ -244,21 +254,21 @@ fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { "google-docs.insert_table" => Ok("insert_table"), "google-docs.create_list" => Ok("create_list"), "google-docs.batch_update" => Ok("batch_update"), - _ => Err("unsupported_google_docs_capability".to_string()), + _ => Err(input_failure("unsupported_google_docs_capability")), } } -fn params_with_action(params: &str, action: &str) -> Result { +fn params_with_action(params: &str, action: &str) -> Result { let mut params: serde_json::Value = if params.trim().is_empty() { serde_json::json!({}) } else { - serde_json::from_str(params).map_err(|_| "invalid_parameters".to_string())? + serde_json::from_str(params).map_err(|_| input_failure("invalid_parameters"))? }; let obj = params .as_object_mut() - .ok_or_else(|| "invalid_parameters".to_string())?; + .ok_or_else(|| input_failure("invalid_parameters"))?; if obj.contains_key("action") { - return Err("invalid_parameters".to_string()); + return Err(input_failure("invalid_parameters")); } obj.insert( "action".to_string(), @@ -273,10 +283,14 @@ mod tests { #[test] fn params_with_action_rejects_caller_supplied_action() { - let result = - params_with_action(r#"{"action":"delete_all","document_id":"doc-1"}"#, "get_document"); + let error = params_with_action( + r#"{"action":"delete_all","document_id":"doc-1"}"#, + "get_document", + ) + .unwrap_err(); - assert_eq!(result, Err("invalid_parameters".to_string())); + assert_eq!(error.kind, ErrorKind::Input); + assert_eq!(error.code.as_deref(), Some("invalid_parameters")); } } diff --git a/crates/extensions/packages/google-docs/wasm/google_docs_tool.wasm b/crates/extensions/packages/google-docs/wasm/google_docs_tool.wasm index 7e2bf6c11c1..9d1ad19d3d4 100644 Binary files a/crates/extensions/packages/google-docs/wasm/google_docs_tool.wasm and b/crates/extensions/packages/google-docs/wasm/google_docs_tool.wasm differ diff --git a/crates/extensions/packages/google-drive/wasm-src/src/api.rs b/crates/extensions/packages/google-drive/wasm-src/src/api.rs index 188963cd520..65bc707e314 100644 --- a/crates/extensions/packages/google-drive/wasm-src/src/api.rs +++ b/crates/extensions/packages/google-drive/wasm-src/src/api.rs @@ -6,6 +6,7 @@ use base64::Engine as _; +use crate::exports::near::agent::tool::{ErrorKind, GuestFailure}; use crate::near::agent::host; use crate::types::*; @@ -19,8 +20,53 @@ const FILE_FIELDS: &str = "id,name,mimeType,description,size,createdTime,modifie webViewLink,parents,shared,starred,trashed,ownedByMe,driveId,\ owners(emailAddress,displayName)"; +/// Bound a free-text message to a sane length before it rides in a +/// `guest-failure`; the host re-bounds and scrubs downstream, but the guest +/// should never hand over an unbounded string in the first place. +pub(crate) fn bounded_message(message: &str) -> String { + const MAX_MESSAGE_CHARS: usize = 512; + message.chars().take(MAX_MESSAGE_CHARS).collect() +} + +// ponytail: duplicated across isolated WASM guest packages; consolidate only +// when guests share a supported contracts crate. +fn transport_failure(failure: &host::HttpFailure) -> GuestFailure { + let kind = match failure.kind { + host::HttpErrorKind::AuthRequired => ErrorKind::AuthRequired, + host::HttpErrorKind::Input => ErrorKind::Input, + host::HttpErrorKind::OutputTooLarge => ErrorKind::OutputTooLarge, + host::HttpErrorKind::Executor => ErrorKind::Executor, + host::HttpErrorKind::NetworkDenied => ErrorKind::NetworkDenied, + host::HttpErrorKind::Client => ErrorKind::Client, + host::HttpErrorKind::OperationFailed => ErrorKind::OperationFailed, + }; + GuestFailure { + kind, + code: failure.code.clone().or_else(|| Some("google_api_transport_error".into())), + message: failure.message.as_deref().map(bounded_message), + } +} + +/// A guest-side JSON encode/decode of an already-well-formed payload failed +/// — a tool-side processing failure, not anything the caller did wrong. +pub(crate) fn serialization_failure(error: &serde_json::Error) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Executor, + code: Some("serialization_failed".to_string()), + message: Some(bounded_message(&error.to_string())), + } +} + +fn utf8_decode_failure(error: &std::string::FromUtf8Error) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Executor, + code: Some("invalid_utf8_response".to_string()), + message: Some(bounded_message(&error.to_string())), + } +} + /// Make a Drive API call. -fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { +fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { let url = format!("{}/{}", DRIVE_API_BASE, path); let headers = if body.is_some() { @@ -36,7 +82,8 @@ fn api_call(method: &str, path: &str, body: Option<&str>) -> Result= 300 { return Err(api_status_error("Drive", response.status, &response.body)); @@ -46,17 +93,18 @@ fn api_call(method: &str, path: &str, body: Option<&str>) -> Result Result, String> { +fn api_call_raw(method: &str, url: &str) -> Result, GuestFailure> { host::log( host::LogLevel::Debug, &format!("Drive API raw: {} {}", method, url), ); - let response = host::http_request(method, url, "{}", None, None)?; + let response = + host::http_request(method, url, "{}", None, None).map_err(|e| transport_failure(&e))?; if response.status < 200 || response.status >= 300 { return Err(api_status_error("Drive", response.status, &response.body)); @@ -65,16 +113,22 @@ fn api_call_raw(method: &str, url: &str) -> Result, String> { Ok(response.body) } -fn api_status_error(service: &str, status: u16, body: &[u8]) -> String { +fn api_status_error(service: &str, status: u16, body: &[u8]) -> GuestFailure { if status == 401 { - return serde_json::json!({ - "code": GOOGLE_API_AUTH_REQUIRED_ERROR, - "kind": "auth_required", - }) - .to_string(); + return GuestFailure { + kind: ErrorKind::AuthRequired, + code: Some(GOOGLE_API_AUTH_REQUIRED_ERROR.to_string()), + message: None, + }; } let body_text = String::from_utf8_lossy(body); - format!("{service} API returned status {status}: {body_text}") + GuestFailure { + kind: ErrorKind::Client, + code: Some(format!("api_status_{status}")), + message: Some(bounded_message(&format!( + "{service} API returned status {status}: {body_text}" + ))), + } } /// Parse a file resource from the API response. @@ -125,7 +179,7 @@ pub fn list_files( corpora: &str, drive_id: Option<&str>, page_token: Option<&str>, -) -> Result { +) -> Result { let mut params = vec![ format!("pageSize={}", page_size), format!("fields=nextPageToken,files({})", FILE_FIELDS), @@ -150,7 +204,7 @@ pub fn list_files( let path = format!("files?{}", params.join("&")); let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; let files = parsed["files"] .as_array() @@ -164,7 +218,7 @@ pub fn list_files( } /// Get file metadata. -pub fn get_file(file_id: &str) -> Result { +pub fn get_file(file_id: &str) -> Result { let path = format!( "files/{}?fields={}&supportsAllDrives=true", url_encode(file_id), @@ -172,7 +226,7 @@ pub fn get_file(file_id: &str) -> Result { ); let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(FileResult { file: parse_file(&parsed), @@ -183,7 +237,7 @@ pub fn get_file(file_id: &str) -> Result { pub fn download_file( file_id: &str, export_mime_type: Option<&str>, -) -> Result { +) -> Result { let meta = get_file(file_id)?; let is_google_apps = meta .file @@ -300,7 +354,7 @@ pub fn upload_file( mime_type: &str, parent_id: Option<&str>, description: Option<&str>, -) -> Result { +) -> Result { let mut metadata = serde_json::json!({ "name": name, "mimeType": mime_type, @@ -312,7 +366,7 @@ pub fn upload_file( metadata["description"] = serde_json::Value::String(desc.to_string()); } - let metadata_str = serde_json::to_string(&metadata).map_err(|e| e.to_string())?; + let metadata_str = serde_json::to_string(&metadata).map_err(|e| serialization_failure(&e))?; let boundary = multipart_boundary(&metadata_str, content); // Build multipart body @@ -339,16 +393,17 @@ pub fn upload_file( "Drive API: POST upload/files (multipart)", ); - let response = host::http_request("POST", &url, &headers, Some(body.as_bytes()), None)?; + let response = host::http_request("POST", &url, &headers, Some(body.as_bytes()), None) + .map_err(|e| transport_failure(&e))?; if response.status < 200 || response.status >= 300 { return Err(api_status_error("Drive", response.status, &response.body)); } let parsed: serde_json::Value = serde_json::from_str( - &String::from_utf8(response.body).map_err(|e| format!("Invalid UTF-8: {}", e))?, + &String::from_utf8(response.body).map_err(|e| utf8_decode_failure(&e))?, ) - .map_err(|e| format!("Failed to parse response: {}", e))?; + .map_err(|e| serialization_failure(&e))?; Ok(FileResult { file: parse_file(&parsed), @@ -379,7 +434,7 @@ pub fn update_file( description: Option<&str>, move_to_parent: Option<&str>, starred: Option, -) -> Result { +) -> Result { let mut patch = serde_json::json!({}); if let Some(n) = name { @@ -413,12 +468,12 @@ pub fn update_file( } } - let body = serde_json::to_string(&patch).map_err(|e| e.to_string())?; + let body = serde_json::to_string(&patch).map_err(|e| serialization_failure(&e))?; let path = format!("files/{}?{}", url_encode(file_id), params.join("&")); let response = api_call("PATCH", &path, Some(&body))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(FileResult { file: parse_file(&parsed), @@ -430,7 +485,7 @@ pub fn create_folder( name: &str, parent_id: Option<&str>, description: Option<&str>, -) -> Result { +) -> Result { let mut metadata = serde_json::json!({ "name": name, "mimeType": "application/vnd.google-apps.folder", @@ -442,12 +497,12 @@ pub fn create_folder( metadata["description"] = serde_json::Value::String(desc.to_string()); } - let body = serde_json::to_string(&metadata).map_err(|e| e.to_string())?; + let body = serde_json::to_string(&metadata).map_err(|e| serialization_failure(&e))?; let path = format!("files?fields={}&supportsAllDrives=true", FILE_FIELDS); let response = api_call("POST", &path, Some(&body))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(FileResult { file: parse_file(&parsed), @@ -455,7 +510,7 @@ pub fn create_folder( } /// Delete a file permanently. -pub fn delete_file(file_id: &str) -> Result { +pub fn delete_file(file_id: &str) -> Result { let path = format!("files/{}?supportsAllDrives=true", url_encode(file_id)); api_call("DELETE", &path, None)?; @@ -466,7 +521,7 @@ pub fn delete_file(file_id: &str) -> Result { } /// Move a file to trash. -pub fn trash_file(file_id: &str) -> Result { +pub fn trash_file(file_id: &str) -> Result { let body = r#"{"trashed": true}"#; let path = format!( "files/{}?fields={}&supportsAllDrives=true", @@ -488,14 +543,14 @@ pub fn share_file( email: &str, role: &str, message: Option<&str>, -) -> Result { +) -> Result { let permission = serde_json::json!({ "type": "user", "role": role, "emailAddress": email, }); - let body = serde_json::to_string(&permission).map_err(|e| e.to_string())?; + let body = serde_json::to_string(&permission).map_err(|e| serialization_failure(&e))?; let mut path = format!( "files/{}/permissions?supportsAllDrives=true", @@ -507,7 +562,7 @@ pub fn share_file( let response = api_call("POST", &path, Some(&body))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(ShareResult { permission_id: parsed["id"].as_str().unwrap_or("").to_string(), @@ -517,7 +572,7 @@ pub fn share_file( } /// List permissions on a file. -pub fn list_permissions(file_id: &str) -> Result { +pub fn list_permissions(file_id: &str) -> Result { let path = format!( "files/{}/permissions?fields=permissions(id,role,type,emailAddress,displayName)&supportsAllDrives=true", url_encode(file_id) @@ -525,7 +580,7 @@ pub fn list_permissions(file_id: &str) -> Result let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; let permissions = parsed["permissions"] .as_array() @@ -546,7 +601,7 @@ pub fn list_permissions(file_id: &str) -> Result } /// Remove a sharing permission. -pub fn remove_permission(file_id: &str, permission_id: &str) -> Result { +pub fn remove_permission(file_id: &str, permission_id: &str) -> Result { let path = format!( "files/{}/permissions/{}?supportsAllDrives=true", url_encode(file_id), @@ -562,11 +617,11 @@ pub fn remove_permission(file_id: &str, permission_id: &str) -> Result Result { +pub fn list_shared_drives(page_size: u32) -> Result { let path = format!("drives?pageSize={}", page_size); let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; let drives = parsed["drives"] .as_array() @@ -591,6 +646,28 @@ fn url_encode(s: &str) -> String { mod tests { use super::*; + #[test] + fn api_status_error_401_maps_to_auth_required() { + let err = api_status_error("Drive", 401, b"{\"error\":\"invalid_token\"}"); + + assert_eq!(err.kind, ErrorKind::AuthRequired); + assert_eq!(err.code.as_deref(), Some(GOOGLE_API_AUTH_REQUIRED_ERROR)); + } + + #[test] + fn api_status_error_non_401_maps_to_client() { + let err = api_status_error("Drive", 429, b"rate limited"); + + assert_eq!(err.kind, ErrorKind::Client); + assert_eq!(err.code.as_deref(), Some("api_status_429")); + assert!( + err.message + .as_deref() + .is_some_and(|message| message.contains("rate limited")), + "{err:?}" + ); + } + #[test] fn multipart_boundary_does_not_appear_in_metadata_or_content() { let metadata = r#"{"name":"ironclaw_upload_boundary_marker"}"#; diff --git a/crates/extensions/packages/google-drive/wasm-src/src/lib.rs b/crates/extensions/packages/google-drive/wasm-src/src/lib.rs index 84889390c35..d8193bc231f 100644 --- a/crates/extensions/packages/google-drive/wasm-src/src/lib.rs +++ b/crates/extensions/packages/google-drive/wasm-src/src/lib.rs @@ -44,19 +44,15 @@ wit_bindgen::generate!({ path: "../../../../lanes/ironclaw_wasm/wit/tool.wit", }); +use exports::near::agent::tool::{ErrorKind, GuestFailure, Response}; + struct GoogleDriveTool; impl exports::near::agent::tool::Guest for GoogleDriveTool { fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response { match execute_inner(&req.params, req.context.as_deref()) { - Ok(result) => exports::near::agent::tool::Response { - output: Some(result), - error: None, - }, - Err(e) => exports::near::agent::tool::Response { - output: None, - error: Some(e), - }, + Ok(result) => Response::Success(result), + Err(failure) => Response::Failure(failure), } } @@ -83,11 +79,25 @@ impl exports::near::agent::tool::Guest for GoogleDriveTool { } } -fn execute_inner(params: &str, context: Option<&str>) -> Result { +/// Build an `input`-kind guest failure with a stable code and no free-text +/// message (the code alone is the actionable signal for these host-plumbing +/// failures). +fn input_failure(code: &'static str) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: None, + } +} + +fn execute_inner(params: &str, context: Option<&str>) -> Result { let action_name = action_from_context(context)?; let params = params_with_action(params, action_name)?; - let action: GoogleDriveAction = - serde_json::from_value(params).map_err(|e| format!("Invalid parameters: {}", e))?; + let action: GoogleDriveAction = serde_json::from_value(params).map_err(|e| GuestFailure { + kind: ErrorKind::Input, + code: Some("invalid_parameters".to_string()), + message: Some(api::bounded_message(&e.to_string())), + })?; crate::near::agent::host::log( crate::near::agent::host::LogLevel::Debug, @@ -111,12 +121,12 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result drive_id.as_deref(), page_token.as_deref(), )?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::GetFile { file_id } => { let result = api::get_file(&file_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::DownloadFile { @@ -124,7 +134,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result export_mime_type, } => { let result = api::download_file(&file_id, export_mime_type.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::UploadFile { @@ -141,7 +151,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result parent_id.as_deref(), description.as_deref(), )?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::UpdateFile { @@ -158,7 +168,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result move_to_parent.as_deref(), starred, )?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::CreateFolder { @@ -167,17 +177,17 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result description, } => { let result = api::create_folder(&name, parent_id.as_deref(), description.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::DeleteFile { file_id } => { let result = api::delete_file(&file_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::TrashFile { file_id } => { let result = api::trash_file(&file_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::ShareFile { @@ -187,12 +197,12 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result message, } => { let result = api::share_file(&file_id, &email, &role, message.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::ListPermissions { file_id } => { let result = api::list_permissions(&file_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::RemovePermission { @@ -200,22 +210,22 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result permission_id, } => { let result = api::remove_permission(&file_id, &permission_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleDriveAction::ListSharedDrives { page_size } => { let result = api::list_shared_drives(page_size)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } }; Ok(result) } -fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { - let context = context.ok_or_else(|| "missing_invocation_context".to_string())?; +fn action_from_context(context: Option<&str>) -> Result<&'static str, GuestFailure> { + let context = context.ok_or_else(|| input_failure("missing_invocation_context"))?; let context: ToolContext = - serde_json::from_str(context).map_err(|_| "invalid_invocation_context".to_string())?; + serde_json::from_str(context).map_err(|_| input_failure("invalid_invocation_context"))?; match context.capability_id.as_str() { "google-drive.list_files" => Ok("list_files"), "google-drive.get_file" => Ok("get_file"), @@ -229,21 +239,21 @@ fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { "google-drive.list_permissions" => Ok("list_permissions"), "google-drive.remove_permission" => Ok("remove_permission"), "google-drive.list_shared_drives" => Ok("list_shared_drives"), - _ => Err("unsupported_google_drive_capability".to_string()), + _ => Err(input_failure("unsupported_google_drive_capability")), } } -fn params_with_action(params: &str, action: &str) -> Result { +fn params_with_action(params: &str, action: &str) -> Result { let mut params: serde_json::Value = if params.trim().is_empty() { serde_json::json!({}) } else { - serde_json::from_str(params).map_err(|_| "invalid_parameters".to_string())? + serde_json::from_str(params).map_err(|_| input_failure("invalid_parameters"))? }; let obj = params .as_object_mut() - .ok_or_else(|| "invalid_parameters".to_string())?; + .ok_or_else(|| input_failure("invalid_parameters"))?; if obj.contains_key("action") { - return Err("invalid_parameters".to_string()); + return Err(input_failure("invalid_parameters")); } obj.insert( "action".to_string(), diff --git a/crates/extensions/packages/google-drive/wasm/google_drive_tool.wasm b/crates/extensions/packages/google-drive/wasm/google_drive_tool.wasm index 033aca77dd4..3a56318b21d 100644 Binary files a/crates/extensions/packages/google-drive/wasm/google_drive_tool.wasm and b/crates/extensions/packages/google-drive/wasm/google_drive_tool.wasm differ diff --git a/crates/extensions/packages/google-sheets/wasm-src/src/api.rs b/crates/extensions/packages/google-sheets/wasm-src/src/api.rs index b31898759d7..5339ecdb637 100644 --- a/crates/extensions/packages/google-sheets/wasm-src/src/api.rs +++ b/crates/extensions/packages/google-sheets/wasm-src/src/api.rs @@ -4,14 +4,62 @@ //! credential injection and rate limiting. The WASM tool never sees //! the actual OAuth token. +use crate::exports::near::agent::tool::{ErrorKind, GuestFailure}; use crate::near::agent::host; use crate::types::*; const SHEETS_API_BASE: &str = "https://sheets.googleapis.com/v4/spreadsheets"; const GOOGLE_API_AUTH_REQUIRED_ERROR: &str = "google_api_error_status_401"; +/// Bound a free-text message to a sane length before it rides in a +/// `guest-failure`; the host re-bounds and scrubs downstream, but the guest +/// should never hand over an unbounded string in the first place. +pub(crate) fn bounded_message(message: &str) -> String { + const MAX_MESSAGE_CHARS: usize = 512; + message.chars().take(MAX_MESSAGE_CHARS).collect() +} + +// ponytail: duplicated across isolated WASM guest packages; consolidate only +// when guests share a supported contracts crate. +fn transport_failure(failure: &host::HttpFailure) -> GuestFailure { + let kind = match failure.kind { + host::HttpErrorKind::AuthRequired => ErrorKind::AuthRequired, + host::HttpErrorKind::Input => ErrorKind::Input, + host::HttpErrorKind::OutputTooLarge => ErrorKind::OutputTooLarge, + host::HttpErrorKind::Executor => ErrorKind::Executor, + host::HttpErrorKind::NetworkDenied => ErrorKind::NetworkDenied, + host::HttpErrorKind::Client => ErrorKind::Client, + host::HttpErrorKind::OperationFailed => ErrorKind::OperationFailed, + }; + GuestFailure { + kind, + code: failure.code.clone().or_else(|| Some("google_api_transport_error".into())), + message: failure.message.as_deref().map(bounded_message), + } +} + +/// A guest-side JSON encode/decode of an already-well-formed payload failed +/// — a tool-side processing failure, not anything the caller did wrong. +pub(crate) fn serialization_failure(error: &serde_json::Error) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Executor, + code: Some("serialization_failed".to_string()), + message: Some(bounded_message(&error.to_string())), + } +} + +/// Build an `input`-kind guest failure for a caller-supplied argument that +/// fails local validation before any egress. +fn input_failure(code: &'static str, message: impl Into) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: Some(bounded_message(&message.into())), + } +} + /// Make a Google Sheets API call. -fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { +fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { let url = if path.is_empty() { SHEETS_API_BASE.to_string() } else { @@ -31,29 +79,44 @@ fn api_call(method: &str, path: &str, body: Option<&str>) -> Result= 300 { - return Err(api_status_error("Google Sheets", response.status, &response.body)); + return Err(api_status_error( + "Google Sheets", + response.status, + &response.body, + )); } if response.body.is_empty() { return Ok(String::new()); } - String::from_utf8(response.body).map_err(|e| format!("Invalid UTF-8 in response: {}", e)) + String::from_utf8(response.body).map_err(|e| GuestFailure { + kind: ErrorKind::Executor, + code: Some("invalid_utf8_response".to_string()), + message: Some(bounded_message(&e.to_string())), + }) } -fn api_status_error(service: &str, status: u16, body: &[u8]) -> String { +fn api_status_error(service: &str, status: u16, body: &[u8]) -> GuestFailure { if status == 401 { - return serde_json::json!({ - "code": GOOGLE_API_AUTH_REQUIRED_ERROR, - "kind": "auth_required", - }) - .to_string(); + return GuestFailure { + kind: ErrorKind::AuthRequired, + code: Some(GOOGLE_API_AUTH_REQUIRED_ERROR.to_string()), + message: None, + }; } let body_text = String::from_utf8_lossy(body); - format!("{service} API returned status {status}: {body_text}") + GuestFailure { + kind: ErrorKind::Client, + code: Some(format!("api_status_{status}")), + message: Some(bounded_message(&format!( + "{service} API returned status {status}: {body_text}" + ))), + } } /// Parse sheet info from the API's JSON. @@ -97,7 +160,7 @@ fn format_grid_range(v: &serde_json::Value) -> String { pub fn create_spreadsheet( title: &str, sheet_names: &[String], -) -> Result { +) -> Result { let sheets: Vec = if sheet_names.is_empty() { vec![serde_json::json!({"properties": {"title": "Sheet1"}})] } else { @@ -112,10 +175,10 @@ pub fn create_spreadsheet( "sheets": sheets, }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("POST", "", Some(&body_str))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(CreateSpreadsheetResult { spreadsheet_id: parsed["spreadsheetId"].as_str().unwrap_or("").to_string(), @@ -132,7 +195,7 @@ pub fn create_spreadsheet( } /// Get spreadsheet metadata. -pub fn get_spreadsheet(spreadsheet_id: &str) -> Result { +pub fn get_spreadsheet(spreadsheet_id: &str) -> Result { let path = format!( "{}?fields=spreadsheetId,properties.title,spreadsheetUrl,sheets.properties,namedRanges", url_encode(spreadsheet_id) @@ -140,7 +203,7 @@ pub fn get_spreadsheet(spreadsheet_id: &str) -> Result Result Result { +pub fn read_values(spreadsheet_id: &str, range: &str) -> Result { let path = format!( "{}/values/{}", url_encode(spreadsheet_id), @@ -170,7 +233,7 @@ pub fn read_values(spreadsheet_id: &str, range: &str) -> Result Result Result { +) -> Result { let range_params: Vec = ranges .iter() .map(|r| format!("ranges={}", url_encode(r))) @@ -203,7 +266,7 @@ pub fn batch_read_values( let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; let value_ranges = parsed["valueRanges"] .as_array() @@ -235,7 +298,7 @@ pub fn write_values( range: &str, values: &[Vec], value_input_option: &str, -) -> Result { +) -> Result { let path = format!( "{}/values/{}?valueInputOption={}", url_encode(spreadsheet_id), @@ -249,10 +312,10 @@ pub fn write_values( "values": values, }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("PUT", &path, Some(&body_str))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(UpdateResult { updated_range: parsed["updatedRange"].as_str().unwrap_or("").to_string(), @@ -268,7 +331,7 @@ pub fn append_values( range: &str, values: &[Vec], value_input_option: &str, -) -> Result { +) -> Result { let path = format!( "{}/values/{}:append?valueInputOption={}&insertDataOption=INSERT_ROWS", url_encode(spreadsheet_id), @@ -282,10 +345,10 @@ pub fn append_values( "values": values, }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("POST", &path, Some(&body_str))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; let updates = &parsed["updates"]; Ok(UpdateResult { @@ -297,7 +360,7 @@ pub fn append_values( } /// Clear values from a range. -pub fn clear_values(spreadsheet_id: &str, range: &str) -> Result { +pub fn clear_values(spreadsheet_id: &str, range: &str) -> Result { let path = format!( "{}/values/{}:clear", url_encode(spreadsheet_id), @@ -306,7 +369,7 @@ pub fn clear_values(spreadsheet_id: &str, range: &str) -> Result Result, -) -> Result { +) -> Result { let path = format!("{}:batchUpdate", url_encode(spreadsheet_id)); let body = serde_json::json!({ "requests": requests }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("POST", &path, Some(&body_str))?; - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e)) + serde_json::from_str(&response).map_err(|e| serialization_failure(&e)) } /// Add a new sheet (tab) to the spreadsheet. -pub fn add_sheet(spreadsheet_id: &str, title: &str) -> Result { +pub fn add_sheet(spreadsheet_id: &str, title: &str) -> Result { let requests = vec![serde_json::json!({ "addSheet": { "properties": { @@ -344,7 +407,11 @@ pub fn add_sheet(spreadsheet_id: &str, title: &str) -> Result Result Result { +pub fn delete_sheet( + spreadsheet_id: &str, + sheet_id: i64, +) -> Result { let requests = vec![serde_json::json!({ "deleteSheet": { "sheetId": sheet_id @@ -380,7 +450,7 @@ pub fn rename_sheet( spreadsheet_id: &str, sheet_id: i64, title: &str, -) -> Result { +) -> Result { let requests = vec![serde_json::json!({ "updateSheetProperties": { "properties": { @@ -434,7 +504,7 @@ pub struct FormatOptions<'a> { } /// Format cells in a range. -pub fn format_cells(opts: FormatOptions<'_>) -> Result { +pub fn format_cells(opts: FormatOptions<'_>) -> Result { let mut format = serde_json::json!({}); let mut fields = Vec::new(); @@ -491,7 +561,10 @@ pub fn format_cells(opts: FormatOptions<'_>) -> Result { } if fields.is_empty() { - return Err("No formatting options specified".to_string()); + return Err(input_failure( + "no_formatting_options", + "No formatting options specified", + )); } let requests = vec![serde_json::json!({ @@ -521,3 +594,57 @@ pub fn format_cells(opts: FormatOptions<'_>) -> Result { fn url_encode(s: &str) -> String { urlencoding::encode(s).into_owned() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn api_status_error_401_maps_to_auth_required() { + let err = api_status_error("Google Sheets", 401, b"{\"error\":\"invalid_token\"}"); + + assert_eq!(err.kind, ErrorKind::AuthRequired); + assert_eq!( + err.code.as_deref(), + Some(GOOGLE_API_AUTH_REQUIRED_ERROR) + ); + } + + #[test] + fn api_status_error_non_401_maps_to_client() { + let err = api_status_error("Google Sheets", 429, b"rate limited"); + + assert_eq!(err.kind, ErrorKind::Client); + assert_eq!(err.code.as_deref(), Some("api_status_429")); + assert!( + err.message + .as_deref() + .is_some_and(|message| message.contains("rate limited")), + "{err:?}" + ); + } + + #[test] + fn format_cells_rejects_no_formatting_options() { + let err = format_cells(FormatOptions { + spreadsheet_id: "sheet-1", + sheet_id: 0, + start_row: 0, + end_row: 1, + start_column: 0, + end_column: 1, + bold: None, + italic: None, + font_size: None, + text_color: None, + background_color: None, + horizontal_alignment: None, + number_format: None, + number_format_type: None, + }) + .unwrap_err(); + + assert_eq!(err.kind, ErrorKind::Input); + assert_eq!(err.code.as_deref(), Some("no_formatting_options")); + } +} diff --git a/crates/extensions/packages/google-sheets/wasm-src/src/lib.rs b/crates/extensions/packages/google-sheets/wasm-src/src/lib.rs index 1e42ca86b7d..0f0afa120db 100644 --- a/crates/extensions/packages/google-sheets/wasm-src/src/lib.rs +++ b/crates/extensions/packages/google-sheets/wasm-src/src/lib.rs @@ -50,19 +50,15 @@ wit_bindgen::generate!({ path: "../../../../lanes/ironclaw_wasm/wit/tool.wit", }); +use exports::near::agent::tool::{ErrorKind, GuestFailure, Response}; + struct GoogleSheetsTool; impl exports::near::agent::tool::Guest for GoogleSheetsTool { fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response { match execute_inner(&req.params, req.context.as_deref()) { - Ok(result) => exports::near::agent::tool::Response { - output: Some(result), - error: None, - }, - Err(e) => exports::near::agent::tool::Response { - output: None, - error: Some(e), - }, + Ok(result) => Response::Success(result), + Err(failure) => Response::Failure(failure), } } @@ -86,11 +82,25 @@ impl exports::near::agent::tool::Guest for GoogleSheetsTool { } } -fn execute_inner(params: &str, context: Option<&str>) -> Result { +/// Build an `input`-kind guest failure with a stable code and no free-text +/// message (the code alone is the actionable signal for these host-plumbing +/// failures). +fn input_failure(code: &'static str) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: None, + } +} + +fn execute_inner(params: &str, context: Option<&str>) -> Result { let action_name = action_from_context(context)?; let params = params_with_action(params, action_name)?; - let action: GoogleSheetsAction = - serde_json::from_value(params).map_err(|e| format!("Invalid parameters: {}", e))?; + let action: GoogleSheetsAction = serde_json::from_value(params).map_err(|e| GuestFailure { + kind: ErrorKind::Input, + code: Some("invalid_parameters".to_string()), + message: Some(api::bounded_message(&e.to_string())), + })?; crate::near::agent::host::log( crate::near::agent::host::LogLevel::Debug, @@ -100,12 +110,12 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result let result = match action { GoogleSheetsAction::CreateSpreadsheet { title, sheet_names } => { let result = api::create_spreadsheet(&title, &sheet_names)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::GetSpreadsheet { spreadsheet_id } => { let result = api::get_spreadsheet(&spreadsheet_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::ReadValues { @@ -113,7 +123,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result range, } => { let result = api::read_values(&spreadsheet_id, &range)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::BatchReadValues { @@ -121,7 +131,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result ranges, } => { let result = api::batch_read_values(&spreadsheet_id, &ranges)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::WriteValues { @@ -131,7 +141,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result value_input_option, } => { let result = api::write_values(&spreadsheet_id, &range, &values, &value_input_option)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::AppendValues { @@ -141,7 +151,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result value_input_option, } => { let result = api::append_values(&spreadsheet_id, &range, &values, &value_input_option)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::ClearValues { @@ -149,7 +159,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result range, } => { let result = api::clear_values(&spreadsheet_id, &range)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::AddSheet { @@ -157,7 +167,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result title, } => { let result = api::add_sheet(&spreadsheet_id, &title)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::DeleteSheet { @@ -165,7 +175,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result sheet_id, } => { let result = api::delete_sheet(&spreadsheet_id, sheet_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::RenameSheet { @@ -174,7 +184,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result title, } => { let result = api::rename_sheet(&spreadsheet_id, sheet_id, &title)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSheetsAction::FormatCells { @@ -209,17 +219,17 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result number_format: number_format.as_deref(), number_format_type: number_format_type.as_deref(), })?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } }; Ok(result) } -fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { - let context = context.ok_or_else(|| "missing_invocation_context".to_string())?; +fn action_from_context(context: Option<&str>) -> Result<&'static str, GuestFailure> { + let context = context.ok_or_else(|| input_failure("missing_invocation_context"))?; let context: ToolContext = - serde_json::from_str(context).map_err(|_| "invalid_invocation_context".to_string())?; + serde_json::from_str(context).map_err(|_| input_failure("invalid_invocation_context"))?; match context.capability_id.as_str() { "google-sheets.create_spreadsheet" => Ok("create_spreadsheet"), "google-sheets.get_spreadsheet" => Ok("get_spreadsheet"), @@ -232,21 +242,21 @@ fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { "google-sheets.delete_sheet" => Ok("delete_sheet"), "google-sheets.rename_sheet" => Ok("rename_sheet"), "google-sheets.format_cells" => Ok("format_cells"), - _ => Err("unsupported_google_sheets_capability".to_string()), + _ => Err(input_failure("unsupported_google_sheets_capability")), } } -fn params_with_action(params: &str, action: &str) -> Result { +fn params_with_action(params: &str, action: &str) -> Result { let mut params: serde_json::Value = if params.trim().is_empty() { serde_json::json!({}) } else { - serde_json::from_str(params).map_err(|_| "invalid_parameters".to_string())? + serde_json::from_str(params).map_err(|_| input_failure("invalid_parameters"))? }; let obj = params .as_object_mut() - .ok_or_else(|| "invalid_parameters".to_string())?; + .ok_or_else(|| input_failure("invalid_parameters"))?; if obj.contains_key("action") { - return Err("invalid_parameters".to_string()); + return Err(input_failure("invalid_parameters")); } obj.insert( "action".to_string(), @@ -255,4 +265,21 @@ fn params_with_action(params: &str, action: &str) -> Result String { + const MAX_MESSAGE_CHARS: usize = 512; + message.chars().take(MAX_MESSAGE_CHARS).collect() +} + +// ponytail: duplicated across isolated WASM guest packages; consolidate only +// when guests share a supported contracts crate. +fn transport_failure(failure: &host::HttpFailure) -> GuestFailure { + let kind = match failure.kind { + host::HttpErrorKind::AuthRequired => ErrorKind::AuthRequired, + host::HttpErrorKind::Input => ErrorKind::Input, + host::HttpErrorKind::OutputTooLarge => ErrorKind::OutputTooLarge, + host::HttpErrorKind::Executor => ErrorKind::Executor, + host::HttpErrorKind::NetworkDenied => ErrorKind::NetworkDenied, + host::HttpErrorKind::Client => ErrorKind::Client, + host::HttpErrorKind::OperationFailed => ErrorKind::OperationFailed, + }; + GuestFailure { + kind, + code: failure.code.clone().or_else(|| Some("google_api_transport_error".into())), + message: failure.message.as_deref().map(bounded_message), + } +} + +/// A guest-side JSON encode/decode of an already-well-formed payload failed +/// — a tool-side processing failure, not anything the caller did wrong. +pub(crate) fn serialization_failure(error: &serde_json::Error) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Executor, + code: Some("serialization_failed".to_string()), + message: Some(bounded_message(&error.to_string())), + } +} + +/// Build an `input`-kind guest failure for a caller-supplied argument that +/// fails local validation before any egress. +fn input_failure(code: &'static str, message: impl Into) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: Some(bounded_message(&message.into())), + } +} + /// Make a Google Slides API call. -fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { +fn api_call(method: &str, path: &str, body: Option<&str>) -> Result { let url = if path.is_empty() { SLIDES_API_BASE.to_string() } else { @@ -31,43 +79,58 @@ fn api_call(method: &str, path: &str, body: Option<&str>) -> Result= 300 { - return Err(api_status_error("Google Slides", response.status, &response.body)); + return Err(api_status_error( + "Google Slides", + response.status, + &response.body, + )); } if response.body.is_empty() { return Ok(String::new()); } - String::from_utf8(response.body).map_err(|e| format!("Invalid UTF-8 in response: {}", e)) + String::from_utf8(response.body).map_err(|e| GuestFailure { + kind: ErrorKind::Executor, + code: Some("invalid_utf8_response".to_string()), + message: Some(bounded_message(&e.to_string())), + }) } -fn api_status_error(service: &str, status: u16, body: &[u8]) -> String { +fn api_status_error(service: &str, status: u16, body: &[u8]) -> GuestFailure { if status == 401 { - return serde_json::json!({ - "code": GOOGLE_API_AUTH_REQUIRED_ERROR, - "kind": "auth_required", - }) - .to_string(); + return GuestFailure { + kind: ErrorKind::AuthRequired, + code: Some(GOOGLE_API_AUTH_REQUIRED_ERROR.to_string()), + message: None, + }; } let body_text = String::from_utf8_lossy(body); - format!("{service} API returned status {status}: {body_text}") + GuestFailure { + kind: ErrorKind::Client, + code: Some(format!("api_status_{status}")), + message: Some(bounded_message(&format!( + "{service} API returned status {status}: {body_text}" + ))), + } } /// Send a batchUpdate to the presentation. fn batch_update_raw( presentation_id: &str, requests: Vec, -) -> Result { +) -> Result { let path = format!("{}:batchUpdate", url_encode(presentation_id)); let body = serde_json::json!({ "requests": requests }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("POST", &path, Some(&body_str))?; - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e)) + serde_json::from_str(&response).map_err(|e| serialization_failure(&e)) } /// Extract text content from a shape's textElements array. @@ -119,13 +182,13 @@ fn parse_element(el: &serde_json::Value) -> ElementInfo { } /// Create a new presentation. -pub fn create_presentation(title: &str) -> Result { +pub fn create_presentation(title: &str) -> Result { let body = serde_json::json!({ "title": title }); - let body_str = serde_json::to_string(&body).map_err(|e| e.to_string())?; + let body_str = serde_json::to_string(&body).map_err(|e| serialization_failure(&e))?; let response = api_call("POST", "", Some(&body_str))?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(CreatePresentationResult { presentation_id: parsed["presentationId"].as_str().unwrap_or("").to_string(), @@ -134,12 +197,12 @@ pub fn create_presentation(title: &str) -> Result Result { +pub fn get_presentation(presentation_id: &str) -> Result { let path = url_encode(presentation_id); let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; let slides: Vec = parsed["slides"] .as_array() @@ -179,7 +242,7 @@ pub fn get_presentation(presentation_id: &str) -> Result Result { +) -> Result { let path = format!( "{}/pages/{}/thumbnail", url_encode(presentation_id), @@ -188,7 +251,7 @@ pub fn get_thumbnail( let response = api_call("GET", &path, None)?; let parsed: serde_json::Value = - serde_json::from_str(&response).map_err(|e| format!("Failed to parse response: {}", e))?; + serde_json::from_str(&response).map_err(|e| serialization_failure(&e))?; Ok(ThumbnailResult { content_url: parsed["contentUrl"].as_str().unwrap_or("").to_string(), @@ -202,7 +265,7 @@ pub fn create_slide( presentation_id: &str, insertion_index: Option, layout: &str, -) -> Result { +) -> Result { let mut request = serde_json::json!({ "createSlide": { "slideLayoutReference": { @@ -228,7 +291,7 @@ pub fn create_slide( } /// Delete a slide or page element. -pub fn delete_object(presentation_id: &str, object_id: &str) -> Result { +pub fn delete_object(presentation_id: &str, object_id: &str) -> Result { let request = serde_json::json!({ "deleteObject": { "objectId": object_id } }); @@ -247,7 +310,7 @@ pub fn insert_text( object_id: &str, text: &str, insertion_index: i64, -) -> Result { +) -> Result { let request = serde_json::json!({ "insertText": { "objectId": object_id, @@ -270,7 +333,7 @@ pub fn delete_text( object_id: &str, start_index: i64, end_index: Option, -) -> Result { +) -> Result { let text_range = if let Some(end) = end_index { serde_json::json!({ "type": "FIXED_RANGE", @@ -305,7 +368,7 @@ pub fn replace_all_text( find: &str, replace: &str, match_case: bool, -) -> Result { +) -> Result { let request = serde_json::json!({ "replaceAllText": { "containsText": { @@ -342,7 +405,7 @@ pub fn create_shape( y: f64, width: f64, height: f64, -) -> Result { +) -> Result { let request = serde_json::json!({ "createShape": { "shapeType": shape_type, @@ -386,7 +449,7 @@ pub fn insert_image( y: f64, width: f64, height: f64, -) -> Result { +) -> Result { let request = serde_json::json!({ "createImage": { "url": image_url, @@ -456,7 +519,7 @@ pub struct FormatTextOptions<'a> { } /// Format text in a shape. -pub fn format_text(opts: FormatTextOptions<'_>) -> Result { +pub fn format_text(opts: FormatTextOptions<'_>) -> Result { let mut style = serde_json::json!({}); let mut fields = Vec::new(); @@ -488,7 +551,10 @@ pub fn format_text(opts: FormatTextOptions<'_>) -> Result } if fields.is_empty() { - return Err("No formatting options specified".to_string()); + return Err(input_failure( + "no_formatting_options", + "No formatting options specified", + )); } let text_range = match (opts.start_index, opts.end_index) { @@ -528,7 +594,7 @@ pub fn format_paragraph( alignment: &str, start_index: Option, end_index: Option, -) -> Result { +) -> Result { let text_range = match (start_index, end_index) { (Some(start), Some(end)) => serde_json::json!({ "type": "FIXED_RANGE", @@ -565,7 +631,7 @@ pub fn replace_shapes_with_image( find: &str, image_url: &str, match_case: bool, -) -> Result { +) -> Result { let request = serde_json::json!({ "replaceAllShapesWithImage": { "containsText": { @@ -593,7 +659,7 @@ pub fn replace_shapes_with_image( pub fn batch_update( presentation_id: &str, requests: Vec, -) -> Result { +) -> Result { let parsed = batch_update_raw(presentation_id, requests)?; let replies = parsed["replies"] @@ -610,3 +676,53 @@ pub fn batch_update( fn url_encode(s: &str) -> String { urlencoding::encode(s).into_owned() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn api_status_error_401_maps_to_auth_required() { + let err = api_status_error("Google Slides", 401, b"{\"error\":\"invalid_token\"}"); + + assert_eq!(err.kind, ErrorKind::AuthRequired); + assert_eq!( + err.code.as_deref(), + Some(GOOGLE_API_AUTH_REQUIRED_ERROR) + ); + } + + #[test] + fn api_status_error_non_401_maps_to_client() { + let err = api_status_error("Google Slides", 429, b"rate limited"); + + assert_eq!(err.kind, ErrorKind::Client); + assert_eq!(err.code.as_deref(), Some("api_status_429")); + assert!( + err.message + .as_deref() + .is_some_and(|message| message.contains("rate limited")), + "{err:?}" + ); + } + + #[test] + fn format_text_rejects_no_formatting_options() { + let err = format_text(FormatTextOptions { + presentation_id: "presentation-1", + object_id: "object-1", + start_index: None, + end_index: None, + bold: None, + italic: None, + underline: None, + font_size: None, + font_family: None, + foreground_color: None, + }) + .unwrap_err(); + + assert_eq!(err.kind, ErrorKind::Input); + assert_eq!(err.code.as_deref(), Some("no_formatting_options")); + } +} diff --git a/crates/extensions/packages/google-slides/wasm-src/src/lib.rs b/crates/extensions/packages/google-slides/wasm-src/src/lib.rs index 8ef148a1498..90f8d9c49dc 100644 --- a/crates/extensions/packages/google-slides/wasm-src/src/lib.rs +++ b/crates/extensions/packages/google-slides/wasm-src/src/lib.rs @@ -59,19 +59,15 @@ wit_bindgen::generate!({ path: "../../../../lanes/ironclaw_wasm/wit/tool.wit", }); +use exports::near::agent::tool::{ErrorKind, GuestFailure, Response}; + struct GoogleSlidesTool; impl exports::near::agent::tool::Guest for GoogleSlidesTool { fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response { match execute_inner(&req.params, req.context.as_deref()) { - Ok(result) => exports::near::agent::tool::Response { - output: Some(result), - error: None, - }, - Err(e) => exports::near::agent::tool::Response { - output: None, - error: Some(e), - }, + Ok(result) => Response::Success(result), + Err(failure) => Response::Failure(failure), } } @@ -98,11 +94,25 @@ impl exports::near::agent::tool::Guest for GoogleSlidesTool { } } -fn execute_inner(params: &str, context: Option<&str>) -> Result { +/// Build an `input`-kind guest failure with a stable code and no free-text +/// message (the code alone is the actionable signal for these host-plumbing +/// failures). +fn input_failure(code: &'static str) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: None, + } +} + +fn execute_inner(params: &str, context: Option<&str>) -> Result { let action_name = action_from_context(context)?; let params = params_with_action(params, action_name)?; - let action: GoogleSlidesAction = - serde_json::from_value(params).map_err(|e| format!("Invalid parameters: {}", e))?; + let action: GoogleSlidesAction = serde_json::from_value(params).map_err(|e| GuestFailure { + kind: ErrorKind::Input, + code: Some("invalid_parameters".to_string()), + message: Some(api::bounded_message(&e.to_string())), + })?; crate::near::agent::host::log( crate::near::agent::host::LogLevel::Debug, @@ -112,12 +122,12 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result let result = match action { GoogleSlidesAction::CreatePresentation { title } => { let result = api::create_presentation(&title)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::GetPresentation { presentation_id } => { let result = api::get_presentation(&presentation_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::GetThumbnail { @@ -125,7 +135,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result slide_object_id, } => { let result = api::get_thumbnail(&presentation_id, &slide_object_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::CreateSlide { @@ -134,7 +144,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result layout, } => { let result = api::create_slide(&presentation_id, insertion_index, &layout)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::DeleteObject { @@ -142,7 +152,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result object_id, } => { let result = api::delete_object(&presentation_id, &object_id)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::InsertText { @@ -152,7 +162,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result insertion_index, } => { let result = api::insert_text(&presentation_id, &object_id, &text, insertion_index)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::DeleteText { @@ -162,7 +172,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result end_index, } => { let result = api::delete_text(&presentation_id, &object_id, start_index, end_index)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::ReplaceAllText { @@ -172,7 +182,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result match_case, } => { let result = api::replace_all_text(&presentation_id, &find, &replace, match_case)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::CreateShape { @@ -193,7 +203,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result width, height, )?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::InsertImage { @@ -214,7 +224,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result width, height, )?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::FormatText { @@ -241,7 +251,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result font_family: font_family.as_deref(), foreground_color: foreground_color.as_deref(), })?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::FormatParagraph { @@ -258,7 +268,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result start_index, end_index, )?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::ReplaceShapesWithImage { @@ -269,7 +279,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result } => { let result = api::replace_shapes_with_image(&presentation_id, &find, &image_url, match_case)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } GoogleSlidesAction::BatchUpdate { @@ -277,17 +287,17 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result requests, } => { let result = api::batch_update(&presentation_id, requests)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } }; Ok(result) } -fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { - let context = context.ok_or_else(|| "missing_invocation_context".to_string())?; +fn action_from_context(context: Option<&str>) -> Result<&'static str, GuestFailure> { + let context = context.ok_or_else(|| input_failure("missing_invocation_context"))?; let context: ToolContext = - serde_json::from_str(context).map_err(|_| "invalid_invocation_context".to_string())?; + serde_json::from_str(context).map_err(|_| input_failure("invalid_invocation_context"))?; match context.capability_id.as_str() { "google-slides.create_presentation" => Ok("create_presentation"), "google-slides.get_presentation" => Ok("get_presentation"), @@ -303,21 +313,21 @@ fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { "google-slides.format_paragraph" => Ok("format_paragraph"), "google-slides.replace_shapes_with_image" => Ok("replace_shapes_with_image"), "google-slides.batch_update" => Ok("batch_update"), - _ => Err("unsupported_google_slides_capability".to_string()), + _ => Err(input_failure("unsupported_google_slides_capability")), } } -fn params_with_action(params: &str, action: &str) -> Result { +fn params_with_action(params: &str, action: &str) -> Result { let mut params: serde_json::Value = if params.trim().is_empty() { serde_json::json!({}) } else { - serde_json::from_str(params).map_err(|_| "invalid_parameters".to_string())? + serde_json::from_str(params).map_err(|_| input_failure("invalid_parameters"))? }; let obj = params .as_object_mut() - .ok_or_else(|| "invalid_parameters".to_string())?; + .ok_or_else(|| input_failure("invalid_parameters"))?; if obj.contains_key("action") { - return Err("invalid_parameters".to_string()); + return Err(input_failure("invalid_parameters")); } obj.insert( "action".to_string(), @@ -326,4 +336,21 @@ fn params_with_action(params: &str, action: &str) -> Result String { +/// Build the typed guest-failure (WIT `guest-failure`, near:agent@0.4.1) for +/// a Slack failure, so a failure keeps its actionable error code instead of +/// collapsing to a generic "the tool operation failed". +fn structured_error(code: &str, kind: ErrorKind) -> GuestFailure { // Slack error codes are snake_case ASCII identifiers; reduce to that shape // so a hostile response body cannot smuggle free text into the error // channel (the host sanitizes again before anything reaches the model). @@ -38,7 +35,11 @@ fn structured_error(code: &str, kind: &'static str) -> String { } else { code }; - serde_json::json!({ "code": code, "kind": kind }).to_string() + GuestFailure { + kind, + code: Some(code), + message: None, + } } /// True for Slack error codes that mean the credential itself is invalid or @@ -102,8 +103,7 @@ fn slack_error_to_standard_code(code: &str) -> &'static str { /// The WASM structured-error `kind` for a standard messaging error code, /// chosen from the finite set the host actually parses -/// (`StructuredWasmGuestErrorKind` in -/// `crates/kernel/ironclaw_host_runtime/src/services/wasm_execution.rs:333-343`) — +/// (`error-kind` in `crates/lanes/ironclaw_wasm/wit/tool.wit`) — /// NOT the spec §8 class-column labels verbatim, which do not name real /// variants of that enum. `input` covers the invalid-input-class codes /// (immediately model-visible; the model can retry with different @@ -118,27 +118,44 @@ fn slack_error_to_standard_code(code: &str) -> &'static str { /// non-taxonomy synthetic failures (a malformed/missing conversation /// identity, a send with no `ts`) on the exact kind they used before this /// task. -fn standard_messaging_error_kind(standard_code: &str) -> &'static str { +fn standard_messaging_error_kind(standard_code: &str) -> ErrorKind { match standard_code { "messaging.unknown_conversation" | "messaging.unknown_message" | "messaging.unknown_user" | "messaging.message_too_long" - | "messaging.unsupported_content" => "input", - "messaging.rate_limited" => "client", - _ => "operation_failed", + | "messaging.unsupported_content" => ErrorKind::Input, + "messaging.rate_limited" => ErrorKind::Client, + _ => ErrorKind::OperationFailed, } } -/// Map a raw Slack error code straight to the host's structured guest-error -/// JSON via the standard taxonomy — the shared tail every [`RawSlackFailure`] -/// arm not requiring special handling (auth, `as_user` retry) funnels -/// through. -fn structured_taxonomy_error(slack_code: &str) -> String { +/// Map a raw Slack error code straight to the typed guest-failure via the +/// standard taxonomy — the shared tail every [`RawSlackFailure`] arm not +/// requiring special handling (auth, `as_user` retry) funnels through. +fn structured_taxonomy_error(slack_code: &str) -> GuestFailure { let standard_code = slack_error_to_standard_code(slack_code); structured_error(standard_code, standard_messaging_error_kind(standard_code)) } +/// A guest-side JSON encode of an already-constructed payload failed — an +/// internal invariant break, not anything the caller did wrong. +pub(crate) fn serialization_failure(error: &serde_json::Error) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Executor, + code: Some("serialization_failed".to_string()), + message: Some(bounded_message(&error.to_string())), + } +} + +/// Bound a free-text message to a sane length before it rides in a +/// `guest-failure`; the host re-bounds and scrubs downstream, but the guest +/// should never hand over an unbounded string in the first place. +pub(crate) fn bounded_message(message: &str) -> String { + const MAX_MESSAGE_CHARS: usize = 512; + message.chars().take(MAX_MESSAGE_CHARS).collect() +} + /// Percent-encode a string for use as a URL query parameter value. fn url_encode(s: &str) -> String { let mut out = String::with_capacity(s.len()); @@ -169,17 +186,15 @@ fn next_cursor_from_response(parsed: &serde_json::Value) -> Option { } /// One Slack API failure, before taxonomy mapping. Kept distinct from the -/// final structured JSON error so `send_message` can inspect the RAW vendor +/// final typed guest-failure so `send_message` can inspect the RAW vendor /// code for the classic-vs-granular-app `as_user` retry without -/// string-matching an already-mapped/JSON-encoded error. +/// string-matching an already-mapped error. #[derive(Debug)] enum RawSlackFailure { - /// A host-level transport failure (network denial, timeout, ...). The - /// string is already one of the host's own literal error identifiers - /// (`host_http_network_denied` etc., see `wasm_guest_error_kind`'s - /// literal-string table) — passed straight through unmapped, exactly as - /// before this task. - Transport(String), + /// A host-level transport failure. The host supplies a closed error kind, + /// optional stable code, and bounded message; `structured_error_for` + /// preserves that typed classification in the guest response. + Transport(host::HttpFailure), /// Non-2xx HTTP status that was not itself a recognized rate limit. HttpStatus(u16), /// HTTP 429 / Slack-signaled rate limiting. @@ -190,20 +205,34 @@ enum RawSlackFailure { Vendor(String), } -/// Map a [`RawSlackFailure`] to the host's structured guest-error JSON: -/// genuine credential problems keep riding the existing `AuthRequired` -/// re-auth gate; everything else maps onto the closed `messaging.*` -/// vocabulary. -fn structured_error_for(failure: RawSlackFailure) -> String { +/// Map a [`RawSlackFailure`] to the typed guest-failure: genuine credential +/// problems keep riding the existing `AuthRequired` re-auth gate; everything +/// else maps onto the closed `messaging.*` vocabulary. +fn structured_error_for(failure: RawSlackFailure) -> GuestFailure { match failure { - RawSlackFailure::Transport(raw) => raw, + RawSlackFailure::Transport(failure) => { + let kind = match failure.kind { + host::HttpErrorKind::AuthRequired => ErrorKind::AuthRequired, + host::HttpErrorKind::Input => ErrorKind::Input, + host::HttpErrorKind::OutputTooLarge => ErrorKind::OutputTooLarge, + host::HttpErrorKind::Executor => ErrorKind::Executor, + host::HttpErrorKind::NetworkDenied => ErrorKind::NetworkDenied, + host::HttpErrorKind::Client => ErrorKind::Client, + host::HttpErrorKind::OperationFailed => ErrorKind::OperationFailed, + }; + GuestFailure { + kind, + code: failure.code, + message: failure.message.as_deref().map(bounded_message), + } + } RawSlackFailure::RateLimited => structured_taxonomy_error("ratelimited"), RawSlackFailure::HttpStatus(status) => { structured_taxonomy_error(&format!("http_status_{status}")) } RawSlackFailure::InvalidJson => structured_taxonomy_error("invalid_json_response"), RawSlackFailure::Vendor(code) if slack_error_requires_reauth(&code) => { - structured_error(&code, "auth_required") + structured_error(&code, ErrorKind::AuthRequired) } RawSlackFailure::Vendor(code) => structured_taxonomy_error(&code), } @@ -212,7 +241,7 @@ fn structured_error_for(failure: RawSlackFailure) -> String { /// Make a Slack API call and return the parsed JSON value, surfacing HTTP /// and Slack (`ok: false`) failures as the RAW [`RawSlackFailure`] shape — /// before taxonomy mapping. Shared by [`slack_api_call`] (which maps every -/// failure to the host's structured guest-error JSON) and `send_message` +/// failure to the host's typed [`GuestFailure`]) and `send_message` /// (which additionally needs the RAW vendor code to decide whether to retry /// without `as_user`). fn slack_api_call_raw( @@ -253,8 +282,6 @@ fn slack_api_call_raw( ), ); // Slack signals rate limiting at the HTTP layer (429 + Retry-After); - // the host's structured error shape carries only {code, kind}, so the - // Retry-After value cannot ride along. if response.status == 429 { return Err(RawSlackFailure::RateLimited); } @@ -279,13 +306,13 @@ fn slack_api_call_raw( Ok(parsed) } -/// [`slack_api_call_raw`], mapped to the host's structured guest-error JSON +/// [`slack_api_call_raw`], mapped to the host's typed [`GuestFailure`] /// — the call every op except `send_message`'s first attempt uses. fn slack_api_call( method: &str, endpoint: &str, body: Option<&str>, -) -> Result { +) -> Result { slack_api_call_raw(method, endpoint, body).map_err(structured_error_for) } @@ -349,7 +376,7 @@ fn civil_from_days(z: i64) -> (i64, u32, u32) { const MAX_USER_NAME_LOOKUPS: usize = 25; /// Resolve the CONNECTED account via `auth.test`: `(user_id, team_id)`. -fn auth_test() -> Result<(String, Option), String> { +fn auth_test() -> Result<(String, Option), GuestFailure> { let parsed = slack_api_call("GET", "auth.test", None)?; let user_id = parsed["user_id"] .as_str() @@ -369,7 +396,7 @@ fn current_user_id_best_effort() -> Option { Err(error) => { host::log( host::LogLevel::Debug, - &format!("auth.test identity lookup skipped: {error}"), + &format!("auth.test identity lookup skipped: {error:?}"), ); None } @@ -393,7 +420,7 @@ fn mark_is_self(messages: &mut [Message], current_user_id: Option<&str>) { /// [`get_user_info`] (the canonical public result) because the display-name /// fallback chain below needs Slack's raw username, which has no canonical /// field to live in. -fn raw_user_info(user_id: &str) -> Result { +fn raw_user_info(user_id: &str) -> Result { let url = format!("users.info?user={}", url_encode(user_id)); slack_api_call("GET", &url, None) } @@ -462,7 +489,7 @@ fn resolve_user_display_names( Err(error) => { host::log( host::LogLevel::Debug, - &format!("users.info lookup skipped: {error}"), + &format!("users.info lookup skipped: {error:?}"), ); } } @@ -659,7 +686,7 @@ pub fn list_conversations( kinds: Option<&[ConversationKind]>, limit: Option, cursor: Option<&str>, -) -> Result { +) -> Result { let types = slack_types_for_kinds(kinds); if types.is_empty() { return Ok(ListConversationsResult { @@ -710,7 +737,7 @@ pub fn list_conversations( /// Retrieve one exact Slack conversation by ID. Unlike /// `list_conversations`, this response cannot be hidden beyond a model-output /// preview boundary or confused with another same-name DM. -pub fn get_conversation_info(conversation: &str) -> Result { +pub fn get_conversation_info(conversation: &str) -> Result { let url = format!("conversations.info?channel={}", url_encode(conversation)); let parsed = slack_api_call("GET", &url, None)?; let mut info = conversation_info_from_value(&parsed["channel"]); @@ -830,7 +857,7 @@ pub fn get_conversation_history( conversation: &str, limit: Option, cursor: Option<&str>, -) -> Result { +) -> Result { // Slack rejects limit=1000; 999 is the real maximum. let limit = limit.unwrap_or(50).clamp(1, 999); let mut url = format!( @@ -855,7 +882,7 @@ pub fn get_thread_replies( thread: &str, limit: Option, cursor: Option<&str>, -) -> Result { +) -> Result { // Slack rejects limit=1000; 999 is the real maximum. let limit = limit.unwrap_or(50).clamp(1, 999); let mut url = format!( @@ -917,7 +944,7 @@ pub fn search_messages( sort: Option, limit: Option, cursor: Option<&str>, -) -> Result { +) -> Result { let count = limit.unwrap_or(20).clamp(1, 100); // W14 (pre-merge amendment wave, binding ruling): a SUPPLIED cursor that // fails to decode as a Slack page number must surface a model-visible @@ -935,7 +962,10 @@ pub fn search_messages( host::LogLevel::Debug, &format!("search_messages: unrecognized pagination cursor: {raw_cursor}"), ); - return Err(structured_error("messaging.unsupported_content", "input")); + return Err(structured_error( + "messaging.unsupported_content", + ErrorKind::Input, + )); } }, }; @@ -979,7 +1009,7 @@ pub fn search_messages( } /// Get information about a user. -pub fn get_user_info(user_ref: &str) -> Result { +pub fn get_user_info(user_ref: &str) -> Result { let parsed = raw_user_info(user_ref)?; let user = &parsed["user"]; @@ -1017,14 +1047,14 @@ pub fn get_user_info(user_ref: &str) -> Result { /// Resolve who the CONNECTED account is: `auth.test` for the user id (the /// operation itself, so its failure fails the call) plus a best-effort /// `users.info` for the human-readable name. -pub fn whoami() -> Result { +pub fn whoami() -> Result { let (user_id, _team_id) = auth_test()?; let display_name = match raw_user_info(&user_id) { Ok(parsed) => display_name_fallback_from_user_info(&parsed), Err(error) => { host::log( host::LogLevel::Debug, - &format!("whoami users.info lookup skipped: {error}"), + &format!("whoami users.info lookup skipped: {error:?}"), ); None } @@ -1040,7 +1070,7 @@ fn send_message_payload( text: &str, thread: Option<&str>, as_user: bool, -) -> Result { +) -> Result { let mut payload = serde_json::json!({ "channel": conversation, "text": text, @@ -1051,7 +1081,7 @@ fn send_message_payload( if let Some(ts) = thread { payload["thread_ts"] = serde_json::Value::String(ts.to_string()); } - serde_json::to_string(&payload).map_err(|e| e.to_string()) + serde_json::to_string(&payload).map_err(|e| serialization_failure(&e)) } /// Send a message as the user. @@ -1084,7 +1114,7 @@ pub fn send_message( text: &str, thread: Option<&str>, reply_to: Option<&MessageRefInput>, -) -> Result { +) -> Result { let effective_thread_ts = thread.or_else(|| reply_to.map(|reply_to| reply_to.message_id.as_str())); let payload = send_message_payload(conversation, text, effective_thread_ts, true)?; @@ -1148,10 +1178,10 @@ fn message_ref_payload(message_ref: &MessageRefInput) -> serde_json::Value { pub fn edit_message( message_ref: &MessageRefInput, text: &str, -) -> Result { +) -> Result { let mut payload = message_ref_payload(message_ref); payload["text"] = serde_json::Value::String(text.to_string()); - let payload = serde_json::to_string(&payload).map_err(|e| e.to_string())?; + let payload = serde_json::to_string(&payload).map_err(|e| serialization_failure(&e))?; let parsed = slack_api_call("POST", "chat.update", Some(&payload))?; @@ -1177,9 +1207,9 @@ pub fn edit_message( /// restating the message — so the returned ref falls back to the input /// address when the response omits it. `deleted` is always `true`: a delete /// that did not happen has already returned an error above. -pub fn delete_message(message_ref: &MessageRefInput) -> Result { - let payload = - serde_json::to_string(&message_ref_payload(message_ref)).map_err(|e| e.to_string())?; +pub fn delete_message(message_ref: &MessageRefInput) -> Result { + let payload = serde_json::to_string(&message_ref_payload(message_ref)) + .map_err(|e| serialization_failure(&e))?; let parsed = slack_api_call("POST", "chat.delete", Some(&payload))?; @@ -1212,13 +1242,13 @@ fn normalize_emoji(emoji: &str) -> String { } /// `reactions.add`/`reactions.remove` share this body shape. -fn reaction_payload(message_ref: &MessageRefInput, name: &str) -> Result { +fn reaction_payload(message_ref: &MessageRefInput, name: &str) -> Result { serde_json::to_string(&serde_json::json!({ "channel": message_ref.conversation, "timestamp": message_ref.message_id, "name": name, })) - .map_err(|e| e.to_string()) + .map_err(|e| serialization_failure(&e)) } /// Slack's "you already reacted with this" code — `reactions.add`'s @@ -1239,7 +1269,7 @@ const NO_REACTION: &str = "no_reaction"; fn reaction_write_outcome( result: Result, end_state_code: &str, -) -> Result<(), String> { +) -> Result<(), GuestFailure> { match result { Ok(_) => Ok(()), Err(RawSlackFailure::Vendor(code)) if code == end_state_code => Ok(()), @@ -1251,10 +1281,13 @@ fn reaction_write_outcome( pub fn add_reaction( message_ref: &MessageRefInput, emoji: &str, -) -> Result { +) -> Result { let name = normalize_emoji(emoji); if name.is_empty() { - return Err(structured_error("messaging.unsupported_content", "input")); + return Err(structured_error( + "messaging.unsupported_content", + ErrorKind::Input, + )); } let payload = reaction_payload(message_ref, &name)?; @@ -1270,7 +1303,7 @@ pub fn add_reaction( } /// Remove one named reaction. -fn remove_one_reaction(message_ref: &MessageRefInput, name: &str) -> Result<(), String> { +fn remove_one_reaction(message_ref: &MessageRefInput, name: &str) -> Result<(), GuestFailure> { let payload = reaction_payload(message_ref, name)?; reaction_write_outcome( slack_api_call_raw("POST", "reactions.remove", Some(&payload)), @@ -1286,7 +1319,7 @@ fn remove_one_reaction(message_ref: &MessageRefInput, name: &str) -> Result<(), /// else's — so unlike the best-effort identity marking on reads, an /// `auth.test` failure fails the call instead of degrading it. Removing /// someone else's reaction is the failure this guards against. -fn own_reaction_names(message_ref: &MessageRefInput) -> Result, String> { +fn own_reaction_names(message_ref: &MessageRefInput) -> Result, GuestFailure> { let (current_user_id, _team_id) = auth_test()?; // `full=true` is load-bearing: without it Slack truncates each // reaction's `users` array on popular messages, and a truncated list @@ -1348,12 +1381,15 @@ fn own_reaction_names_from_response( pub fn remove_reaction( message_ref: &MessageRefInput, emoji: Option<&str>, -) -> Result { +) -> Result { match emoji { Some(emoji) => { let name = normalize_emoji(emoji); if name.is_empty() { - return Err(structured_error("messaging.unsupported_content", "input")); + return Err(structured_error( + "messaging.unsupported_content", + ErrorKind::Input, + )); } remove_one_reaction(message_ref, &name)?; Ok(RemoveReactionResult { @@ -1378,17 +1414,17 @@ pub fn remove_reaction( /// /// Slack returns the existing DM when one is already open, so this is safe to /// call repeatedly and never creates a duplicate conversation. -pub fn open_dm(user_ref: &str) -> Result { +pub fn open_dm(user_ref: &str) -> Result { // Slack's `users` field takes a comma-separated LIST: two ids would // silently open a multi-person group DM while every contract layer // promises the 1:1 DM with one person. Requiring a single well-formed // user id here (commas and lowercase both fail the check) keeps that // promise instead of delegating it to the model's good behavior. if !is_slack_user_id(user_ref) { - return Err(structured_error("messaging.unknown_user", "input")); + return Err(structured_error("messaging.unknown_user", ErrorKind::Input)); } let payload = serde_json::to_string(&serde_json::json!({ "users": user_ref })) - .map_err(|e| e.to_string())?; + .map_err(|e| serialization_failure(&e))?; let parsed = slack_api_call("POST", "conversations.open", Some(&payload))?; @@ -1425,7 +1461,7 @@ fn exact_message( /// miss falls back to `conversations.replies`, which returns the whole thread /// a ts belongs to. Only an exact ts match is ever returned; anything else is /// `messaging.unknown_message` rather than a neighbouring message. -pub fn get_message(message_ref: &MessageRefInput) -> Result { +pub fn get_message(message_ref: &MessageRefInput) -> Result { let conversation = message_ref.conversation.as_str(); let target_ts = message_ref.message_id.as_str(); @@ -1465,7 +1501,10 @@ pub fn get_message(message_ref: &MessageRefInput) -> Result, cursor: Option<&str>, -) -> Result { +) -> Result { let limit = limit .unwrap_or(RESOLVE_USER_SCAN_PAGE) .clamp(1, RESOLVE_USER_SCAN_PAGE); let needle = query.trim().to_lowercase(); if needle.is_empty() { - return Err(structured_error("messaging.unsupported_content", "input")); + return Err(structured_error( + "messaging.unsupported_content", + ErrorKind::Input, + )); } let mut url = format!("users.list?limit={limit}"); @@ -1601,7 +1643,7 @@ pub fn list_members( conversation: &str, limit: Option, cursor: Option<&str>, -) -> Result { +) -> Result { // Slack rejects limit=1000; 999 is the real maximum. let limit = limit.unwrap_or(100).clamp(1, 999); let mut url = format!( @@ -1732,11 +1774,11 @@ mod tests { fn unknown_message_is_an_input_class_failure() { assert_eq!( standard_messaging_error_kind("messaging.unknown_message"), - "input" + ErrorKind::Input ); assert_eq!( standard_messaging_error_kind("messaging.cannot_message_user"), - "operation_failed" + ErrorKind::OperationFailed ); } @@ -1827,9 +1869,10 @@ mod tests { // Everything else still maps through the closed taxonomy. let error = reaction_write_outcome(vendor("message_not_found"), ALREADY_REACTED) .expect_err("an unresolvable message is a failure"); - assert!( - error.contains("messaging.unknown_message"), - "expected the canonical code, got {error}" + assert_eq!( + error.code.as_deref(), + Some("messaging.unknown_message"), + "expected the canonical code, got {error:?}" ); } diff --git a/crates/extensions/packages/slack/wasm-src/src/lib.rs b/crates/extensions/packages/slack/wasm-src/src/lib.rs index 0806aef9548..d0c5cfad720 100644 --- a/crates/extensions/packages/slack/wasm-src/src/lib.rs +++ b/crates/extensions/packages/slack/wasm-src/src/lib.rs @@ -51,20 +51,16 @@ wit_bindgen::generate!({ path: "../../../../lanes/ironclaw_wasm/wit/tool.wit", }); +use exports::near::agent::tool::{ErrorKind, GuestFailure, Response}; + /// Implementation of the tool interface. struct SlackUserTool; impl exports::near::agent::tool::Guest for SlackUserTool { fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response { match execute_inner(&req.params, req.context.as_deref()) { - Ok(result) => exports::near::agent::tool::Response { - output: Some(result), - error: None, - }, - Err(e) => exports::near::agent::tool::Response { - output: None, - error: Some(e), - }, + Ok(result) => Response::Success(result), + Err(failure) => Response::Failure(failure), } } @@ -87,15 +83,29 @@ impl exports::near::agent::tool::Guest for SlackUserTool { } } +/// Build an `input`-kind guest failure with a stable code and no free-text +/// message (the code alone is the actionable signal for these host-plumbing +/// failures). +fn input_failure(code: &'static str) -> GuestFailure { + GuestFailure { + kind: ErrorKind::Input, + code: Some(code.to_string()), + message: None, + } +} + /// Inner execution logic. The host selects the operation via the capability id /// in the invocation context; params carry only the operation's fields (no /// `action` key). The Slack user token is injected by the host as a bearer /// credential — a missing credential surfaces as an auth gate, not here. -fn execute_inner(params: &str, context: Option<&str>) -> Result { +fn execute_inner(params: &str, context: Option<&str>) -> Result { let action_name = action_from_context(context)?; let params = params_with_action(params, action_name)?; - let action: SlackUserAction = - serde_json::from_value(params).map_err(|e| format!("Invalid parameters: {}", e))?; + let action: SlackUserAction = serde_json::from_value(params).map_err(|e| GuestFailure { + kind: ErrorKind::Input, + code: Some("invalid_parameters".to_string()), + message: Some(api::bounded_message(&e.to_string())), + })?; crate::near::agent::host::log( crate::near::agent::host::LogLevel::Debug, @@ -110,7 +120,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result cursor, } => { let result = api::search_messages(&query, sort, limit, cursor.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::ListConversations { @@ -119,12 +129,12 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result cursor, } => { let result = api::list_conversations(kinds.as_deref(), limit, cursor.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::GetConversationInfo { conversation } => { let result = api::get_conversation_info(&conversation)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::GetConversationHistory { @@ -133,7 +143,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result cursor, } => { let result = api::get_conversation_history(&conversation, limit, cursor.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::GetThreadReplies { @@ -143,17 +153,17 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result cursor, } => { let result = api::get_thread_replies(&conversation, &thread, limit, cursor.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::GetUserInfo { user_ref } => { let result = api::get_user_info(&user_ref)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::Whoami => { let result = api::whoami()?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::SendMessage { @@ -164,37 +174,37 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result } => { let result = api::send_message(&conversation, &text, thread.as_deref(), reply_to.as_ref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::EditMessage { message_ref, text } => { let result = api::edit_message(&message_ref, &text)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::DeleteMessage { message_ref } => { let result = api::delete_message(&message_ref)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::AddReaction { message_ref, emoji } => { let result = api::add_reaction(&message_ref, &emoji)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::RemoveReaction { message_ref, emoji } => { let result = api::remove_reaction(&message_ref, emoji.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::OpenDm { user_ref } => { let result = api::open_dm(&user_ref)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::GetMessage { message_ref } => { let result = api::get_message(&message_ref)?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::ResolveUser { @@ -203,7 +213,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result cursor, } => { let result = api::resolve_user(&query, limit, cursor.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } SlackUserAction::ListMembers { @@ -212,7 +222,7 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result cursor, } => { let result = api::list_members(&conversation, limit, cursor.as_deref())?; - serde_json::to_string(&result).map_err(|e| e.to_string())? + serde_json::to_string(&result).map_err(|e| api::serialization_failure(&e))? } }; @@ -221,10 +231,13 @@ fn execute_inner(params: &str, context: Option<&str>) -> Result /// Map a capability id (e.g. `slack.search_messages`) to the serde action /// tag the params enum expects. -fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { - let context = context.ok_or_else(|| "missing_invocation_context".to_string())?; - let context: ToolContext = - serde_json::from_str(context).map_err(|e| format!("invalid_invocation_context: {e}"))?; +fn action_from_context(context: Option<&str>) -> Result<&'static str, GuestFailure> { + let context = context.ok_or_else(|| input_failure("missing_invocation_context"))?; + let context: ToolContext = serde_json::from_str(context).map_err(|e| GuestFailure { + kind: ErrorKind::Input, + code: Some("invalid_invocation_context".to_string()), + message: Some(api::bounded_message(&e.to_string())), + })?; match context.capability_id.as_str() { "slack.search_messages" => Ok("search_messages"), "slack.list_conversations" => Ok("list_conversations"), @@ -242,24 +255,24 @@ fn action_from_context(context: Option<&str>) -> Result<&'static str, String> { "slack.get_message" => Ok("get_message"), "slack.resolve_user" => Ok("resolve_user"), "slack.list_members" => Ok("list_members"), - _ => Err("unsupported_slack_user_capability".to_string()), + _ => Err(input_failure("unsupported_slack_user_capability")), } } /// Inject the host-selected `action` tag into the params object so the tagged /// `SlackUserAction` enum can deserialize. Rejects params that already carry an /// `action` key (the host owns operation selection). -fn params_with_action(params: &str, action: &str) -> Result { +fn params_with_action(params: &str, action: &str) -> Result { let mut params: serde_json::Value = if params.trim().is_empty() { serde_json::json!({}) } else { - serde_json::from_str(params).map_err(|_| "invalid_parameters".to_string())? + serde_json::from_str(params).map_err(|_| input_failure("invalid_parameters"))? }; let obj = params .as_object_mut() - .ok_or_else(|| "invalid_parameters".to_string())?; + .ok_or_else(|| input_failure("invalid_parameters"))?; if obj.contains_key("action") { - return Err("invalid_parameters".to_string()); + return Err(input_failure("invalid_parameters")); } obj.insert( "action".to_string(), diff --git a/crates/extensions/packages/slack/wasm/slack_user_tool.wasm b/crates/extensions/packages/slack/wasm/slack_user_tool.wasm index edbc9ade836..d1c43ca8287 100644 Binary files a/crates/extensions/packages/slack/wasm/slack_user_tool.wasm and b/crates/extensions/packages/slack/wasm/slack_user_tool.wasm differ diff --git a/crates/extensions/packages/telegram/src/linked/conformance.rs b/crates/extensions/packages/telegram/src/linked/conformance.rs index 38127f84dd9..094fe0ca85a 100644 --- a/crates/extensions/packages/telegram/src/linked/conformance.rs +++ b/crates/extensions/packages/telegram/src/linked/conformance.rs @@ -36,7 +36,7 @@ use std::panic::{self, AssertUnwindSafe}; use ironclaw_extension_contracts::tool_adapter::ToolError; use ironclaw_host_api::{ - dispatch::{DispatchFailureKind, RuntimeDispatchErrorKind}, + dispatch::RuntimeDispatchErrorKind, messaging::{StandardMessagingErrorCode, StandardMessagingOp}, test_support::messaging_conformance::{ assert_canonical_input_accepted, assert_canonical_output, message_ref_from_output, @@ -71,23 +71,20 @@ fn conversation() -> ConversationRef { fn failure_kind(error: &ToolError) -> Option { match error { - ToolError::Failed { kind, .. } => Some(*kind), - // Rejected's kind is a superset (DispatchFailureKind); only its - // Runtime(..) variant carries a RuntimeDispatchErrorKind to unwrap. - ToolError::Rejected { kind, .. } => match kind { - DispatchFailureKind::Runtime(runtime_kind) => Some(*runtime_kind), - _ => None, - }, + ToolError::Rejected { kind, .. } => Some(*kind), ToolError::AuthRequired { .. } => None, } } fn failure_summary(error: &ToolError) -> String { match error { - ToolError::Failed { safe_summary, .. } => { - safe_summary.clone().unwrap_or_else(|| "".to_string()) - } - ToolError::Rejected { kind, .. } => kind.human_summary().to_string(), + ToolError::Rejected { + kind, diagnostic, .. + } => diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.code.as_ref()) + .map(|code| code.as_str().to_string()) + .unwrap_or_else(|| kind.human_summary().to_string()), ToolError::AuthRequired { .. } => "auth_required".to_string(), } } @@ -286,15 +283,13 @@ fn an_unknown_write_outcome_is_a_vendor_error_never_an_unverified_send() { // difference: "the send failed" invites a re-send that double-messages // a human, and "the message was sent" suppresses a re-send that may be // the only delivery. - let ToolError::Failed { - model_visible_cause, - .. - } = &mapped - else { - panic!("an unknown write outcome is a failure"); + let ToolError::Rejected { diagnostic, .. } = &mapped else { + panic!("an unknown write outcome is a rejection"); }; - let cause = model_visible_cause - .clone() + let cause = diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.message.as_ref()) + .map(|message| message.as_str()) .expect("an unknown outcome must say so"); assert!(cause.contains("before the outcome was known"), "{cause}"); @@ -303,7 +298,7 @@ fn an_unknown_write_outcome_is_a_vendor_error_never_an_unverified_send() { // `send_result` builds when the vendor RETURNED a message. An error // path never reaches that builder, so the marker cannot appear here — // which is what keeps "unknown" from being reported as "delivered". - assert!(matches!(mapped, ToolError::Failed { .. })); + assert!(matches!(mapped, ToolError::Rejected { .. })); } // The contrast that makes the rule visible: the *same* op family, given a diff --git a/crates/extensions/packages/telegram/src/linked/mapping.rs b/crates/extensions/packages/telegram/src/linked/mapping.rs index 4dc893f8b4e..8438f4aeff9 100644 --- a/crates/extensions/packages/telegram/src/linked/mapping.rs +++ b/crates/extensions/packages/telegram/src/linked/mapping.rs @@ -31,11 +31,15 @@ use ironclaw_extension_contracts::tool_adapter::ToolError; use ironclaw_host_api::{ capability::RuntimeCredentialAccountSetup, decision::RuntimeCredentialAuthRequirement, - dispatch::{DispatchAuthRequirement, RuntimeDispatchErrorKind}, + dispatch::{ + DispatchAuthRequirement, ProviderDiagnostic, ProviderErrorCode, RuntimeDispatchErrorKind, + UntrustedProviderMessage, + }, ids::{ExtensionId, SecretHandle, VendorId}, messaging::StandardMessagingErrorCode, }; use serde_json::{Value, json}; +use std::time::Duration; use super::{MAX_MESSAGE_TEXT_BYTES, MAX_RESULT_BYTES}; @@ -67,26 +71,41 @@ const CURSOR_TAG: &str = "p1"; // Failure construction // --------------------------------------------------------------------------- -/// A canonical messaging failure. `safe_summary` carries only the fixed -/// canonical code string (never vendor payload); `model_visible_cause` carries -/// the one piece of vendor detail worth surfacing — today, a flood wait's -/// retry-after — as prose, because no structured retry-after slot is plumbed -/// through tool dispatch (§6.6). +/// A canonical messaging rejection. The closed code crosses the adapter +/// boundary as a typed value; the extension host turns it into the trusted +/// public summary. `ProviderDiagnostic` carries only vendor detail and is +/// scrubbed by the host before model visibility. pub(crate) fn failed(code: StandardMessagingErrorCode) -> ToolError { - ToolError::Failed { + ToolError::Rejected { kind: RuntimeDispatchErrorKind::OperationFailed, - safe_summary: Some(format!("telegram rejected the request: {}", code.as_str())), - model_visible_cause: None, + diagnostic: Some(Box::new(ProviderDiagnostic { + code: Some(ProviderErrorCode::new(code.as_str())), + message: None, + retry_after: None, + })), + detail: None, } } -/// Same, plus a model-visible cause. The cause is vendor-derived and is NOT +/// Same, plus a provider diagnostic. The cause is vendor-derived and is NOT /// display-safe; downstream scrubbing owns that. pub(crate) fn failed_because(code: StandardMessagingErrorCode, cause: String) -> ToolError { - ToolError::Failed { + failed_with_diagnostic(code, cause, None) +} + +fn failed_with_diagnostic( + code: StandardMessagingErrorCode, + cause: String, + retry_after: Option, +) -> ToolError { + ToolError::Rejected { kind: RuntimeDispatchErrorKind::OperationFailed, - safe_summary: Some(format!("telegram rejected the request: {}", code.as_str())), - model_visible_cause: Some(cause), + diagnostic: Some(Box::new(ProviderDiagnostic { + code: Some(ProviderErrorCode::new(code.as_str())), + message: Some(UntrustedProviderMessage::new(cause)), + retry_after, + })), + detail: None, } } @@ -95,28 +114,27 @@ pub(crate) fn failed_because(code: StandardMessagingErrorCode, cause: String) -> /// run and offers the connect affordance, which is a thing the user can fix, /// whereas a messaging code would tell the model to rephrase its arguments. pub(crate) fn auth_required() -> ToolError { + let (Ok(required_secret), Ok(provider), Ok(requester_extension)) = ( + SecretHandle::new(TELEGRAM_LINKED_SESSION_HANDLE), + VendorId::new(TELEGRAM_VENDOR_ID), + ExtensionId::new(TELEGRAM_EXTENSION_ID), + ) else { + return ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Manifest, + diagnostic: None, + detail: None, + }; + }; + ToolError::AuthRequired { requirement: Box::new(DispatchAuthRequirement { - required_secrets: SecretHandle::new(TELEGRAM_LINKED_SESSION_HANDLE) - .map(|handle| vec![handle]) - .unwrap_or_default(), - credential_requirements: match ( - VendorId::new(TELEGRAM_VENDOR_ID), - ExtensionId::new(TELEGRAM_EXTENSION_ID), - ) { - (Ok(provider), Ok(requester_extension)) => { - vec![RuntimeCredentialAuthRequirement { - provider, - setup: RuntimeCredentialAccountSetup::DeviceLink, - requester_extension, - provider_scopes: Vec::new(), - }] - } - // Both ids are compile-time literals that satisfy their - // validators; an empty requirement list still parks the run on the - // generic re-auth gate, so this arm degrades rather than panics. - _ => Vec::new(), - }, + required_secrets: vec![required_secret], + credential_requirements: vec![RuntimeCredentialAuthRequirement { + provider, + setup: RuntimeCredentialAccountSetup::DeviceLink, + requester_extension, + provider_scopes: Vec::new(), + }], model_visible_cause: None, }), } @@ -668,14 +686,10 @@ pub(crate) fn map_vendor_error(family: OpFamily, error: &InvocationError) -> Too match rpc.name.as_str() { "FLOOD_WAIT" | "FLOOD_PREMIUM_WAIT" | "SLOWMODE_WAIT" | "FLOOD_TEST_PHONE_WAIT" => { match rpc.value { - // Prose is the only carrier available: `safe_summary` is fixed - // host-authored text and may not interpolate a vendor value, - // and nothing plumbs a tool-dispatch retry-after into the - // structured `ToolRecoveryObservation` slot today. Do not read - // this as a machine-readable back-off. - Some(seconds) => failed_because( + Some(seconds) => failed_with_diagnostic( RateLimited, format!("telegram asked us to wait {seconds} seconds before retrying"), + Some(Duration::from_secs(u64::from(seconds))), ), None => failed(RateLimited), } diff --git a/crates/extensions/packages/telegram/src/linked/mapping/tests.rs b/crates/extensions/packages/telegram/src/linked/mapping/tests.rs index 7d1e3f56370..98115bb1cd9 100644 --- a/crates/extensions/packages/telegram/src/linked/mapping/tests.rs +++ b/crates/extensions/packages/telegram/src/linked/mapping/tests.rs @@ -27,10 +27,13 @@ fn rpc(name: &str, value: Option) -> InvocationError { fn code_of(error: &ToolError) -> String { match error { - ToolError::Failed { safe_summary, .. } => { - safe_summary.clone().unwrap_or_else(|| "".to_string()) - } - ToolError::Rejected { kind, .. } => kind.human_summary().to_string(), + ToolError::Rejected { + kind, diagnostic, .. + } => diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.code.as_ref()) + .map(|code| code.as_str().to_string()) + .unwrap_or_else(|| kind.human_summary().to_string()), ToolError::AuthRequired { .. } => "auth_required".to_string(), } } @@ -301,7 +304,7 @@ fn credential_failures_leave_the_messaging_vocabulary() { "SESSION_EXPIRED", ] { let mapped = map_vendor_error(OpFamily::Read, &rpc(name, None)); - let ToolError::AuthRequired { requirement, .. } = mapped else { + let ToolError::AuthRequired { requirement } = mapped else { panic!("{name} must park the run on the re-auth gate, not answer messaging.*"); }; assert_eq!(requirement.required_secrets.len(), 1); @@ -334,20 +337,33 @@ fn an_unknown_write_outcome_is_a_vendor_error_and_never_sent_unverified() { } #[test] -fn a_flood_wait_carries_its_retry_after_as_prose_only() { +fn a_flood_wait_carries_typed_retry_after_and_bounded_diagnostic_prose() { let mapped = map_vendor_error(OpFamily::Write, &rpc("FLOOD_WAIT", Some(31))); - let ToolError::Failed { - safe_summary, - model_visible_cause, - .. + let ToolError::Rejected { + detail, diagnostic, .. } = mapped else { - panic!("flood wait is a failure"); + panic!("flood wait is a rejection"); }; - // The fixed half names only the canonical code; the vendor's number rides - // the free-form half, because no structured retry-after slot exists. - let safe_summary = safe_summary.expect("summary"); - assert!(safe_summary.contains(StandardMessagingErrorCode::RateLimited.as_str())); - assert!(!safe_summary.contains("31")); - assert!(model_visible_cause.expect("cause").contains("31")); + assert!( + detail.is_none(), + "the extension must not mint a host summary" + ); + assert!( + diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.code.as_ref()) + .is_some_and(|code| code.as_str() == StandardMessagingErrorCode::RateLimited.as_str()), + "canonical messaging code must cross the adapter boundary" + ); + assert!( + diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.message.as_ref()) + .is_some_and(|message| message.as_str().contains("31")) + ); + assert_eq!( + diagnostic.and_then(|diagnostic| diagnostic.retry_after), + Some(std::time::Duration::from_secs(31)) + ); } diff --git a/crates/extensions/packages/telegram/src/linked/ops/mod.rs b/crates/extensions/packages/telegram/src/linked/ops/mod.rs index 3c9eb2e3ed4..940d4d870ce 100644 --- a/crates/extensions/packages/telegram/src/linked/ops/mod.rs +++ b/crates/extensions/packages/telegram/src/linked/ops/mod.rs @@ -14,7 +14,9 @@ //! where available") is stated in the vendor addendum. use ironclaw_extension_contracts::tool_adapter::ToolError; -use ironclaw_host_api::messaging::StandardMessagingErrorCode; +use ironclaw_host_api::{ + dispatch::RuntimeDispatchErrorKind, messaging::StandardMessagingErrorCode, +}; use serde_json::Value; use super::{ @@ -138,13 +140,11 @@ where // and silently substituting an empty string would send a message nobody asked // for. -fn missing_field(field: &str) -> ToolError { - ToolError::Failed { - kind: ironclaw_host_api::dispatch::RuntimeDispatchErrorKind::Unknown, - safe_summary: Some(format!( - "the telegram adapter received input without its required {field} field" - )), - model_visible_cause: None, +fn missing_field(_field: &str) -> ToolError { + ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Unknown, + diagnostic: None, + detail: None, } } diff --git a/crates/extensions/packages/telegram/src/linked/ops/tests.rs b/crates/extensions/packages/telegram/src/linked/ops/tests.rs index 882c8734c7a..975c5b7cf9d 100644 --- a/crates/extensions/packages/telegram/src/linked/ops/tests.rs +++ b/crates/extensions/packages/telegram/src/linked/ops/tests.rs @@ -13,10 +13,13 @@ use crate::linked::mapping::{ConversationRef, UserRef}; fn summary(error: &ToolError) -> String { match error { - ToolError::Failed { safe_summary, .. } => { - safe_summary.clone().unwrap_or_else(|| "".to_string()) - } - ToolError::Rejected { kind, .. } => kind.human_summary().to_string(), + ToolError::Rejected { + kind, diagnostic, .. + } => diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.code.as_ref()) + .map(|code| code.as_str().to_string()) + .unwrap_or_else(|| kind.human_summary().to_string()), ToolError::AuthRequired { .. } => "auth_required".to_string(), } } @@ -122,18 +125,23 @@ fn a_revoked_session_parks_on_the_auth_gate() { let poisoned = ToolError::from(SessionPoolError::Poisoned); let not_configured = ToolError::from(SessionPoolError::NotConfigured); assert!( - matches!(&poisoned, ToolError::Failed { .. }), + matches!(&poisoned, ToolError::Rejected { .. }), "a poisoned pool is a failure, never an auth prompt: {poisoned:?}" ); match ¬_configured { - ToolError::Failed { - model_visible_cause: Some(cause), + ToolError::Rejected { + diagnostic: Some(diagnostic), .. } => assert!( - cause.contains("MTProto application identity"), - "the not-configured cause must name the missing config: {cause}" + diagnostic + .message + .as_ref() + .expect("not-configured cause") + .as_str() + .contains("MTProto application identity"), + "the not-configured cause must name the missing config: {not_configured:?}" ), - other => panic!("expected a Failed with a cause, got {other:?}"), + other => panic!("expected a Rejected with a cause, got {other:?}"), } assert!(summary(&at_capacity).contains(StandardMessagingErrorCode::VendorError.as_str())); } diff --git a/crates/extensions/packages/telegram/src/linked/tools.rs b/crates/extensions/packages/telegram/src/linked/tools.rs index f64aabd506c..237d2966c9e 100644 --- a/crates/extensions/packages/telegram/src/linked/tools.rs +++ b/crates/extensions/packages/telegram/src/linked/tools.rs @@ -21,7 +21,10 @@ use ironclaw_extension_contracts::linked_session::LinkedAccountResolver; use ironclaw_extension_contracts::tool_adapter::{ ToolAdapter, ToolCall, ToolError, ToolPorts, ToolResult, }; -use ironclaw_host_api::messaging::{StandardMessagingErrorCode, StandardMessagingOp}; +use ironclaw_host_api::{ + dispatch::RuntimeDispatchErrorKind, + messaging::{StandardMessagingErrorCode, StandardMessagingOp}, +}; use serde_json::Value; use super::{ @@ -161,13 +164,11 @@ async fn run( } } -fn undeclared_capability(id: &str) -> ToolError { - ToolError::Failed { - kind: ironclaw_host_api::dispatch::RuntimeDispatchErrorKind::UndeclaredCapability, - safe_summary: Some(format!( - "the telegram extension does not implement the capability {id}" - )), - model_visible_cause: None, +fn undeclared_capability(_id: &str) -> ToolError { + ToolError::Rejected { + kind: RuntimeDispatchErrorKind::UndeclaredCapability, + diagnostic: None, + detail: None, } } diff --git a/crates/extensions/packages/telegram/src/linked/tools/tests.rs b/crates/extensions/packages/telegram/src/linked/tools/tests.rs index 0b23a2b5c0b..83b26ae0bee 100644 --- a/crates/extensions/packages/telegram/src/linked/tools/tests.rs +++ b/crates/extensions/packages/telegram/src/linked/tools/tests.rs @@ -243,7 +243,7 @@ fn every_bound_content_returning_op_is_covered_by_the_framing_check() { #[test] fn an_unroutable_capability_reports_an_undeclared_capability() { let error = undeclared_capability("telegram.get_thread_replies"); - let ToolError::Failed { kind, .. } = error else { + let ToolError::Rejected { kind, .. } = error else { panic!("an unknown capability is not an auth problem"); }; assert_eq!( diff --git a/crates/kernel/ironclaw_capabilities/src/dispatch.rs b/crates/kernel/ironclaw_capabilities/src/dispatch.rs index 1c05efc8ca9..7743471ed28 100644 --- a/crates/kernel/ironclaw_capabilities/src/dispatch.rs +++ b/crates/kernel/ironclaw_capabilities/src/dispatch.rs @@ -18,12 +18,9 @@ use ironclaw_host_api::{ authorized::Authorized, dispatch::{ CapabilityDispatchRequest, CapabilityDispatchResult, CapabilityDispatcher, - CapabilityDisplayOutputPreview, DispatchError, DispatchFailureDetail, + CapabilityDisplayOutputPreview, DispatchError, DispatchFailureKind, RuntimeDispatchErrorKind, }, - runtime::DispatchErrorLane, -}; -use ironclaw_host_api::{ ids::{CapabilityId, ExtensionId, InvocationId}, invocation::{Actor, InvocationOrigin}, lane::RuntimeLane, @@ -418,30 +415,16 @@ fn dispatch_resource_error( let cause = error.to_string(); // System has no runtime backend to attribute a resource-reservation // failure to, so it classifies as MissingRuntimeBackend here rather than - // joining FirstParty's lane (unlike the other three RuntimeKind -> - // DispatchError sites, which route System into FirstParty uniformly). + // as a generic provider rejection. if runtime == RuntimeKind::System { return DispatchError::MissingRuntimeBackend { runtime }; } - match runtime.dispatch_error_lane() { - DispatchErrorLane::Wasm => DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: Some(cause), - }, - DispatchErrorLane::Script => DispatchError::Script { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: Some(cause), - }, - DispatchErrorLane::Mcp => DispatchError::Mcp { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: Some(cause), - }, - DispatchErrorLane::FirstParty => DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::Resource, - safe_summary: None, - detail: Some(DispatchFailureDetail::Diagnostic { text: cause }), - }, - } + DispatchError::provider_rejected( + Some(runtime), + DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + Some(cause), + None, + ) } #[async_trait] diff --git a/crates/kernel/ironclaw_capabilities/src/error.rs b/crates/kernel/ironclaw_capabilities/src/error.rs index 8f9749cd778..57aa96645d4 100644 --- a/crates/kernel/ironclaw_capabilities/src/error.rs +++ b/crates/kernel/ironclaw_capabilities/src/error.rs @@ -1,3 +1,5 @@ +use std::fmt; + use ironclaw_authorization::CapabilityLeaseError; use ironclaw_host_api::{ decision::{DenyReason, Obligation}, @@ -22,7 +24,7 @@ pub enum ResumeContextMismatchKind { } /// Capability invocation failures before or during dispatch. -#[derive(Debug, Error)] +#[derive(Error)] pub enum CapabilityInvocationError { #[error("unknown capability {capability}")] UnknownCapability { capability: CapabilityId }, @@ -115,11 +117,165 @@ pub enum CapabilityInvocationError { /// Provider-authored metadata remains typed and Debug-redacted until /// the runtime's model-diagnostic scrub/fence seam. provider_diagnostic: Option>, + /// Candidate public label — persisted, published, and rendered by + /// product surfaces (the chat tool-failure card reads this field). + /// Three-tier precedence, most-trusted first: + /// + /// 1. A host-authored summary (`DispatchFailureDetail::HostSummary`, + /// set via `DispatchError::with_host_summary`), when present — + /// e.g. a first-party capability's fixed rejection summary. + /// 2. Otherwise the provider diagnostic's text (formatted + /// `code`/`message`, or a bare `message`), carried forward + /// deliberately — not accidentally — so the user still sees the + /// real vendor reason ("token lacks repo scope") instead of a + /// generic sentence. This is validation-gated downstream: only + /// summaries that pass the strict `LoopSafeSummary` gate (bounded, + /// no control chars, no delimiters, no credential markers) + /// reach the public surface; anything that fails validation + /// degrades to the kind's fixed sentence there. + /// 3. `None` when neither is available, which the downstream gate + /// also renders as the kind's fixed sentence + /// (`kind.human_summary()`). + /// + /// Debug-redacted here too (see `provider_diagnostic`'s doc) even + /// though it is a plain `String`, so Debug output never depends on + /// which downstream seam scrubs first. safe_summary: Option, detail: Option, }, } +impl fmt::Debug for CapabilityInvocationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnknownCapability { capability } => f + .debug_struct("UnknownCapability") + .field("capability", capability) + .finish(), + Self::AuthorizationDenied { + capability, + reason, + detail, + } => f + .debug_struct("AuthorizationDenied") + .field("capability", capability) + .field("reason", reason) + .field("detail", detail) + .finish(), + Self::UnsupportedObligations { + capability, + obligations, + } => f + .debug_struct("UnsupportedObligations") + .field("capability", capability) + .field("obligations", obligations) + .finish(), + Self::ObligationFailed { capability, kind } => f + .debug_struct("ObligationFailed") + .field("capability", capability) + .field("kind", kind) + .finish(), + Self::AuthorizationRequiresApproval { capability } => f + .debug_struct("AuthorizationRequiresApproval") + .field("capability", capability) + .finish(), + Self::AuthorizationRequiresAuth { + capability, + requirement, + } => f + .debug_struct("AuthorizationRequiresAuth") + .field("capability", capability) + .field( + "required_secrets", + &format!( + "[{} handle(s) redacted]", + requirement.required_secrets.len() + ), + ) + .field( + "credential_requirements", + &format!( + "[{} requirement(s) redacted]", + requirement.credential_requirements.len() + ), + ) + .field("model_visible_cause", &requirement.model_visible_cause) + .finish(), + Self::InvocationFingerprint { capability, source } => f + .debug_struct("InvocationFingerprint") + .field("capability", capability) + .field("source", source) + .finish(), + Self::ApprovalRequestMismatch { capability, field } => f + .debug_struct("ApprovalRequestMismatch") + .field("capability", capability) + .field("field", field) + .finish(), + Self::ApprovalFingerprintMismatch { capability } => f + .debug_struct("ApprovalFingerprintMismatch") + .field("capability", capability) + .finish(), + Self::ApprovalNotApproved { capability, status } => f + .debug_struct("ApprovalNotApproved") + .field("capability", capability) + .field("status", status) + .finish(), + Self::ApprovalStoreMissing { capability, store } => f + .debug_struct("ApprovalStoreMissing") + .field("capability", capability) + .field("store", store) + .finish(), + Self::ApprovalLeaseMissing { capability } => f + .debug_struct("ApprovalLeaseMissing") + .field("capability", capability) + .finish(), + Self::ResumeStoreMissing { capability, store } => f + .debug_struct("ResumeStoreMissing") + .field("capability", capability) + .field("store", store) + .finish(), + Self::ProcessManagerMissing { capability } => f + .debug_struct("ProcessManagerMissing") + .field("capability", capability) + .finish(), + Self::ResumeNotBlocked { capability, status } => f + .debug_struct("ResumeNotBlocked") + .field("capability", capability) + .field("status", status) + .finish(), + Self::ResumeContextMismatch { capability, kind } => f + .debug_struct("ResumeContextMismatch") + .field("capability", capability) + .field("kind", kind) + .finish(), + Self::Lease(source) => f.debug_tuple("Lease").field(source).finish(), + Self::ApprovalStore(source) => f.debug_tuple("ApprovalStore").field(source).finish(), + Self::InvocationState(source) => { + f.debug_tuple("InvocationState").field(source).finish() + } + Self::Process(source) => f.debug_tuple("Process").field(source).finish(), + // `safe_summary` carries the same untrusted provider text as + // `provider_diagnostic` (see `From`), so it is + // redacted here too — never log or render it directly. + Self::Dispatch { + kind, + provider_diagnostic, + detail, + .. + } => f + .debug_struct("Dispatch") + .field("kind", kind) + .field("provider_diagnostic", provider_diagnostic) + .field("safe_summary", &"") + // `DispatchFailureDetail`'s Debug implementation selectively + // preserves structured input issues while redacting raw + // provider/backend causes. + .field("detail", detail) + .finish(), + } + } +} + impl From for CapabilityInvocationError { fn from(error: ApprovalStoreError) -> Self { Self::ApprovalStore(Box::new(error)) @@ -153,12 +309,49 @@ impl From for CapabilityInvocationError { diagnostic, detail, .. - } => Self::Dispatch { - kind, - provider_diagnostic: diagnostic, - safe_summary: None, - detail, - }, + } => { + // Three-tier precedence (see the `safe_summary` field doc): + // 1. A host-authored `DispatchFailureDetail::HostSummary` + // wins outright — it is the caller's own trusted label. + // 2. Otherwise the vendor/provider diagnostic's text is + // carried forward deliberately, so the user still sees + // the real reason instead of a generic sentence. A + // structured `code` (e.g. a WASM guest's stable taxonomy + // code) uses the formatted `code`/`message` combination so + // the code always surfaces; a bare `message` with no + // `code` rides through unprefixed. This text still fails + // closed downstream through the strict `LoopSafeSummary` + // gate (`dispatch_failure_message`), which degrades + // anything that doesn't validate to the kind's fixed + // sentence — this layer only carries the candidate text + // forward. + // 3. `None` when neither is available; the same downstream + // gate renders the kind's fixed sentence. + let (safe_summary, detail) = match detail { + Some(DispatchFailureDetail::HostSummary { summary, detail }) => { + (Some(summary.into_inner()), detail.map(|detail| *detail)) + } + detail => { + let summary = diagnostic.as_ref().and_then(|diagnostic| { + if diagnostic.code.is_some() { + provider_diagnostic_model_cause(diagnostic) + } else { + diagnostic + .message + .as_ref() + .map(|message| message.as_str().to_string()) + } + }); + (summary, detail) + } + }; + Self::Dispatch { + kind, + provider_diagnostic: diagnostic, + safe_summary, + detail, + } + } other @ (DispatchError::UnknownCapability { .. } | DispatchError::UnknownProvider { .. } | DispatchError::RuntimeMismatch { .. } @@ -166,15 +359,11 @@ impl From for CapabilityInvocationError { | DispatchError::UnsupportedRuntime { .. } | DispatchError::MissingAuthorization { .. } | DispatchError::AuthorizationExpired { .. } - | DispatchError::MissingProcessAuthorization { .. } - | DispatchError::Mcp { .. } - | DispatchError::Script { .. } - | DispatchError::Wasm { .. } - | DispatchError::FirstParty { .. }) => Self::Dispatch { + | DispatchError::MissingProcessAuthorization { .. }) => Self::Dispatch { kind: dispatch_error_kind(&other), provider_diagnostic: None, safe_summary: dispatch_error_model_visible_cause(&other), - detail: dispatch_error_detail(&other), + detail: None, }, } } @@ -184,30 +373,14 @@ fn dispatch_error_kind(error: &DispatchError) -> DispatchFailureKind { error.failure_kind() } +/// These variants carry no free-form runtime string; their `Display` is a +/// stable capability-id + category description that is itself the real +/// cause. Carry it so the model-visible detail channel keeps it (scrubbing +/// of any secret VALUE happens downstream at the Diagnostic-building layer, +/// which lives in a crate that may depend on `ironclaw_turns` — this crate +/// must not). fn dispatch_error_model_visible_cause(error: &DispatchError) -> Option { match error { - DispatchError::Rejected { diagnostic, .. } => diagnostic - .as_deref() - .and_then(provider_diagnostic_model_cause), - DispatchError::Mcp { - model_visible_cause, - .. - } - | DispatchError::Script { - model_visible_cause, - .. - } - | DispatchError::Wasm { - model_visible_cause, - .. - } => model_visible_cause.clone(), - DispatchError::FirstParty { safe_summary, .. } => safe_summary.clone(), - // These variants carry no free-form runtime string; their `Display` - // is a stable capability-id + category description that is itself the - // real cause. Carry it so the model-visible detail channel keeps it - // (scrubbing of any secret VALUE happens downstream at the - // Diagnostic-building layer, which lives in a crate that may depend on - // `ironclaw_turns` — this crate must not). DispatchError::UnknownCapability { .. } | DispatchError::UnknownProvider { .. } | DispatchError::RuntimeMismatch { .. } @@ -217,16 +390,9 @@ fn dispatch_error_model_visible_cause(error: &DispatchError) -> Option { | DispatchError::AuthorizationExpired { .. } | DispatchError::MissingProcessAuthorization { .. } => Some(error.to_string()), // Auth-required carries redacted secret handles; keep it summary-free. - DispatchError::AuthRequired { .. } => None, - } -} - -fn dispatch_error_detail(error: &DispatchError) -> Option { - match error { - DispatchError::FirstParty { detail, .. } | DispatchError::Rejected { detail, .. } => { - detail.clone() - } - _ => None, + // Rejected's cause rides the typed `provider_diagnostic` channel + // instead of this raw-string one (see the `Rejected` arm above). + DispatchError::AuthRequired { .. } | DispatchError::Rejected { .. } => None, } } @@ -236,11 +402,12 @@ mod tests { use ironclaw_host_api::{ decision::RuntimeCredentialAuthRequirement, dispatch::{ - DispatchFailureDetail, DispatchInputIssue, DispatchInputIssueCode, - RuntimeDispatchErrorKind, + DispatchAuthRequirement, DispatchFailureDetail, DispatchInputIssue, + DispatchInputIssueCode, RuntimeDispatchErrorKind, }, ids::{ExtensionId, SecretHandle, VendorId}, runtime::RuntimeKind, + safe_summary::SafeSummary, }; fn cap() -> CapabilityId { @@ -294,26 +461,40 @@ mod tests { } #[test] - fn dispatch_error_kind_forwards_mcp_runtime_kind_as_str() { - // Regression (Phase 1): an MCP dispatch error's raw cause must be - // carried on the model-visible-cause channel — including path/JSON delimiters + fn dispatch_error_kind_forwards_runtime_kind_via_rejected() { + // Regression (Phase 1): a runtime dispatch error's raw cause must be + // carried on the typed diagnostic channel — including path/JSON delimiters // that the strict summary validator rejects — so it reaches the // model-visible Diagnostic/detail downstream instead of being dropped. - let error = DispatchError::Mcp { - kind: RuntimeDispatchErrorKind::Backend, - model_visible_cause: Some("MCP request failed at /tmp/{socket}".to_string()), + let error = DispatchError::Rejected { + runtime: Some(RuntimeKind::Mcp), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Backend), + diagnostic: Some(Box::new(ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "MCP request failed at /tmp/{socket}", + )), + retry_after: None, + })), + detail: None, }; let kind = dispatch_error_kind(&error); assert_eq!(kind.as_str(), "Backend"); + let DispatchError::Rejected { + diagnostic: Some(diagnostic), + .. + } = &error + else { + panic!("expected Rejected variant"); + }; assert_eq!( - dispatch_error_model_visible_cause(&error).as_deref(), - Some("MCP request failed at /tmp/{socket}") + provider_diagnostic_model_cause(diagnostic.as_ref()).as_deref(), + Some("provider message: MCP request failed at /tmp/{socket}") ); } #[test] fn provider_rejection_preserves_typed_diagnostic_for_model_projection() { - let detail_marker = "CAPABILITY_DIAGNOSTIC_SECRET_MARKER"; let error = CapabilityInvocationError::from(DispatchError::Rejected { runtime: Some(RuntimeKind::Mcp), kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Client), @@ -326,16 +507,9 @@ mod tests { )), retry_after: None, })), - detail: Some(DispatchFailureDetail::Diagnostic { - text: detail_marker.to_string(), - }), + detail: None, }); - let debug = format!("{error:?}"); - assert!(!debug.contains("token lacks repo scope")); - assert!( - !debug.contains(detail_marker), - "diagnostic detail leaked: {debug}" - ); + assert!(!format!("{error:?}").contains("token lacks repo scope")); let CapabilityInvocationError::Dispatch { kind, @@ -350,7 +524,18 @@ mod tests { kind, DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Client) ); - assert!(safe_summary.is_none()); + // Tier 2 (no host summary attached): the formatted vendor cause is + // the candidate public label too — it still fails closed downstream + // through the strict `LoopSafeSummary` gate (`dispatch_failure_message` + // in `ironclaw_host_runtime`), which degrades anything unsafe to the + // kind's fixed sentence; this layer only carries the candidate text + // forward so the user still sees the real reason. + assert_eq!( + safe_summary.as_deref(), + Some( + "provider error code: mcp_tool_rejected; provider message: token lacks repo scope" + ) + ); assert_eq!( provider_diagnostic_model_cause(&diagnostic).as_deref(), Some( @@ -359,34 +544,6 @@ mod tests { ); } - #[test] - fn dispatch_error_kind_forwards_script_runtime_kind_as_str() { - let kind = dispatch_error_kind(&DispatchError::Script { - kind: RuntimeDispatchErrorKind::OutputTooLarge, - model_visible_cause: None, - }); - assert_eq!(kind.as_str(), "OutputTooLarge"); - } - - #[test] - fn dispatch_error_kind_forwards_wasm_runtime_kind_as_str() { - let kind = dispatch_error_kind(&DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Memory, - model_visible_cause: None, - }); - assert_eq!(kind.as_str(), "Memory"); - } - - #[test] - fn dispatch_error_kind_forwards_first_party_runtime_kind_as_str() { - let kind = dispatch_error_kind(&DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::UndeclaredCapability, - safe_summary: None, - detail: None, - }); - assert_eq!(kind.as_str(), "UndeclaredCapability"); - } - #[test] fn from_dispatch_error_preserves_top_level_dispatch_kind() { let err = @@ -401,9 +558,11 @@ mod tests { #[test] fn from_dispatch_error_preserves_redacted_runtime_kind() { - let err = CapabilityInvocationError::from(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Guest, - model_visible_cause: None, + let err = CapabilityInvocationError::from(DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest), + diagnostic: None, + detail: None, }); match err { CapabilityInvocationError::Dispatch { kind, .. } => { @@ -421,22 +580,192 @@ mod tests { let issue = DispatchInputIssue::new("schedule.kind", DispatchInputIssueCode::MissingRequired) .expected("cron or once"); - let err = CapabilityInvocationError::from(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::InputEncode, - safe_summary: Some("trigger_create input failed validation".to_string()), + let err = CapabilityInvocationError::from(DispatchError::Rejected { + runtime: Some(RuntimeKind::FirstParty), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::InputEncode), + diagnostic: Some(Box::new(ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "trigger_create input failed validation", + )), + retry_after: None, + })), detail: Some(DispatchFailureDetail::InvalidInput { issues: vec![issue.clone()], }), }); match err { - CapabilityInvocationError::Dispatch { detail, .. } => { + CapabilityInvocationError::Dispatch { + detail, + safe_summary, + .. + } => { assert_eq!( detail, Some(DispatchFailureDetail::InvalidInput { issues: vec![issue] }) ); + // Tier 2: `detail` here is `InvalidInput`, not a host + // summary, so `safe_summary` falls through to the vendor + // diagnostic. `code: None` rides the bare-message branch + // unprefixed — no "provider error code:"/"provider message:" + // label. + assert_eq!( + safe_summary.as_deref(), + Some("trigger_create input failed validation") + ); + } + other => panic!("expected Dispatch variant, got {other:?}"), + } + } + + #[test] + fn capability_invocation_error_dispatch_debug_redacts_diagnostic_detail_text() { + // `DispatchFailureDetail::Diagnostic { text }` carries an untrusted + // raw provider/backend cause (never-log content); the folded + // `Dispatch` variant's Debug must not print it, mirroring + // `DispatchError::Rejected`'s Debug redaction. + let err = CapabilityInvocationError::from(DispatchError::Rejected { + runtime: Some(RuntimeKind::FirstParty), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::OperationFailed), + diagnostic: None, + detail: Some(DispatchFailureDetail::Diagnostic { + text: "leak-me-not: /secret/path token=abc123".to_string(), + }), + }); + + let debug_output = format!("{err:?}"); + assert!(!debug_output.contains("leak-me-not")); + assert!(!debug_output.contains("/secret/path")); + assert!(!debug_output.contains("abc123")); + } + + #[test] + fn capability_invocation_error_dispatch_debug_keeps_structured_input_detail_visible() { + let err = CapabilityInvocationError::from(DispatchError::Rejected { + runtime: Some(RuntimeKind::FirstParty), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::InputEncode), + diagnostic: None, + detail: Some(DispatchFailureDetail::InvalidInput { + issues: vec![DispatchInputIssue::new( + "schedule.kind", + DispatchInputIssueCode::MissingRequired, + )], + }), + }); + + let debug_output = format!("{err:?}"); + assert!(debug_output.contains("InvalidInput")); + assert!(debug_output.contains("schedule.kind")); + } + + /// Invariant pin, tier 1: a `Rejected` carrying BOTH a host-authored + /// summary (`DispatchFailureDetail::HostSummary`) and a vendor-authored + /// cause keeps the host summary as the public `safe_summary` — it must + /// never be silently dropped in favor of the vendor cause (the defect + /// `registry.rs`'s old `model_visible_cause.or(safe_summary)` had) — while + /// the vendor text still rides `provider_diagnostic` for the + /// model-visible channel. The two channels are never merged into one. + #[test] + fn rejected_host_summary_wins_over_vendor_diagnostic() { + let vendor_cause = "vendor backend returned 503 at /internal/route"; + let host_summary = "the tool's backend failed"; + let error = DispatchError::provider_rejected( + Some(RuntimeKind::FirstParty), + DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Backend), + Some(vendor_cause.to_string()), + Some(DispatchFailureDetail::HostSummary { + summary: SafeSummary::new(host_summary).unwrap(), + detail: Some(Box::new(DispatchFailureDetail::InvalidInput { + issues: vec![DispatchInputIssue::new( + "schedule.kind", + DispatchInputIssueCode::TypeMismatch, + )], + })), + }), + ); + let err = CapabilityInvocationError::from(error); + + match err { + CapabilityInvocationError::Dispatch { + safe_summary, + provider_diagnostic, + detail, + .. + } => { + assert_eq!(safe_summary.as_deref(), Some(host_summary)); + let diagnostic = provider_diagnostic.expect("vendor cause must ride diagnostic"); + assert_eq!( + provider_diagnostic_model_cause(&diagnostic).as_deref(), + Some(format!("provider message: {vendor_cause}").as_str()) + ); + assert!(matches!( + detail, + Some(DispatchFailureDetail::InvalidInput { issues }) + if issues.len() == 1 && issues[0].path == "schedule.kind" + )); + } + other => panic!("expected Dispatch variant, got {other:?}"), + } + } + + /// Invariant pin, tier 2: no host summary attached — the vendor + /// diagnostic's text becomes the public `safe_summary` (carried forward + /// deliberately, still validation-gated downstream by the strict + /// `LoopSafeSummary` gate in `ironclaw_host_runtime`) rather than + /// dropping to `None`. This is the same text that also rides + /// `provider_diagnostic` for the model-visible channel. + #[test] + fn rejected_diagnostic_without_host_summary_becomes_the_public_label() { + let err = CapabilityInvocationError::from(DispatchError::Rejected { + runtime: Some(RuntimeKind::Mcp), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Backend), + diagnostic: Some(Box::new(ProviderDiagnostic { + code: None, + message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( + "backend exploded", + )), + retry_after: None, + })), + detail: None, + }); + + match err { + CapabilityInvocationError::Dispatch { + safe_summary, + provider_diagnostic, + .. + } => { + assert_eq!(safe_summary.as_deref(), Some("backend exploded")); + assert!(provider_diagnostic.is_some()); + } + other => panic!("expected Dispatch variant, got {other:?}"), + } + } + + /// Invariant pin, tier 3: neither a host summary nor a vendor diagnostic + /// is present — `safe_summary` is `None`, and the downstream strict + /// `LoopSafeSummary` gate renders the kind's fixed sentence + /// (`kind.human_summary()`) instead. + #[test] + fn rejected_without_host_summary_or_diagnostic_yields_none_safe_summary() { + let err = CapabilityInvocationError::from(DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Guest), + diagnostic: None, + detail: None, + }); + + match err { + CapabilityInvocationError::Dispatch { + safe_summary, + provider_diagnostic, + .. + } => { + assert_eq!(safe_summary, None); + assert!(provider_diagnostic.is_none()); } other => panic!("expected Dispatch variant, got {other:?}"), } @@ -486,7 +815,7 @@ mod tests { #[test] fn from_dispatch_auth_required_round_trips_credential_requirements() { - let requirement = RuntimeCredentialAuthRequirement { + let credential_requirement = RuntimeCredentialAuthRequirement { provider: VendorId::new("google").unwrap(), setup: ironclaw_host_api::capability::RuntimeCredentialAccountSetup::OAuth { scopes: vec!["https://www.googleapis.com/auth/gmail.readonly".to_string()], @@ -498,7 +827,7 @@ mod tests { capability: cap(), requirement: Box::new(DispatchAuthRequirement { required_secrets: Vec::new(), - credential_requirements: vec![requirement.clone()], + credential_requirements: vec![credential_requirement.clone()], model_visible_cause: Some(ProviderDiagnostic { code: None, message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( @@ -512,13 +841,16 @@ mod tests { match err { CapabilityInvocationError::AuthorizationRequiresAuth { capability, - requirement: auth_requirement, + requirement, } => { assert_eq!(capability, cap()); - assert!(auth_requirement.required_secrets.is_empty()); - assert_eq!(auth_requirement.credential_requirements, vec![requirement]); + assert!(requirement.required_secrets.is_empty()); + assert_eq!( + requirement.credential_requirements, + vec![credential_requirement] + ); assert_eq!( - auth_requirement + requirement .model_visible_cause .as_ref() .and_then(|diagnostic| diagnostic.message.as_ref()) @@ -526,8 +858,7 @@ mod tests { Some("Bad credentials") ); assert!( - !format!("{:?}", auth_requirement.model_visible_cause) - .contains("Bad credentials") + !format!("{:?}", requirement.model_visible_cause).contains("Bad credentials") ); } other => panic!("expected AuthorizationRequiresAuth, got {other:?}"), diff --git a/crates/kernel/ironclaw_capabilities/src/lib.rs b/crates/kernel/ironclaw_capabilities/src/lib.rs index 3e1dc22fede..01a1f283ec7 100644 --- a/crates/kernel/ironclaw_capabilities/src/lib.rs +++ b/crates/kernel/ironclaw_capabilities/src/lib.rs @@ -27,8 +27,8 @@ pub use ironclaw_host_api::{ authorized::Authorized, dispatch::{ CapabilityDispatchRequest, CapabilityDispatchResult, CapabilityDispatcher, - CapabilityDisplayOutputPreview, DispatchError, DispatchFailureDetail, - RuntimeDispatchErrorKind, + CapabilityDisplayOutputPreview, DispatchError, DispatchFailureDetail, DispatchFailureKind, + ProviderDiagnostic, RuntimeDispatchErrorKind, UntrustedProviderMessage, }, }; pub use obligations::{ diff --git a/crates/kernel/ironclaw_capabilities/src/registry.rs b/crates/kernel/ironclaw_capabilities/src/registry.rs index 004ad9f5716..028bc489b8e 100644 --- a/crates/kernel/ironclaw_capabilities/src/registry.rs +++ b/crates/kernel/ironclaw_capabilities/src/registry.rs @@ -14,12 +14,10 @@ use ironclaw_extension_contracts::tool_adapter::{ }; use ironclaw_host_api::{ capability::CapabilityDescriptor, - dispatch::{ - CapabilityDispatchRequest, DispatchError, DispatchFailureDetail, RuntimeDispatchErrorKind, - }, + dispatch::{CapabilityDispatchRequest, DispatchError, DispatchFailureKind}, ids::{CapabilityId, ExtensionId}, resource::{ReservationStatus, ResourceReceipt, ResourceUsage}, - runtime::{DispatchErrorLane, RuntimeKind}, + runtime::RuntimeKind, }; use crate::dispatch::{ @@ -178,48 +176,18 @@ fn tool_error_to_dispatch_error( requirement, }, ToolError::Rejected { - runtime, kind, diagnostic, detail, + .. } => DispatchError::Rejected { - runtime, - kind, + // Runtime provenance belongs to the trusted registry binding, not + // to the extension-supplied error payload. + runtime: Some(runtime), + kind: DispatchFailureKind::Runtime(kind), diagnostic, detail, }, - ToolError::Failed { - kind, - safe_summary, - model_visible_cause, - } => runtime_dispatch_error(runtime, kind, safe_summary, model_visible_cause), - } -} - -fn runtime_dispatch_error( - runtime: RuntimeKind, - kind: RuntimeDispatchErrorKind, - safe_summary: Option, - model_visible_cause: Option, -) -> DispatchError { - match runtime.dispatch_error_lane() { - DispatchErrorLane::Mcp => DispatchError::Mcp { - kind, - model_visible_cause, - }, - DispatchErrorLane::Wasm => DispatchError::Wasm { - kind, - model_visible_cause, - }, - DispatchErrorLane::Script => DispatchError::Script { - kind, - model_visible_cause, - }, - DispatchErrorLane::FirstParty => DispatchError::FirstParty { - kind, - safe_summary, - detail: model_visible_cause.map(|text| DispatchFailureDetail::Diagnostic { text }), - }, } } @@ -257,8 +225,9 @@ mod tests { use ironclaw_host_api::{ capability::{CapabilityDescriptor, EffectKind, PermissionMode}, dispatch::{ - CapabilityDispatchRequest, DispatchError, DispatchFailureKind, ProviderDiagnostic, - ProviderErrorCode, UntrustedProviderMessage, + CapabilityDispatchRequest, DispatchError, DispatchFailureDetail, DispatchFailureKind, + ProviderDiagnostic, ProviderErrorCode, RuntimeDispatchErrorKind, + UntrustedProviderMessage, }, ids::{ExtensionId, InvocationId, ProductKind, TenantId, UserId}, invocation::InvocationOrigin, @@ -418,8 +387,7 @@ mod tests { _ports: &ToolPorts<'_>, ) -> Result { Err(ToolError::Rejected { - runtime: Some(RuntimeKind::FirstParty), - kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::PolicyDenied), + kind: RuntimeDispatchErrorKind::PolicyDenied, diagnostic: Some(Box::new(ProviderDiagnostic { code: Some(ProviderErrorCode::new("channel_not_found")), message: Some(UntrustedProviderMessage::new("no such channel")), @@ -475,8 +443,12 @@ mod tests { match error { DispatchError::Rejected { - kind, diagnostic, .. + runtime, + kind, + diagnostic, + .. } => { + assert_eq!(runtime, Some(RuntimeKind::FirstParty)); assert_eq!( kind, DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::PolicyDenied) @@ -497,4 +469,118 @@ mod tests { other => panic!("expected DispatchError::Rejected, got {other:?}"), } } + + #[tokio::test] + async fn tool_adapter_rejection_keeps_host_summary_separate_from_vendor_cause() { + struct RejectedToolAdapter; + + #[async_trait] + impl ToolAdapter for RejectedToolAdapter { + async fn invoke( + &self, + _call: ToolCall, + _ports: &ToolPorts<'_>, + ) -> Result { + Err(ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Backend, + diagnostic: Some(Box::new(ProviderDiagnostic { + code: None, + message: Some(UntrustedProviderMessage::new("vendor backend returned 503")), + retry_after: None, + })), + detail: Some(DispatchFailureDetail::HostSummary { + summary: ironclaw_host_api::safe_summary::SafeSummary::new( + "the tool's backend failed", + ) + .unwrap(), + detail: None, + }), + }) + } + } + + let mut registry = CapabilityDispatchRegistry::new(); + registry + .register_extension(extension("provider-a", Some(Arc::new(RejectedToolAdapter)))) + .expect("extension registration"); + let resolved = registry + .resolve(&CapabilityId::new("provider-a.echo").expect("capability id")) + .expect("resolved"); + + let error = resolved + .adapter + .dispatch_json(sample_dispatch_request("provider-a.echo")) + .await + .expect_err("failure propagated"); + let DispatchError::Rejected { + diagnostic, detail, .. + } = error + else { + panic!("expected Rejected dispatch error"); + }; + assert_eq!( + diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.message.as_ref()) + .map(|message| message.as_str()), + Some("vendor backend returned 503") + ); + assert!(matches!( + detail, + Some(DispatchFailureDetail::HostSummary { summary, detail }) + if summary.as_str() == "the tool's backend failed" && detail.is_none() + )); + } + + #[tokio::test] + async fn tool_adapter_rejection_without_host_summary_carries_only_vendor_cause() { + struct RejectedToolAdapter; + + #[async_trait] + impl ToolAdapter for RejectedToolAdapter { + async fn invoke( + &self, + _call: ToolCall, + _ports: &ToolPorts<'_>, + ) -> Result { + Err(ToolError::Rejected { + kind: RuntimeDispatchErrorKind::Guest, + diagnostic: Some(Box::new(ProviderDiagnostic { + code: None, + message: Some(UntrustedProviderMessage::new("guest trapped")), + retry_after: None, + })), + detail: None, + }) + } + } + + let mut registry = CapabilityDispatchRegistry::new(); + registry + .register_extension(extension("provider-a", Some(Arc::new(RejectedToolAdapter)))) + .expect("extension registration"); + let resolved = registry + .resolve(&CapabilityId::new("provider-a.echo").expect("capability id")) + .expect("resolved"); + + let error = resolved + .adapter + .dispatch_json(sample_dispatch_request("provider-a.echo")) + .await + .expect_err("failure propagated"); + let DispatchError::Rejected { + diagnostic, detail, .. + } = error + else { + panic!("expected Rejected dispatch error"); + }; + assert_eq!( + diagnostic + .as_ref() + .and_then(|diagnostic| diagnostic.message.as_ref()) + .map(|message| message.as_str()), + Some("guest trapped") + ); + assert_eq!(detail, None); + } } diff --git a/crates/kernel/ironclaw_capabilities/tests/capability_host_dispatcher_integration.rs b/crates/kernel/ironclaw_capabilities/tests/capability_host_dispatcher_integration.rs index 17d063eb1d8..ba14f465a2e 100644 --- a/crates/kernel/ironclaw_capabilities/tests/capability_host_dispatcher_integration.rs +++ b/crates/kernel/ironclaw_capabilities/tests/capability_host_dispatcher_integration.rs @@ -16,7 +16,7 @@ use ironclaw_host_api::{ Timestamp, action::NetworkPolicy, capability::{CapabilitySet, EffectKind, GrantConstraints}, - dispatch::{DispatchError, RuntimeDispatchErrorKind}, + dispatch::{DispatchError, DispatchFailureKind, RuntimeDispatchErrorKind}, ids::{ApprovalRequestId, CapabilityId, ExtensionId, InvocationId, UserId}, mount::MountView, resource::{ResourceEstimate, ResourceReservation, ResourceScope, ResourceUsage}, @@ -407,18 +407,22 @@ impl BoundCapabilityAdapter for RecordingRuntimeAdapter { None => self .governor .reserve(request.scope, request.estimate) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?, }; let output_bytes = usage.output_bytes; let receipt = self .governor .reconcile(reservation.id, usage.clone()) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?; Ok(RuntimeAdapterResult { output, diff --git a/crates/kernel/ironclaw_capabilities/tests/capability_host_invocation_state_contract.rs b/crates/kernel/ironclaw_capabilities/tests/capability_host_invocation_state_contract.rs index ba47c9fd718..1d76718e06c 100644 --- a/crates/kernel/ironclaw_capabilities/tests/capability_host_invocation_state_contract.rs +++ b/crates/kernel/ironclaw_capabilities/tests/capability_host_invocation_state_contract.rs @@ -24,6 +24,7 @@ use ironclaw_host_api::{ mount::MountView, path::VirtualPath, resource::{ResourceEstimate, ResourceScope}, + runtime::RuntimeKind, scope::{ExecutionContext, Principal}, }; use ironclaw_processes::*; @@ -566,9 +567,11 @@ async fn capability_host_returns_specific_error_for_authorizer_fingerprint_misma async fn capability_host_retains_fresh_pending_invocation_for_outcome_terminalization() { let registry = registry_with_echo_capability(); let dispatcher = TestDispatcher::responding(|_, _| { - Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Backend, - model_visible_cause: None, + Err(DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Backend), + diagnostic: None, + detail: None, }) }); let authorizer = GrantAuthorizer::new(); @@ -905,9 +908,11 @@ async fn capability_host_denies_resume_when_trust_ceiling_omits_capability_effec async fn capability_host_revokes_claimed_lease_when_dispatch_fails_after_resume() { let registry = registry_with_echo_capability(); let dispatcher = TestDispatcher::responding(|_, _| { - Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Backend, - model_visible_cause: None, + Err(DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Backend), + diagnostic: None, + detail: None, }) }); let run_state = ironclaw_processes::in_memory_backed_process_invocation_state_store(); diff --git a/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_contract.rs b/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_contract.rs index 2d0f7f1db21..6184f4474cd 100644 --- a/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_contract.rs +++ b/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_contract.rs @@ -23,7 +23,8 @@ use ironclaw_capabilities::{ use ironclaw_host_api::{ authorized::Authorized, dispatch::{ - CapabilityDispatchRequest, CapabilityDispatcher, DispatchError, RuntimeDispatchErrorKind, + CapabilityDispatchRequest, CapabilityDispatcher, DispatchError, DispatchFailureKind, + RuntimeDispatchErrorKind, }, ids::{ ActivityId, CapabilityId, CorrelationId, ExtensionId, InvocationId, MissionId, ProductKind, @@ -102,9 +103,11 @@ async fn dispatcher_routes_capability_through_resolved_binding() { async fn dispatcher_redacts_binding_failure_details() { let governor = Arc::new(InMemoryResourceGovernor::new()); let binding = RecordingBinding::failing( - || DispatchError::Script { - kind: RuntimeDispatchErrorKind::ExitFailure, - model_visible_cause: None, + || DispatchError::Rejected { + runtime: Some(RuntimeKind::Script), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::ExitFailure), + diagnostic: None, + detail: None, }, Arc::clone(&governor), ); @@ -121,8 +124,8 @@ async fn dispatcher_redacts_binding_failure_details() { assert!(matches!( err, - DispatchError::Script { - kind: RuntimeDispatchErrorKind::ExitFailure, + DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::ExitFailure), .. } )); @@ -313,16 +316,24 @@ async fn dispatcher_fails_closed_when_prepared_reservation_was_revoked_before_bi .await .unwrap_err(); - let DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: Some(cause), + let DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: Some(diagnostic), + .. } = &err else { panic!("expected resource failure with preserved cause, got {err:?}"); }; + let cause = diagnostic + .message + .as_ref() + .expect("resource failure must preserve a cause") + .as_str(); assert!(cause.contains("resource reservation")); assert!( - err.to_string().contains("WASM dispatch failed: Resource"), + err.to_string() + .contains("provider dispatch rejected: Resource"), "dispatch error remains redacted at the public surface" ); assert!(binding.requests().is_empty()); @@ -495,17 +506,21 @@ impl BoundCapabilityAdapter for RecordingBinding { None => self .governor .reserve(request.scope.clone(), request.estimate.clone()) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?, }; let receipt = self .governor .reconcile(reservation.id, usage.clone()) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?; Ok(RuntimeAdapterResult { output: self.output.clone(), diff --git a/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_event_contract.rs b/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_event_contract.rs index 03b673d4aeb..323bc9260b1 100644 --- a/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_event_contract.rs +++ b/crates/kernel/ironclaw_capabilities/tests/runtime_dispatch_event_contract.rs @@ -19,7 +19,9 @@ use ironclaw_capabilities::{ use ironclaw_event_log::*; use ironclaw_host_api::{ authorized::Authorized, - dispatch::{CapabilityDispatchRequest, DispatchError, RuntimeDispatchErrorKind}, + dispatch::{ + CapabilityDispatchRequest, DispatchError, DispatchFailureKind, RuntimeDispatchErrorKind, + }, ids::{ ActivityId, CapabilityId, CorrelationId, ExtensionId, InvocationId, MissionId, ProcessId, ProductKind, ProjectId, ResourceReservationId, RunId, TenantId, ThreadId, UserId, @@ -191,9 +193,11 @@ async fn dispatcher_marks_loop_dispatch_failure_events_with_parent_run() { provider: ExtensionId::new("echo-script").unwrap(), runtime: RuntimeKind::Script, adapter: Arc::new(FailingBinding { - error: || DispatchError::Script { - kind: RuntimeDispatchErrorKind::ExitFailure, - model_visible_cause: None, + error: || DispatchError::Rejected { + runtime: Some(RuntimeKind::Script), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::ExitFailure), + diagnostic: None, + detail: None, }, }), }, @@ -213,8 +217,8 @@ async fn dispatcher_marks_loop_dispatch_failure_events_with_parent_run() { assert!(matches!( error, - DispatchError::Script { - kind: RuntimeDispatchErrorKind::ExitFailure, + DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::ExitFailure), .. } )); @@ -329,9 +333,11 @@ async fn dispatcher_emits_redacted_runtime_error_kind_for_binding_failure() { provider: ExtensionId::new("echo-script").unwrap(), runtime: RuntimeKind::Script, adapter: Arc::new(FailingBinding { - error: || DispatchError::Script { - kind: RuntimeDispatchErrorKind::ExitFailure, - model_visible_cause: None, + error: || DispatchError::Rejected { + runtime: Some(RuntimeKind::Script), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::ExitFailure), + diagnostic: None, + detail: None, }, }), }, @@ -348,8 +354,8 @@ async fn dispatcher_emits_redacted_runtime_error_kind_for_binding_failure() { assert!(matches!( err, - DispatchError::Script { - kind: RuntimeDispatchErrorKind::ExitFailure, + DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::ExitFailure), .. } )); @@ -484,17 +490,21 @@ impl BoundCapabilityAdapter for EchoBinding { None => self .governor .reserve(request.scope.clone(), request.estimate.clone()) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?, }; let receipt = self .governor .reconcile(reservation.id, usage.clone()) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?; Ok(RuntimeAdapterResult { output, diff --git a/crates/kernel/ironclaw_host_runtime/src/production.rs b/crates/kernel/ironclaw_host_runtime/src/production.rs index 61ac8ac0cb0..b51401e0916 100644 --- a/crates/kernel/ironclaw_host_runtime/src/production.rs +++ b/crates/kernel/ironclaw_host_runtime/src/production.rs @@ -714,6 +714,8 @@ impl HostRuntime for DefaultHostRuntime { // replacing the former host_runtime pre-authorization + `context.trust` // stamp. let registry = self.registry.snapshot(); + let scope = context.resource_scope.clone(); + let invocation_id = context.invocation_id; let host = self.capability_host(®istry); match host .resume_spawn_json( @@ -734,35 +736,18 @@ impl HostRuntime for DefaultHostRuntime { error_kind = failure_kind_from(&error).as_str(), "capability spawn resume failed" ); - // Mirror resume_capability: AuthorizationRequiresAuth must return - // AuthRequired, not Failed. Without this arm a spawned capability - // that needs re-auth after an approval resume silently fails. - match error { - CapabilityInvocationError::AuthorizationRequiresAuth { - capability, - requirement, - } => { - let ironclaw_host_api::dispatch::DispatchAuthRequirement { - required_secrets, - credential_requirements, - model_visible_cause, - } = *requirement; - Ok(auth_required_outcome( - capability, - required_secrets, - credential_requirements, - model_visible_cause.map(Box::new), - )) - } - other => { - let is_standard_write = - capability_is_standard_write(®istry, &capability_id); - Ok(RuntimeCapabilityOutcome::Failed( - failure_from(other, capability_id) - .with_is_standard_write(is_standard_write), - )) - } - } + process_capability_response( + self, + CapabilityResponseContext { + registry: ®istry, + capability_id, + scope: &scope, + invocation_id, + mode: InlineInvocationMode::ApprovalResume, + }, + Err(error), + ) + .await } } } diff --git a/crates/kernel/ironclaw_host_runtime/src/services.rs b/crates/kernel/ironclaw_host_runtime/src/services.rs index 3b39033d0f1..736f03850aa 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services.rs @@ -32,12 +32,14 @@ use ironclaw_filesystem::LibSqlRootFilesystem; use ironclaw_filesystem::PostgresRootFilesystem; use ironclaw_filesystem::{DiskFilesystem, RootFilesystem, ScopedFilesystem}; use ironclaw_host_api::{ - dispatch::{CapabilityDispatcher, DispatchError, RuntimeDispatchErrorKind}, + dispatch::{ + CapabilityDispatcher, DispatchError, DispatchFailureKind, RuntimeDispatchErrorKind, + }, http::RuntimeHttpEgress, ids::{CapabilityId, ResourceReservationId, SecretHandle}, lane::RuntimeLane, resource::{ResourceScope, ResourceUsage}, - runtime::{DispatchErrorLane, RuntimeKind}, + runtime::RuntimeKind, runtime_policy::{ DeploymentMode, EffectiveRuntimePolicy, FilesystemBackendKind, NetworkMode, ProcessBackendKind, RuntimeProfile, SecretMode, @@ -63,8 +65,8 @@ use ironclaw_turns::{ use ironclaw_wasm::{ DenyWasmHostHttp, EmptyWasmRuntimeCredentials, PreparedWitTool, WasmError, WasmRuntimeCredentialProvider, WasmRuntimeHttpAdapter, WasmRuntimePolicyDiscarder, - WasmStagedRuntimeCredentials, WitToolExecution, WitToolHost, WitToolRequest, WitToolRuntime, - WitToolRuntimeConfig, + WasmStagedRuntimeCredentials, WitErrorKind, WitGuestFailure, WitToolExecution, WitToolHost, + WitToolOutcome, WitToolRequest, WitToolRuntime, WitToolRuntimeConfig, }; use secrecy::ExposeSecret; diff --git a/crates/kernel/ironclaw_host_runtime/src/services/extension_tool_binder.rs b/crates/kernel/ironclaw_host_runtime/src/services/extension_tool_binder.rs index 9ef83a55c9f..145ceff49f4 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/extension_tool_binder.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/extension_tool_binder.rs @@ -22,8 +22,15 @@ use ironclaw_extension_contracts::tool_adapter::{ }; use ironclaw_extension_registry::ExtensionPackage; use ironclaw_host_api::{ - capability::CapabilityDescriptor, dispatch::DispatchError, ids::CapabilityId, - lane::RuntimeLane, runtime::RuntimeKind, runtime_policy::EffectiveRuntimePolicy, + capability::CapabilityDescriptor, + dispatch::{ + DispatchError, DispatchFailureDetail, DispatchFailureKind, RuntimeDispatchErrorKind, + }, + ids::CapabilityId, + lane::RuntimeLane, + runtime::RuntimeKind, + runtime_policy::EffectiveRuntimePolicy, + safe_summary::SafeSummary, }; use ironclaw_resources::ResourceGovernor; @@ -139,10 +146,10 @@ where _ports: &ToolPorts<'_>, ) -> Result { let Some(descriptor) = self.descriptors.get(&call.capability_id) else { - return Err(ToolError::Failed { - kind: ironclaw_host_api::dispatch::RuntimeDispatchErrorKind::UndeclaredCapability, - safe_summary: None, - model_visible_cause: None, + return Err(ToolError::Rejected { + kind: RuntimeDispatchErrorKind::UndeclaredCapability, + diagnostic: None, + detail: None, }); }; let execution = self @@ -190,45 +197,46 @@ where pub(super) fn tool_error_from_dispatch(error: DispatchError) -> ToolError { match error { DispatchError::AuthRequired { requirement, .. } => ToolError::AuthRequired { requirement }, - DispatchError::Wasm { - kind, - model_visible_cause, - } - | DispatchError::Mcp { - kind, - model_visible_cause, - } - | DispatchError::Script { - kind, - model_visible_cause, - } => ToolError::Failed { - kind, - safe_summary: None, - model_visible_cause, - }, - DispatchError::FirstParty { - kind, safe_summary, .. - } => ToolError::Failed { - kind, - safe_summary, - model_visible_cause: None, - }, DispatchError::Rejected { - runtime, kind, diagnostic, detail, + .. } => ToolError::Rejected { - runtime, - kind, + kind: tool_runtime_error_kind(kind), diagnostic, detail, }, - other => ToolError::Failed { - kind: ironclaw_host_api::dispatch::RuntimeDispatchErrorKind::Client, - safe_summary: Some(other.event_kind().replace('_', " ")), - model_visible_cause: None, - }, + other => { + let summary = other.event_kind().replace('_', " "); + let summary = match SafeSummary::new(summary) { + Ok(summary) => summary, + Err(_) => SafeSummary::placeholder(), + }; + ToolError::Rejected { + kind: tool_runtime_error_kind(other.failure_kind()), + diagnostic: None, + detail: Some(DispatchFailureDetail::HostSummary { + summary, + detail: None, + }), + } + } + } +} + +fn tool_runtime_error_kind(kind: DispatchFailureKind) -> RuntimeDispatchErrorKind { + match kind { + DispatchFailureKind::Runtime(kind) => kind, + DispatchFailureKind::UnknownCapability => RuntimeDispatchErrorKind::UndeclaredCapability, + DispatchFailureKind::UnknownProvider => RuntimeDispatchErrorKind::Manifest, + DispatchFailureKind::RuntimeMismatch => RuntimeDispatchErrorKind::ExtensionRuntimeMismatch, + DispatchFailureKind::MissingRuntimeBackend | DispatchFailureKind::UnsupportedRuntime => { + RuntimeDispatchErrorKind::UnsupportedRunner + } + // Auth gates use `DispatchError::AuthRequired`; this category inside + // `Rejected` is malformed and retains no control-plane authority. + DispatchFailureKind::AuthRequired => RuntimeDispatchErrorKind::Unknown, } } diff --git a/crates/kernel/ironclaw_host_runtime/src/services/process_executor.rs b/crates/kernel/ironclaw_host_runtime/src/services/process_executor.rs index 4517f0718cd..3483db86cf2 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/process_executor.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/process_executor.rs @@ -266,7 +266,9 @@ mod tests { use ironclaw_host_api::dispatch_test_support::TestDispatcher; use ironclaw_host_api::{ authorized::{ProcessAuthorizedContinuation, ProcessAuthorizedInvocation}, - dispatch::{CapabilityDispatchResult, DispatchError, RuntimeDispatchErrorKind}, + dispatch::{ + CapabilityDispatchResult, DispatchError, DispatchFailureKind, RuntimeDispatchErrorKind, + }, ids::{ ActivityId, AgentId, CapabilityId, CorrelationId, ExtensionId, InvocationId, ProcessId, ProductKind, ProjectId, ResourceReservationId, TenantId, ThreadId, UserId, @@ -548,23 +550,29 @@ mod tests { "unsupported_runtime", ), ( - DispatchError::Script { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + DispatchError::Rejected { + runtime: Some(RuntimeKind::Script), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, }, "resource", ), ( - DispatchError::Mcp { - kind: RuntimeDispatchErrorKind::NetworkDenied, - model_visible_cause: None, + DispatchError::Rejected { + runtime: Some(RuntimeKind::Mcp), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied), + diagnostic: None, + detail: None, }, "network_denied", ), ( - DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::OutputDecode, - model_visible_cause: None, + DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::OutputDecode), + diagnostic: None, + detail: None, }, "output_decode", ), diff --git a/crates/kernel/ironclaw_host_runtime/src/services/runtime_adapters.rs b/crates/kernel/ironclaw_host_runtime/src/services/runtime_adapters.rs index ed8164056d6..d64eba92037 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/runtime_adapters.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/runtime_adapters.rs @@ -24,7 +24,7 @@ use serde_json::Value; use super::wasm_blocking::run_wasm_prepare_blocking; use super::wasm_execution::{ReservationGuard, execute_prepared_wasm}; use super::{ - CapabilityId, DenyWasmHostHttp, DispatchError, DispatchErrorLane, ExtensionRuntime, + CapabilityId, DenyWasmHostHttp, DispatchError, DispatchFailureKind, ExtensionRuntime, FirstPartyCapabilityRegistry, FirstPartyCapabilityRequest, InvocationServicesResolutionRequest, InvocationServicesResolver, McpError, McpExecutionRequest, McpExecutor, McpInvocation, NetworkObligationPolicyStore, PlannerError, PreparedWitTool, ResourceGovernor, @@ -44,6 +44,49 @@ use crate::{ services::wasm_secrets::StagedWasmHostSecrets, }; +/// Builds a provider-rejection `DispatchError` for the first-party lane. +/// `safe_summary` rides the typed diagnostic channel like other lanes' +/// causes; `detail`, when the caller already has a structured +/// [`ironclaw_host_api::dispatch::DispatchFailureDetail`], is carried +/// through verbatim. +fn first_party_dispatch_error( + kind: RuntimeDispatchErrorKind, + safe_summary: Option, + detail: Option, +) -> DispatchError { + let (detail, cause) = match safe_summary { + Some(summary) => { + let (safe_summary, cause) = + match ironclaw_host_api::safe_summary::SafeSummary::new(summary.as_str()) { + Ok(safe_summary) => (safe_summary, None), + Err(_) => { + tracing::warn!("first-party capability supplied an invalid safe summary"); + ( + ironclaw_host_api::safe_summary::SafeSummary::placeholder(), + Some(summary), + ) + } + }; + ( + Some( + ironclaw_host_api::dispatch::DispatchFailureDetail::HostSummary { + summary: safe_summary, + detail: detail.map(Box::new), + }, + ), + cause, + ) + } + None => (detail, None), + }; + DispatchError::provider_rejected( + Some(RuntimeKind::FirstParty), + DispatchFailureKind::Runtime(kind), + cause, + detail, + ) +} + /// Per-invocation execution request handed to a runtime lane. /// /// Host-internal seam behind the prebound @@ -403,9 +446,12 @@ where }, }, ) - .map_err(|error| DispatchError::Script { - kind: script_error_kind(&error), - model_visible_cause: Some(error.to_string()), + .map_err(|error| { + dispatch_error_for_runtime( + RuntimeKind::Script, + script_error_kind(&error), + Some(error.to_string()), + ) })?; Ok(RuntimeAdapterResult { @@ -480,10 +526,11 @@ where diagnostic: Some(Box::new(rejection.diagnostic)), detail: None, }, - error => DispatchError::Mcp { - kind: mcp_error_kind(&error), - model_visible_cause: Some(error.to_string()), - }, + error => dispatch_error_for_runtime( + RuntimeKind::Mcp, + mcp_error_kind(&error), + Some(sanitize_mcp_client_error(&error)), + ), })?; Ok(RuntimeAdapterResult { @@ -643,11 +690,11 @@ where RuntimeDispatchErrorKind::UndeclaredCapability.as_str(), used_prepared_reservation, ); - return Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::UndeclaredCapability, - safe_summary: None, - detail: None, - }); + return Err(first_party_dispatch_error( + RuntimeDispatchErrorKind::UndeclaredCapability, + None, + None, + )); }; trace_first_party_latency_ok( "lookup_handler", @@ -676,11 +723,7 @@ where kind.as_str(), used_prepared_reservation, ); - DispatchError::FirstParty { - kind, - safe_summary: Some(error.to_string()), - detail: None, - } + first_party_dispatch_error(kind, Some(error.to_string()), None) })?; trace_first_party_latency_ok( "plan_capability", @@ -720,11 +763,7 @@ where error.kind().as_str(), used_prepared_reservation, ); - DispatchError::FirstParty { - kind: error.kind(), - safe_summary: Some(error.to_string()), - detail: None, - } + first_party_dispatch_error(error.kind(), Some(error.to_string()), None) })?; trace_first_party_latency_ok( "resolve_services", @@ -769,11 +808,7 @@ where RuntimeDispatchErrorKind::Resource.as_str(), used_prepared_reservation, ); - DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::Resource, - safe_summary: None, - detail: None, - } + first_party_dispatch_error(RuntimeDispatchErrorKind::Resource, None, None) })?, }; tracing::debug!( @@ -788,11 +823,8 @@ where // below drops the still-armed guard, which releases. let reservation_id = reservation.id; let guard = ReservationGuard::new(request.governor, reservation_id); - let first_party_resource_error = || DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::Resource, - safe_summary: None, - detail: None, - }; + let first_party_resource_error = + || first_party_dispatch_error(RuntimeDispatchErrorKind::Resource, None, None); tracing::debug!( reservation_id = %reservation_id, @@ -872,11 +904,11 @@ where safe_summary, detail, .. - } => Err(DispatchError::FirstParty { + } => Err(first_party_dispatch_error( kind, safe_summary, - detail: detail.map(|detail| *detail), - }), + detail.map(|detail| *detail), + )), }; } Err(_) => { @@ -893,11 +925,11 @@ where used_prepared_reservation, ); // Dropping `guard` releases the reservation. - return Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::Backend, - safe_summary: None, - detail: None, - }); + return Err(first_party_dispatch_error( + RuntimeDispatchErrorKind::Backend, + None, + None, + )); } }; @@ -918,11 +950,7 @@ where used_prepared_reservation, ); // Dropping `guard` releases the reservation. - DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::OutputDecode, - safe_summary: None, - detail: None, - } + first_party_dispatch_error(RuntimeDispatchErrorKind::OutputDecode, None, None) })?; trace_first_party_latency_ok( "serialize_output", @@ -971,11 +999,11 @@ where RuntimeDispatchErrorKind::Resource.as_str(), used_prepared_reservation, ); - return Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::Resource, - safe_summary: None, - detail: None, - }); + return Err(first_party_dispatch_error( + RuntimeDispatchErrorKind::Resource, + None, + None, + )); } }; tracing::debug!( @@ -1052,9 +1080,12 @@ impl WasmRuntimeAdapter { fn prepared_guard( &self, ) -> Result>>, DispatchError> { - self.prepared.lock().map_err(|error| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Executor, - model_visible_cause: Some(error.to_string()), + self.prepared.lock().map_err(|error| { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::Executor, + Some(error.to_string()), + ) }) } @@ -1114,27 +1145,31 @@ where let module_path = match &request.package.manifest.runtime { ExtensionRuntime::Wasm { module } => ironclaw_extension_registry::resolve_asset_under( module, - request - .package - .materialized_root() - .map_err(|error| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Manifest, - model_visible_cause: Some(error.to_string()), - })?, + request.package.materialized_root().map_err(|error| { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::Manifest, + Some(error.to_string()), + ) + })?, ) - .map_err(|error| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Manifest, - model_visible_cause: Some(error.to_string()), + .map_err(|error| { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::Manifest, + Some(error.to_string()), + ) })?, other => { - return Err(DispatchError::Wasm { - kind: if other.kind() == RuntimeKind::Wasm { + return Err(dispatch_error_for_runtime( + RuntimeKind::Wasm, + if other.kind() == RuntimeKind::Wasm { RuntimeDispatchErrorKind::Manifest } else { RuntimeDispatchErrorKind::ExtensionRuntimeMismatch }, - model_visible_cause: None, - }); + None, + )); } }; let cache_key = module_path.as_str().to_string(); @@ -1148,9 +1183,12 @@ where .filesystem .read_file(&module_path) .await - .map_err(|error| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::FilesystemDenied, - model_visible_cause: Some(error.to_string()), + .map_err(|error| { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::FilesystemDenied, + Some(error.to_string()), + ) })?; let prepared = Arc::new( run_wasm_prepare_blocking( @@ -1159,9 +1197,12 @@ where wasm_bytes, ) .await - .map_err(|error| DispatchError::Wasm { - kind: error.kind(), - model_visible_cause: Some(error.source().to_string()), + .map_err(|error| { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + error.kind(), + Some(error.source().to_string()), + ) })?, ); let prepared = { @@ -1205,30 +1246,20 @@ where } } -fn dispatch_error_for_runtime( +/// Builds a provider-rejection `DispatchError` for a given runtime lane. +/// `cause` rides the typed diagnostic channel (#5965): raw-or-better cause +/// text, scrubbed downstream at the model-visible Diagnostic seam. +pub(super) fn dispatch_error_for_runtime( runtime: RuntimeKind, kind: RuntimeDispatchErrorKind, cause: Option, ) -> DispatchError { - match runtime.dispatch_error_lane() { - DispatchErrorLane::Mcp => DispatchError::Mcp { - kind, - model_visible_cause: cause, - }, - DispatchErrorLane::Script => DispatchError::Script { - kind, - model_visible_cause: cause, - }, - DispatchErrorLane::Wasm => DispatchError::Wasm { - kind, - model_visible_cause: cause, - }, - DispatchErrorLane::FirstParty => DispatchError::FirstParty { - kind, - safe_summary: cause, - detail: None, - }, - } + DispatchError::provider_rejected( + Some(runtime), + DispatchFailureKind::Runtime(kind), + cause, + None, + ) } fn planner_error_kind(error: &PlannerError) -> RuntimeDispatchErrorKind { @@ -1295,7 +1326,15 @@ pub(super) fn wasm_error_kind(error: &WasmError) -> RuntimeDispatchErrorKind { WasmError::StoreConfiguration(_) => RuntimeDispatchErrorKind::Executor, WasmError::LinkerConfiguration(_) => RuntimeDispatchErrorKind::Executor, WasmError::InstantiationFailed(_) => RuntimeDispatchErrorKind::MethodMissing, + WasmError::UnsupportedContract(_) => RuntimeDispatchErrorKind::Manifest, WasmError::ExecutionFailed { .. } => RuntimeDispatchErrorKind::Guest, WasmError::InvalidSchema(_) => RuntimeDispatchErrorKind::Manifest, } } + +fn sanitize_mcp_client_error(error: &McpError) -> String { + let raw = error.to_string(); + let sanitized = ironclaw_safety::sanitize_display_text(&raw); + tracing::debug!(reason = %sanitized, "MCP client failure sanitized for provider diagnostic"); + sanitized +} diff --git a/crates/kernel/ironclaw_host_runtime/src/services/tests.rs b/crates/kernel/ironclaw_host_runtime/src/services/tests.rs index b31825a5dd6..885e058d4dd 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/tests.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/tests.rs @@ -20,7 +20,9 @@ use ironclaw_host_api::{ action::{NetworkMethod, NetworkPolicy, NetworkScheme, NetworkTargetPattern}, capability::{CapabilityDescriptor, CapabilitySet, EffectKind, PermissionMode}, decision::Obligation, - dispatch::{CapabilityDispatchResult, DispatchError, RuntimeDispatchErrorKind}, + dispatch::{ + CapabilityDispatchResult, DispatchError, DispatchFailureKind, RuntimeDispatchErrorKind, + }, host_port::HostPortCatalog, http::{ RuntimeCredentialInjection, RuntimeCredentialSource, RuntimeCredentialTarget, @@ -986,8 +988,8 @@ async fn service_guard_releases_reservation_on_planner_denial() { assert!(matches!( result, - Err(DispatchError::Script { - kind: RuntimeDispatchErrorKind::UnsupportedRunner, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::UnsupportedRunner), .. }) )); @@ -1044,8 +1046,8 @@ async fn service_guard_rejects_resolution_before_wasm_dispatch() { assert!(matches!( result, - Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::NetworkDenied, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied), .. }) )); @@ -1107,8 +1109,8 @@ async fn service_guard_releases_reservation_on_invocation_service_resolution_den assert!(matches!( result, - Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::NetworkDenied, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied), .. }) )); @@ -1165,8 +1167,8 @@ async fn service_guard_rejects_required_secret_without_secret_store_before_dispa assert!(matches!( result, - Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::SecretDenied, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::SecretDenied), .. }) )); @@ -1230,8 +1232,8 @@ async fn first_party_adapter_releases_reservation_when_invocation_service_resolu assert!(matches!( result, - Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::NetworkDenied, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied), .. }) )); @@ -1362,8 +1364,8 @@ async fn first_party_adapter_releases_reservation_when_planner_denies() { assert!(matches!( result, - Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::NetworkDenied, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied), .. }) )); @@ -1513,7 +1515,8 @@ async fn assert_first_party_denies_before_handler( assert!( matches!( result, - Err(DispatchError::FirstParty { kind, .. }) if kind == expected_kind + Err(DispatchError::Rejected { kind, .. }) + if kind == DispatchFailureKind::Runtime(expected_kind) ), "expected first-party denial {expected_kind:?}, got {result:?}" ); @@ -1543,17 +1546,21 @@ impl RuntimeAdapter for RecordingRunti None => request .governor .reserve(request.scope, request.estimate) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?, }; let receipt: ResourceReceipt = request .governor .reconcile(reservation.id, usage.clone()) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?; Ok(RuntimeAdapterResult { output: Value::Null, diff --git a/crates/kernel/ironclaw_host_runtime/src/services/tests/extension_tool_binder.rs b/crates/kernel/ironclaw_host_runtime/src/services/tests/extension_tool_binder.rs index 618cd19f935..1064d3d913d 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/tests/extension_tool_binder.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/tests/extension_tool_binder.rs @@ -9,8 +9,8 @@ use ironclaw_extension_contracts::tool_adapter::{ ToolCall, ToolCallResources, ToolError, ToolPorts, }; use ironclaw_host_api::{ - dispatch::DispatchAuthRequirement, path::VirtualPath, resource::RuntimeResourceBudget, - runtime::TrustClass, trust::RequestedTrustClass, + path::VirtualPath, resource::RuntimeResourceBudget, runtime::TrustClass, + trust::RequestedTrustClass, }; use super::super::ExtensionToolBindError; @@ -142,7 +142,7 @@ async fn binder_routes_by_capability_id_through_the_first_party_lane() { assert!( matches!( undeclared, - ToolError::Failed { + ToolError::Rejected { kind: RuntimeDispatchErrorKind::UndeclaredCapability, .. } @@ -187,7 +187,7 @@ fn binder_preserves_the_raw_auth_diagnostic_across_the_tool_abi() { let error = crate::services::extension_tool_binder::tool_error_from_dispatch( DispatchError::AuthRequired { capability: CapabilityId::new("github.list_issues").unwrap(), - requirement: Box::new(DispatchAuthRequirement { + requirement: Box::new(ironclaw_host_api::dispatch::DispatchAuthRequirement { required_secrets: Vec::new(), credential_requirements: Vec::new(), model_visible_cause: Some(ironclaw_host_api::dispatch::ProviderDiagnostic { @@ -206,7 +206,7 @@ fn binder_preserves_the_raw_auth_diagnostic_across_the_tool_abi() { }; let cause = requirement .model_visible_cause - .expect("binder must preserve the auth diagnostic"); + .expect("binder preserves auth diagnostic"); assert_eq!( cause.message.as_ref().map(|message| message.as_str()), Some(diagnostic) @@ -252,6 +252,33 @@ fn binder_preserves_provider_rejection_across_the_tool_abi() { assert!(!format!("{diagnostic:?}").contains("Bad credentials")); } +#[test] +fn binder_maps_non_rejected_failure_to_the_closed_tool_runtime_kind() { + use ironclaw_host_api::dispatch::DispatchFailureDetail; + + let error = crate::services::extension_tool_binder::tool_error_from_dispatch( + DispatchError::UnknownCapability { + capability: CapabilityId::new("missing.tool").unwrap(), + }, + ); + + let ToolError::Rejected { + kind, + diagnostic, + detail, + } = error + else { + panic!("non-Rejected routing failures must remain typed Rejected errors"); + }; + assert_eq!(kind, RuntimeDispatchErrorKind::UndeclaredCapability); + assert!(diagnostic.is_none()); + assert!(matches!( + detail, + Some(DispatchFailureDetail::HostSummary { summary, detail }) + if summary.as_str() == "unknown capability" && detail.is_none() + )); +} + #[tokio::test] async fn binder_fails_typed_for_an_unconfigured_lane() { // No MCP runtime configured: binding an MCP-runtime package fails with diff --git a/crates/kernel/ironclaw_host_runtime/src/services/tests/first_party_runtime_adapter.rs b/crates/kernel/ironclaw_host_runtime/src/services/tests/first_party_runtime_adapter.rs index ce5a3012799..937ba328b54 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/tests/first_party_runtime_adapter.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/tests/first_party_runtime_adapter.rs @@ -4,7 +4,7 @@ use async_trait::async_trait; use ironclaw_filesystem::InMemoryBackend; use ironclaw_host_api::{ decision::RuntimeCredentialAuthRequirement, - dispatch::{DispatchError, RuntimeDispatchErrorKind}, + dispatch::{DispatchError, DispatchFailureKind, RuntimeDispatchErrorKind}, ids::{ExtensionId, RunId, SecretHandle, UserId, VendorId}, invocation::InvocationOrigin, resource::{ResourceEstimate, ResourceReservation, ResourceScope}, @@ -295,6 +295,7 @@ async fn first_party_adapter_maps_handler_auth_required_to_dispatch_auth_require Err(DispatchError::AuthRequired { capability, requirement, + .. }) => { assert_eq!(capability, descriptor.id); assert!( @@ -478,10 +479,9 @@ async fn first_party_adapter_forwards_credential_requirements_from_auth_required match result { Err(DispatchError::AuthRequired { - requirement: auth_requirement, - .. + requirement: got, .. }) => { - assert_eq!(auth_requirement.credential_requirements, vec![requirement]); + assert_eq!(got.credential_requirements, vec![requirement]); } other => panic!("expected AuthRequired, got {other:?}"), } @@ -537,8 +537,8 @@ async fn first_party_adapter_maps_panicking_handler_to_backend() { assert!( matches!( result, - Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::Backend, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Backend), .. }) ), @@ -611,7 +611,7 @@ impl crate::FirstPartyCapabilityHandler for PanicOnDispatchHandler { // Test double: reconcile always fails with UnknownReservation. // Used to verify the reconcile-failure path in FirstPartyRuntimeAdapter -// releases the reservation and returns DispatchError::FirstParty { Resource }. +// releases the reservation and returns DispatchError::Rejected { Resource }. struct ReconcileFailingGovernor { inner: InMemoryResourceGovernor, } @@ -734,8 +734,8 @@ async fn first_party_adapter_releases_reservation_when_reconcile_fails_after_suc assert!( matches!( result, - Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::Resource, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), .. }) ), @@ -1236,7 +1236,7 @@ impl crate::FirstPartyCapabilityHandler for DispatchFailingWithUsageHandler { /// /// When `governor.reconcile` fails (simulated by `ReconcileFailingGovernor`): /// (a) The adapter must return the **original** handler error -/// (`DispatchError::FirstParty { OperationFailed }`) — NOT the +/// (`DispatchError::Rejected { OperationFailed }`) — NOT the /// `Resource` accounting error that `first_party_resource_error` produces. /// (b) The reservation must be released (reserved tally returns to baseline), /// because `account_failed` calls `governor.release` after a reconcile @@ -1288,12 +1288,12 @@ async fn first_party_adapter_preserves_handler_error_when_account_failed_reconci }) .await; - // (a) Must return the original handler error — NOT DispatchError::FirstParty{Resource}. + // (a) Must return the original handler error — NOT DispatchError::Rejected{Resource}. assert!( matches!( result, - Err(DispatchError::FirstParty { - kind: RuntimeDispatchErrorKind::OperationFailed, + Err(DispatchError::Rejected { + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::OperationFailed), .. }) ), diff --git a/crates/kernel/ironclaw_host_runtime/src/services/tests/mcp_runtime_adapter.rs b/crates/kernel/ironclaw_host_runtime/src/services/tests/mcp_runtime_adapter.rs index 4b6e03082bd..ffc03552199 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/tests/mcp_runtime_adapter.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/tests/mcp_runtime_adapter.rs @@ -59,98 +59,22 @@ async fn mcp_adapter_maps_executor_auth_required_to_dispatch_auth_required() { match result { Err(DispatchError::AuthRequired { capability, - requirement: auth_requirement, + requirement: got, + .. }) => { assert_eq!(capability, descriptor.id); - assert!(auth_requirement.required_secrets.is_empty()); - assert_eq!(auth_requirement.credential_requirements, vec![requirement]); + assert!(got.required_secrets.is_empty()); + assert_eq!(got.credential_requirements, vec![requirement]); } other => panic!("expected AuthRequired, got {other:?}"), } } #[tokio::test] -async fn mcp_adapter_maps_provider_rejection_to_typed_dispatch_rejection() { - let adapter = McpRuntimeAdapter::from_executor(Arc::new(ProviderRejectedMcpExecutor { - rejection: ironclaw_mcp::McpProviderRejection { - diagnostic: ironclaw_host_api::dispatch::ProviderDiagnostic { - code: Some(ironclaw_host_api::dispatch::ProviderErrorCode::new( - "mcp_tool_rejected", - )), - message: Some(ironclaw_host_api::dispatch::UntrustedProviderMessage::new( - "provider says no", - )), - retry_after: None, - }, - receipt: ResourceReceipt { - id: ResourceReservationId::new(), - scope: sample_scope(), - status: ReservationStatus::Released, - estimate: ResourceEstimate::default(), - actual: None, - }, - usage: ResourceUsage::default(), - }, - })); - let descriptor = test_descriptor(RuntimeKind::Mcp, Vec::new()); - let filesystem = DiskFilesystem::new(); - let governor = InMemoryResourceGovernor::new(); - let package = test_package(MCP_MANIFEST, "test"); - let policy = policy_with( - FilesystemBackendKind::HostWorkspace, - ProcessBackendKind::LocalHost, - NetworkMode::DirectLogged, - SecretMode::ScrubbedEnv, - ); - - let result = adapter - .dispatch_json(RuntimeLaneRequest { - run_id: None, - origin: None, - package: &package, - descriptor: &descriptor, - filesystem: &filesystem, - governor: &governor, - runtime_policy: &policy, - capability_id: &descriptor.id, - scope: sample_scope(), - authenticated_actor_user_id: None, - estimate: ResourceEstimate::default(), - mounts: None, - resource_reservation: None, - input: json!({"query": "provider rejection through adapter"}), - }) - .await; - - match result { - Err(DispatchError::Rejected { - runtime: Some(RuntimeKind::Mcp), - kind: - ironclaw_host_api::dispatch::DispatchFailureKind::Runtime( - ironclaw_host_api::dispatch::RuntimeDispatchErrorKind::Client, - ), - diagnostic: Some(diagnostic), - .. - }) => { - assert_eq!( - diagnostic.code.as_ref().map(|code| code.as_str()), - Some("mcp_tool_rejected") - ); - assert_eq!( - diagnostic.message.as_ref().map(|message| message.as_str()), - Some("provider says no") - ); - } - other => panic!("expected typed MCP rejection, got {other:?}"), - } -} - -#[tokio::test] -async fn mcp_adapter_preserves_executor_failure_cause() { - // Regression (Phase 1): an MCP dispatch failure's raw cause — including - // path/JSON delimiters — must ride the model-visible-cause channel so the - // model-visible Diagnostic downstream keeps it instead of collapsing to a - // bare failure category. +async fn mcp_adapter_sanitizes_executor_failure_paths() { + // MCP client errors may contain host filesystem paths. The provider + // diagnostic keeps the corrective context but never exposes those paths; + // raw backend details stay in host-side diagnostics only. let raw = "MCP client failed at /tmp/{socket}"; let adapter = McpRuntimeAdapter::from_executor(Arc::new(FailingMcpExecutor { reason: raw.to_string(), @@ -186,12 +110,16 @@ async fn mcp_adapter_preserves_executor_failure_cause() { .await; match result { - Err(DispatchError::Mcp { - model_visible_cause, - .. - }) => { - let summary = model_visible_cause.expect("MCP cause should be retained"); - assert!(summary.contains(raw), "unexpected cause: {summary}"); + Err(DispatchError::Rejected { diagnostic, .. }) => { + let summary = diagnostic + .and_then(|diagnostic| diagnostic.message) + .map(|message| message.as_str().to_string()) + .expect("MCP cause should be retained"); + assert!(!summary.contains(raw), "raw MCP path leaked: {summary}"); + assert!( + summary.contains("[redacted]"), + "path was not sanitized: {summary}" + ); } other => panic!("expected MCP dispatch failure, got {other:?}"), } @@ -229,10 +157,6 @@ struct AuthRequiredMcpExecutor { requirement: RuntimeCredentialAuthRequirement, } -struct ProviderRejectedMcpExecutor { - rejection: ironclaw_mcp::McpProviderRejection, -} - struct FailingMcpExecutor { reason: String, } @@ -250,17 +174,6 @@ impl McpExecutor for FailingMcpExecutor { } } -#[async_trait] -impl McpExecutor for ProviderRejectedMcpExecutor { - async fn execute_extension_json( - &self, - _budget: &dyn RuntimeResourceBudget, - _request: McpExecutionRequest<'_>, - ) -> Result { - Err(McpError::ProviderRejected(Box::new(self.rejection.clone()))) - } -} - #[async_trait] impl McpExecutor for AuthRequiredMcpExecutor { async fn execute_extension_json( diff --git a/crates/kernel/ironclaw_host_runtime/src/services/tests/registry_lane_tool_resolver.rs b/crates/kernel/ironclaw_host_runtime/src/services/tests/registry_lane_tool_resolver.rs index c4c98957b15..a234bd4d7c3 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/tests/registry_lane_tool_resolver.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/tests/registry_lane_tool_resolver.rs @@ -78,17 +78,21 @@ impl RuntimeAdapter for EchoLane { None => self .governor .reserve(request.scope, request.estimate) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?, }; let receipt = self .governor .reconcile(reservation.id, usage.clone()) - .map_err(|_| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .map_err(|_| DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::Resource), + diagnostic: None, + detail: None, })?; Ok(RuntimeAdapterResult { output, diff --git a/crates/kernel/ironclaw_host_runtime/src/services/tests/wasm_execution_fault_profiles.rs b/crates/kernel/ironclaw_host_runtime/src/services/tests/wasm_execution_fault_profiles.rs index 22a5fdae6ca..6f1ed45b595 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/tests/wasm_execution_fault_profiles.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/tests/wasm_execution_fault_profiles.rs @@ -18,9 +18,9 @@ //! ```text //! profile status provider_fault_proxy.py //! -> "github_api_error_status_{status}" request.rs:45 -//! -> guest kind tag github wasm-src lib.rs:55 -//! -> WasmGuestErrorKind wasm_guest_error_kind -//! -> DispatchError wasm_guest_dispatch_error +//! -> guest kind tag github wasm-src lib.rs:55 (typed near:agent@0.4.1 `guest-failure`) +//! -> WitErrorKind guest-computed, carried on `WitGuestFailure::kind` +//! -> DispatchError typed_wasm_guest_dispatch_error //! -> FailureKind From //! -> FailureFate FailureKind::fate //! ``` @@ -35,7 +35,7 @@ use ironclaw_host_api::{ result_meta::{FailureFate, FailureKind}, }; -use super::wasm_guest_dispatch_error; +use super::{WitErrorKind, WitGuestFailure, typed_wasm_guest_dispatch_error}; /// The e2e fault-profile catalogue, as source text. const FAULT_PROFILE_CATALOGUE: &str = @@ -180,28 +180,29 @@ fn catalogue_profiles() -> Vec<(String, Option)> { profiles } -/// The kind tag the GitHub guest emits for an HTTP status. +/// The `WitErrorKind` the GitHub guest computes for an HTTP status. /// /// Mirrors `guest_error_kind` in the extension's wasm source, which is a /// separate crate compiled to wasm and so cannot be linked into a host test. /// The status side is not guesswork: `request.rs:45` builds the code as /// `github_api_error_status_{status}` for every non-2xx. -fn guest_kind_for_status(status: u16) -> &'static str { +fn guest_kind_for_status(status: u16) -> WitErrorKind { match status { - 401 => "auth_required", - 403 | 429 => "client", - _ => "operation_failed", + 401 => WitErrorKind::AuthRequired, + 403 | 429 => WitErrorKind::Client, + _ => WitErrorKind::OperationFailed, } } -/// The wire payload the GitHub guest emits for a failed request -/// (`{"code": ..., "kind": ...}`, github wasm-src lib.rs:47-52). -fn guest_error_payload(status: u16) -> String { - serde_json::json!({ - "code": format!("github_api_error_status_{status}"), - "kind": guest_kind_for_status(status), - }) - .to_string() +/// The typed `guest-failure` the GitHub guest emits for a failed request +/// (near:agent@0.4.1 `guest-failure`, github wasm-src lib.rs:30-33: `code` is +/// the plain error string, `kind` is computed guest-side). +fn guest_failure(status: u16) -> WitGuestFailure { + WitGuestFailure { + kind: guest_kind_for_status(status), + code: Some(format!("github_api_error_status_{status}")), + message: None, + } } /// The catalogue status for a profile, or a failure naming the profile. @@ -228,8 +229,8 @@ fn status_fault_profiles_classify_to_their_declared_fate() { for case in STATUS_PROFILE_FATES { let status = catalogue_status(case.profile); - let payload = guest_error_payload(status); - let dispatch = wasm_guest_dispatch_error(&payload, &capability); + let failure = guest_failure(status); + let dispatch = typed_wasm_guest_dispatch_error(failure, &capability); let failure_kind: FailureKind = dispatch.failure_kind().into(); assert_eq!( @@ -258,20 +259,19 @@ fn status_fault_profiles_classify_to_their_declared_fate() { #[test] fn a_401_parks_for_reauth_and_is_never_reported_as_a_tool_failure() { let capability = CapabilityId::new("github.list_issues").expect("a legal capability id"); - let payload = serde_json::json!({ - "code": format!( + let failure = WitGuestFailure { + kind: WitErrorKind::AuthRequired, + code: Some(format!( "github_api_error_status_{}", catalogue_status("expired_credential") - ), - "kind": "auth_required", - "message": "Bad credentials", - }) - .to_string(); + )), + message: Some("Bad credentials".to_string()), + }; // The variant matters, not just the fate: a re-auth gate needs the // capability and credential requirements carried through, which only // `DispatchError::AuthRequired` does. - let dispatch = wasm_guest_dispatch_error(&payload, &capability); + let dispatch = typed_wasm_guest_dispatch_error(failure, &capability); let DispatchError::AuthRequired { requirement, .. } = &dispatch else { panic!("an expired credential must produce an auth gate, got {dispatch:?}"); }; @@ -289,18 +289,18 @@ fn a_401_parks_for_reauth_and_is_never_reported_as_a_tool_failure() { ); assert!(!format!("{dispatch:?}").contains("Bad credentials")); - let code_only_payload = serde_json::json!({ - "code": "github_api_error_status_401", - "kind": "auth_required", - }) - .to_string(); - let code_only_dispatch = wasm_guest_dispatch_error(&code_only_payload, &capability); + let code_only_failure = WitGuestFailure { + kind: WitErrorKind::AuthRequired, + code: Some("github_api_error_status_401".to_string()), + message: None, + }; + let code_only_dispatch = typed_wasm_guest_dispatch_error(code_only_failure, &capability); let DispatchError::AuthRequired { requirement, .. } = code_only_dispatch else { panic!("a code-only auth rejection must retain its diagnostic"); }; let code_only_cause = requirement .model_visible_cause - .expect("a code-only auth rejection must retain its diagnostic"); + .expect("code-only auth rejection retains its diagnostic"); assert_eq!( code_only_cause.code.as_ref().map(|code| code.as_str()), Some("github_api_error_status_401") diff --git a/crates/kernel/ironclaw_host_runtime/src/services/wasm_diagnostics.rs b/crates/kernel/ironclaw_host_runtime/src/services/wasm_diagnostics.rs index fe67f7f9e75..927b7881d8e 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/wasm_diagnostics.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/wasm_diagnostics.rs @@ -1,20 +1,29 @@ +use std::sync::LazyLock; + use ironclaw_host_api::ids::CapabilityId; +use ironclaw_host_api::{ + dispatch::truncate_capability_display_text, result_meta::MODEL_DIAGNOSTIC_MAX_BYTES, +}; +use ironclaw_safety::LeakDetector; use ironclaw_wasm::{WasmError, WasmLogLevel, WasmLogRecord}; +static WASM_DIAGNOSTIC_LEAK_DETECTOR: LazyLock = LazyLock::new(LeakDetector::new); + pub(super) fn log_wasm_runtime_error(capability_id: &CapabilityId, error: &WasmError) { if let WasmError::ExecutionFailed { message, logs, .. } = error { log_wasm_guest_logs(capability_id, logs); tracing::debug!( capability_id = %capability_id, - wasm_error = %message, - "WASM runtime execution failed with raw guest error" + wasm_error = %sanitize_wasm_diagnostic(message), + "WASM runtime execution failed with guest error" ); return; } + let wasm_error = sanitize_wasm_diagnostic(&error.to_string()); tracing::debug!( capability_id = %capability_id, - wasm_error = %error, + wasm_error = %wasm_error, "WASM runtime execution failed" ); } @@ -27,39 +36,76 @@ pub(super) fn log_wasm_guest_error( log_wasm_guest_logs(capability_id, logs); tracing::debug!( capability_id = %capability_id, - wasm_error = %error, - "WASM guest returned raw capability error" + wasm_error = %sanitize_wasm_diagnostic(error), + "WASM guest returned capability error" ); } fn log_wasm_guest_logs(capability_id: &CapabilityId, logs: &[WasmLogRecord]) { for log in logs { + let message = sanitize_wasm_diagnostic(&log.message); match log.level { WasmLogLevel::Trace => tracing::trace!( capability_id = %capability_id, - wasm_log = %log.message, + wasm_log = %message, "WASM guest log" ), WasmLogLevel::Debug => tracing::debug!( capability_id = %capability_id, - wasm_log = %log.message, + wasm_log = %message, "WASM guest log" ), WasmLogLevel::Info => tracing::info!( capability_id = %capability_id, - wasm_log = %log.message, + wasm_log = %message, "WASM guest log" ), WasmLogLevel::Warn => tracing::warn!( capability_id = %capability_id, - wasm_log = %log.message, + wasm_log = %message, "WASM guest log" ), WasmLogLevel::Error => tracing::error!( capability_id = %capability_id, - wasm_log = %log.message, + wasm_log = %message, "WASM guest log" ), } } } + +fn sanitize_wasm_diagnostic(value: &str) -> String { + let (redacted, _) = WASM_DIAGNOSTIC_LEAK_DETECTOR.redact_all_secrets(value); + truncate_capability_display_text(&redacted, MODEL_DIAGNOSTIC_MAX_BYTES).text +} + +#[cfg(test)] +mod tests { + use super::*; + use tracing_test::traced_test; + + const GITHUB_TOKEN_SHAPE: &str = "ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; + + #[test] + #[traced_test] + fn guest_error_and_logs_are_redacted_before_host_tracing() { + let capability_id = CapabilityId::new("github.search_issues").expect("capability id"); + let guest_logs = [WasmLogRecord { + level: WasmLogLevel::Warn, + message: format!("provider response echoed {GITHUB_TOKEN_SHAPE}"), + }]; + + log_wasm_guest_error( + &capability_id, + &guest_logs, + &format!("auth failed with {GITHUB_TOKEN_SHAPE}"), + ); + + assert!( + !logs_contain(GITHUB_TOKEN_SHAPE), + "host diagnostics must not trace credential-shaped guest text" + ); + assert!(logs_contain("WASM guest log")); + assert!(logs_contain("WASM guest returned capability error")); + } +} diff --git a/crates/kernel/ironclaw_host_runtime/src/services/wasm_execution.rs b/crates/kernel/ironclaw_host_runtime/src/services/wasm_execution.rs index 8a45bccd352..7336b263672 100644 --- a/crates/kernel/ironclaw_host_runtime/src/services/wasm_execution.rs +++ b/crates/kernel/ironclaw_host_runtime/src/services/wasm_execution.rs @@ -1,9 +1,9 @@ use std::sync::Arc; -use serde::Deserialize; #[cfg(test)] use tokio::sync::Semaphore; +use super::runtime_adapters::dispatch_error_for_runtime; use super::wasm_blocking::run_wasm_execution_blocking; #[cfg(test)] use super::wasm_blocking::{ @@ -14,14 +14,26 @@ use super::wasm_diagnostics::{log_wasm_guest_error, log_wasm_runtime_error}; use super::{ CapabilityId, DispatchError, PreparedWitTool, ResourceGovernor, ResourceReservationId, ResourceUsage, RootFilesystem, RuntimeAdapterResult, RuntimeDispatchErrorKind, - RuntimeLaneRequest, WasmError, WitToolHost, WitToolRuntime, + RuntimeLaneRequest, WasmError, WitErrorKind, WitGuestFailure, WitToolHost, WitToolOutcome, + WitToolRuntime, }; use ironclaw_host_api::dispatch::{ - DispatchAuthRequirement, ProviderDiagnostic, ProviderErrorCode, UntrustedProviderMessage, + DispatchAuthRequirement, DispatchFailureKind, ProviderDiagnostic, ProviderErrorCode, + UntrustedProviderMessage, }; use ironclaw_host_api::resource::ResourceReceipt; - -const MAX_WASM_GUEST_MESSAGE_BYTES: usize = 256; +use ironclaw_host_api::runtime::RuntimeKind; + +/// Bound for a guest-supplied provider message before it rides +/// `model_visible_cause`/`ProviderDiagnostic.message`. Well under the +/// downstream ceilings that would otherwise re-truncate it: `ProviderDiagnostic` +/// bounds to `MODEL_DIAGNOSTIC_MAX_BYTES` (4096, via `bound_provider_text` in +/// `ironclaw_host_api::dispatch`), and the general `Wasm` failure's +/// `CapabilityFailureDetail::Diagnostic { text }` is bounded to the same 4096 +/// (`MODEL_OBSERVATION_DETAIL_MAX_BYTES` in `ironclaw_loop_contracts`) — so a +/// real provider explanation now has room to survive intact instead of being +/// clipped to a near-useless 256 bytes. +const MAX_WASM_GUEST_MESSAGE_BYTES: usize = 2048; /// RAII guard over an in-flight `ResourceGovernor` reservation. /// @@ -175,9 +187,12 @@ where None => request .governor .reserve(request.scope.clone(), request.estimate.clone()) - .map_err(|error| DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: Some(error.to_string()), + .map_err(|error| { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::Resource, + Some(error.to_string()), + ) })?, }; // Hold the reservation in an RAII guard from here on. The guard is carried @@ -186,18 +201,17 @@ where // releases the reservation instead of leaking it permanently. Every early // `return` below drops the still-armed guard, which releases. let guard = ReservationGuard::new(request.governor, reservation.id); - let wasm_resource_error = || DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, - }; + let wasm_resource_error = + || dispatch_error_for_runtime(RuntimeKind::Wasm, RuntimeDispatchErrorKind::Resource, None); let input_json = match serde_json::to_string(&request.input) { Ok(json) => json, Err(error) => { // Dropping `guard` releases the reservation. - return Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::InputEncode, - model_visible_cause: Some(error.to_string()), - }); + return Err(dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::InputEncode, + Some(error.to_string()), + )); } }; let context_json = wasm_invocation_context(request.capability_id); @@ -227,32 +241,37 @@ where preserved_wasm_error_usage(error.source()).as_ref(), wasm_resource_error, )?; - return Err(DispatchError::Wasm { - kind: error.kind(), - model_visible_cause: Some(error.source().to_string()), - }); + return Err(dispatch_error_for_runtime( + RuntimeKind::Wasm, + error.kind(), + Some(error.source().to_string()), + )); } }; - if let Some(error) = execution.error { - log_wasm_guest_error(request.capability_id, &execution.logs, &error); - guard.account_failed(Some(&execution.usage), wasm_resource_error)?; - return Err(wasm_guest_dispatch_error(&error, request.capability_id)); - } - let Some(output_json) = execution.output_json else { - guard.account_failed(Some(&execution.usage), wasm_resource_error)?; - return Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::InvalidResult, - model_visible_cause: Some("WASM execution returned no output".to_string()), - }); + let output_json = match execution.outcome { + WitToolOutcome::Success(output_json) => output_json, + WitToolOutcome::Failure(failure) => { + log_wasm_guest_error( + request.capability_id, + &execution.logs, + &format!("{failure:?}"), + ); + guard.account_failed(Some(&execution.usage), wasm_resource_error)?; + return Err(typed_wasm_guest_dispatch_error( + failure, + request.capability_id, + )); + } }; let output = match serde_json::from_str(&output_json) { Ok(output) => output, Err(error) => { guard.account_failed(Some(&execution.usage), wasm_resource_error)?; - return Err(DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::OutputDecode, - model_visible_cause: Some(error.to_string()), - }); + return Err(dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::OutputDecode, + Some(error.to_string()), + )); } }; let receipt = guard.reconcile(execution.usage.clone(), wasm_resource_error)?; @@ -292,78 +311,80 @@ fn has_accountable_effects(usage: &ResourceUsage) -> bool { || usage.process_count > 0 } -fn wasm_guest_dispatch_error(error: &str, capability: &CapabilityId) -> DispatchError { - match wasm_guest_error_kind(error) { - WasmGuestErrorKind::AuthRequired => DispatchError::AuthRequired { +/// Maps a typed WIT `guest-failure` (near:agent@0.4.1) directly to a +/// `DispatchError`. `kind == auth-required` maps to +/// `DispatchError::AuthRequired` with empty +/// `required_secrets`/`credential_requirements` (the capability host +/// enriches these), everything else maps through +/// `RuntimeDispatchErrorKind`. +fn typed_wasm_guest_dispatch_error( + failure: WitGuestFailure, + capability: &CapabilityId, +) -> DispatchError { + if matches!(failure.kind, WitErrorKind::AuthRequired) { + return DispatchError::AuthRequired { capability: capability.clone(), requirement: Box::new(DispatchAuthRequirement { required_secrets: Vec::new(), credential_requirements: Vec::new(), - model_visible_cause: wasm_guest_provider_diagnostic(error), + model_visible_cause: typed_wasm_guest_provider_diagnostic(&failure), }), - }, - WasmGuestErrorKind::Runtime(kind) => DispatchError::Wasm { - kind, - model_visible_cause: wasm_guest_error_cause(error).or_else(|| Some(error.to_string())), - }, + }; + } + DispatchError::Rejected { + runtime: Some(RuntimeKind::Wasm), + kind: DispatchFailureKind::Runtime(typed_wasm_guest_runtime_kind(failure.kind)), + diagnostic: typed_wasm_guest_provider_diagnostic(&failure).map(Box::new), + detail: None, } } -/// Extract the stable error `code` from a structured guest error payload so -/// the model-visible failure keeps its actionable cause (e.g. a Slack -/// `channel_not_found`) instead of collapsing to the kind's generic sentence. -/// -/// Guests are sandboxed but not trusted with free text on this channel: the -/// code is reduced to a short `[A-Za-z0-9_.-]` identifier, and the composed -/// summary is still re-validated downstream (`LoopSafeSummary`) before it -/// reaches the model. Returns `None` for legacy plain-string guest errors. -#[cfg(test)] -fn wasm_guest_error_code(error: &str) -> Option { - let payload = structured_wasm_guest_error(error)?; - wasm_guest_error_code_from(&payload) +fn typed_wasm_guest_runtime_kind(kind: WitErrorKind) -> RuntimeDispatchErrorKind { + match kind { + // Handled by the caller before this is reached. + WitErrorKind::AuthRequired => RuntimeDispatchErrorKind::OperationFailed, + WitErrorKind::Input => RuntimeDispatchErrorKind::InputEncode, + WitErrorKind::OutputTooLarge => RuntimeDispatchErrorKind::OutputTooLarge, + WitErrorKind::Executor => RuntimeDispatchErrorKind::Executor, + WitErrorKind::NetworkDenied => RuntimeDispatchErrorKind::NetworkDenied, + WitErrorKind::Client => RuntimeDispatchErrorKind::Client, + WitErrorKind::OperationFailed => RuntimeDispatchErrorKind::OperationFailed, + } } -fn wasm_guest_error_code_from(payload: &StructuredWasmGuestError) -> Option { - let code: String = payload - .code +/// Sanitize a typed guest failure's `code`: reduced to `[A-Za-z0-9_.-]` +/// identifier characters, bounded to 64, `None` if empty. +fn sanitized_wasm_guest_code(code: Option<&str>) -> Option { + let sanitized: String = code? .chars() .filter(|character| { character.is_ascii_alphanumeric() || matches!(character, '_' | '-' | '.') }) .take(64) .collect(); - (!code.is_empty()).then_some(code) + (!sanitized.is_empty()).then_some(sanitized) } -fn wasm_guest_error_cause(error: &str) -> Option { - let payload = structured_wasm_guest_error(error)?; - let code = wasm_guest_error_code_from(&payload)?; - let stable_cause = format!("provider error code: {code}"); - let message = bounded_wasm_guest_message(payload.message.as_deref().unwrap_or_default().trim()); - if message.is_empty() { - return Some(stable_cause); - } - Some(format!("{stable_cause}; provider message: {message}")) +fn typed_wasm_guest_provider_diagnostic(failure: &WitGuestFailure) -> Option { + provider_error_diagnostic(failure.code.as_deref(), failure.message.as_deref()) } -fn wasm_guest_provider_diagnostic(error: &str) -> Option { - let payload = structured_wasm_guest_error(error)?; - let code = wasm_guest_error_code_from(&payload).map(ProviderErrorCode::new); - let message = bounded_wasm_guest_message(payload.message.as_deref().unwrap_or_default().trim()); - let message = (!message.is_empty()).then(|| UntrustedProviderMessage::new(message)); - (code.is_some() || message.is_some()).then_some(ProviderDiagnostic { - code, - message, +/// Shared decode over a guest error's `(code, message)` pair. +fn provider_error_diagnostic( + code: Option<&str>, + message: Option<&str>, +) -> Option { + let sanitized_code = sanitized_wasm_guest_code(code).map(ProviderErrorCode::new); + let bounded_message = bounded_wasm_guest_message(message.unwrap_or_default().trim()); + let bounded_message = + (!bounded_message.is_empty()).then(|| UntrustedProviderMessage::new(bounded_message)); + (sanitized_code.is_some() || bounded_message.is_some()).then_some(ProviderDiagnostic { + code: sanitized_code, + message: bounded_message, retry_after: None, }) } -fn structured_wasm_guest_error(error: &str) -> Option { - // silent-ok: structured diagnostics are optional; legacy plain-string - // guest errors continue through the existing stable-kind fallback. - serde_json::from_str(error).ok() -} - fn bounded_wasm_guest_message(message: &str) -> String { let mut bounded = String::new(); for character in message.chars() { @@ -375,94 +396,6 @@ fn bounded_wasm_guest_message(message: &str) -> String { bounded } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum WasmGuestErrorKind { - AuthRequired, - Runtime(RuntimeDispatchErrorKind), -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "snake_case")] -enum StructuredWasmGuestErrorKind { - AuthRequired, - Input, - OutputTooLarge, - Executor, - NetworkDenied, - Client, - OperationFailed, -} - -#[derive(Debug, Deserialize)] -struct StructuredWasmGuestError { - code: String, - kind: StructuredWasmGuestErrorKind, - #[serde(default)] - message: Option, -} - -fn wasm_guest_error_kind(error: &str) -> WasmGuestErrorKind { - if let Ok(payload) = serde_json::from_str::(error) { - return match payload.kind { - StructuredWasmGuestErrorKind::AuthRequired => WasmGuestErrorKind::AuthRequired, - StructuredWasmGuestErrorKind::Input => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::InputEncode) - } - StructuredWasmGuestErrorKind::OutputTooLarge => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OutputTooLarge) - } - StructuredWasmGuestErrorKind::Executor => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Executor) - } - StructuredWasmGuestErrorKind::NetworkDenied => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied) - } - StructuredWasmGuestErrorKind::Client => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Client) - } - StructuredWasmGuestErrorKind::OperationFailed => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OperationFailed) - } - }; - } - - match error { - "AuthRequired" => WasmGuestErrorKind::AuthRequired, - "missing_invocation_context" - | "invalid_invocation_context" - | "unsupported_capability" - | "invalid_parameters" - | "invalid_repository" - | "invalid_query_empty" - | "invalid_query_too_large" - | "invalid_author" - | "invalid_assignee" - | "invalid_involves" - | "invalid_state" - | "invalid_type" - | "invalid_sort" - | "invalid_order" - | "invalid_page" - | "invalid_limit" - | "invalid_issue_number" - | "invalid_body_empty" - | "invalid_body_too_large" => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::InputEncode) - } - "host_http_body_limit" => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OutputTooLarge) - } - "host_http_timeout" => WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Executor), - "host_http_network_denied" => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied) - } - "host_http_forbidden" | "host_http_rate_limited" => { - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Client) - } - _ => WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OperationFailed), - } -} - #[cfg(test)] #[path = "tests/wasm_execution_fault_profiles.rs"] mod fault_profile_tests; @@ -617,9 +550,12 @@ mod tests { let id = ResourceReservationId::new(); let guard = ReservationGuard::new(&governor, id); let receipt = guard - .reconcile(accountable_usage(), || DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .reconcile(accountable_usage(), || { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::Resource, + None, + ) }) .expect("reconcile must succeed"); assert_eq!(receipt.status, ReservationStatus::Reconciled); @@ -638,9 +574,12 @@ mod tests { let id = ResourceReservationId::new(); let guard = ReservationGuard::new(&governor, id); guard - .account_failed(Some(&accountable_usage()), || DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .account_failed(Some(&accountable_usage()), || { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::Resource, + None, + ) }) .expect("account_failed with accountable usage must reconcile"); assert_eq!(governor.reconcile_calls(), 1); @@ -658,9 +597,12 @@ mod tests { let guard = ReservationGuard::new(&governor, id); // No usage → release path; guard consumed, so Drop does not fire again. guard - .account_failed(None, || DispatchError::Wasm { - kind: RuntimeDispatchErrorKind::Resource, - model_visible_cause: None, + .account_failed(None, || { + dispatch_error_for_runtime( + RuntimeKind::Wasm, + RuntimeDispatchErrorKind::Resource, + None, + ) }) .expect("account_failed with no usage releases and returns Ok"); assert_eq!( @@ -701,12 +643,12 @@ mod tests { (type (;2;) (func (param i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32))) (type (;3;) (func (param i32 i32 i32 i32 i32))) (type (;4;) (func (param i32 i32) (result i32))) - (import "near:agent/host@0.3.0" "log" (func $log (type 0))) - (import "near:agent/host@0.3.0" "now-millis" (func $now (type 1))) - (import "near:agent/host@0.3.0" "workspace-read" (func $workspace_read (type 0))) - (import "near:agent/host@0.3.0" "http-request" (func $http_request (type 2))) - (import "near:agent/host@0.3.0" "tool-invoke" (func $tool_invoke (type 3))) - (import "near:agent/host@0.3.0" "secret-exists" (func $secret_exists (type 4))) + (import "near:agent/host@0.4.1" "log" (func $log (type 0))) + (import "near:agent/host@0.4.1" "now-millis" (func $now (type 1))) + (import "near:agent/host@0.4.1" "workspace-read" (func $workspace_read (type 0))) + (import "near:agent/host@0.4.1" "http-request" (func $http_request (type 2))) + (import "near:agent/host@0.4.1" "tool-invoke" (func $tool_invoke (type 3))) + (import "near:agent/host@0.4.1" "secret-exists" (func $secret_exists (type 4))) (memory (export "memory") 1) (global $heap (mut i32) (i32.const 4096)) (data (i32.const 1024) "{\"type\":\"object\"}") @@ -728,9 +670,14 @@ mod tests { i32.const 12 i32.store i32.const 32) + ;; Encode `response` as the `success(string)` case of the near:agent@0.4.1 + ;; typed variant. Canonical ABI layout (align 4, size 32 bytes) for + ;; `variant response { success(string), failure(guest-failure) }`: + ;; offset 0: discriminant (0 = success, 1 = failure) + ;; offset 4: payload — success case is `string` (ptr: u32, len: u32) (func $execute (param i32 i32 i32 i32 i32) (result i32) i32.const 48 - i32.const 1 + i32.const 0 i32.store i32.const 52 i32.const 3072 @@ -738,9 +685,6 @@ mod tests { i32.const 56 i32.const 1 i32.store - i32.const 60 - i32.const 0 - i32.store i32.const 48) (func $post (param i32)) (func $realloc (param $old i32) (param $old_align i32) (param $new_size i32) (param $new_align i32) (result i32) @@ -753,12 +697,12 @@ mod tests { global.set $heap local.get $ret) (func $_initialize) - (export "near:agent/tool@0.3.0#execute" (func $execute)) - (export "cabi_post_near:agent/tool@0.3.0#execute" (func $post)) - (export "near:agent/tool@0.3.0#schema" (func $schema)) - (export "cabi_post_near:agent/tool@0.3.0#schema" (func $post)) - (export "near:agent/tool@0.3.0#description" (func $description)) - (export "cabi_post_near:agent/tool@0.3.0#description" (func $post)) + (export "near:agent/tool@0.4.1#execute" (func $execute)) + (export "cabi_post_near:agent/tool@0.4.1#execute" (func $post)) + (export "near:agent/tool@0.4.1#schema" (func $schema)) + (export "cabi_post_near:agent/tool@0.4.1#schema" (func $post)) + (export "near:agent/tool@0.4.1#description" (func $description)) + (export "cabi_post_near:agent/tool@0.4.1#description" (func $post)) (export "cabi_realloc" (func $realloc)) (export "_initialize" (func $_initialize)) ) @@ -774,12 +718,12 @@ mod tests { (type (;2;) (func (param i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32))) (type (;3;) (func (param i32 i32 i32 i32 i32))) (type (;4;) (func (param i32 i32) (result i32))) - (import "near:agent/host@0.3.0" "log" (func $log (type 0))) - (import "near:agent/host@0.3.0" "now-millis" (func $now (type 1))) - (import "near:agent/host@0.3.0" "workspace-read" (func $workspace_read (type 0))) - (import "near:agent/host@0.3.0" "http-request" (func $http_request (type 2))) - (import "near:agent/host@0.3.0" "tool-invoke" (func $tool_invoke (type 3))) - (import "near:agent/host@0.3.0" "secret-exists" (func $secret_exists (type 4))) + (import "near:agent/host@0.4.1" "log" (func $log (type 0))) + (import "near:agent/host@0.4.1" "now-millis" (func $now (type 1))) + (import "near:agent/host@0.4.1" "workspace-read" (func $workspace_read (type 0))) + (import "near:agent/host@0.4.1" "http-request" (func $http_request (type 2))) + (import "near:agent/host@0.4.1" "tool-invoke" (func $tool_invoke (type 3))) + (import "near:agent/host@0.4.1" "secret-exists" (func $secret_exists (type 4))) (memory (export "memory") 1) (global $heap (mut i32) (i32.const 4096)) (data (i32.const 128) "POST") @@ -805,6 +749,7 @@ mod tests { i32.const 12 i32.store i32.const 32) + ;; See SIMPLE_TOOL_WAT above for the `response` success-case layout. (func $execute (param i32 i32 i32 i32 i32) (result i32) i32.const 128 i32.const 4 @@ -821,7 +766,7 @@ mod tests { call $http_request i32.const 48 - i32.const 1 + i32.const 0 i32.store i32.const 52 i32.const 3072 @@ -829,9 +774,6 @@ mod tests { i32.const 56 i32.const 1 i32.store - i32.const 60 - i32.const 0 - i32.store i32.const 48) (func $post (param i32)) (func $realloc (param $old i32) (param $old_align i32) (param $new_size i32) (param $new_align i32) (result i32) @@ -844,12 +786,12 @@ mod tests { global.set $heap local.get $ret) (func $_initialize) - (export "near:agent/tool@0.3.0#execute" (func $execute)) - (export "cabi_post_near:agent/tool@0.3.0#execute" (func $post)) - (export "near:agent/tool@0.3.0#schema" (func $schema)) - (export "cabi_post_near:agent/tool@0.3.0#schema" (func $post)) - (export "near:agent/tool@0.3.0#description" (func $description)) - (export "cabi_post_near:agent/tool@0.3.0#description" (func $post)) + (export "near:agent/tool@0.4.1#execute" (func $execute)) + (export "cabi_post_near:agent/tool@0.4.1#execute" (func $post)) + (export "near:agent/tool@0.4.1#schema" (func $schema)) + (export "cabi_post_near:agent/tool@0.4.1#schema" (func $post)) + (export "near:agent/tool@0.4.1#description" (func $description)) + (export "cabi_post_near:agent/tool@0.4.1#description" (func $post)) (export "cabi_realloc" (func $realloc)) (export "_initialize" (func $_initialize)) ) @@ -1336,144 +1278,43 @@ mod tests { drop(b); } - #[test] - fn wasm_guest_error_kind_maps_structured_payloads() { - let cases = [ - ( - r#"{"code":"AuthRequired","kind":"auth_required"}"#, - WasmGuestErrorKind::AuthRequired, - ), - ( - r#"{"code":"invalid_repository","kind":"input"}"#, - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::InputEncode), - ), - ( - r#"{"code":"host_http_body_limit","kind":"output_too_large"}"#, - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OutputTooLarge), - ), - ( - r#"{"code":"host_http_timeout","kind":"executor"}"#, - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Executor), - ), - ( - r#"{"code":"host_http_network_denied","kind":"network_denied"}"#, - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied), - ), - ( - r#"{"code":"host_http_forbidden","kind":"client"}"#, - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Client), - ), - ( - r#"{"code":"host_http_request_failed","kind":"operation_failed"}"#, - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OperationFailed), - ), - ]; - - for (error, expected) in cases { - assert_eq!(wasm_guest_error_kind(error), expected); - } - } - - #[test] - fn wasm_guest_error_kind_preserves_legacy_error_mapping_without_prefix_catch_all() { - let cases = [ - ("AuthRequired", WasmGuestErrorKind::AuthRequired), - ( - "invalid_repository", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::InputEncode), - ), - ( - "missing_invocation_context", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::InputEncode), - ), - ( - "unsupported_capability", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::InputEncode), - ), - ( - "host_http_body_limit", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OutputTooLarge), - ), - ( - "host_http_timeout", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Executor), - ), - ( - "host_http_network_denied", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::NetworkDenied), - ), - ( - "host_http_forbidden", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Client), - ), - ( - "host_http_rate_limited", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::Client), - ), - ( - "invalid_internal_state", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OperationFailed), - ), - ( - "unknown_error", - WasmGuestErrorKind::Runtime(RuntimeDispatchErrorKind::OperationFailed), - ), - ]; - - for (error, expected) in cases { - assert_eq!(wasm_guest_error_kind(error), expected); - } - } - - /// A structured guest error's `code` must ride the dispatch error as a + /// A typed guest failure's `code` must ride the dispatch error as a /// sanitized safe summary so the model sees the actionable cause (e.g. /// `channel_not_found`), while hostile codes are reduced to identifier - /// characters and legacy plain-string errors stay summary-less. + /// characters. #[test] - fn wasm_guest_dispatch_error_carries_sanitized_structured_code() { + fn typed_wasm_guest_dispatch_error_carries_sanitized_code() { let capability = CapabilityId::new("slack.get_conversation_history").unwrap(); - match wasm_guest_dispatch_error( - r#"{"code":"channel_not_found","kind":"input"}"#, + match typed_wasm_guest_dispatch_error( + WitGuestFailure { + kind: WitErrorKind::Input, + code: Some("channel_not_found".to_string()), + message: None, + }, &capability, ) { - DispatchError::Wasm { - kind, - model_visible_cause, + DispatchError::Rejected { + kind, diagnostic, .. } => { - assert_eq!(kind, RuntimeDispatchErrorKind::InputEncode); assert_eq!( - model_visible_cause.as_deref(), + kind, + DispatchFailureKind::Runtime(RuntimeDispatchErrorKind::InputEncode) + ); + let diagnostic = diagnostic.expect("a structured code must produce a diagnostic"); + assert_eq!( + ironclaw_host_api::dispatch::provider_diagnostic_model_cause(&diagnostic) + .as_deref(), Some("provider error code: channel_not_found") ); } - other => panic!("expected Wasm dispatch error, got {other:?}"), + other => panic!("expected Rejected dispatch error, got {other:?}"), } // Hostile codes are reduced to identifier characters, never free text. assert_eq!( - wasm_guest_error_code(r#"{"code":"bad {} `code`