Skip to content

Commit b7bbea2

Browse files
committed
feat(gpui): add a host Sandbox request for remote workspace backends
A host can now be built with a SandboxBackend that starts, ends and recovers an agent's session on a provider. The backend gets the agent's launch identity (community, owner, attestation and nsec) from the host's custody, so the key never travels to the GUI. Provider refusal codes come back as data in SandboxResponse::Failed, since RpcError carries only text. A host without a backend answers with the "unsupported" code, and an older host cannot decode the request at all. Signed-off-by: Tee8z <[email protected]>
1 parent f677b7b commit b7bbea2

17 files changed

Lines changed: 598 additions & 1 deletion

File tree

‎apps/buzz-gpui/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎apps/buzz-gpui/crates/app/src/agent_plugins/claude_code/e2e.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ async fn connect_host() -> (Arc<HostClient<HostProtocol>>, Spawner) {
175175
state_dir: state.join("state"),
176176
credentials: Arc::new(FileCredentials::new(state.join("keys")).unwrap()),
177177
legacy_dir: None,
178+
sandbox: None,
178179
})
179180
.unwrap();
180181
let (connector, listener) = transport::memory();

‎apps/buzz-gpui/crates/app/src/agent_plugins/codex/live.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ async fn host() -> Spawner {
5454
state_dir: state.join("state"),
5555
credentials: Arc::new(FileCredentials::new(state.join("keys")).unwrap()),
5656
legacy_dir: None,
57+
sandbox: None,
5758
})
5859
.unwrap();
5960
let (connector, listener) = transport::memory();

