1use crate::agents::ResidentAgentBroker;
4use crate::development::{DevelopmentError, DevelopmentResult, ToolCall};
5use serde_json::{Value, json};
6use std::fs;
7use std::io::{Read, Write};
8use std::path::{Path, PathBuf};
9use std::process::{Child, ChildStdin, Command, Stdio};
10use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
11use std::thread;
12use std::time::{Duration, Instant};
13
14const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
15const EVENT_CAPACITY: usize = 256;
16const RUNTIME_SOURCE: &str = include_str!("../assets/pi-runtime.mjs");
17
18#[derive(Debug, Clone)]
19pub enum PiSessionRequest {
20 Hello,
21 Prompt { text: String },
22 Steer { text: String },
23 FollowUp { text: String },
24 Abort,
25 State,
26 Models,
27 SetModel { provider: String, model_id: String },
28 SetThinking { level: String },
29 NewSession,
30 Compact { instructions: Option<String> },
31 CloneSession,
32 Fork { entry_id: String },
33 SwitchSession { path: String },
34 ListSessions,
35 Entries { since: Option<String> },
36 Tree,
37 Messages,
38 SessionStats,
39 SetSessionName { name: String },
40}
41
42#[derive(Debug, Clone, Default)]
43pub struct PiRuntimeOptions {
44 pub unrestricted: bool,
45 pub session_dir: PathBuf,
46 pub name: Option<String>,
47 pub model: Option<String>,
48 pub thinking: Option<String>,
49 pub broker: Option<ResidentAgentBroker>,
50 pub additional_system_prompt: Option<String>,
51 pub resume: bool,
52}
53
54pub struct GlassPiRuntime {
55 child: Child,
56 input: ChildStdin,
57 output: Receiver<Result<Value, String>>,
58 root: PathBuf,
59 broker: Option<ResidentAgentBroker>,
60 unrestricted: bool,
61 next_id: u64,
62}
63
64impl std::fmt::Debug for GlassPiRuntime {
65 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 formatter
67 .debug_struct("GlassPiRuntime")
68 .field("pid", &self.child.id())
69 .field("root", &self.root)
70 .finish_non_exhaustive()
71 }
72}
73
74impl GlassPiRuntime {
75 pub fn spawn(root: &Path, options: PiRuntimeOptions) -> DevelopmentResult<Self> {
76 validate_options(&options)?;
77 let root = fs::canonicalize(root)?;
78 fs::create_dir_all(&options.session_dir)?;
79 let session_dir = fs::canonicalize(&options.session_dir)?;
80 let runtime_path = materialize_runtime()?;
81 let sdk_entry = locate_sdk_entry()?;
82 let agent_dir = runtime_path
83 .parent()
84 .ok_or_else(|| DevelopmentError::Process("Pi runtime cache has no parent".into()))?
85 .join("agent-home");
86 fs::create_dir_all(&agent_dir)?;
87
88 let mut command = Command::new("node");
89 command
90 .arg(&runtime_path)
91 .env("GLASS_PI_SDK_ENTRY", sdk_entry)
92 .env("GLASS_PI_CWD", &root)
93 .env("GLASS_PI_SESSION_DIR", &session_dir)
94 .env("GLASS_PI_AGENT_DIR", &agent_dir)
95 .stdin(Stdio::piped())
96 .stdout(Stdio::piped())
97 .stderr(Stdio::inherit());
98 for (key, value) in [
99 ("GLASS_PI_SESSION_NAME", options.name.as_deref()),
100 ("GLASS_PI_MODEL", options.model.as_deref()),
101 ("GLASS_PI_THINKING", options.thinking.as_deref()),
102 (
103 "GLASS_PI_SYSTEM_PROMPT",
104 options.additional_system_prompt.as_deref(),
105 ),
106 ] {
107 if let Some(value) = value {
108 command.env(key, value);
109 }
110 }
111 if options.resume {
112 command.env("GLASS_PI_RESUME", "1");
113 }
114
115 let mut child = command.spawn().map_err(|error| {
116 DevelopmentError::Process(format!("failed to start Glass Pi SDK runtime: {error}"))
117 })?;
118 let input = child
119 .stdin
120 .take()
121 .ok_or_else(|| DevelopmentError::Process("Pi runtime stdin is unavailable".into()))?;
122 let output_stream = child
123 .stdout
124 .take()
125 .ok_or_else(|| DevelopmentError::Process("Pi runtime stdout is unavailable".into()))?;
126 let (sender, output) = mpsc::sync_channel(EVENT_CAPACITY);
127 thread::Builder::new()
128 .name("glass-pi-sdk-output".into())
129 .spawn(move || read_frames(output_stream, sender))?;
130
131 let mut runtime = Self {
132 child,
133 input,
134 output,
135 root,
136 broker: options.broker,
137 unrestricted: options.unrestricted,
138 next_id: 1,
139 };
140 match runtime.recv_raw(Duration::from_secs(15))? {
141 Some(value) if value.get("type").and_then(Value::as_str) == Some("ready") => {
142 Ok(runtime)
143 }
144 Some(value) => Err(DevelopmentError::Process(format!(
145 "Pi SDK runtime emitted an unexpected startup frame: {value}"
146 ))),
147 None => Err(DevelopmentError::Process(
148 "Pi SDK runtime did not become ready within 15 seconds".into(),
149 )),
150 }
151 }
152
153 pub fn start_request(&mut self, request: PiSessionRequest) -> DevelopmentResult<String> {
154 let (operation, params) = request_parts(request);
155 let id = format!("glass-{}", self.next_id);
156 self.next_id = self.next_id.saturating_add(1);
157 self.send(&json!({"id": id, "operation": operation, "params": params}))?;
158 Ok(id)
159 }
160
161 pub fn recv_event_timeout(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
162 let deadline = Instant::now() + timeout;
163 loop {
164 let Some(value) = self.recv_raw(deadline.saturating_duration_since(Instant::now()))?
165 else {
166 return Ok(None);
167 };
168 if value.get("type").and_then(Value::as_str) == Some("toolCall") {
169 self.handle_tool_call(&value)?;
170 continue;
171 }
172 return Ok(Some(value));
173 }
174 }
175
176 fn recv_raw(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
177 match self.output.recv_timeout(timeout) {
178 Ok(Ok(value)) => Ok(Some(value)),
179 Ok(Err(error)) => Err(DevelopmentError::Process(error)),
180 Err(RecvTimeoutError::Timeout) => Ok(None),
181 Err(RecvTimeoutError::Disconnected) => Err(DevelopmentError::Process(
182 "Pi SDK runtime event stream closed".into(),
183 )),
184 }
185 }
186
187 fn handle_tool_call(&mut self, value: &Value) -> DevelopmentResult<()> {
188 let frame_id = value
189 .get("id")
190 .and_then(Value::as_str)
191 .ok_or_else(|| DevelopmentError::Serialization("Pi tool frame has no id".into()))?;
192 let call: ToolCall =
193 serde_json::from_value(value.get("call").cloned().ok_or_else(|| {
194 DevelopmentError::Serialization("Pi tool frame has no call".into())
195 })?)?;
196 let result = match &self.broker {
197 Some(broker) => {
198 let runtime = tokio::runtime::Builder::new_current_thread()
199 .enable_io()
200 .build()
201 .map_err(DevelopmentError::Io)?;
202 runtime.block_on(crate::daemon::forward_resident_tool_call_with_context(
203 broker,
204 &call,
205 &self.root,
206 self.unrestricted,
207 self.unrestricted,
208 ))
209 }
210 None => Err("resident Pi has no authoritative Glass daemon broker".into()),
211 };
212 let response = match result {
213 Ok(result) => json!({
214 "operation": "toolResult", "id": frame_id, "ok": true, "result": result,
215 }),
216 Err(error) => json!({
217 "operation": "toolResult", "id": frame_id, "ok": false,
218 "error": error.to_string(),
219 }),
220 };
221 self.send(&response)
222 }
223
224 fn send(&mut self, value: &Value) -> DevelopmentResult<()> {
225 let encoded = serde_json::to_vec(value)?;
226 if encoded.is_empty() || encoded.len() > MAX_FRAME_BYTES {
227 return Err(DevelopmentError::InvalidInput(
228 "Pi SDK command exceeds the framed protocol limit".into(),
229 ));
230 }
231 self.input
232 .write_all(&(encoded.len() as u32).to_be_bytes())?;
233 self.input.write_all(&encoded)?;
234 self.input.flush()?;
235 Ok(())
236 }
237}
238
239impl Drop for GlassPiRuntime {
240 fn drop(&mut self) {
241 let _ = self.child.kill();
242 let _ = self.child.wait();
243 }
244}
245
246fn request_parts(request: PiSessionRequest) -> (&'static str, Value) {
247 match request {
248 PiSessionRequest::Hello => ("hello", Value::Null),
249 PiSessionRequest::Prompt { text } => ("prompt", json!({"text": text})),
250 PiSessionRequest::Steer { text } => ("steer", json!({"text": text})),
251 PiSessionRequest::FollowUp { text } => ("followUp", json!({"text": text})),
252 PiSessionRequest::Abort => ("abort", Value::Null),
253 PiSessionRequest::State => ("state", Value::Null),
254 PiSessionRequest::Models => ("models", Value::Null),
255 PiSessionRequest::SetModel { provider, model_id } => (
256 "setModel",
257 json!({"provider": provider, "modelId": model_id}),
258 ),
259 PiSessionRequest::SetThinking { level } => ("setThinking", json!({"level": level})),
260 PiSessionRequest::NewSession => ("newSession", Value::Null),
261 PiSessionRequest::Compact { instructions } => {
262 ("compact", json!({"instructions": instructions}))
263 }
264 PiSessionRequest::CloneSession => ("cloneSession", Value::Null),
265 PiSessionRequest::Fork { entry_id } => ("fork", json!({"entryId": entry_id})),
266 PiSessionRequest::SwitchSession { path } => ("switchSession", json!({"path": path})),
267 PiSessionRequest::ListSessions => ("listSessions", Value::Null),
268 PiSessionRequest::Entries { since } => ("entries", json!({"since": since})),
269 PiSessionRequest::Tree => ("tree", Value::Null),
270 PiSessionRequest::Messages => ("messages", Value::Null),
271 PiSessionRequest::SessionStats => ("stats", Value::Null),
272 PiSessionRequest::SetSessionName { name } => ("setName", json!({"name": name})),
273 }
274}
275
276fn read_frames(mut stream: impl Read, sender: mpsc::SyncSender<Result<Value, String>>) {
277 loop {
278 let mut header = [0_u8; 4];
279 if let Err(error) = stream.read_exact(&mut header) {
280 let _ = sender.send(Err(format!("Pi SDK runtime frame header failed: {error}")));
281 return;
282 }
283 let length = u32::from_be_bytes(header) as usize;
284 if length == 0 || length > MAX_FRAME_BYTES {
285 let _ = sender.send(Err("Pi SDK runtime emitted an invalid frame length".into()));
286 return;
287 }
288 let mut encoded = vec![0_u8; length];
289 if let Err(error) = stream.read_exact(&mut encoded) {
290 let _ = sender.send(Err(format!("Pi SDK runtime frame body failed: {error}")));
291 return;
292 }
293 let value = serde_json::from_slice(&encoded).map_err(|error| error.to_string());
294 if sender.send(value).is_err() {
295 return;
296 }
297 }
298}
299
300fn materialize_runtime() -> DevelopmentResult<PathBuf> {
301 let base = dirs::cache_dir()
302 .ok_or_else(|| DevelopmentError::Process("user cache directory is unavailable".into()))?
303 .join("glass")
304 .join("pi-sdk-v1");
305 fs::create_dir_all(&base)?;
306 let path = base.join("runtime.mjs");
307 if fs::read_to_string(&path).ok().as_deref() != Some(RUNTIME_SOURCE) {
308 let temporary = base.join(format!("runtime-{}.tmp", std::process::id()));
309 fs::write(&temporary, RUNTIME_SOURCE)?;
310 fs::rename(temporary, &path)?;
311 }
312 Ok(path)
313}
314
315fn locate_sdk_entry() -> DevelopmentResult<PathBuf> {
316 if let Some(path) = std::env::var_os("GLASS_PI_SDK_ENTRY") {
317 return canonical_file(PathBuf::from(path), "GLASS_PI_SDK_ENTRY");
318 }
319 let local = Path::new(env!("CARGO_MANIFEST_DIR")).join(
320 "../../packages/pi-runtime/node_modules/@earendil-works/pi-coding-agent/dist/index.js",
321 );
322 if local.is_file() {
323 return fs::canonicalize(local).map_err(DevelopmentError::Io);
324 }
325 let pi = find_on_path("pi").ok_or_else(|| {
326 DevelopmentError::NotFound(
327 "Pi SDK; install @earendil-works/pi-coding-agent or set GLASS_PI_SDK_ENTRY".into(),
328 )
329 })?;
330 let cli = fs::canonicalize(pi)?;
331 canonical_file(cli.with_file_name("index.js"), "installed Pi SDK")
332}
333
334fn canonical_file(path: PathBuf, label: &str) -> DevelopmentResult<PathBuf> {
335 let canonical = fs::canonicalize(&path).map_err(|error| {
336 DevelopmentError::Process(format!(
337 "{label} is unavailable at {}: {error}",
338 path.display()
339 ))
340 })?;
341 if !canonical.is_file() {
342 return Err(DevelopmentError::Process(format!(
343 "{label} is not a file: {}",
344 canonical.display()
345 )));
346 }
347 Ok(canonical)
348}
349
350fn find_on_path(name: &str) -> Option<PathBuf> {
351 std::env::var_os("PATH").and_then(|path| {
352 std::env::split_paths(&path)
353 .map(|directory| directory.join(name))
354 .find(|candidate| candidate.is_file())
355 })
356}
357
358fn validate_options(options: &PiRuntimeOptions) -> DevelopmentResult<()> {
359 if options.session_dir.as_os_str().is_empty() {
360 return Err(DevelopmentError::InvalidInput(
361 "Pi session directory is required".into(),
362 ));
363 }
364 for (label, value, limit) in [
365 ("Pi session name", options.name.as_deref(), 1024),
366 ("Pi model", options.model.as_deref(), 1024),
367 ("Pi thinking level", options.thinking.as_deref(), 128),
368 (
369 "Pi system prompt",
370 options.additional_system_prompt.as_deref(),
371 128 * 1024,
372 ),
373 ] {
374 if value.is_some_and(|value| value.len() > limit || value.contains('\0')) {
375 return Err(DevelopmentError::InvalidInput(format!("invalid {label}")));
376 }
377 }
378 Ok(())
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384
385 fn response(runtime: &mut GlassPiRuntime, request: PiSessionRequest) -> Value {
386 let id = runtime.start_request(request).unwrap();
387 loop {
388 let value = runtime
389 .recv_event_timeout(Duration::from_secs(10))
390 .unwrap()
391 .expect("native SDK response");
392 if value.get("type").and_then(Value::as_str) == Some("response")
393 && value.get("id").and_then(Value::as_str) == Some(&id)
394 {
395 return value;
396 }
397 }
398 }
399
400 #[test]
401 fn request_mapping_uses_native_sdk_operations() {
402 assert_eq!(request_parts(PiSessionRequest::Hello).0, "hello");
403 assert_eq!(
404 request_parts(PiSessionRequest::FollowUp {
405 text: "next".into()
406 })
407 .0,
408 "followUp"
409 );
410 assert_eq!(request_parts(PiSessionRequest::SessionStats).0, "stats");
411 }
412
413 #[test]
414 fn runtime_asset_never_invokes_pi_rpc_cli() {
415 assert!(!RUNTIME_SOURCE.contains("--mode"));
416 assert!(!RUNTIME_SOURCE.contains("--mode rpc"));
417 assert!(RUNTIME_SOURCE.contains("createAgentSession"));
418 assert!(RUNTIME_SOURCE.contains("SessionManager"));
419 }
420
421 #[test]
422 fn native_sdk_starts_and_reports_capabilities_when_installed() {
423 if locate_sdk_entry().is_err() {
424 return;
425 }
426 let root =
427 std::env::temp_dir().join(format!("glass-pi-native-sdk-test-{}", std::process::id()));
428 let sessions = root.join("sessions");
429 fs::create_dir_all(&root).unwrap();
430 let mut runtime = GlassPiRuntime::spawn(
431 &root,
432 PiRuntimeOptions {
433 session_dir: sessions,
434 name: Some("native SDK contract test".into()),
435 ..PiRuntimeOptions::default()
436 },
437 )
438 .unwrap();
439 let hello = response(&mut runtime, PiSessionRequest::Hello);
440 assert_eq!(hello.get("ok").and_then(Value::as_bool), Some(true));
441 assert_eq!(
442 hello.pointer("/result/protocol").and_then(Value::as_str),
443 Some("glass-pi-sdk-v1")
444 );
445 let named = response(
446 &mut runtime,
447 PiSessionRequest::SetSessionName {
448 name: "renamed SDK session".into(),
449 },
450 );
451 assert_eq!(named.get("ok").and_then(Value::as_bool), Some(true));
452 assert_eq!(
453 response(&mut runtime, PiSessionRequest::SessionStats)
454 .get("ok")
455 .and_then(Value::as_bool),
456 Some(true)
457 );
458 assert!(
459 response(&mut runtime, PiSessionRequest::Tree)
460 .pointer("/result")
461 .is_some()
462 );
463 assert!(
464 response(&mut runtime, PiSessionRequest::Messages)
465 .pointer("/result")
466 .is_some()
467 );
468 let cloned = response(&mut runtime, PiSessionRequest::CloneSession);
469 assert_eq!(
470 cloned.get("ok").and_then(Value::as_bool),
471 Some(false),
472 "{cloned}"
473 );
474 assert!(
475 cloned
476 .get("error")
477 .and_then(Value::as_str)
478 .is_some_and(|error| error.contains("empty or invalid"))
479 );
480 assert_eq!(
481 response(&mut runtime, PiSessionRequest::NewSession)
482 .get("ok")
483 .and_then(Value::as_bool),
484 Some(true)
485 );
486 assert!(
487 response(&mut runtime, PiSessionRequest::ListSessions)
488 .pointer("/result")
489 .and_then(Value::as_array)
490 .is_some()
491 );
492 let rejected = response(
493 &mut runtime,
494 PiSessionRequest::SwitchSession {
495 path: root.join("outside.jsonl").display().to_string(),
496 },
497 );
498 assert_eq!(rejected.get("ok").and_then(Value::as_bool), Some(false));
499 drop(runtime);
500 fs::remove_dir_all(&root).unwrap();
501 }
502}