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