‎apps/buzz-gpui/crates/app/src/hosts.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,7 @@ fn start_embedded(
208208
state_dir: data.join("host"),
209209
credentials,
210210
legacy_dir: dirs::data_dir(),
211+
sandbox: None,
211212
})?;
212213
let (connector, listener) = transport::memory();
213214
let server = runtime.spawn(buzz_host_rpc::serve(

‎apps/buzz-gpui/crates/buzzd/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ async fn run(config: Config, state_dir: PathBuf, token: String) -> Result<()> {
100100
state_dir: state_dir.clone(),
101101
credentials,
102102
legacy_dir: dirs::data_dir(),
103+
sandbox: None,
103104
})
104105
.map_err(anyhow::Error::msg)?;
105106
let handler = Arc::new(RpcHandler(host));

‎apps/buzz-gpui/crates/host/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ buzz-keychain = { path = "../keychain" }
1212
buzz-desktop.workspace = true
1313
buzz-host-rpc = { path = "../host-rpc" }
1414
base64 = "0.22"
15+
# Agent keys as `nsec1…` for remote workspaces; already in the build.
16+
bech32 = "0.11"
1517
futures = "0.3"
1618
libc = "0.2"
1719
reqwest = { version = "0.13", default-features = false, features = ["rustls"] }

‎apps/buzz-gpui/crates/host/src/api.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ use std::collections::BTreeMap;
1616

1717
mod app_agent;
1818
pub use app_agent::*;
19+
mod sandbox;
20+
pub use sandbox::*;
1921

2022
pub use crate::terminal::{TerminalContext, TerminalOutput};
2123

@@ -34,6 +36,9 @@ pub enum Request {
3436
// Agents2 custody
3537
/// An Agents2 agent's key, held by this host: see [`AppAgentRequest`].
3638
AppAgent(AppAgentRequest),
39+
/// An agent's remote workspace: see [`SandboxRequest`]. Hosts from
40+
/// before this answer that they do not support it.
41+
Sandbox(SandboxRequest),
3742
// claude code
3843
/// Starts process `process`, one that agent type `owner` declares (see
3944
/// `processes.rs`), with `args` after its declared arguments. `handle`
@@ -111,6 +116,7 @@ pub enum Response {
111116
Done,
112117
// Agents2 custody
113118
AppAgent(AppAgentResponse),
119+
Sandbox(SandboxResponse),
114120
// claude code
115121
/// A process request succeeded.
116122
ProcessDone,
Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
//! Remote workspaces: agents whose sessions run on a provider the host
2+
//! starts, such as a Kubernetes sandbox per thread. The host adds what only
3+
//! it holds, the agent's key and owner attestation, to the launch the GUI
4+
//! describes; the key never comes back. A provider's refusal comes back as
5+
//! [`SandboxResponse::Failed`] with its code, which an error could not
6+
//! carry. JSON payloads travel as JSON text.
7+
8+
use serde::{Deserialize, Serialize};
9+
use std::collections::BTreeMap;
10+
11+
/// The code a host without remote workspaces fails with.
12+
pub const SANDBOX_UNSUPPORTED: &str = "unsupported";
13+
14+
#[derive(Clone, Debug, Serialize, Deserialize)]
15+
pub enum SandboxRequest {
16+
/// The providers this host can start. Answers
17+
/// [`SandboxResponse::Providers`].
18+
Providers,
19+
/// Starts or updates the agent's session for a thread. Answers
20+
/// [`SandboxResponse::Started`].
21+
Start {
22+
session: SandboxSession,
23+
/// Unix seconds the harness replays from, so it sees the message
24+
/// that started it.
25+
#[serde(default)]
26+
replay_floor: Option<u64>,
27+
},
28+
/// Ends the thread's session. Answers [`SandboxResponse::Ended`].
29+
End { session: SandboxSession },
30+
/// Brings back the thread's ended session. Answers
31+
/// [`SandboxResponse::Started`].
32+
Recover {
33+
session: SandboxSession,
34+
mode: RecoveryMode,
35+
},
36+
/// Whether the agent's provider can end and recover sessions. Answers
37+
/// [`SandboxResponse::Lifecycle`].
38+
Lifecycle { pubkey: String, spec: LaunchSpec },
39+
}
40+
41+
#[derive(Clone, Debug, Serialize, Deserialize)]
42+
pub enum SandboxResponse {
43+
Providers(Vec<SandboxProvider>),
44+
Started,
45+
Ended {
46+
state: EndState,
47+
},
48+
Lifecycle(bool),
49+
/// `code` is the provider's refusal code, such as `session_ended`, or
50+
/// [`SANDBOX_UNSUPPORTED`]; `None` for a failure without one. Codes a
51+
/// GUI does not know pass through.
52+
Failed {
53+
message: String,
54+
#[serde(default)]
55+
code: Option<String>,
56+
},
57+
}
58+
59+
impl SandboxResponse {
60+
/// What a host without a sandbox backend answers.
61+
pub fn unsupported() -> Self {
62+
Self::Failed {
63+
message: "This host does not run remote workspaces.".into(),
64+
code: Some(SANDBOX_UNSUPPORTED.into()),
65+
}
66+
}
67+
}
68+
69+
/// One agent's session in one thread, as the GUI asks for it.
70+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
71+
pub struct SandboxSession {
72+
pub pubkey: String,
73+
pub tenant: SandboxTenant,
74+
pub scope: SandboxScope,
75+
pub spec: LaunchSpec,
76+
}
77+
78+
/// The community and signed-in person the GUI asks for, which the host
79+
/// checks against the agent it holds.
80+
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
81+
pub struct SandboxTenant {
82+
/// The community's `wss://` origin.
83+
pub relay: String,
84+
/// The viewer's pubkey, as hex.
85+
pub signer: String,
86+
}
87+
88+
/// The thread a session belongs to.
89+
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
90+
pub struct SandboxScope {
91+
/// The channel's UUID.
92+
pub channel_id: String,
93+
/// The thread's root event id, as lowercase hex.
94+
pub thread_root: String,
95+
}
96+
97+
/// What the agent's type says to launch. Never the agent's key, community
98+
/// or attestation: the host adds those, and refuses them here.
99+
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
100+
#[serde(default)]
101+
pub struct LaunchSpec {
102+
/// The provider's id, such as `kubernetes`.
103+
pub provider: String,
104+
/// The provider's config, as JSON text.
105+
pub provider_config_json: String,
106+
/// The user's environment for the agent.
107+
pub env: BTreeMap<String, String>,
108+
pub launch: Launch,
109+
/// The agent's display name.
110+
pub name: String,
111+
}
112+
113+
/// The harness to run and its environment.
114+
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
115+
#[serde(default)]
116+
pub struct Launch {
117+
/// A command name, found on the provider's PATH.
118+
pub command: String,
119+
pub args: Vec<String>,
120+
pub env: BTreeMap<String, String>,
121+
/// Defaults the user's environment overrides.
122+
pub policy_env: BTreeMap<String, String>,
123+
}
124+
125+
/// Environment values may be secrets: only their names are shown.
126+
impl std::fmt::Debug for LaunchSpec {
127+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128+
f.debug_struct("LaunchSpec")
129+
.field("provider", &self.provider)
130+
.field("provider_config_json", &self.provider_config_json)
131+
.field("env", &self.env.keys().collect::<Vec<_>>())
132+
.field("launch", &self.launch)
133+
.field("name", &self.name)
134+
.finish()
135+
}
136+
}
137+
138+
impl std::fmt::Debug for Launch {
139+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140+
f.debug_struct("Launch")
141+
.field("command", &self.command)
142+
.field("args", &self.args)
143+
.field("env", &self.env.keys().collect::<Vec<_>>())
144+
.field("policy_env", &self.policy_env.keys().collect::<Vec<_>>())
145+
.finish()
146+
}
147+
}
148+
149+
/// How [`SandboxRequest::Recover`] brings a session back.
150+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
151+
#[serde(rename_all = "lowercase")]
152+
pub enum RecoveryMode {
153+
/// From the ended session's checkpoint.
154+
Checkpoint,
155+
/// With an empty workspace.
156+
Fresh,
157+
}
158+
159+
/// Where [`SandboxRequest::End`] left the session.
160+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
161+
#[serde(rename_all = "lowercase")]
162+
pub enum EndState {
163+
/// Still stopping; ask again.
164+
Ending,
165+
Ended,
166+
/// The thread had none.
167+
Absent,
168+
}
169+
170+
/// A provider the host found.
171+
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
172+
#[serde(default)]
173+
pub struct SandboxProvider {
174+
pub id: String,
175+
pub path: String,
176+
pub version: String,
177+
/// The operations it supports, such as `stop` and `recover`.
178+
pub ops: Vec<String>,
179+
/// Its config's JSON Schema, as JSON text.
180+
pub config_schema_json: String,
181+
}
182+
183+
#[cfg(test)]
184+
mod tests {
185+
use super::*;
186+
use crate::api::{Request, Response};
187+
188+
fn wire<T: Serialize>(value: &T) -> Vec<u8> {
189+
rmp_serde::to_vec_named(value).unwrap()
190+
}
191+
192+
/// The requests as hosts from before remote workspaces have them.
193+
mod old {
194+
use serde::{Deserialize, Serialize};
195+
196+
#[derive(Debug, Serialize, Deserialize)]
197+
pub enum Request {
198+
TerminalOwner,
199+
}
200+
}
201+
202+
fn session() -> SandboxSession {
203+
SandboxSession {
204+
pubkey: "a".repeat(64),
205+
tenant: SandboxTenant {
206+
relay: "wss://relay.example".into(),
207+
signer: "b".repeat(64),
208+
},
209+
scope: SandboxScope {
210+
channel_id: "6f1c3c7e-8f0e-4b8e-9d55-1a3c1f5b2e10".into(),
211+
thread_root: "c".repeat(64),
212+
},
213+
spec: LaunchSpec {
214+
provider: "kubernetes".into(),
215+
provider_config_json: r#"{"sandbox":true}"#.into(),
216+
env: [("API_TOKEN".into(), "hunter2".into())].into(),
217+
launch: Launch {
218+
command: "buzz-acp".into(),
219+
policy_env: [("BUZZ_ACP_TIMEOUT".into(), "600".into())].into(),
220+
..Default::default()
221+
},
222+
name: "Ada".into(),
223+
},
224+
}
225+
}
226+
227+
#[test]
228+
fn requests_and_answers_round_trip() {
229+
let start = Request::Sandbox(SandboxRequest::Start {
230+
session: session(),
231+
replay_floor: Some(1_700_000_000),
232+
});
233+
match rmp_serde::from_slice(&wire(&start)).unwrap() {
234+
Request::Sandbox(SandboxRequest::Start {
235+
session: read,
236+
replay_floor,
237+
}) => {
238+
assert_eq!(read, session());
239+
assert_eq!(replay_floor, Some(1_700_000_000));
240+
}
241+
other => panic!("expected Start, got {other:?}"),
242+
}
243+
let recover = SandboxRequest::Recover {
244+
session: session(),
245+
mode: RecoveryMode::Checkpoint,
246+
};
247+
assert!(matches!(
248+
rmp_serde::from_slice(&wire(&recover)).unwrap(),
249+
SandboxRequest::Recover {
250+
mode: RecoveryMode::Checkpoint,
251+
..
252+
}
253+
));
254+
let failed = Response::Sandbox(SandboxResponse::Failed {
255+
message: "The session ended".into(),
256+
code: Some("a_code_from_later".into()),
257+
});
258+
assert!(matches!(
259+
rmp_serde::from_slice(&wire(&failed)).unwrap(),
260+
Response::Sandbox(SandboxResponse::Failed { code: Some(code), .. })
261+
if code == "a_code_from_later"
262+
));
263+
let ended = SandboxResponse::Ended {
264+
state: EndState::Ending,
265+
};
266+
assert!(matches!(
267+
rmp_serde::from_slice(&wire(&ended)).unwrap(),
268+
SandboxResponse::Ended {
269+
state: EndState::Ending
270+
}
271+
));
272+
}
273+
274+
#[test]
275+
fn older_hosts_refuse_sandbox_requests() {
276+
let start = Request::Sandbox(SandboxRequest::End { session: session() });
277+
// An older host cannot decode it, so it answers that it does not
278+
// support the request.
279+
assert!(rmp_serde::from_slice::<old::Request>(&wire(&start)).is_err());
280+
assert!(matches!(
281+
rmp_serde::from_slice(&wire(&old::Request::TerminalOwner)).unwrap(),
282+
Request::TerminalOwner
283+
));
284+
}
285+
286+
#[test]
287+
fn debug_hides_environment_values() {
288+
let shown = format!("{:?}", SandboxRequest::End { session: session() });
289+
assert!(shown.contains("API_TOKEN") && shown.contains("BUZZ_ACP_TIMEOUT"));
290+
assert!(
291+
!shown.contains("hunter2") && !shown.contains("600"),
292+
"{shown}"
293+
);
294+
}
295+
}

0 commit comments

Comments
 (0)