Skip to main content

glass_dev/
pi_runtime.rs

1//! Glass-owned host for Pi's native `AgentSession` SDK runtime.
2
3use crate::agents::ResidentAgentBroker;
4use crate::development::{DevelopmentError, DevelopmentResult, ToolCall};
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7use std::collections::VecDeque;
8use std::fs;
9use std::io::{Read, Write};
10use std::path::{Path, PathBuf};
11use std::process::{Child, ChildStdin, Command, Stdio};
12use std::sync::Arc;
13use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
14use std::thread;
15use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
16
17const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
18const EVENT_CAPACITY: usize = 256;
19const RUNTIME_SOURCE: &str = include_str!("../assets/pi-runtime.mjs");
20pub const PINNED_PI_SDK_VERSION: &str = "0.84.3";
21const MINIMUM_NODE_VERSION: (u64, u64, u64) = (22, 19, 0);
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub enum PiReadinessState {
26    Ready,
27    Missing,
28    Incompatible,
29    Expired,
30    Unknown,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct PiReadinessComponent {
36    pub state: PiReadinessState,
37    pub version: Option<String>,
38    pub path: Option<PathBuf>,
39    pub detail: String,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct PiReadiness {
45    pub ready: bool,
46    pub node: PiReadinessComponent,
47    pub sdk: PiReadinessComponent,
48    pub authentication: PiReadinessComponent,
49    pub provider: Option<String>,
50    pub model: Option<String>,
51    pub session: Option<String>,
52    pub agent_dir: PathBuf,
53    pub managed_root: PathBuf,
54    pub remediation: Vec<String>,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59struct SelectedPiRuntime {
60    sdk_entry: PathBuf,
61    agent_dir: PathBuf,
62}
63
64#[derive(Debug, Clone)]
65pub enum PiSessionRequest {
66    Hello,
67    Prompt {
68        text: String,
69        context: Option<Value>,
70    },
71    Steer {
72        text: String,
73        context: Option<Value>,
74    },
75    FollowUp {
76        text: String,
77        context: Option<Value>,
78    },
79    Complete {
80        prefix: String,
81        suffix: String,
82    },
83    Abort,
84    State,
85    Models,
86    SetModel {
87        provider: String,
88        model_id: String,
89    },
90    SetThinking {
91        level: String,
92    },
93    NewSession,
94    Compact {
95        instructions: Option<String>,
96    },
97    CloneSession,
98    Rewind {
99        entry_id: String,
100    },
101    Fork {
102        entry_id: String,
103    },
104    SwitchSession {
105        path: String,
106    },
107    ListSessions,
108    Entries {
109        since: Option<String>,
110    },
111    Tree,
112    Messages,
113    SessionStats,
114    SetSessionName {
115        name: String,
116    },
117}
118
119pub type PiToolExecutor =
120    Arc<dyn Fn(&ToolCall, bool, bool) -> DevelopmentResult<Value> + Send + Sync>;
121
122#[derive(Clone, Default)]
123pub struct PiRuntimeOptions {
124    pub unrestricted: bool,
125    pub session_dir: PathBuf,
126    pub name: Option<String>,
127    pub model: Option<String>,
128    pub thinking: Option<String>,
129    pub broker: Option<ResidentAgentBroker>,
130    pub local_tool_executor: Option<PiToolExecutor>,
131    pub additional_system_prompt: Option<String>,
132    pub resume: bool,
133    pub fork_from: Option<PathBuf>,
134}
135
136impl std::fmt::Debug for PiRuntimeOptions {
137    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        formatter
139            .debug_struct("PiRuntimeOptions")
140            .field("unrestricted", &self.unrestricted)
141            .field("session_dir", &self.session_dir)
142            .field("name", &self.name)
143            .field("model", &self.model)
144            .field("thinking", &self.thinking)
145            .field("broker", &self.broker)
146            .field(
147                "local_tool_executor",
148                &self.local_tool_executor.as_ref().map(|_| "configured"),
149            )
150            .field("additional_system_prompt", &self.additional_system_prompt)
151            .field("resume", &self.resume)
152            .field("fork_from", &self.fork_from)
153            .finish()
154    }
155}
156
157struct PendingPiToolApproval {
158    frame_id: String,
159    call: ToolCall,
160}
161
162pub struct GlassPiRuntime {
163    child: Child,
164    input: ChildStdin,
165    output: Receiver<Result<Value, String>>,
166    root: PathBuf,
167    broker: Option<ResidentAgentBroker>,
168    local_tool_executor: Option<PiToolExecutor>,
169    unrestricted: bool,
170    next_id: u64,
171    host_events: VecDeque<Value>,
172    pending_tool_approval: Option<PendingPiToolApproval>,
173    aborting_turn: bool,
174    unknown_tool_failures: u8,
175}
176
177impl std::fmt::Debug for GlassPiRuntime {
178    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179        formatter
180            .debug_struct("GlassPiRuntime")
181            .field("pid", &self.child.id())
182            .field("root", &self.root)
183            .finish_non_exhaustive()
184    }
185}
186
187impl GlassPiRuntime {
188    pub fn spawn(root: &Path, options: PiRuntimeOptions) -> DevelopmentResult<Self> {
189        validate_options(&options)?;
190        let root = fs::canonicalize(root)?;
191        fs::create_dir_all(&options.session_dir)?;
192        let session_dir = fs::canonicalize(&options.session_dir)?;
193        let runtime_path = materialize_runtime()?;
194        let sdk_entry = locate_sdk_entry()?;
195        let agent_dir = active_agent_dir(&sdk_entry)?;
196        fs::create_dir_all(&agent_dir)?;
197
198        let mut command = Command::new("node");
199        command
200            .arg(&runtime_path)
201            .env("GLASS_PI_SDK_ENTRY", sdk_entry)
202            .env("GLASS_PI_CWD", &root)
203            .env("GLASS_PI_SESSION_DIR", &session_dir)
204            .env("GLASS_PI_AGENT_DIR", &agent_dir)
205            .stdin(Stdio::piped())
206            .stdout(Stdio::piped())
207            .stderr(Stdio::inherit());
208        for (key, value) in [
209            ("GLASS_PI_SESSION_NAME", options.name.as_deref()),
210            ("GLASS_PI_MODEL", options.model.as_deref()),
211            ("GLASS_PI_THINKING", options.thinking.as_deref()),
212            (
213                "GLASS_PI_SYSTEM_PROMPT",
214                options.additional_system_prompt.as_deref(),
215            ),
216        ] {
217            if let Some(value) = value {
218                command.env(key, value);
219            }
220        }
221        if options.resume {
222            command.env("GLASS_PI_RESUME", "1");
223        }
224        if let Some(path) = &options.fork_from {
225            command.env("GLASS_PI_FORK_FROM", path);
226        }
227
228        let mut child = command.spawn().map_err(|error| {
229            DevelopmentError::Process(format!("failed to start Glass Pi SDK runtime: {error}"))
230        })?;
231        let input = child
232            .stdin
233            .take()
234            .ok_or_else(|| DevelopmentError::Process("Pi runtime stdin is unavailable".into()))?;
235        let output_stream = child
236            .stdout
237            .take()
238            .ok_or_else(|| DevelopmentError::Process("Pi runtime stdout is unavailable".into()))?;
239        let (sender, output) = mpsc::sync_channel(EVENT_CAPACITY);
240        thread::Builder::new()
241            .name("glass-pi-sdk-output".into())
242            .spawn(move || read_frames(output_stream, sender))?;
243
244        let mut runtime = Self {
245            child,
246            input,
247            output,
248            root,
249            local_tool_executor: options.local_tool_executor,
250            broker: options.broker,
251            unrestricted: options.unrestricted,
252            next_id: 1,
253            host_events: VecDeque::new(),
254            pending_tool_approval: None,
255            aborting_turn: false,
256            unknown_tool_failures: 0,
257        };
258        match runtime.recv_raw(Duration::from_secs(15))? {
259            Some(value) if value.get("type").and_then(Value::as_str) == Some("ready") => {
260                Ok(runtime)
261            }
262            Some(value) => Err(DevelopmentError::Process(format!(
263                "Pi SDK runtime emitted an unexpected startup frame: {value}"
264            ))),
265            None => Err(DevelopmentError::Process(
266                "Pi SDK runtime did not become ready within 15 seconds".into(),
267            )),
268        }
269    }
270
271    pub fn start_request(&mut self, request: PiSessionRequest) -> DevelopmentResult<String> {
272        let (operation, params) = request_parts(request);
273        let id = format!("glass-{}", self.next_id);
274        self.next_id = self.next_id.saturating_add(1);
275        self.send(&json!({"id": id, "operation": operation, "params": params}))?;
276        Ok(id)
277    }
278
279    pub fn recv_event_timeout(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
280        if let Some(event) = self.host_events.pop_front() {
281            return Ok(Some(event));
282        }
283        let deadline = Instant::now() + timeout;
284        loop {
285            if let Some(event) = self.host_events.pop_front() {
286                return Ok(Some(event));
287            }
288            let Some(value) = self.recv_raw(deadline.saturating_duration_since(Instant::now()))?
289            else {
290                return Ok(None);
291            };
292            if value.get("type").and_then(Value::as_str) == Some("toolCall") {
293                if let Some(event) = self.handle_tool_call(&value)? {
294                    return Ok(Some(event));
295                }
296                continue;
297            }
298            if value.get("type").and_then(Value::as_str) == Some("agent_settled") {
299                self.aborting_turn = false;
300                self.unknown_tool_failures = 0;
301            }
302            return Ok(Some(value));
303        }
304    }
305
306    pub fn resolve_tool_approval(
307        &mut self,
308        frame_id: &str,
309        approved: bool,
310    ) -> DevelopmentResult<()> {
311        let pending = self.pending_tool_approval.as_ref().ok_or_else(|| {
312            DevelopmentError::Conflict("no Pi tool call is awaiting approval".into())
313        })?;
314        if pending.frame_id != frame_id {
315            return Err(DevelopmentError::Conflict(format!(
316                "Pi approval frame {} is not the pending frame",
317                frame_id
318            )));
319        }
320        let pending = self
321            .pending_tool_approval
322            .take()
323            .ok_or_else(|| DevelopmentError::Conflict("Pi approval request disappeared".into()))?;
324        let result = if approved {
325            self.execute_tool_call(&pending.call, true, true)
326        } else {
327            Err(DevelopmentError::Conflict(
328                "Glass denied this Pi tool call".into(),
329            ))
330        };
331        self.send_tool_result(&pending.frame_id, &result)?;
332        self.host_events.push_back(json!({
333            "type": "glass_tool_approval_resolved",
334            "frameId": pending.frame_id,
335            "toolName": pending.call.name,
336            "approved": approved,
337            "ok": result.is_ok(),
338        }));
339        if approved {
340            self.host_events
341                .push_back(browser_evidence(&pending.call, &result));
342        }
343        Ok(())
344    }
345
346    fn recv_raw(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
347        match self.output.recv_timeout(timeout) {
348            Ok(Ok(value)) => Ok(Some(value)),
349            Ok(Err(error)) => Err(DevelopmentError::Process(error)),
350            Err(RecvTimeoutError::Timeout) => Ok(None),
351            Err(RecvTimeoutError::Disconnected) => Err(DevelopmentError::Process(
352                "Pi SDK runtime event stream closed".into(),
353            )),
354        }
355    }
356
357    fn handle_tool_call(&mut self, value: &Value) -> DevelopmentResult<Option<Value>> {
358        let frame_id = value
359            .get("id")
360            .and_then(Value::as_str)
361            .ok_or_else(|| DevelopmentError::Serialization("Pi tool frame has no id".into()))?;
362        let call: ToolCall = normalize_tool_call(serde_json::from_value(
363            value.get("call").cloned().ok_or_else(|| {
364                DevelopmentError::Serialization("Pi tool frame has no call".into())
365            })?,
366        )?);
367        if !self.unrestricted && crate::tools::tool_requires_mutation(&call.name) {
368            if self.pending_tool_approval.is_some() {
369                return Err(DevelopmentError::Conflict(
370                    "Pi emitted a second tool call while approval was pending".into(),
371                ));
372            }
373            self.pending_tool_approval = Some(PendingPiToolApproval {
374                frame_id: frame_id.into(),
375                call: call.clone(),
376            });
377            return Ok(Some(json!({
378                "type": "glass_tool_approval_request",
379                "frameId": frame_id,
380                "toolName": call.name,
381                "arguments": redact_tool_arguments(&call.arguments),
382            })));
383        }
384        let result = self.execute_tool_call(&call, self.unrestricted, self.unrestricted);
385        let unknown_tool = is_unknown_tool_error(&result);
386        let result = if unknown_tool {
387            result.map_err(|error| {
388                DevelopmentError::InvalidInput(format!(
389                    "{error}; use a registered Glass capability such as `read`, `edit`, `bash`, `grep`, or `glass_tool`"
390                ))
391            })
392        } else {
393            result
394        };
395        self.send_tool_result(frame_id, &result)?;
396        self.host_events.push_back(browser_evidence(&call, &result));
397        if unknown_tool && !self.aborting_turn {
398            self.unknown_tool_failures = self.unknown_tool_failures.saturating_add(1);
399            if self.unknown_tool_failures >= 3 {
400                self.aborting_turn = true;
401                let abort_id = self.start_request(PiSessionRequest::Abort)?;
402                self.host_events.push_back(json!({
403                    "type": "glass_tool_rejected",
404                    "toolName": call.name,
405                    "reason": "Repeated unknown Glass tool calls; the turn was aborted after three recoverable failures",
406                    "recoverable": false,
407                    "attempt": self.unknown_tool_failures,
408                    "abortRequestId": abort_id,
409                }));
410            } else {
411                self.host_events.push_back(json!({
412                    "type": "glass_tool_rejected",
413                    "toolName": call.name,
414                    "reason": "Glass returned an unknown tool error; the tool result was returned so Pi can retry with a registered tool",
415                    "recoverable": true,
416                    "attempt": self.unknown_tool_failures,
417                }));
418            }
419        }
420        Ok(None)
421    }
422
423    fn execute_tool_call(
424        &self,
425        call: &ToolCall,
426        allow_mutation: bool,
427        confirmed: bool,
428    ) -> DevelopmentResult<Value> {
429        if let Some(executor) = &self.local_tool_executor {
430            return executor(call, allow_mutation, confirmed);
431        }
432        match &self.broker {
433            Some(broker) => {
434                let runtime = tokio::runtime::Builder::new_current_thread()
435                    .enable_io()
436                    .build()
437                    .map_err(DevelopmentError::Io)?;
438                runtime
439                    .block_on(crate::daemon::forward_resident_tool_call_with_context(
440                        broker,
441                        call,
442                        &self.root,
443                        allow_mutation,
444                        confirmed,
445                    ))
446                    .map_err(|error| DevelopmentError::Process(error.to_string()))
447            }
448            None => Err(DevelopmentError::Process(
449                "resident Pi has no authoritative Glass daemon broker".into(),
450            )),
451        }
452    }
453
454    fn send_tool_result(
455        &mut self,
456        frame_id: &str,
457        result: &DevelopmentResult<Value>,
458    ) -> DevelopmentResult<()> {
459        let response = match result {
460            Ok(result) => json!({
461                "operation": "toolResult", "id": frame_id, "ok": true, "result": result,
462            }),
463            Err(error) => json!({
464                "operation": "toolResult", "id": frame_id, "ok": false,
465                "error": error.to_string(),
466            }),
467        };
468        self.send(&response)
469    }
470
471    fn send(&mut self, value: &Value) -> DevelopmentResult<()> {
472        let encoded = serde_json::to_vec(value)?;
473        if encoded.is_empty() || encoded.len() > MAX_FRAME_BYTES {
474            return Err(DevelopmentError::InvalidInput(
475                "Pi SDK command exceeds the framed protocol limit".into(),
476            ));
477        }
478        self.input
479            .write_all(&(encoded.len() as u32).to_be_bytes())?;
480        self.input.write_all(&encoded)?;
481        self.input.flush()?;
482        Ok(())
483    }
484}
485
486fn normalize_tool_call(mut call: ToolCall) -> ToolCall {
487    let requested_name = call.name.clone();
488    let canonical = match requested_name.as_str() {
489        "read" | "glass.fs.read" => Some("glass.file.read"),
490        "ls" | "glass.fs.list" => Some("glass.file.list"),
491        "grep" | "glass.fs.grep" => Some("glass.file.grep"),
492        "find" | "glass.fs.find" => Some("glass.file.find"),
493        "write" | "glass.fs.write" => Some("glass.file.write"),
494        "edit" | "glass.fs.edit" => Some("glass.file.edit"),
495        "glass.fs.patch" => Some("glass.file.patch"),
496        "glass.fs.mkdir" => Some("glass.file.mkdir"),
497        "glass.fs.rename" => Some("glass.file.rename"),
498        "glass.fs.delete" | "glass.fs.remove" => Some("glass.file.delete"),
499        "bash" | "shell" | "terminal" | "glass.fs.shell" => Some("glass.command.run"),
500        _ => None,
501    };
502    let Some(canonical) = canonical else {
503        return call;
504    };
505    call.name = canonical.into();
506    if canonical == "glass.command.run" {
507        let mut arguments = match call.arguments {
508            Value::Object(arguments) => arguments,
509            _ => serde_json::Map::new(),
510        };
511        if !arguments.contains_key("name") {
512            let id = call
513                .id
514                .chars()
515                .map(|character| {
516                    if character.is_ascii_alphanumeric() || matches!(character, '-' | '_') {
517                        character
518                    } else {
519                        '-'
520                    }
521                })
522                .take(48)
523                .collect::<String>();
524            arguments.insert("name".into(), Value::String(format!("pi-{id}")));
525        }
526        if let Some(timeout) = arguments.remove("timeout") {
527            arguments.insert("timeoutSeconds".into(), timeout);
528        }
529        call.arguments = Value::Object(arguments);
530    }
531    call
532}
533
534fn is_unknown_tool_error(result: &DevelopmentResult<Value>) -> bool {
535    matches!(
536        result,
537        Err(DevelopmentError::NotFound(message)) if message.starts_with("tool ")
538    )
539}
540fn browser_evidence(call: &ToolCall, result: &DevelopmentResult<Value>) -> Value {
541    let browser = call.name.starts_with("glass.browser.");
542    let mut evidence = serde_json::Map::new();
543    evidence.insert(
544        "type".into(),
545        Value::String(
546            if browser {
547                "glass_browser_evidence"
548            } else {
549                "glass_tool_evidence"
550            }
551            .into(),
552        ),
553    );
554    evidence.insert("toolName".into(), Value::String(call.name.clone()));
555    evidence.insert("ok".into(), Value::Bool(result.is_ok()));
556    if let Err(error) = result {
557        evidence.insert(
558            "error".into(),
559            Value::String(redact_text(&error.to_string())),
560        );
561    }
562    if let Ok(value) = result {
563        for key in [
564            "browserRevision",
565            "currentRevision",
566            "finalRevision",
567            "targetId",
568            "url",
569            "title",
570            "workflowState",
571        ] {
572            if let Some(value) = value
573                .get(key)
574                .filter(|value| value.is_string() || value.is_number() || value.is_boolean())
575            {
576                let value = if key == "url" {
577                    value
578                        .as_str()
579                        .map(redact_url)
580                        .map(Value::String)
581                        .unwrap_or_else(|| value.clone())
582                } else {
583                    value.clone()
584                };
585                evidence.insert(key.into(), value);
586            }
587        }
588        if let Some(revision) = value
589            .pointer("/accessibility/revision")
590            .and_then(Value::as_u64)
591        {
592            evidence.insert("browserRevision".into(), Value::from(revision));
593        }
594        if let Some(url) = value.pointer("/page/url").and_then(Value::as_str) {
595            evidence.insert("url".into(), Value::String(redact_url(url)));
596        }
597        if let Some(title) = value.pointer("/page/title").and_then(Value::as_str) {
598            evidence.insert("title".into(), Value::String(title.into()));
599        }
600        if let Some(count) = value
601            .pointer("/accessibility/interactive")
602            .and_then(Value::as_array)
603            .map(Vec::len)
604        {
605            evidence.insert("semanticEntityCount".into(), Value::from(count));
606        }
607    }
608    Value::Object(evidence)
609}
610fn redact_url(url: &str) -> String {
611    url.split(['?', '#'])
612        .next()
613        .unwrap_or(url)
614        .chars()
615        .take(2_048)
616        .collect()
617}
618
619fn redact_tool_arguments(value: &Value) -> Value {
620    match value {
621        Value::Object(object) => Value::Object(
622            object
623                .iter()
624                .map(|(key, value)| {
625                    let redacted = key.to_ascii_lowercase();
626                    let value = if [
627                        "password",
628                        "token",
629                        "secret",
630                        "cookie",
631                        "authorization",
632                        "api_key",
633                        "apikey",
634                    ]
635                    .iter()
636                    .any(|needle| redacted.contains(needle))
637                    {
638                        Value::String("[redacted]".into())
639                    } else {
640                        redact_tool_arguments(value)
641                    };
642                    (key.clone(), value)
643                })
644                .collect(),
645        ),
646        Value::Array(values) => Value::Array(values.iter().map(redact_tool_arguments).collect()),
647        _ => value.clone(),
648    }
649}
650
651fn redact_text(text: &str) -> String {
652    text.chars().take(2_048).collect()
653}
654
655impl Drop for GlassPiRuntime {
656    fn drop(&mut self) {
657        let _ = self.child.kill();
658        let _ = self.child.wait();
659    }
660}
661
662fn request_parts(request: PiSessionRequest) -> (&'static str, Value) {
663    match request {
664        PiSessionRequest::Hello => ("hello", Value::Null),
665        PiSessionRequest::Prompt { text, context } => {
666            ("prompt", json!({"text": text, "context": context}))
667        }
668        PiSessionRequest::Steer { text, context } => {
669            ("steer", json!({"text": text, "context": context}))
670        }
671        PiSessionRequest::FollowUp { text, context } => {
672            ("followUp", json!({"text": text, "context": context}))
673        }
674        PiSessionRequest::Complete { prefix, suffix } => {
675            ("complete", json!({"prefix": prefix, "suffix": suffix}))
676        }
677        PiSessionRequest::Abort => ("abort", Value::Null),
678        PiSessionRequest::State => ("state", Value::Null),
679        PiSessionRequest::Models => ("models", Value::Null),
680        PiSessionRequest::SetModel { provider, model_id } => (
681            "setModel",
682            json!({"provider": provider, "modelId": model_id}),
683        ),
684        PiSessionRequest::SetThinking { level } => ("setThinking", json!({"level": level})),
685        PiSessionRequest::NewSession => ("newSession", Value::Null),
686        PiSessionRequest::Compact { instructions } => {
687            ("compact", json!({"instructions": instructions}))
688        }
689        PiSessionRequest::CloneSession => ("cloneSession", Value::Null),
690        PiSessionRequest::Rewind { entry_id } => ("rewind", json!({"entryId": entry_id})),
691        PiSessionRequest::Fork { entry_id } => ("fork", json!({"entryId": entry_id})),
692        PiSessionRequest::SwitchSession { path } => ("switchSession", json!({"path": path})),
693        PiSessionRequest::ListSessions => ("listSessions", Value::Null),
694        PiSessionRequest::Entries { since } => ("entries", json!({"since": since})),
695        PiSessionRequest::Tree => ("tree", Value::Null),
696        PiSessionRequest::Messages => ("messages", Value::Null),
697        PiSessionRequest::SessionStats => ("stats", Value::Null),
698        PiSessionRequest::SetSessionName { name } => ("setName", json!({"name": name})),
699    }
700}
701
702fn read_frames(mut stream: impl Read, sender: mpsc::SyncSender<Result<Value, String>>) {
703    loop {
704        let mut header = [0_u8; 4];
705        if let Err(error) = stream.read_exact(&mut header) {
706            let _ = sender.send(Err(format!("Pi SDK runtime frame header failed: {error}")));
707            return;
708        }
709        let length = u32::from_be_bytes(header) as usize;
710        if length == 0 || length > MAX_FRAME_BYTES {
711            let _ = sender.send(Err("Pi SDK runtime emitted an invalid frame length".into()));
712            return;
713        }
714        let mut encoded = vec![0_u8; length];
715        if let Err(error) = stream.read_exact(&mut encoded) {
716            let _ = sender.send(Err(format!("Pi SDK runtime frame body failed: {error}")));
717            return;
718        }
719        let value = serde_json::from_slice(&encoded).map_err(|error| error.to_string());
720        if sender.send(value).is_err() {
721            return;
722        }
723    }
724}
725
726pub fn pi_readiness() -> DevelopmentResult<PiReadiness> {
727    let managed_root = managed_pi_root()?;
728    let node = node_readiness();
729    let sdk_candidate = locate_sdk_candidate();
730    let (sdk, agent_dir) = match sdk_candidate {
731        Ok((path, source)) => {
732            let version = sdk_version(&path);
733            let compatible = version
734                .as_deref()
735                .and_then(parse_version)
736                .is_some_and(|version| version >= (0, 84, 1));
737            let state = if compatible {
738                PiReadinessState::Ready
739            } else {
740                PiReadinessState::Incompatible
741            };
742            let agent_dir = active_agent_dir(&path)?;
743            (
744                PiReadinessComponent {
745                    state,
746                    version,
747                    path: Some(path),
748                    detail: if compatible {
749                        format!("compatible {source} Pi SDK")
750                    } else {
751                        format!("{source} Pi SDK version is missing or older than 0.84.3")
752                    },
753                },
754                agent_dir,
755            )
756        }
757        Err(error) => (
758            PiReadinessComponent {
759                state: PiReadinessState::Missing,
760                version: None,
761                path: None,
762                detail: error.to_string(),
763            },
764            managed_agent_dir()?,
765        ),
766    };
767    let (authentication, provider) = authentication_readiness(&agent_dir);
768    let ready = node.state == PiReadinessState::Ready
769        && sdk.state == PiReadinessState::Ready
770        && authentication.state == PiReadinessState::Ready;
771    let mut remediation = Vec::new();
772    if node.state != PiReadinessState::Ready {
773        remediation.push(format!(
774            "Install Node {}.{}.{} or newer, then run `glass agent setup`.",
775            MINIMUM_NODE_VERSION.0, MINIMUM_NODE_VERSION.1, MINIMUM_NODE_VERSION.2
776        ));
777    }
778    if sdk.state != PiReadinessState::Ready {
779        remediation.push("Run `glass agent setup` to install the pinned managed Pi SDK, or select an existing SDK with `--sdk-entry`.".into());
780    }
781    if authentication.state != PiReadinessState::Ready {
782        remediation.push("Run `glass agent setup --login`, use Pi `/login`, or configure a supported provider API-key environment variable.".into());
783    }
784    Ok(PiReadiness {
785        ready,
786        node,
787        sdk,
788        authentication,
789        provider,
790        model: None,
791        session: newest_session(&agent_dir),
792        agent_dir,
793        managed_root,
794        remediation,
795    })
796}
797
798pub fn setup_pi_runtime(
799    sdk_entry: Option<&Path>,
800    agent_dir: Option<&Path>,
801    update: bool,
802    login: bool,
803) -> DevelopmentResult<PiReadiness> {
804    let node = node_readiness();
805    if node.state != PiReadinessState::Ready {
806        return Err(DevelopmentError::Process(node.detail));
807    }
808    let managed_root = managed_pi_root()?;
809    fs::create_dir_all(&managed_root)?;
810    let selected = if let Some(entry) = sdk_entry {
811        let entry = canonical_file(entry.to_path_buf(), "selected Pi SDK")?;
812        let agent_dir = match agent_dir {
813            Some(path) => canonical_directory(path, "selected Pi agent directory")?,
814            None => default_pi_agent_dir()?,
815        };
816        SelectedPiRuntime {
817            sdk_entry: entry,
818            agent_dir,
819        }
820    } else {
821        let entry = managed_sdk_entry()?;
822        let installed = sdk_version(&entry).as_deref() == Some(PINNED_PI_SDK_VERSION);
823        if update || !installed {
824            install_managed_sdk(&managed_root)?;
825        }
826        SelectedPiRuntime {
827            sdk_entry: canonical_file(managed_sdk_entry()?, "managed Pi SDK")?,
828            agent_dir: managed_agent_dir()?,
829        }
830    };
831    fs::create_dir_all(&selected.agent_dir)?;
832    write_selected_runtime(&selected)?;
833    if login {
834        run_pi_login(&selected)?;
835    }
836    pi_readiness()
837}
838
839fn node_readiness() -> PiReadinessComponent {
840    let path = find_on_path(if cfg!(windows) { "node.exe" } else { "node" });
841    let Some(path) = path else {
842        return PiReadinessComponent {
843            state: PiReadinessState::Missing,
844            version: None,
845            path: None,
846            detail: "Node is not available on PATH".into(),
847        };
848    };
849    match Command::new(&path).arg("--version").output() {
850        Ok(output) if output.status.success() => {
851            let version = String::from_utf8_lossy(&output.stdout)
852                .trim()
853                .trim_start_matches('v')
854                .to_string();
855            let compatible =
856                parse_version(&version).is_some_and(|value| value >= MINIMUM_NODE_VERSION);
857            PiReadinessComponent {
858                state: if compatible {
859                    PiReadinessState::Ready
860                } else {
861                    PiReadinessState::Incompatible
862                },
863                version: Some(version.clone()),
864                path: Some(path),
865                detail: if compatible {
866                    "compatible Node runtime".into()
867                } else {
868                    format!("Node {version} is older than 22.19.0")
869                },
870            }
871        }
872        Ok(output) => PiReadinessComponent {
873            state: PiReadinessState::Unknown,
874            version: None,
875            path: Some(path),
876            detail: format!("Node version check exited {}", output.status),
877        },
878        Err(error) => PiReadinessComponent {
879            state: PiReadinessState::Unknown,
880            version: None,
881            path: Some(path),
882            detail: format!("Node version check failed: {error}"),
883        },
884    }
885}
886
887fn authentication_readiness(agent_dir: &Path) -> (PiReadinessComponent, Option<String>) {
888    const PROVIDER_KEYS: [(&str, &str); 10] = [
889        ("ANTHROPIC_API_KEY", "anthropic"),
890        ("OPENAI_API_KEY", "openai"),
891        ("GEMINI_API_KEY", "google"),
892        ("GOOGLE_API_KEY", "google"),
893        ("MISTRAL_API_KEY", "mistral"),
894        ("GROQ_API_KEY", "groq"),
895        ("XAI_API_KEY", "xai"),
896        ("OPENROUTER_API_KEY", "openrouter"),
897        ("ZAI_API_KEY", "zai"),
898        ("AWS_BEARER_TOKEN_BEDROCK", "amazon-bedrock"),
899    ];
900    if let Some((_, provider)) = PROVIDER_KEYS
901        .iter()
902        .find(|(key, _)| std::env::var_os(key).is_some())
903    {
904        return (
905            PiReadinessComponent {
906                state: PiReadinessState::Ready,
907                version: None,
908                path: None,
909                detail: format!("{provider} authentication is available from the environment"),
910            },
911            Some((*provider).into()),
912        );
913    }
914    let path = agent_dir.join("auth.json");
915    let encoded = match fs::read(&path) {
916        Ok(encoded) => encoded,
917        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
918            return (
919                PiReadinessComponent {
920                    state: PiReadinessState::Missing,
921                    version: None,
922                    path: Some(path),
923                    detail: "no Pi credentials are configured".into(),
924                },
925                None,
926            );
927        }
928        Err(error) => {
929            return (
930                PiReadinessComponent {
931                    state: PiReadinessState::Unknown,
932                    version: None,
933                    path: Some(path),
934                    detail: format!("Pi credential metadata is unreadable: {error}"),
935                },
936                None,
937            );
938        }
939    };
940    let value: Value = match serde_json::from_slice(&encoded) {
941        Ok(value) => value,
942        Err(error) => {
943            return (
944                PiReadinessComponent {
945                    state: PiReadinessState::Unknown,
946                    version: None,
947                    path: Some(path),
948                    detail: format!("Pi credential metadata is invalid JSON: {error}"),
949                },
950                None,
951            );
952        }
953    };
954    let providers = value
955        .as_object()
956        .map(|items| items.keys().take(8).cloned().collect::<Vec<_>>())
957        .unwrap_or_default();
958    if providers.is_empty() {
959        return (
960            PiReadinessComponent {
961                state: PiReadinessState::Missing,
962                version: None,
963                path: Some(path),
964                detail: "Pi credential file contains no providers".into(),
965            },
966            None,
967        );
968    }
969    let expired = value
970        .as_object()
971        .is_some_and(|items| items.values().all(credential_expired));
972    let state = if expired {
973        PiReadinessState::Expired
974    } else {
975        PiReadinessState::Ready
976    };
977    (
978        PiReadinessComponent {
979            state,
980            version: None,
981            path: Some(path),
982            detail: if expired {
983                "all stored Pi credentials appear expired".into()
984            } else {
985                format!("stored Pi credentials for {}", providers.join(", "))
986            },
987        },
988        providers.first().cloned(),
989    )
990}
991
992fn credential_expired(value: &Value) -> bool {
993    let now = SystemTime::now()
994        .duration_since(UNIX_EPOCH)
995        .unwrap_or_default()
996        .as_secs();
997    ["expires", "expiresAt", "expires_at", "expiration"]
998        .iter()
999        .find_map(|key| value.get(key))
1000        .and_then(|value| value.as_u64().or_else(|| value.as_str()?.parse().ok()))
1001        .is_some_and(|expires| {
1002            let seconds = if expires > 10_000_000_000 {
1003                expires / 1_000
1004            } else {
1005                expires
1006            };
1007            seconds <= now
1008        })
1009}
1010
1011fn newest_session(agent_dir: &Path) -> Option<String> {
1012    let sessions = agent_dir.join("sessions");
1013    let mut newest = None;
1014    for entry in fs::read_dir(sessions).ok()? {
1015        let entry = entry.ok()?;
1016        let modified = entry.metadata().ok()?.modified().ok()?;
1017        if newest
1018            .as_ref()
1019            .is_none_or(|(current, _)| modified > *current)
1020        {
1021            newest = Some((modified, entry.file_name().to_string_lossy().into_owned()));
1022        }
1023    }
1024    newest.map(|(_, name)| name)
1025}
1026
1027fn materialize_runtime() -> DevelopmentResult<PathBuf> {
1028    let base = dirs::cache_dir()
1029        .ok_or_else(|| DevelopmentError::Process("user cache directory is unavailable".into()))?
1030        .join("glass")
1031        .join("pi-sdk-v1");
1032    fs::create_dir_all(&base)?;
1033    let path = base.join("runtime.mjs");
1034    if fs::read_to_string(&path).ok().as_deref() != Some(RUNTIME_SOURCE) {
1035        let temporary = base.join(format!("runtime-{}.tmp", std::process::id()));
1036        fs::write(&temporary, RUNTIME_SOURCE)?;
1037        fs::rename(temporary, &path)?;
1038    }
1039    Ok(path)
1040}
1041
1042fn locate_sdk_entry() -> DevelopmentResult<PathBuf> {
1043    locate_sdk_candidate().map(|(path, _)| path)
1044}
1045
1046fn locate_sdk_candidate() -> DevelopmentResult<(PathBuf, &'static str)> {
1047    if let Some(path) = std::env::var_os("GLASS_PI_SDK_ENTRY") {
1048        return canonical_file(PathBuf::from(path), "GLASS_PI_SDK_ENTRY")
1049            .map(|path| (path, "environment-selected"));
1050    }
1051    if let Some(selected) = read_selected_runtime()
1052        && let Ok(path) = canonical_file(selected.sdk_entry, "selected Pi SDK")
1053    {
1054        return Ok((path, "Glass-selected"));
1055    }
1056    let managed = managed_sdk_entry()?;
1057    if managed.is_file() {
1058        return fs::canonicalize(managed)
1059            .map(|path| (path, "Glass-managed"))
1060            .map_err(DevelopmentError::Io);
1061    }
1062    let local = Path::new(env!("CARGO_MANIFEST_DIR")).join(
1063        "../../packages/pi-runtime/node_modules/@earendil-works/pi-coding-agent/dist/index.js",
1064    );
1065    if local.is_file() {
1066        return fs::canonicalize(local)
1067            .map(|path| (path, "repository"))
1068            .map_err(DevelopmentError::Io);
1069    }
1070    let pi = find_on_path("pi").ok_or_else(|| {
1071        DevelopmentError::NotFound(
1072            "Pi SDK is not ready; run `glass agent setup` or select an existing installation"
1073                .into(),
1074        )
1075    })?;
1076    let cli = fs::canonicalize(pi)?;
1077    canonical_file(cli.with_file_name("index.js"), "installed Pi SDK").map(|path| (path, "system"))
1078}
1079
1080fn active_agent_dir(sdk_entry: &Path) -> DevelopmentResult<PathBuf> {
1081    if let Some(path) = std::env::var_os("GLASS_PI_AGENT_DIR") {
1082        let path = PathBuf::from(path);
1083        fs::create_dir_all(&path)?;
1084        return fs::canonicalize(path).map_err(DevelopmentError::Io);
1085    }
1086    if let Some(selected) = read_selected_runtime()
1087        && canonical_file(selected.sdk_entry, "selected Pi SDK")
1088            .is_ok_and(|selected| selected == sdk_entry)
1089    {
1090        fs::create_dir_all(&selected.agent_dir)?;
1091        return fs::canonicalize(selected.agent_dir).map_err(DevelopmentError::Io);
1092    }
1093    managed_agent_dir()
1094}
1095
1096fn managed_pi_root() -> DevelopmentResult<PathBuf> {
1097    dirs::data_local_dir()
1098        .ok_or_else(|| DevelopmentError::Process("user local-data directory is unavailable".into()))
1099        .map(|root| root.join("glass").join("runtime").join("pi"))
1100}
1101
1102fn managed_agent_dir() -> DevelopmentResult<PathBuf> {
1103    Ok(managed_pi_root()?.join("agent"))
1104}
1105
1106fn default_pi_agent_dir() -> DevelopmentResult<PathBuf> {
1107    dirs::home_dir()
1108        .ok_or_else(|| DevelopmentError::Process("user home directory is unavailable".into()))
1109        .map(|home| home.join(".pi").join("agent"))
1110}
1111
1112fn managed_sdk_entry() -> DevelopmentResult<PathBuf> {
1113    Ok(managed_pi_root()?
1114        .join("node_modules")
1115        .join("@earendil-works")
1116        .join("pi-coding-agent")
1117        .join("dist")
1118        .join("index.js"))
1119}
1120
1121fn selected_runtime_path() -> DevelopmentResult<PathBuf> {
1122    Ok(managed_pi_root()?.join("selected-runtime.json"))
1123}
1124
1125fn read_selected_runtime() -> Option<SelectedPiRuntime> {
1126    let path = selected_runtime_path().ok()?;
1127    serde_json::from_slice(&fs::read(path).ok()?).ok()
1128}
1129
1130fn write_selected_runtime(selected: &SelectedPiRuntime) -> DevelopmentResult<()> {
1131    let path = selected_runtime_path()?;
1132    let parent = path.parent().ok_or_else(|| {
1133        DevelopmentError::Process("selected Pi runtime path has no parent".into())
1134    })?;
1135    fs::create_dir_all(parent)?;
1136    let temporary = parent.join(format!("selected-runtime-{}.tmp", std::process::id()));
1137    fs::write(&temporary, serde_json::to_vec_pretty(selected)?)?;
1138    fs::rename(temporary, path)?;
1139    Ok(())
1140}
1141
1142fn install_managed_sdk(root: &Path) -> DevelopmentResult<()> {
1143    let manifest = serde_json::json!({
1144        "name":"@glass-dev/managed-pi-runtime",
1145        "private":true,
1146        "dependencies":{"@earendil-works/pi-coding-agent":PINNED_PI_SDK_VERSION}
1147    });
1148    fs::write(
1149        root.join("package.json"),
1150        serde_json::to_vec_pretty(&manifest)?,
1151    )?;
1152    let status = Command::new(if cfg!(windows) { "npm.cmd" } else { "npm" })
1153        .args([
1154            "install",
1155            "--ignore-scripts",
1156            "--no-audit",
1157            "--no-fund",
1158            "--save-exact",
1159            &format!("@earendil-works/pi-coding-agent@{PINNED_PI_SDK_VERSION}"),
1160        ])
1161        .current_dir(root)
1162        .status()
1163        .map_err(|error| DevelopmentError::Process(format!("failed to start npm: {error}")))?;
1164    if !status.success() {
1165        return Err(DevelopmentError::Process(format!(
1166            "managed Pi SDK installation exited {status}"
1167        )));
1168    }
1169    Ok(())
1170}
1171
1172fn run_pi_login(selected: &SelectedPiRuntime) -> DevelopmentResult<()> {
1173    let managed_cli = managed_pi_root()?
1174        .join("node_modules")
1175        .join(".bin")
1176        .join(if cfg!(windows) { "pi.cmd" } else { "pi" });
1177    let cli = if managed_cli.is_file() {
1178        managed_cli
1179    } else {
1180        find_on_path(if cfg!(windows) { "pi.cmd" } else { "pi" })
1181            .ok_or_else(|| DevelopmentError::NotFound("Pi CLI for interactive `/login`".into()))?
1182    };
1183    eprintln!(
1184        "Glass is opening Pi with its selected credential directory. Run `/login`, then exit Pi to return to Glass."
1185    );
1186    let status = Command::new(cli)
1187        .env("PI_CODING_AGENT_DIR", &selected.agent_dir)
1188        .status()
1189        .map_err(|error| DevelopmentError::Process(format!("failed to open Pi login: {error}")))?;
1190    if !status.success() {
1191        return Err(DevelopmentError::Process(format!(
1192            "Pi login session exited {status}"
1193        )));
1194    }
1195    Ok(())
1196}
1197
1198fn sdk_version(entry: &Path) -> Option<String> {
1199    let package = entry.parent()?.parent()?.join("package.json");
1200    let value: Value = serde_json::from_slice(&fs::read(package).ok()?).ok()?;
1201    value.get("version")?.as_str().map(str::to_string)
1202}
1203
1204fn parse_version(value: &str) -> Option<(u64, u64, u64)> {
1205    let core = value
1206        .trim()
1207        .trim_start_matches('v')
1208        .split(['-', '+'])
1209        .next()?;
1210    let mut parts = core.split('.');
1211    Some((
1212        parts.next()?.parse().ok()?,
1213        parts.next()?.parse().ok()?,
1214        parts.next()?.parse().ok()?,
1215    ))
1216}
1217
1218fn canonical_directory(path: &Path, label: &str) -> DevelopmentResult<PathBuf> {
1219    let canonical = fs::canonicalize(path).map_err(|error| {
1220        DevelopmentError::Process(format!(
1221            "{label} is unavailable at {}: {error}",
1222            path.display()
1223        ))
1224    })?;
1225    if !canonical.is_dir() {
1226        return Err(DevelopmentError::Process(format!(
1227            "{label} is not a directory: {}",
1228            canonical.display()
1229        )));
1230    }
1231    Ok(canonical)
1232}
1233
1234fn canonical_file(path: PathBuf, label: &str) -> DevelopmentResult<PathBuf> {
1235    let canonical = fs::canonicalize(&path).map_err(|error| {
1236        DevelopmentError::Process(format!(
1237            "{label} is unavailable at {}: {error}",
1238            path.display()
1239        ))
1240    })?;
1241    if !canonical.is_file() {
1242        return Err(DevelopmentError::Process(format!(
1243            "{label} is not a file: {}",
1244            canonical.display()
1245        )));
1246    }
1247    Ok(canonical)
1248}
1249
1250fn find_on_path(name: &str) -> Option<PathBuf> {
1251    std::env::var_os("PATH").and_then(|path| {
1252        std::env::split_paths(&path)
1253            .map(|directory| directory.join(name))
1254            .find(|candidate| candidate.is_file())
1255    })
1256}
1257
1258fn validate_options(options: &PiRuntimeOptions) -> DevelopmentResult<()> {
1259    if options.session_dir.as_os_str().is_empty() {
1260        return Err(DevelopmentError::InvalidInput(
1261            "Pi session directory is required".into(),
1262        ));
1263    }
1264    for (label, value, limit) in [
1265        ("Pi session name", options.name.as_deref(), 1024),
1266        ("Pi model", options.model.as_deref(), 1024),
1267        ("Pi thinking level", options.thinking.as_deref(), 128),
1268        (
1269            "Pi system prompt",
1270            options.additional_system_prompt.as_deref(),
1271            128 * 1024,
1272        ),
1273    ] {
1274        if value.is_some_and(|value| value.len() > limit || value.contains('\0')) {
1275            return Err(DevelopmentError::InvalidInput(format!("invalid {label}")));
1276        }
1277    }
1278    Ok(())
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283    use super::*;
1284    use std::sync::Arc;
1285
1286    fn response(runtime: &mut GlassPiRuntime, request: PiSessionRequest) -> Value {
1287        let id = runtime.start_request(request).unwrap();
1288        loop {
1289            let value = runtime
1290                .recv_event_timeout(Duration::from_secs(10))
1291                .unwrap()
1292                .expect("native SDK response");
1293            if value.get("type").and_then(Value::as_str) == Some("response")
1294                && value.get("id").and_then(Value::as_str) == Some(&id)
1295            {
1296                return value;
1297            }
1298        }
1299    }
1300    fn unknown_tool_rejection_count(runtime: &GlassPiRuntime) -> usize {
1301        runtime
1302            .host_events
1303            .iter()
1304            .filter(|event| {
1305                event.get("type").and_then(Value::as_str) == Some("glass_tool_rejected")
1306            })
1307            .count()
1308    }
1309
1310    #[test]
1311    fn request_mapping_uses_native_sdk_operations() {
1312        assert_eq!(request_parts(PiSessionRequest::Hello).0, "hello");
1313        assert_eq!(
1314            request_parts(PiSessionRequest::FollowUp {
1315                text: "next".into(),
1316                context: None,
1317            })
1318            .0,
1319            "followUp"
1320        );
1321        let (_, params) = request_parts(PiSessionRequest::Prompt {
1322            text: "inspect".into(),
1323            context: Some(json!({
1324                "schemaVersion": "glass.agent-context.v1",
1325                "browser": {"browserRevision": 7}
1326            })),
1327        });
1328        assert_eq!(params["context"]["browser"]["browserRevision"], 7);
1329        assert_eq!(request_parts(PiSessionRequest::SessionStats).0, "stats");
1330        assert_eq!(
1331            request_parts(PiSessionRequest::Complete {
1332                prefix: "fn main() {".into(),
1333                suffix: "}".into(),
1334            })
1335            .0,
1336            "complete"
1337        );
1338    }
1339
1340    #[test]
1341    fn runtime_asset_never_invokes_pi_rpc_cli() {
1342        assert!(!RUNTIME_SOURCE.contains("--mode"));
1343        assert!(!RUNTIME_SOURCE.contains("--mode rpc"));
1344        assert!(RUNTIME_SOURCE.contains("createAgentSession"));
1345        assert!(RUNTIME_SOURCE.contains("SessionManager"));
1346        assert!(RUNTIME_SOURCE.contains("completeFill"));
1347        assert!(RUNTIME_SOURCE.contains("GLASS_PI_FORK_FROM"));
1348    }
1349
1350    #[test]
1351    fn runtime_asset_registers_governed_custom_tools_without_builtins() {
1352        assert!(RUNTIME_SOURCE.contains("noTools: \"builtin\""));
1353        assert!(RUNTIME_SOURCE.contains("tools: [\"glass_tool\", \"delegate\", \"read\""));
1354        assert!(RUNTIME_SOURCE.contains("\"glass.agent.delegate\""));
1355        assert!(RUNTIME_SOURCE.contains("customTools: [glassTool, ...nativeTools]"));
1356    }
1357    #[test]
1358    fn unknown_tool_call_recovers_then_aborts_once() {
1359        if locate_sdk_entry().is_err() {
1360            return;
1361        }
1362        let root =
1363            std::env::temp_dir().join(format!("glass-pi-unknown-tool-test-{}", std::process::id()));
1364        let sessions = root.join("sessions");
1365        fs::create_dir_all(&root).unwrap();
1366        let executor: PiToolExecutor =
1367            Arc::new(|_, _, _| Err(DevelopmentError::NotFound("tool glass.fs.list".into())));
1368        let mut runtime = GlassPiRuntime::spawn(
1369            &root,
1370            PiRuntimeOptions {
1371                session_dir: sessions,
1372                local_tool_executor: Some(executor),
1373                ..PiRuntimeOptions::default()
1374            },
1375        )
1376        .unwrap();
1377        let call = serde_json::json!({
1378            "type": "toolCall",
1379            "id": "unknown-tool-frame",
1380            "call": {"id": "unknown-tool-call", "name": "glass.fs.list", "arguments": {}}
1381        });
1382
1383        assert!(runtime.handle_tool_call(&call).unwrap().is_none());
1384        assert!(!runtime.aborting_turn);
1385        assert_eq!(unknown_tool_rejection_count(&runtime), 1);
1386        assert_eq!(
1387            runtime
1388                .host_events
1389                .back()
1390                .and_then(|event| event.get("attempt")),
1391            Some(&json!(1))
1392        );
1393
1394        assert!(runtime.handle_tool_call(&call).unwrap().is_none());
1395        assert!(!runtime.aborting_turn);
1396        assert_eq!(unknown_tool_rejection_count(&runtime), 2);
1397
1398        assert!(runtime.handle_tool_call(&call).unwrap().is_none());
1399        assert!(runtime.aborting_turn);
1400        assert_eq!(unknown_tool_rejection_count(&runtime), 3);
1401        assert_eq!(
1402            runtime
1403                .host_events
1404                .back()
1405                .and_then(|event| event.get("recoverable")),
1406            Some(&json!(false))
1407        );
1408
1409        assert!(runtime.handle_tool_call(&call).unwrap().is_none());
1410        assert_eq!(unknown_tool_rejection_count(&runtime), 3);
1411        drop(runtime);
1412        fs::remove_dir_all(&root).unwrap();
1413    }
1414
1415    #[test]
1416    fn readiness_version_and_expiry_checks_are_deterministic() {
1417        assert_eq!(parse_version("v22.19.0"), Some((22, 19, 0)));
1418        assert_eq!(parse_version("0.84.3-beta.1"), Some((0, 84, 3)));
1419        assert_eq!(parse_version("invalid"), None);
1420        assert!(credential_expired(&serde_json::json!({"expires":1})));
1421        assert!(!credential_expired(&serde_json::json!({
1422            "expires":9_999_999_999_u64
1423        })));
1424        assert!(!credential_expired(&serde_json::json!({"type":"api_key"})));
1425    }
1426
1427    #[test]
1428    fn browser_evidence_redacts_url_query_and_fragment() {
1429        assert_eq!(
1430            redact_url("https://example.test/orders/7?token=secret#receipt"),
1431            "https://example.test/orders/7"
1432        );
1433    }
1434
1435    #[test]
1436    fn native_sdk_starts_and_reports_capabilities_when_installed() {
1437        if locate_sdk_entry().is_err() {
1438            return;
1439        }
1440        let root =
1441            std::env::temp_dir().join(format!("glass-pi-native-sdk-test-{}", std::process::id()));
1442        let sessions = root.join("sessions");
1443        fs::create_dir_all(&root).unwrap();
1444        let mut runtime = GlassPiRuntime::spawn(
1445            &root,
1446            PiRuntimeOptions {
1447                session_dir: sessions,
1448                name: Some("native SDK contract test".into()),
1449                ..PiRuntimeOptions::default()
1450            },
1451        )
1452        .unwrap();
1453        let hello = response(&mut runtime, PiSessionRequest::Hello);
1454        assert_eq!(hello.get("ok").and_then(Value::as_bool), Some(true));
1455        assert_eq!(
1456            hello.pointer("/result/protocol").and_then(Value::as_str),
1457            Some("glass-pi-sdk-v1")
1458        );
1459        let named = response(
1460            &mut runtime,
1461            PiSessionRequest::SetSessionName {
1462                name: "renamed SDK session".into(),
1463            },
1464        );
1465        assert_eq!(named.get("ok").and_then(Value::as_bool), Some(true));
1466        assert_eq!(
1467            response(&mut runtime, PiSessionRequest::SessionStats)
1468                .get("ok")
1469                .and_then(Value::as_bool),
1470            Some(true)
1471        );
1472        assert!(
1473            response(&mut runtime, PiSessionRequest::Tree)
1474                .pointer("/result")
1475                .is_some()
1476        );
1477        assert!(
1478            response(&mut runtime, PiSessionRequest::Messages)
1479                .pointer("/result")
1480                .is_some()
1481        );
1482        let cloned = response(&mut runtime, PiSessionRequest::CloneSession);
1483        assert_eq!(
1484            cloned.get("ok").and_then(Value::as_bool),
1485            Some(false),
1486            "{cloned}"
1487        );
1488        assert!(
1489            cloned
1490                .get("error")
1491                .and_then(Value::as_str)
1492                .is_some_and(|error| error.contains("empty or invalid"))
1493        );
1494        assert_eq!(
1495            response(&mut runtime, PiSessionRequest::NewSession)
1496                .get("ok")
1497                .and_then(Value::as_bool),
1498            Some(true)
1499        );
1500        assert!(
1501            response(&mut runtime, PiSessionRequest::ListSessions)
1502                .pointer("/result")
1503                .and_then(Value::as_array)
1504                .is_some()
1505        );
1506        let rejected = response(
1507            &mut runtime,
1508            PiSessionRequest::SwitchSession {
1509                path: root.join("outside.jsonl").display().to_string(),
1510            },
1511        );
1512        assert_eq!(rejected.get("ok").and_then(Value::as_bool), Some(false));
1513        drop(runtime);
1514        fs::remove_dir_all(&root).unwrap();
1515    }
1516}