diff --git a/.cargo/config.toml b/.cargo/config.toml index 91bdb04b9..c6ff01c10 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -3,3 +3,6 @@ rustflags = ["-C", "link-args=/FORCE:MULTIPLE /STACK:8388608"] [target.aarch64-pc-windows-msvc] rustflags = ["-C", "link-args=/FORCE:MULTIPLE /STACK:8388608"] + +[target.wasm32-unknown-unknown] +runner = "wasm-bindgen-test-runner" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 260bdaa05..a191e2323 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -135,6 +135,36 @@ jobs: hermit uninstall rustup just check-lean-size + rust-check-wasm: + name: Check and Test GDK Agent Crates on wasm32 + runs-on: ubuntu-latest + needs: changes + if: needs.changes.outputs.code == 'true' || github.event_name != 'pull_request' + steps: + - name: Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: actions-rust-lang/setup-rust-toolchain@ecabd13d1c56bd1345c230e542e9144811ad706f # v2.0.0 + with: + target: wasm32-unknown-unknown + + - name: Install wasm-bindgen test runner + run: | + version=$(sed -n '/^name = "wasm-bindgen"$/{n;s/^version = "\(.*\)"$/\1/p}' Cargo.lock) + cargo install wasm-bindgen-cli --version "$version" --locked + + - name: Check wasm32 build + run: cargo check --locked --target wasm32-unknown-unknown -p goose-agent -p goose-provider-types + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-D warnings" + + - name: Run agent loop on wasm32 + run: cargo test --locked --target wasm32-unknown-unknown -p goose-agent --test wasm + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-D warnings" + goose-sdk-uniffi: name: Check goose-sdk UniFFI runs-on: ubuntu-latest diff --git a/Cargo.lock b/Cargo.lock index 1a4a77332..d791cf4e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2190,6 +2190,12 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "castaway" version = "0.2.4" @@ -5314,6 +5320,7 @@ dependencies = [ "async-trait", "futures", "goose-provider-types", + "js-sys", "rmcp 3.4.1", "schemars 1.2.2", "serde", @@ -5323,6 +5330,8 @@ dependencies = [ "tracing", "tracing-futures", "uuid", + "wasm-bindgen-futures", + "wasm-bindgen-test", ] [[package]] @@ -5490,6 +5499,8 @@ dependencies = [ "chrono", "env-lock", "futures", + "getrandom 0.4.3", + "gloo-timers", "once_cell", "rand 0.10.2", "regex", @@ -7419,6 +7430,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "minicov" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d" +dependencies = [ + "cc", + "walkdir", +] + [[package]] name = "minijinja" version = "2.24.0" @@ -8492,6 +8513,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + [[package]] name = "opaque-debug" version = "0.3.1" @@ -14443,6 +14470,45 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-bindgen-test" +version = "0.3.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45863ef0bef521c12124eb39d9a38513c47db75f22e503c06beacd40afeb35db" +dependencies = [ + "async-trait", + "cast", + "js-sys", + "libm", + "minicov", + "nu-ansi-term", + "num-traits", + "oorandom", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test-macro", + "wasm-bindgen-test-shared", +] + +[[package]] +name = "wasm-bindgen-test-macro" +version = "0.3.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c89dcab8b516b6b603baca9d550b7282d68fcc7f367e3956cff7ebf406a3f12" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "wasm-bindgen-test-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37b4f992cebe528ef34964ae69681ac0fe7080071e7298e46008f9d380302af" + [[package]] name = "wasm-streams" version = "0.5.0" diff --git a/Cargo.toml b/Cargo.toml index db2d83acb..90b572b6b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ uninlined_format_args = "allow" string_slice = "warn" [workspace.dependencies] -rmcp = { version = "3.4.1", default-features = false, features = ["schemars", "auth"] } +rmcp = { version = "3.4.1", default-features = false, features = ["schemars"] } agent-client-protocol-schema = { version = "=1.9.1", default-features = false } agent-client-protocol = { version = "2.2.0", default-features = false } agent-client-protocol-http = { version = "2.2.0", default-features = false } diff --git a/crates/goose-agent/Cargo.toml b/crates/goose-agent/Cargo.toml index 5fc47bc5f..798374511 100644 --- a/crates/goose-agent/Cargo.toml +++ b/crates/goose-agent/Cargo.toml @@ -13,7 +13,7 @@ workspace = true [dependencies] anyhow = { workspace = true } -tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time", "fs", "process", "net", "signal", "io-std", "io-util"] } +tokio = { workspace = true, features = ["macros", "sync", "rt", "time"] } tokio-util = { workspace = true, features = ["compat"] } async-trait = { workspace = true } goose-provider-types = { version = "0.1.0-alpha.11", path = "../goose-provider-types", default-features = false } @@ -24,6 +24,14 @@ futures = { workspace = true } tracing = { workspace = true } tracing-futures = { workspace = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +rmcp = { workspace = true, features = ["local"] } + [dev-dependencies] schemars.workspace = true serde = { workspace = true, features = ["derive"] } + +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] +js-sys = "0.3.105" +wasm-bindgen-futures = "0.4.78" +wasm-bindgen-test = "0.3.78" diff --git a/crates/goose-agent/README.md b/crates/goose-agent/README.md index 02864986e..04fe722c7 100644 --- a/crates/goose-agent/README.md +++ b/crates/goose-agent/README.md @@ -52,5 +52,23 @@ Cancellation is cooperative. Once the token fires, remaining steps are treated a not-applicable and each step's `cancel` hook gets a chance to rewrite its result; anything applied while cancelled yields to the client. +## WebAssembly + +The crate builds for `wasm32-unknown-unknown` and runs without a tokio runtime, +so it can be embedded in a JavaScript host. There, the clock and randomness come +from JavaScript. Some things differ from native: + +- The traits you implement (`Provider`, `Operation`, `ToolProvider`, + `SessionLoader`, `EffectHandler`, and the rest) do not require `Send` or + `Sync`, and neither does `MessageStream`. So you can await JavaScript promises + and hold host handles directly. Implement the traits with + `#[async_trait(?Send)]`. The bounds are `MaybeSend` and `MaybeSync` from + `goose_provider_types::maybe_send`, which are the real `Send` and `Sync` + natively. +- `SyncTool`s run inline instead of on a blocking thread, so cancellation cannot + interrupt one that has started. +- `ProviderRetry` waits between attempts on the host's `setTimeout` instead of + tokio's timer, so retries work without a tokio runtime. + The reference assembly of these pieces is `goose::agents::state_machine` in the [`goose`](../goose) crate. diff --git a/crates/goose-agent/src/inference.rs b/crates/goose-agent/src/inference.rs index 8425b76e6..bba092a6f 100644 --- a/crates/goose-agent/src/inference.rs +++ b/crates/goose-agent/src/inference.rs @@ -20,6 +20,7 @@ use crate::operation::{ applied, messages_since_kickoff, not_applicable, trailing_error, yielded_with, Emitter, Inference, InferenceInput, Operation, OperationResult, }; +use goose_provider_types::maybe_send::{MaybeSend, MaybeSync}; pub struct PreparedInferenceRequest { pub system_prompt: String, @@ -27,8 +28,9 @@ pub struct PreparedInferenceRequest { pub additional_messages: Vec, } -#[async_trait] -pub trait InferenceRequestPreparer: Send + Sync { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +pub trait InferenceRequestPreparer: MaybeSend + MaybeSync { async fn prepare( &self, session: &S, @@ -39,8 +41,9 @@ pub trait InferenceRequestPreparer: Send + Sync { pub struct IdentityInferenceRequestPreparer; -#[async_trait] -impl InferenceRequestPreparer for IdentityInferenceRequestPreparer { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +impl InferenceRequestPreparer for IdentityInferenceRequestPreparer { async fn prepare( &self, _session: &S, @@ -60,7 +63,7 @@ impl InferenceRequestPreparer for IdentityInferenceRequestPreparer { } } -pub trait InferenceEffect: From + Send + 'static { +pub trait InferenceEffect: From + MaybeSend + 'static { fn record_usage(usage: ProviderUsage) -> Self; } @@ -300,7 +303,7 @@ fn inference_span(provider: &dyn Provider, model_config: &ModelConfig) -> tracin span } -impl<'a, S: Sync, E: InferenceEffect> InferenceRunner<'a, S, E> { +impl<'a, S: MaybeSync, E: InferenceEffect> InferenceRunner<'a, S, E> { pub fn new(provider: Arc, model_config: ModelConfig) -> Self { Self { provider, @@ -327,8 +330,9 @@ impl<'a, S: Sync, E: InferenceEffect> InferenceRunner<'a, S, E> { } } -#[async_trait] -impl Operation for InferenceRunner<'_, S, E> { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +impl Operation for InferenceRunner<'_, S, E> { fn name(&self) -> &'static str { "llm" } @@ -352,8 +356,9 @@ impl Operation for InferenceRunner<'_, S, E> } } -#[async_trait] -impl Inference for InferenceRunner<'_, S, E> { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +impl Inference for InferenceRunner<'_, S, E> { fn applies(&self, conversation: &Conversation) -> bool { let Ok(turn) = messages_since_kickoff(conversation) else { return false; diff --git a/crates/goose-agent/src/machine.rs b/crates/goose-agent/src/machine.rs index 32708a404..3162ac90e 100644 --- a/crates/goose-agent/src/machine.rs +++ b/crates/goose-agent/src/machine.rs @@ -9,23 +9,26 @@ use crate::operation::{ OperationFuture, OperationResult, StepResult, }; use goose_provider_types::conversation::Conversation; +use goose_provider_types::maybe_send::{MaybeSend, MaybeSync}; -pub trait MachineSession: Send + Sync { +pub trait MachineSession: MaybeSend + MaybeSync { fn id(&self) -> &str; fn conversation(&self) -> Option<&Conversation>; } -#[async_trait] -pub trait SessionLoader: Send + Sync { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +pub trait SessionLoader: MaybeSend + MaybeSync { async fn load(&self, session_id: &str) -> Result; } -#[async_trait] -pub trait EffectHandler: Send + Sync { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +pub trait EffectHandler: MaybeSend + MaybeSync { async fn apply_effects(&self, session: &S, effects: &mut [E], emit: &Emitter) -> Result<()>; } -pub trait EffectUsage: Send + Sync { +pub trait EffectUsage: MaybeSend + MaybeSync { fn usage(&self, _effect: &E) -> Option { None } @@ -36,7 +39,7 @@ pub enum Step<'a, S, E = ConversationEffect> { Inference(Arc + 'a>), } -impl Step<'_, S, E> { +impl Step<'_, S, E> { fn operation(&self) -> &dyn Operation { match self { Step::Operation(operation) => operation.as_ref(), @@ -67,7 +70,7 @@ fn add_tools_to_inference_input( impl<'a, S, E> StateMachine<'a, S, E> where S: MachineSession, - E: MachineEffect + Send + 'static, + E: MachineEffect + MaybeSend + 'static, { pub fn new(steps: Vec>, cancel: CancellationToken) -> Self { Self { steps, cancel } diff --git a/crates/goose-agent/src/operation.rs b/crates/goose-agent/src/operation.rs index fc5a83c04..b478bd256 100644 --- a/crates/goose-agent/src/operation.rs +++ b/crates/goose-agent/src/operation.rs @@ -8,10 +8,15 @@ use tokio_util::sync::CancellationToken; use crate::events::AgentEvent; use goose_provider_types::conversation::message::{Message, MessageContent, MessageErrorKind}; use goose_provider_types::conversation::{effective_role, Conversation, EffectiveRole}; +use goose_provider_types::maybe_send::{MaybeSend, MaybeSync}; use rmcp::model::Tool; +#[cfg(not(target_arch = "wasm32"))] pub type OperationFuture<'a, T> = Pin + Send + 'a>>; +#[cfg(target_arch = "wasm32")] +pub type OperationFuture<'a, T> = Pin + 'a>>; + pub struct SlashCommand<'a> { pub command: &'a str, pub params_str: &'a str, @@ -70,8 +75,9 @@ pub fn ends_turn(messages: &[Message]) -> bool { }) } -#[async_trait] -pub trait Operation: Send + Sync { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +pub trait Operation: MaybeSend + MaybeSync { fn name(&self) -> &'static str; /// Note on a message something this operation did, so that a pipeline rebuilt @@ -139,8 +145,9 @@ pub struct InferenceInput { pub moim_parts: Vec, } -#[async_trait] -pub trait Inference: Operation { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +pub trait Inference: Operation { /// Whether the next step would reach the provider. The machine asks before /// firing the hooks that mark the start of a turn. fn applies(&self, conversation: &Conversation) -> bool; diff --git a/crates/goose-agent/src/tool.rs b/crates/goose-agent/src/tool.rs index 956302310..99989b95f 100644 --- a/crates/goose-agent/src/tool.rs +++ b/crates/goose-agent/src/tool.rs @@ -16,6 +16,7 @@ use crate::operation::{ applied, messages_since_kickoff, not_applicable, Emitter, Operation, OperationFuture, OperationResult, }; +use goose_provider_types::maybe_send::{MaybeSend, MaybeSync}; fn empty_input_schema() -> Arc { Arc::new( @@ -88,12 +89,43 @@ fn result(output: Result) -> Result( + session: S, + parameters: T::Parameter, +) -> Result +where + S: Send + Sync + 'static, + T: SyncTool + 'static, +{ + tokio::task::spawn_blocking(move || result::(T::invoke(&session, parameters))) + .await + .map_err(|error| { + ErrorData::internal_error(format!("synchronous tool task failed: {error}"), None) + })? +} + +// wasm32 has no threads to move blocking work onto, so the tool runs inline +// and cancellation cannot interrupt it. +#[cfg(target_arch = "wasm32")] +async fn invoke_sync( + session: S, + parameters: T::Parameter, +) -> Result +where + S: MaybeSend + MaybeSync + 'static, + T: SyncTool, +{ + result::(T::invoke(&session, parameters)) +} + /// Supplies tools whose definitions and implementations may vary by session. /// /// A provider's tool names and their handlers must remain stable from an inference /// advertisement until every tool call produced by that inference has been handled. -#[async_trait] -pub trait ToolProvider: Send + Sync { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +pub trait ToolProvider: MaybeSend + MaybeSync { async fn tools(&self, session: &S) -> Result>; async fn call( @@ -105,10 +137,17 @@ pub trait ToolProvider: Send + Sync { ) -> Result; } +#[cfg(not(target_arch = "wasm32"))] type ToolHandler = dyn for<'a> Fn(&'a S, Option) -> OperationFuture<'a, Result> + Send + Sync; +#[cfg(target_arch = "wasm32")] +type ToolHandler = dyn for<'a> Fn( + &'a S, + Option, +) -> OperationFuture<'a, Result>; + struct RegisteredTool { definition: Tool, handler: Arc>, @@ -118,10 +157,11 @@ struct RegisteredToolProvider { tools: Vec>, } -#[async_trait] +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] impl ToolProvider for RegisteredToolProvider where - S: Send + Sync + 'static, + S: MaybeSend + MaybeSync + 'static, { async fn tools(&self, _session: &S) -> Result> { Ok(self @@ -160,7 +200,7 @@ pub struct ToolOperation { impl ToolOperation where - S: Send + Sync + 'static, + S: MaybeSend + MaybeSync + 'static, { pub fn new() -> Self { Self { @@ -190,7 +230,7 @@ where pub fn with_sync_tool(mut self) -> Self where S: Clone, - T: SyncTool + Send + Sync + 'static, + T: SyncTool + MaybeSend + MaybeSync + 'static, { self.register(RegisteredTool { definition: definition::(), @@ -198,16 +238,7 @@ where let session = session.clone(); Box::pin(async move { let parameters = parameters::(arguments)?; - tokio::task::spawn_blocking(move || { - result::(T::invoke(&session, parameters)) - }) - .await - .map_err(|error| { - ErrorData::internal_error( - format!("synchronous tool task failed: {error}"), - None, - ) - })? + invoke_sync::(session, parameters).await }) }), }); @@ -216,7 +247,7 @@ where pub fn with_async_tool(mut self) -> Self where - T: AsyncTool + Send + Sync + 'static, + T: AsyncTool + MaybeSend + MaybeSync + 'static, { self.register(RegisteredTool { definition: definition::(), @@ -255,18 +286,19 @@ where impl Default for ToolOperation where - S: Send + Sync + 'static, + S: MaybeSend + MaybeSync + 'static, { fn default() -> Self { Self::new() } } -#[async_trait] +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] impl Operation for ToolOperation where - S: Send + Sync + 'static, - E: From + Send + 'static, + S: MaybeSend + MaybeSync + 'static, + E: From + MaybeSend + 'static, { fn name(&self) -> &'static str { "tools" diff --git a/crates/goose-agent/tests/wasm.rs b/crates/goose-agent/tests/wasm.rs new file mode 100644 index 000000000..643e50e43 --- /dev/null +++ b/crates/goose-agent/tests/wasm.rs @@ -0,0 +1,316 @@ +#![cfg(target_arch = "wasm32")] +// The GDK takes `Arc` on every target, so native and wasm32 share one API. +#![allow(clippy::arc_with_non_send_sync)] + +use std::{ + borrow::Cow, + cell::{Cell, RefCell}, + rc::Rc, + sync::Arc, +}; + +use anyhow::Result; +use async_trait::async_trait; +use goose_agent::{ + inference::{InferenceEffect, InferenceRunner}, + machine::{EffectHandler, MachineSession, SessionLoader, StateMachine, Step}, + operation::{Emitter, MachineEffect}, + tool::ToolOperation, +}; +use goose_provider_types::{ + base::{MessageStream, Provider}, + conversation::{ + message::{Message, MessageContent}, + token_usage::{ProviderUsage, Usage}, + Conversation, + }, + errors::ProviderError, + model::ModelConfig, + retry::{ProviderRetry, RetryConfig}, +}; +use rmcp::{ + handler::server::router::tool::{AsyncTool, SyncTool, ToolBase}, + model::{CallToolRequestParams, ErrorData, Tool}, +}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; +use wasm_bindgen_futures::JsFuture; +use wasm_bindgen_test::wasm_bindgen_test; + +/// Awaits a JavaScript promise, as a host call would. The future is not `Send`, +/// so everything that awaits it must accept non-`Send` futures. +async fn host_call() { + JsFuture::from(js_sys::Promise::resolve(&js_sys::Object::new())) + .await + .unwrap(); +} + +#[derive(Default, Deserialize, JsonSchema)] +struct AddInput { + left: u64, + right: u64, +} + +#[derive(Serialize, JsonSchema)] +struct AddOutput { + sum: u64, +} + +struct Add; + +impl ToolBase for Add { + type Parameter = AddInput; + type Output = AddOutput; + type Error = ErrorData; + + fn name() -> Cow<'static, str> { + "add".into() + } +} + +impl SyncTool for Add { + fn invoke(_session: &Session, input: AddInput) -> Result { + Ok(AddOutput { + sum: input.left + input.right, + }) + } +} + +#[derive(Default, Deserialize, JsonSchema)] +struct GreetInput { + name: String, +} + +#[derive(Serialize, JsonSchema)] +struct GreetOutput { + greeting: String, +} + +struct Greet; + +impl ToolBase for Greet { + type Parameter = GreetInput; + type Output = GreetOutput; + type Error = ErrorData; + + fn name() -> Cow<'static, str> { + "greet".into() + } +} + +impl AsyncTool for Greet { + async fn invoke(_session: &Session, input: GreetInput) -> Result { + host_call().await; + Ok(GreetOutput { + greeting: format!("Hello, {}!", input.name), + }) + } +} + +/// Requests one tool call, then answers with text once the tool has responded. +struct ScriptedProvider { + call: CallToolRequestParams, +} + +#[async_trait(?Send)] +impl Provider for ScriptedProvider { + fn get_name(&self) -> &str { + "scripted" + } + + async fn stream( + &self, + _model_config: &ModelConfig, + _system: &str, + messages: &[Message], + _tools: &[Tool], + ) -> Result { + host_call().await; + let reply = if messages.last().is_some_and(Message::is_tool_response) { + Message::assistant().with_text("done") + } else { + Message::assistant().with_tool_request("call-1", Ok(self.call.clone())) + }; + let usage = ProviderUsage::new("scripted-model".to_string(), Usage::default()); + Ok(Box::pin(futures::stream::once(async move { + host_call().await; + Ok((Some(reply), Some(usage))) + }))) + } +} + +enum Effect { + Message(Message), + Usage, +} + +impl From for Effect { + fn from(message: Message) -> Self { + Effect::Message(message) + } +} + +impl InferenceEffect for Effect { + fn record_usage(_usage: ProviderUsage) -> Self { + Effect::Usage + } +} + +impl MachineEffect for Effect { + fn ensure_message_ids(&mut self) {} +} + +#[derive(Clone)] +struct Session { + conversation: Conversation, +} + +impl MachineSession for Session { + fn id(&self) -> &str { + "wasm" + } + + fn conversation(&self) -> Option<&Conversation> { + Some(&self.conversation) + } +} + +/// Stands in for host storage, which is not `Send` or `Sync` on wasm32. +struct Runtime { + conversation: Rc>, +} + +#[async_trait(?Send)] +impl SessionLoader for Runtime { + async fn load(&self, _session_id: &str) -> Result { + host_call().await; + Ok(Session { + conversation: self.conversation.borrow().clone(), + }) + } +} + +#[async_trait(?Send)] +impl EffectHandler for Runtime { + async fn apply_effects( + &self, + _session: &Session, + effects: &mut [Effect], + _emit: &Emitter, + ) -> Result<()> { + host_call().await; + let mut conversation = self.conversation.borrow_mut(); + for effect in effects { + if let Effect::Message(message) = effect { + conversation.push(message.clone()); + } + } + Ok(()) + } +} + +async fn run_turn(call: CallToolRequestParams) -> Conversation { + let cancel = CancellationToken::new(); + let tools = ToolOperation::new() + .with_sync_tool::() + .with_async_tool::(); + let inference = InferenceRunner::::new( + Arc::new(ScriptedProvider { call }), + ModelConfig::new("scripted-model"), + ); + let machine = StateMachine::new( + vec![ + Step::Operation(Arc::new(tools)), + Step::Inference(Arc::new(inference)), + ], + cancel.clone(), + ); + let runtime = Runtime { + conversation: Rc::new(RefCell::new(Conversation::new_unvalidated([ + Message::user().with_text("use the tool"), + ]))), + }; + let (tx, _rx) = mpsc::channel(16); + let emit = Emitter::new(tx, cancel); + + machine + .run(&runtime, "wasm", &emit) + .await + .unwrap() + .conversation +} + +fn tool_output(conversation: &Conversation) -> serde_json::Value { + let messages = conversation.messages(); + assert_eq!(messages.len(), 4); + let MessageContent::Text(reply) = &messages[3].content[0] else { + panic!("turn should end with the provider's text reply"); + }; + assert_eq!(reply.text, "done"); + messages[2].content[0] + .as_tool_response() + .unwrap() + .tool_result + .as_ref() + .unwrap() + .structured_content + .clone() + .unwrap() +} + +#[wasm_bindgen_test] +async fn runs_a_turn_with_an_async_tool() { + let conversation = run_turn( + CallToolRequestParams::new("greet") + .with_arguments(serde_json::from_value(json!({"name": "Goose"})).unwrap()), + ) + .await; + + assert_eq!( + tool_output(&conversation), + json!({"greeting": "Hello, Goose!"}) + ); +} + +#[wasm_bindgen_test] +async fn runs_a_turn_with_a_sync_tool() { + let conversation = run_turn( + CallToolRequestParams::new("add") + .with_arguments(serde_json::from_value(json!({"left": 2, "right": 3})).unwrap()), + ) + .await; + + assert_eq!(tool_output(&conversation), json!({"sum": 5})); +} + +#[wasm_bindgen_test] +async fn retries_back_off_on_the_host_timer() { + let provider = ScriptedProvider { + call: CallToolRequestParams::new("add"), + }; + let attempts = &Cell::new(0); + let started = js_sys::Date::now(); + + let result = provider + .with_retry_config( + move || async move { + attempts.set(attempts.get() + 1); + host_call().await; + if attempts.get() == 1 { + Err(ProviderError::ServerError("unavailable".to_string())) + } else { + Ok(()) + } + }, + RetryConfig::new(1, 50, 1.0, 50), + ) + .await; + + assert!(result.is_ok()); + assert_eq!(attempts.get(), 2); + // The delay is jittered down to 80% of the 50ms interval at most. + assert!(js_sys::Date::now() - started >= 40.0); +} diff --git a/crates/goose-provider-types/Cargo.toml b/crates/goose-provider-types/Cargo.toml index 39a2902f8..a2ecb7620 100644 --- a/crates/goose-provider-types/Cargo.toml +++ b/crates/goose-provider-types/Cargo.toml @@ -21,7 +21,7 @@ futures = { workspace = true } once_cell = { workspace = true } rand = { workspace = true } regex = { workspace = true, features = ["unicode"] } -reqwest = { workspace = true } +reqwest = { workspace = true, features = ["stream"] } rmcp = { workspace = true, features = ["server", "macros"] } serde = { workspace = true } serde_json = { workspace = true } @@ -33,6 +33,12 @@ unicode-normalization = { version = "0.1.22", default-features = false, features uuid = { workspace = true, features = ["v4", "std"] } zstd = "0.14.0" +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { version = "0.4", features = ["wasm_js"] } +uuid = { workspace = true, features = ["js"] } +chrono = { workspace = true, features = ["wasmbind"] } +gloo-timers = { version = "0.3.0", features = ["futures"] } + [dev-dependencies] env-lock = { workspace = true } tempfile = { workspace = true } diff --git a/crates/goose-provider-types/src/base.rs b/crates/goose-provider-types/src/base.rs index d73ed8b9b..9924796af 100644 --- a/crates/goose-provider-types/src/base.rs +++ b/crates/goose-provider-types/src/base.rs @@ -18,6 +18,7 @@ use crate::{ }, errors::ProviderError, goose_mode::GooseMode, + maybe_send::{MaybeSend, MaybeSync}, model::ModelConfig, permission::PermissionConfirmation, retry::RetryConfig, @@ -327,10 +328,15 @@ pub trait ProviderDescriptor { /// A message stream yields partial text content but complete tool calls, all within the Message object /// So a message with text will contain potentially just a word of a longer response, but tool calls /// messages will only be yielded once concatenated. +#[cfg(not(target_arch = "wasm32"))] pub type MessageStream = Pin< Box, Option), ProviderError>> + Send>, >; +#[cfg(target_arch = "wasm32")] +pub type MessageStream = + Pin, Option), ProviderError>>>>; + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PermissionRouting { ActionRequired, @@ -493,8 +499,9 @@ pub fn stream_from_single_message(message: Message, usage: ProviderUsage) -> Mes } /// Base trait for AI providers (OpenAI, Anthropic, etc) -#[async_trait] -pub trait Provider: Send + Sync { +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +pub trait Provider: MaybeSend + MaybeSync { /// Get the name of this provider instance fn get_name(&self) -> &str; diff --git a/crates/goose-provider-types/src/canonical/registry.rs b/crates/goose-provider-types/src/canonical/registry.rs index a51b68c78..f9f8eed08 100644 --- a/crates/goose-provider-types/src/canonical/registry.rs +++ b/crates/goose-provider-types/src/canonical/registry.rs @@ -141,11 +141,9 @@ pub fn load_cached_catalog(cache_dir: &Path) -> Result { } pub async fn refresh_remote_catalog(url: &str, cache_dir: &Path) -> Result { - let client = reqwest::Client::builder() - .timeout(Duration::from_secs(15)) - .build()?; + let client = reqwest::Client::builder().build()?; let etag_path = cache_dir.join(ETAG_FILENAME); - let mut request = client.get(url).header( + let mut request = client.get(url).timeout(Duration::from_secs(15)).header( "User-Agent", "goose/model-catalog (https://github.com/aaif-goose/goose)", ); diff --git a/crates/goose-provider-types/src/errors.rs b/crates/goose-provider-types/src/errors.rs index 5170a5ea4..0fe21c3bf 100644 --- a/crates/goose-provider-types/src/errors.rs +++ b/crates/goose-provider-types/src/errors.rs @@ -98,8 +98,19 @@ impl ProviderError { } } +#[cfg(not(target_arch = "wasm32"))] +fn is_connect_error(error: &reqwest::Error) -> bool { + error.is_connect() +} + +// reqwest's wasm client does not expose is_connect +#[cfg(target_arch = "wasm32")] +fn is_connect_error(_error: &reqwest::Error) -> bool { + false +} + fn is_network_error(err: &reqwest::Error) -> bool { - err.is_connect() || err.is_timeout() || (err.status().is_none() && err.is_request()) + is_connect_error(err) || err.is_timeout() || (err.status().is_none() && err.is_request()) } fn sanitized_reqwest_url(error: &reqwest::Error) -> Option { @@ -131,7 +142,7 @@ fn provider_error_from_reqwest(error: &reqwest::Error) -> ProviderError { if is_network_error(error) { let msg = if error.is_timeout() { "Request timed out — check your network connection and try again.".to_string() - } else if error.is_connect() { + } else if is_connect_error(error) { if let Some(url) = error.url() { if let Some(host) = url.host_str() { let port_info = url.port().map(|p| format!(":{}", p)).unwrap_or_default(); diff --git a/crates/goose-provider-types/src/formats/anthropic.rs b/crates/goose-provider-types/src/formats/anthropic.rs index 7bc98077f..ceda368b3 100644 --- a/crates/goose-provider-types/src/formats/anthropic.rs +++ b/crates/goose-provider-types/src/formats/anthropic.rs @@ -8,6 +8,7 @@ use crate::documents::{ }; use crate::errors::ProviderError; use crate::images::{convert_image, ImageFormat}; +use crate::maybe_send::MaybeSend; use crate::mcp_utils::extract_text_from_resource; use crate::model::ModelConfig; use crate::thinking::ThinkingEffort; @@ -987,7 +988,7 @@ pub fn response_to_streaming_message( mut stream: S, ) -> impl futures::Stream, Option)>> + 'static where - S: futures::Stream> + Unpin + Send + 'static, + S: futures::Stream> + Unpin + MaybeSend + 'static, { use async_stream::try_stream; use futures::StreamExt; diff --git a/crates/goose-provider-types/src/formats/google.rs b/crates/goose-provider-types/src/formats/google.rs index 352914f8e..9792feb05 100644 --- a/crates/goose-provider-types/src/formats/google.rs +++ b/crates/goose-provider-types/src/formats/google.rs @@ -4,6 +4,7 @@ use crate::documents::{ }; use crate::errors::ProviderError; use crate::formats::openai::{is_valid_function_name, sanitize_function_name}; +use crate::maybe_send::MaybeSend; use crate::mcp_utils::extract_text_from_resource; use crate::model::ModelConfig; use crate::thinking::ThinkingEffort; @@ -454,7 +455,7 @@ pub fn response_to_streaming_message( mut stream: S, ) -> impl futures::Stream, Option)>> + 'static where - S: futures::Stream> + Unpin + Send + 'static, + S: futures::Stream> + Unpin + MaybeSend + 'static, { use async_stream::try_stream; use futures::StreamExt; diff --git a/crates/goose-provider-types/src/formats/ollama.rs b/crates/goose-provider-types/src/formats/ollama.rs index 69ab59f80..25ed862d2 100644 --- a/crates/goose-provider-types/src/formats/ollama.rs +++ b/crates/goose-provider-types/src/formats/ollama.rs @@ -10,6 +10,7 @@ //! - qwen3-coder-32b use crate::conversation::message::{Message, MessageContentBlock}; +use crate::maybe_send::MaybeSend; use crate::{ conversation::token_usage::ProviderUsage, formats::openai::{self, is_valid_function_name}, @@ -160,7 +161,7 @@ pub fn response_to_streaming_message_ollama( stream: S, ) -> impl Stream, Option)>> + 'static where - S: Stream> + Unpin + Send + 'static, + S: Stream> + Unpin + MaybeSend + 'static, { try_stream! { use futures::StreamExt; diff --git a/crates/goose-provider-types/src/formats/openai.rs b/crates/goose-provider-types/src/formats/openai.rs index 0423554fd..9786d65a4 100644 --- a/crates/goose-provider-types/src/formats/openai.rs +++ b/crates/goose-provider-types/src/formats/openai.rs @@ -8,6 +8,7 @@ use crate::documents::{ use crate::errors::ProviderError; use crate::images::{convert_image, detect_image_path, load_image_file, ImageFormat}; use crate::json::{parse_tool_arguments, truncation_error_message}; +use crate::maybe_send::MaybeSend; use crate::mcp_utils::extract_text_from_resource; use crate::model::{is_goose_internal_request_param, ModelConfig}; use crate::thinking::{ @@ -1235,7 +1236,7 @@ pub fn response_to_streaming_message( mut stream: S, ) -> impl Stream, Option)>> + 'static where - S: Stream> + Unpin + Send + 'static, + S: Stream> + Unpin + MaybeSend + 'static, { try_stream! { use futures::StreamExt; diff --git a/crates/goose-provider-types/src/formats/openai_responses.rs b/crates/goose-provider-types/src/formats/openai_responses.rs index 562ecb7e8..71a06090a 100644 --- a/crates/goose-provider-types/src/formats/openai_responses.rs +++ b/crates/goose-provider-types/src/formats/openai_responses.rs @@ -9,6 +9,7 @@ use crate::formats::openai::{ extract_reasoning_effort, is_openai_responses_model, openai_reasoning_effort_for_thinking, sanitize_function_name, }; +use crate::maybe_send::MaybeSend; use crate::mcp_utils::extract_text_from_resource; use crate::model::ModelConfig; use crate::utils::{sanitize_unicode_tags, strip_unicode_tags}; @@ -1005,7 +1006,7 @@ pub fn responses_api_to_streaming_message( mut stream: S, ) -> impl Stream, Option)>> + 'static where - S: Stream> + Unpin + Send + 'static, + S: Stream> + Unpin + MaybeSend + 'static, { try_stream! { use futures::StreamExt; diff --git a/crates/goose-provider-types/src/lib.rs b/crates/goose-provider-types/src/lib.rs index d959ad707..49e310b9a 100644 --- a/crates/goose-provider-types/src/lib.rs +++ b/crates/goose-provider-types/src/lib.rs @@ -9,6 +9,7 @@ pub mod formats; pub mod goose_mode; pub mod images; pub mod json; +pub mod maybe_send; pub(crate) mod mcp_utils; pub mod model; pub mod permission; diff --git a/crates/goose-provider-types/src/maybe_send.rs b/crates/goose-provider-types/src/maybe_send.rs new file mode 100644 index 000000000..95acd9982 --- /dev/null +++ b/crates/goose-provider-types/src/maybe_send.rs @@ -0,0 +1,26 @@ +//! `Send` and `Sync` bounds that apply natively but not on wasm32. +//! +//! A wasm32 host runs on one thread, and its capabilities (fetch, timers, +//! storage) are JavaScript promises whose futures are not `Send`. The GDK traits +//! use these bounds so an embedder there can implement them without asserting +//! `Send` for values that are not. Native builds keep the real bounds. + +#[cfg(not(target_arch = "wasm32"))] +pub trait MaybeSend: Send {} +#[cfg(not(target_arch = "wasm32"))] +impl MaybeSend for T {} + +#[cfg(target_arch = "wasm32")] +pub trait MaybeSend {} +#[cfg(target_arch = "wasm32")] +impl MaybeSend for T {} + +#[cfg(not(target_arch = "wasm32"))] +pub trait MaybeSync: Sync {} +#[cfg(not(target_arch = "wasm32"))] +impl MaybeSync for T {} + +#[cfg(target_arch = "wasm32")] +pub trait MaybeSync {} +#[cfg(target_arch = "wasm32")] +impl MaybeSync for T {} diff --git a/crates/goose-provider-types/src/retry.rs b/crates/goose-provider-types/src/retry.rs index cc7cd0d8e..770d9b57c 100644 --- a/crates/goose-provider-types/src/retry.rs +++ b/crates/goose-provider-types/src/retry.rs @@ -1,8 +1,14 @@ use crate::base::Provider; use crate::errors::ProviderError; +use crate::maybe_send::MaybeSend; use async_trait::async_trait; use std::future::Future; use std::time::Duration; + +// wasm32 hosts run without a tokio runtime, so back off on the host's timer. +#[cfg(target_arch = "wasm32")] +use gloo_timers::future::sleep; +#[cfg(not(target_arch = "wasm32"))] use tokio::time::sleep; pub const DEFAULT_MAX_RETRIES: usize = 3; @@ -114,9 +120,9 @@ pub async fn retry_operation( operation: F, ) -> Result where - F: Fn() -> Fut + Send, - Fut: Future> + Send, - T: Send, + F: Fn() -> Fut + MaybeSend, + Fut: Future> + MaybeSend, + T: MaybeSend, { let mut attempts = 0; @@ -153,7 +159,8 @@ where /// Trait for retry functionality to keep Provider dyn-compatible. /// /// All `Provider` implementors get this via the blanket impl below. -#[async_trait] +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] pub trait ProviderRetry { fn retry_config(&self) -> RetryConfig { RetryConfig::default() @@ -161,9 +168,9 @@ pub trait ProviderRetry { async fn with_retry(&self, operation: F) -> Result where - F: Fn() -> Fut + Send, - Fut: Future> + Send, - T: Send, + F: Fn() -> Fut + MaybeSend, + Fut: Future> + MaybeSend, + T: MaybeSend, { self.with_retry_config(operation, self.retry_config()).await } @@ -174,12 +181,13 @@ pub trait ProviderRetry { config: RetryConfig, ) -> Result where - F: Fn() -> Fut + Send, - Fut: Future> + Send, - T: Send; + F: Fn() -> Fut + MaybeSend, + Fut: Future> + MaybeSend, + T: MaybeSend; } -#[async_trait] +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] impl ProviderRetry for P { fn retry_config(&self) -> RetryConfig { Provider::retry_config(self) @@ -191,9 +199,9 @@ impl ProviderRetry for P { config: RetryConfig, ) -> Result where - F: Fn() -> Fut + Send, - Fut: Future> + Send, - T: Send, + F: Fn() -> Fut + MaybeSend, + Fut: Future> + MaybeSend, + T: MaybeSend, { let mut attempts = 0; let mut auth_retried = false; diff --git a/crates/goose-providers/Cargo.toml b/crates/goose-providers/Cargo.toml index 724fbbf92..353ba907d 100644 --- a/crates/goose-providers/Cargo.toml +++ b/crates/goose-providers/Cargo.toml @@ -40,7 +40,7 @@ chrono = { workspace = true } futures = { workspace = true } goose-provider-types = { version = "0.1.0-alpha.11", path = "../goose-provider-types", default-features = false } goose-local-inference = { version = "0.1.0-alpha.11", path = "../goose-local-inference", default-features = false, optional = true } -reqwest = { workspace = true } +reqwest = { workspace = true, features = ["json", "stream"] } rmcp = { workspace = true, features = ["server", "macros"] } serde = { workspace = true } serde_json = { workspace = true } @@ -48,7 +48,7 @@ tracing = { workspace = true } async-trait = { workspace = true } tokio = { workspace = true } tokio-stream = { workspace = true, features = ["io-util"] } -tokio-util = { workspace = true, features = ["compat"] } +tokio-util = { workspace = true, features = ["compat", "io", "codec"] } url = { workspace = true } urlencoding = { workspace = true } uuid = { workspace = true, features = ["v4"] } diff --git a/crates/goose/Cargo.toml b/crates/goose/Cargo.toml index 1ad06cf14..b7f15ee1f 100644 --- a/crates/goose/Cargo.toml +++ b/crates/goose/Cargo.toml @@ -117,6 +117,7 @@ workspace = true [dependencies] lru = { workspace = true } rmcp = { workspace = true, features = [ + "auth", "client", "transport-child-process", "transport-streamable-http-client",