Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 31 additions & 71 deletions crates/extensions/packages/github/wasm-src/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,18 @@ 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,
retry_after_ms: None,
},
)
}
}
}

Expand All @@ -45,36 +49,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()
}

/// 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": "<the whole json>", "kind": ...}`.
fn is_structured_error_envelope(error: &str) -> bool {
serde_json::from_str::<serde_json::Value>(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) -> exports::near::agent::tool::ErrorKind {
use exports::near::agent::tool::ErrorKind;

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"
Expand Down Expand Up @@ -105,15 +84,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,
}
}

Expand All @@ -128,39 +107,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::{sanitize_host_error, 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!(
Expand Down Expand Up @@ -343,6 +299,8 @@ mod tests {

#[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",
Expand All @@ -351,15 +309,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
);
}

Expand Down
96 changes: 51 additions & 45 deletions crates/extensions/packages/github/wasm-src/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,41 @@ 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<Option<String>> =
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<String> {
LAST_ERROR_MESSAGE.with(|cell| cell.borrow_mut().take())
}

#[cfg(not(test))]
fn set_last_error_message(body: &[u8]) {
let message = serde_json::from_slice::<serde_json::Value>(body)
.ok()
.and_then(|parsed| {
parsed
.get("message")
.and_then(serde_json::Value::as_str)
.map(bounded_message)
});
LAST_ERROR_MESSAGE.with(|cell| *cell.borrow_mut() = message);
}

#[cfg(not(test))]
pub(crate) fn github_request(
method: &str,
Expand Down Expand Up @@ -38,14 +73,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))
}

Expand All @@ -54,23 +89,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<String> {
let parsed: serde_json::Value = serde_json::from_slice(body).ok()?;
let message = parsed.get("message")?.as_str()?.trim();
Expand Down Expand Up @@ -184,50 +202,38 @@ 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};

#[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 payload = unauthorized_error_payload(body.as_bytes());
let value: serde_json::Value = serde_json::from_str(&payload).expect("valid json");
let message = provider_error_message(body.as_bytes()).expect("message present");

assert_eq!(
value["message"].as_str().expect("message string").len(),
512
);
assert_eq!(message.chars().count(), 512);
}

#[test]
Expand Down
Binary file modified crates/extensions/packages/github/wasm/github_tool.wasm
Binary file not shown.
Loading
Loading