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::fs;
8use std::io::{Read, Write};
9use std::path::{Path, PathBuf};
10use std::process::{Child, ChildStdin, Command, Stdio};
11use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
12use std::thread;
13use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
14
15const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
16const EVENT_CAPACITY: usize = 256;
17const RUNTIME_SOURCE: &str = include_str!("../assets/pi-runtime.mjs");
18pub const PINNED_PI_SDK_VERSION: &str = "0.84.1";
19const MINIMUM_NODE_VERSION: (u64, u64, u64) = (22, 19, 0);
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub enum PiReadinessState {
24    Ready,
25    Missing,
26    Incompatible,
27    Expired,
28    Unknown,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub struct PiReadinessComponent {
34    pub state: PiReadinessState,
35    pub version: Option<String>,
36    pub path: Option<PathBuf>,
37    pub detail: String,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct PiReadiness {
43    pub ready: bool,
44    pub node: PiReadinessComponent,
45    pub sdk: PiReadinessComponent,
46    pub authentication: PiReadinessComponent,
47    pub provider: Option<String>,
48    pub model: Option<String>,
49    pub session: Option<String>,
50    pub agent_dir: PathBuf,
51    pub managed_root: PathBuf,
52    pub remediation: Vec<String>,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
56#[serde(rename_all = "camelCase")]
57struct SelectedPiRuntime {
58    sdk_entry: PathBuf,
59    agent_dir: PathBuf,
60}
61
62#[derive(Debug, Clone)]
63pub enum PiSessionRequest {
64    Hello,
65    Prompt { text: String },
66    Steer { text: String },
67    FollowUp { text: String },
68    Abort,
69    State,
70    Models,
71    SetModel { provider: String, model_id: String },
72    SetThinking { level: String },
73    NewSession,
74    Compact { instructions: Option<String> },
75    CloneSession,
76    Fork { entry_id: String },
77    SwitchSession { path: String },
78    ListSessions,
79    Entries { since: Option<String> },
80    Tree,
81    Messages,
82    SessionStats,
83    SetSessionName { name: String },
84}
85
86#[derive(Debug, Clone, Default)]
87pub struct PiRuntimeOptions {
88    pub unrestricted: bool,
89    pub session_dir: PathBuf,
90    pub name: Option<String>,
91    pub model: Option<String>,
92    pub thinking: Option<String>,
93    pub broker: Option<ResidentAgentBroker>,
94    pub additional_system_prompt: Option<String>,
95    pub resume: bool,
96}
97
98pub struct GlassPiRuntime {
99    child: Child,
100    input: ChildStdin,
101    output: Receiver<Result<Value, String>>,
102    root: PathBuf,
103    broker: Option<ResidentAgentBroker>,
104    unrestricted: bool,
105    next_id: u64,
106}
107
108impl std::fmt::Debug for GlassPiRuntime {
109    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        formatter
111            .debug_struct("GlassPiRuntime")
112            .field("pid", &self.child.id())
113            .field("root", &self.root)
114            .finish_non_exhaustive()
115    }
116}
117
118impl GlassPiRuntime {
119    pub fn spawn(root: &Path, options: PiRuntimeOptions) -> DevelopmentResult<Self> {
120        validate_options(&options)?;
121        let root = fs::canonicalize(root)?;
122        fs::create_dir_all(&options.session_dir)?;
123        let session_dir = fs::canonicalize(&options.session_dir)?;
124        let runtime_path = materialize_runtime()?;
125        let sdk_entry = locate_sdk_entry()?;
126        let agent_dir = active_agent_dir(&sdk_entry)?;
127        fs::create_dir_all(&agent_dir)?;
128
129        let mut command = Command::new("node");
130        command
131            .arg(&runtime_path)
132            .env("GLASS_PI_SDK_ENTRY", sdk_entry)
133            .env("GLASS_PI_CWD", &root)
134            .env("GLASS_PI_SESSION_DIR", &session_dir)
135            .env("GLASS_PI_AGENT_DIR", &agent_dir)
136            .stdin(Stdio::piped())
137            .stdout(Stdio::piped())
138            .stderr(Stdio::inherit());
139        for (key, value) in [
140            ("GLASS_PI_SESSION_NAME", options.name.as_deref()),
141            ("GLASS_PI_MODEL", options.model.as_deref()),
142            ("GLASS_PI_THINKING", options.thinking.as_deref()),
143            (
144                "GLASS_PI_SYSTEM_PROMPT",
145                options.additional_system_prompt.as_deref(),
146            ),
147        ] {
148            if let Some(value) = value {
149                command.env(key, value);
150            }
151        }
152        if options.resume {
153            command.env("GLASS_PI_RESUME", "1");
154        }
155
156        let mut child = command.spawn().map_err(|error| {
157            DevelopmentError::Process(format!("failed to start Glass Pi SDK runtime: {error}"))
158        })?;
159        let input = child
160            .stdin
161            .take()
162            .ok_or_else(|| DevelopmentError::Process("Pi runtime stdin is unavailable".into()))?;
163        let output_stream = child
164            .stdout
165            .take()
166            .ok_or_else(|| DevelopmentError::Process("Pi runtime stdout is unavailable".into()))?;
167        let (sender, output) = mpsc::sync_channel(EVENT_CAPACITY);
168        thread::Builder::new()
169            .name("glass-pi-sdk-output".into())
170            .spawn(move || read_frames(output_stream, sender))?;
171
172        let mut runtime = Self {
173            child,
174            input,
175            output,
176            root,
177            broker: options.broker,
178            unrestricted: options.unrestricted,
179            next_id: 1,
180        };
181        match runtime.recv_raw(Duration::from_secs(15))? {
182            Some(value) if value.get("type").and_then(Value::as_str) == Some("ready") => {
183                Ok(runtime)
184            }
185            Some(value) => Err(DevelopmentError::Process(format!(
186                "Pi SDK runtime emitted an unexpected startup frame: {value}"
187            ))),
188            None => Err(DevelopmentError::Process(
189                "Pi SDK runtime did not become ready within 15 seconds".into(),
190            )),
191        }
192    }
193
194    pub fn start_request(&mut self, request: PiSessionRequest) -> DevelopmentResult<String> {
195        let (operation, params) = request_parts(request);
196        let id = format!("glass-{}", self.next_id);
197        self.next_id = self.next_id.saturating_add(1);
198        self.send(&json!({"id": id, "operation": operation, "params": params}))?;
199        Ok(id)
200    }
201
202    pub fn recv_event_timeout(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
203        let deadline = Instant::now() + timeout;
204        loop {
205            let Some(value) = self.recv_raw(deadline.saturating_duration_since(Instant::now()))?
206            else {
207                return Ok(None);
208            };
209            if value.get("type").and_then(Value::as_str) == Some("toolCall") {
210                self.handle_tool_call(&value)?;
211                continue;
212            }
213            return Ok(Some(value));
214        }
215    }
216
217    fn recv_raw(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
218        match self.output.recv_timeout(timeout) {
219            Ok(Ok(value)) => Ok(Some(value)),
220            Ok(Err(error)) => Err(DevelopmentError::Process(error)),
221            Err(RecvTimeoutError::Timeout) => Ok(None),
222            Err(RecvTimeoutError::Disconnected) => Err(DevelopmentError::Process(
223                "Pi SDK runtime event stream closed".into(),
224            )),
225        }
226    }
227
228    fn handle_tool_call(&mut self, value: &Value) -> DevelopmentResult<()> {
229        let frame_id = value
230            .get("id")
231            .and_then(Value::as_str)
232            .ok_or_else(|| DevelopmentError::Serialization("Pi tool frame has no id".into()))?;
233        let call: ToolCall =
234            serde_json::from_value(value.get("call").cloned().ok_or_else(|| {
235                DevelopmentError::Serialization("Pi tool frame has no call".into())
236            })?)?;
237        let result = match &self.broker {
238            Some(broker) => {
239                let runtime = tokio::runtime::Builder::new_current_thread()
240                    .enable_io()
241                    .build()
242                    .map_err(DevelopmentError::Io)?;
243                runtime.block_on(crate::daemon::forward_resident_tool_call_with_context(
244                    broker,
245                    &call,
246                    &self.root,
247                    self.unrestricted,
248                    self.unrestricted,
249                ))
250            }
251            None => Err("resident Pi has no authoritative Glass daemon broker".into()),
252        };
253        let response = match result {
254            Ok(result) => json!({
255                "operation": "toolResult", "id": frame_id, "ok": true, "result": result,
256            }),
257            Err(error) => json!({
258                "operation": "toolResult", "id": frame_id, "ok": false,
259                "error": error.to_string(),
260            }),
261        };
262        self.send(&response)
263    }
264
265    fn send(&mut self, value: &Value) -> DevelopmentResult<()> {
266        let encoded = serde_json::to_vec(value)?;
267        if encoded.is_empty() || encoded.len() > MAX_FRAME_BYTES {
268            return Err(DevelopmentError::InvalidInput(
269                "Pi SDK command exceeds the framed protocol limit".into(),
270            ));
271        }
272        self.input
273            .write_all(&(encoded.len() as u32).to_be_bytes())?;
274        self.input.write_all(&encoded)?;
275        self.input.flush()?;
276        Ok(())
277    }
278}
279
280impl Drop for GlassPiRuntime {
281    fn drop(&mut self) {
282        let _ = self.child.kill();
283        let _ = self.child.wait();
284    }
285}
286
287fn request_parts(request: PiSessionRequest) -> (&'static str, Value) {
288    match request {
289        PiSessionRequest::Hello => ("hello", Value::Null),
290        PiSessionRequest::Prompt { text } => ("prompt", json!({"text": text})),
291        PiSessionRequest::Steer { text } => ("steer", json!({"text": text})),
292        PiSessionRequest::FollowUp { text } => ("followUp", json!({"text": text})),
293        PiSessionRequest::Abort => ("abort", Value::Null),
294        PiSessionRequest::State => ("state", Value::Null),
295        PiSessionRequest::Models => ("models", Value::Null),
296        PiSessionRequest::SetModel { provider, model_id } => (
297            "setModel",
298            json!({"provider": provider, "modelId": model_id}),
299        ),
300        PiSessionRequest::SetThinking { level } => ("setThinking", json!({"level": level})),
301        PiSessionRequest::NewSession => ("newSession", Value::Null),
302        PiSessionRequest::Compact { instructions } => {
303            ("compact", json!({"instructions": instructions}))
304        }
305        PiSessionRequest::CloneSession => ("cloneSession", Value::Null),
306        PiSessionRequest::Fork { entry_id } => ("fork", json!({"entryId": entry_id})),
307        PiSessionRequest::SwitchSession { path } => ("switchSession", json!({"path": path})),
308        PiSessionRequest::ListSessions => ("listSessions", Value::Null),
309        PiSessionRequest::Entries { since } => ("entries", json!({"since": since})),
310        PiSessionRequest::Tree => ("tree", Value::Null),
311        PiSessionRequest::Messages => ("messages", Value::Null),
312        PiSessionRequest::SessionStats => ("stats", Value::Null),
313        PiSessionRequest::SetSessionName { name } => ("setName", json!({"name": name})),
314    }
315}
316
317fn read_frames(mut stream: impl Read, sender: mpsc::SyncSender<Result<Value, String>>) {
318    loop {
319        let mut header = [0_u8; 4];
320        if let Err(error) = stream.read_exact(&mut header) {
321            let _ = sender.send(Err(format!("Pi SDK runtime frame header failed: {error}")));
322            return;
323        }
324        let length = u32::from_be_bytes(header) as usize;
325        if length == 0 || length > MAX_FRAME_BYTES {
326            let _ = sender.send(Err("Pi SDK runtime emitted an invalid frame length".into()));
327            return;
328        }
329        let mut encoded = vec![0_u8; length];
330        if let Err(error) = stream.read_exact(&mut encoded) {
331            let _ = sender.send(Err(format!("Pi SDK runtime frame body failed: {error}")));
332            return;
333        }
334        let value = serde_json::from_slice(&encoded).map_err(|error| error.to_string());
335        if sender.send(value).is_err() {
336            return;
337        }
338    }
339}
340
341pub fn pi_readiness() -> DevelopmentResult<PiReadiness> {
342    let managed_root = managed_pi_root()?;
343    let node = node_readiness();
344    let sdk_candidate = locate_sdk_candidate();
345    let (sdk, agent_dir) = match sdk_candidate {
346        Ok((path, source)) => {
347            let version = sdk_version(&path);
348            let compatible = version
349                .as_deref()
350                .and_then(parse_version)
351                .is_some_and(|version| version >= (0, 84, 1));
352            let state = if compatible {
353                PiReadinessState::Ready
354            } else {
355                PiReadinessState::Incompatible
356            };
357            let agent_dir = active_agent_dir(&path)?;
358            (
359                PiReadinessComponent {
360                    state,
361                    version,
362                    path: Some(path),
363                    detail: if compatible {
364                        format!("compatible {source} Pi SDK")
365                    } else {
366                        format!("{source} Pi SDK version is missing or older than 0.84.1")
367                    },
368                },
369                agent_dir,
370            )
371        }
372        Err(error) => (
373            PiReadinessComponent {
374                state: PiReadinessState::Missing,
375                version: None,
376                path: None,
377                detail: error.to_string(),
378            },
379            managed_agent_dir()?,
380        ),
381    };
382    let (authentication, provider) = authentication_readiness(&agent_dir);
383    let ready = node.state == PiReadinessState::Ready
384        && sdk.state == PiReadinessState::Ready
385        && authentication.state == PiReadinessState::Ready;
386    let mut remediation = Vec::new();
387    if node.state != PiReadinessState::Ready {
388        remediation.push(format!(
389            "Install Node {}.{}.{} or newer, then run `glass agent setup`.",
390            MINIMUM_NODE_VERSION.0, MINIMUM_NODE_VERSION.1, MINIMUM_NODE_VERSION.2
391        ));
392    }
393    if sdk.state != PiReadinessState::Ready {
394        remediation.push("Run `glass agent setup` to install the pinned managed Pi SDK, or select an existing SDK with `--sdk-entry`.".into());
395    }
396    if authentication.state != PiReadinessState::Ready {
397        remediation.push("Run `glass agent setup --login`, use Pi `/login`, or configure a supported provider API-key environment variable.".into());
398    }
399    Ok(PiReadiness {
400        ready,
401        node,
402        sdk,
403        authentication,
404        provider,
405        model: None,
406        session: newest_session(&agent_dir),
407        agent_dir,
408        managed_root,
409        remediation,
410    })
411}
412
413pub fn setup_pi_runtime(
414    sdk_entry: Option<&Path>,
415    agent_dir: Option<&Path>,
416    update: bool,
417    login: bool,
418) -> DevelopmentResult<PiReadiness> {
419    let node = node_readiness();
420    if node.state != PiReadinessState::Ready {
421        return Err(DevelopmentError::Process(node.detail));
422    }
423    let managed_root = managed_pi_root()?;
424    fs::create_dir_all(&managed_root)?;
425    let selected = if let Some(entry) = sdk_entry {
426        let entry = canonical_file(entry.to_path_buf(), "selected Pi SDK")?;
427        let agent_dir = match agent_dir {
428            Some(path) => canonical_directory(path, "selected Pi agent directory")?,
429            None => default_pi_agent_dir()?,
430        };
431        SelectedPiRuntime {
432            sdk_entry: entry,
433            agent_dir,
434        }
435    } else {
436        let entry = managed_sdk_entry()?;
437        let installed = sdk_version(&entry).as_deref() == Some(PINNED_PI_SDK_VERSION);
438        if update || !installed {
439            install_managed_sdk(&managed_root)?;
440        }
441        SelectedPiRuntime {
442            sdk_entry: canonical_file(managed_sdk_entry()?, "managed Pi SDK")?,
443            agent_dir: managed_agent_dir()?,
444        }
445    };
446    fs::create_dir_all(&selected.agent_dir)?;
447    write_selected_runtime(&selected)?;
448    if login {
449        run_pi_login(&selected)?;
450    }
451    pi_readiness()
452}
453
454fn node_readiness() -> PiReadinessComponent {
455    let path = find_on_path(if cfg!(windows) { "node.exe" } else { "node" });
456    let Some(path) = path else {
457        return PiReadinessComponent {
458            state: PiReadinessState::Missing,
459            version: None,
460            path: None,
461            detail: "Node is not available on PATH".into(),
462        };
463    };
464    match Command::new(&path).arg("--version").output() {
465        Ok(output) if output.status.success() => {
466            let version = String::from_utf8_lossy(&output.stdout)
467                .trim()
468                .trim_start_matches('v')
469                .to_string();
470            let compatible =
471                parse_version(&version).is_some_and(|value| value >= MINIMUM_NODE_VERSION);
472            PiReadinessComponent {
473                state: if compatible {
474                    PiReadinessState::Ready
475                } else {
476                    PiReadinessState::Incompatible
477                },
478                version: Some(version.clone()),
479                path: Some(path),
480                detail: if compatible {
481                    "compatible Node runtime".into()
482                } else {
483                    format!("Node {version} is older than 22.19.0")
484                },
485            }
486        }
487        Ok(output) => PiReadinessComponent {
488            state: PiReadinessState::Unknown,
489            version: None,
490            path: Some(path),
491            detail: format!("Node version check exited {}", output.status),
492        },
493        Err(error) => PiReadinessComponent {
494            state: PiReadinessState::Unknown,
495            version: None,
496            path: Some(path),
497            detail: format!("Node version check failed: {error}"),
498        },
499    }
500}
501
502fn authentication_readiness(agent_dir: &Path) -> (PiReadinessComponent, Option<String>) {
503    const PROVIDER_KEYS: [(&str, &str); 10] = [
504        ("ANTHROPIC_API_KEY", "anthropic"),
505        ("OPENAI_API_KEY", "openai"),
506        ("GEMINI_API_KEY", "google"),
507        ("GOOGLE_API_KEY", "google"),
508        ("MISTRAL_API_KEY", "mistral"),
509        ("GROQ_API_KEY", "groq"),
510        ("XAI_API_KEY", "xai"),
511        ("OPENROUTER_API_KEY", "openrouter"),
512        ("ZAI_API_KEY", "zai"),
513        ("AWS_BEARER_TOKEN_BEDROCK", "amazon-bedrock"),
514    ];
515    if let Some((_, provider)) = PROVIDER_KEYS
516        .iter()
517        .find(|(key, _)| std::env::var_os(key).is_some())
518    {
519        return (
520            PiReadinessComponent {
521                state: PiReadinessState::Ready,
522                version: None,
523                path: None,
524                detail: format!("{provider} authentication is available from the environment"),
525            },
526            Some((*provider).into()),
527        );
528    }
529    let path = agent_dir.join("auth.json");
530    let encoded = match fs::read(&path) {
531        Ok(encoded) => encoded,
532        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
533            return (
534                PiReadinessComponent {
535                    state: PiReadinessState::Missing,
536                    version: None,
537                    path: Some(path),
538                    detail: "no Pi credentials are configured".into(),
539                },
540                None,
541            );
542        }
543        Err(error) => {
544            return (
545                PiReadinessComponent {
546                    state: PiReadinessState::Unknown,
547                    version: None,
548                    path: Some(path),
549                    detail: format!("Pi credential metadata is unreadable: {error}"),
550                },
551                None,
552            );
553        }
554    };
555    let value: Value = match serde_json::from_slice(&encoded) {
556        Ok(value) => value,
557        Err(error) => {
558            return (
559                PiReadinessComponent {
560                    state: PiReadinessState::Unknown,
561                    version: None,
562                    path: Some(path),
563                    detail: format!("Pi credential metadata is invalid JSON: {error}"),
564                },
565                None,
566            );
567        }
568    };
569    let providers = value
570        .as_object()
571        .map(|items| items.keys().take(8).cloned().collect::<Vec<_>>())
572        .unwrap_or_default();
573    if providers.is_empty() {
574        return (
575            PiReadinessComponent {
576                state: PiReadinessState::Missing,
577                version: None,
578                path: Some(path),
579                detail: "Pi credential file contains no providers".into(),
580            },
581            None,
582        );
583    }
584    let expired = value
585        .as_object()
586        .is_some_and(|items| items.values().all(credential_expired));
587    let state = if expired {
588        PiReadinessState::Expired
589    } else {
590        PiReadinessState::Ready
591    };
592    (
593        PiReadinessComponent {
594            state,
595            version: None,
596            path: Some(path),
597            detail: if expired {
598                "all stored Pi credentials appear expired".into()
599            } else {
600                format!("stored Pi credentials for {}", providers.join(", "))
601            },
602        },
603        providers.first().cloned(),
604    )
605}
606
607fn credential_expired(value: &Value) -> bool {
608    let now = SystemTime::now()
609        .duration_since(UNIX_EPOCH)
610        .unwrap_or_default()
611        .as_secs();
612    ["expires", "expiresAt", "expires_at", "expiration"]
613        .iter()
614        .find_map(|key| value.get(key))
615        .and_then(|value| value.as_u64().or_else(|| value.as_str()?.parse().ok()))
616        .is_some_and(|expires| {
617            let seconds = if expires > 10_000_000_000 {
618                expires / 1_000
619            } else {
620                expires
621            };
622            seconds <= now
623        })
624}
625
626fn newest_session(agent_dir: &Path) -> Option<String> {
627    let sessions = agent_dir.join("sessions");
628    let mut newest = None;
629    for entry in fs::read_dir(sessions).ok()? {
630        let entry = entry.ok()?;
631        let modified = entry.metadata().ok()?.modified().ok()?;
632        if newest
633            .as_ref()
634            .is_none_or(|(current, _)| modified > *current)
635        {
636            newest = Some((modified, entry.file_name().to_string_lossy().into_owned()));
637        }
638    }
639    newest.map(|(_, name)| name)
640}
641
642fn materialize_runtime() -> DevelopmentResult<PathBuf> {
643    let base = dirs::cache_dir()
644        .ok_or_else(|| DevelopmentError::Process("user cache directory is unavailable".into()))?
645        .join("glass")
646        .join("pi-sdk-v1");
647    fs::create_dir_all(&base)?;
648    let path = base.join("runtime.mjs");
649    if fs::read_to_string(&path).ok().as_deref() != Some(RUNTIME_SOURCE) {
650        let temporary = base.join(format!("runtime-{}.tmp", std::process::id()));
651        fs::write(&temporary, RUNTIME_SOURCE)?;
652        fs::rename(temporary, &path)?;
653    }
654    Ok(path)
655}
656
657fn locate_sdk_entry() -> DevelopmentResult<PathBuf> {
658    locate_sdk_candidate().map(|(path, _)| path)
659}
660
661fn locate_sdk_candidate() -> DevelopmentResult<(PathBuf, &'static str)> {
662    if let Some(path) = std::env::var_os("GLASS_PI_SDK_ENTRY") {
663        return canonical_file(PathBuf::from(path), "GLASS_PI_SDK_ENTRY")
664            .map(|path| (path, "environment-selected"));
665    }
666    if let Some(selected) = read_selected_runtime()
667        && let Ok(path) = canonical_file(selected.sdk_entry, "selected Pi SDK")
668    {
669        return Ok((path, "Glass-selected"));
670    }
671    let managed = managed_sdk_entry()?;
672    if managed.is_file() {
673        return fs::canonicalize(managed)
674            .map(|path| (path, "Glass-managed"))
675            .map_err(DevelopmentError::Io);
676    }
677    let local = Path::new(env!("CARGO_MANIFEST_DIR")).join(
678        "../../packages/pi-runtime/node_modules/@earendil-works/pi-coding-agent/dist/index.js",
679    );
680    if local.is_file() {
681        return fs::canonicalize(local)
682            .map(|path| (path, "repository"))
683            .map_err(DevelopmentError::Io);
684    }
685    let pi = find_on_path("pi").ok_or_else(|| {
686        DevelopmentError::NotFound(
687            "Pi SDK is not ready; run `glass agent setup` or select an existing installation"
688                .into(),
689        )
690    })?;
691    let cli = fs::canonicalize(pi)?;
692    canonical_file(cli.with_file_name("index.js"), "installed Pi SDK").map(|path| (path, "system"))
693}
694
695fn active_agent_dir(sdk_entry: &Path) -> DevelopmentResult<PathBuf> {
696    if let Some(path) = std::env::var_os("GLASS_PI_AGENT_DIR") {
697        let path = PathBuf::from(path);
698        fs::create_dir_all(&path)?;
699        return fs::canonicalize(path).map_err(DevelopmentError::Io);
700    }
701    if let Some(selected) = read_selected_runtime()
702        && canonical_file(selected.sdk_entry, "selected Pi SDK")
703            .is_ok_and(|selected| selected == sdk_entry)
704    {
705        fs::create_dir_all(&selected.agent_dir)?;
706        return fs::canonicalize(selected.agent_dir).map_err(DevelopmentError::Io);
707    }
708    managed_agent_dir()
709}
710
711fn managed_pi_root() -> DevelopmentResult<PathBuf> {
712    dirs::data_local_dir()
713        .ok_or_else(|| DevelopmentError::Process("user local-data directory is unavailable".into()))
714        .map(|root| root.join("glass").join("runtime").join("pi"))
715}
716
717fn managed_agent_dir() -> DevelopmentResult<PathBuf> {
718    Ok(managed_pi_root()?.join("agent"))
719}
720
721fn default_pi_agent_dir() -> DevelopmentResult<PathBuf> {
722    dirs::home_dir()
723        .ok_or_else(|| DevelopmentError::Process("user home directory is unavailable".into()))
724        .map(|home| home.join(".pi").join("agent"))
725}
726
727fn managed_sdk_entry() -> DevelopmentResult<PathBuf> {
728    Ok(managed_pi_root()?
729        .join("node_modules")
730        .join("@earendil-works")
731        .join("pi-coding-agent")
732        .join("dist")
733        .join("index.js"))
734}
735
736fn selected_runtime_path() -> DevelopmentResult<PathBuf> {
737    Ok(managed_pi_root()?.join("selected-runtime.json"))
738}
739
740fn read_selected_runtime() -> Option<SelectedPiRuntime> {
741    let path = selected_runtime_path().ok()?;
742    serde_json::from_slice(&fs::read(path).ok()?).ok()
743}
744
745fn write_selected_runtime(selected: &SelectedPiRuntime) -> DevelopmentResult<()> {
746    let path = selected_runtime_path()?;
747    let parent = path.parent().ok_or_else(|| {
748        DevelopmentError::Process("selected Pi runtime path has no parent".into())
749    })?;
750    fs::create_dir_all(parent)?;
751    let temporary = parent.join(format!("selected-runtime-{}.tmp", std::process::id()));
752    fs::write(&temporary, serde_json::to_vec_pretty(selected)?)?;
753    fs::rename(temporary, path)?;
754    Ok(())
755}
756
757fn install_managed_sdk(root: &Path) -> DevelopmentResult<()> {
758    let manifest = serde_json::json!({
759        "name":"@glass-dev/managed-pi-runtime",
760        "private":true,
761        "dependencies":{"@earendil-works/pi-coding-agent":PINNED_PI_SDK_VERSION}
762    });
763    fs::write(
764        root.join("package.json"),
765        serde_json::to_vec_pretty(&manifest)?,
766    )?;
767    let status = Command::new(if cfg!(windows) { "npm.cmd" } else { "npm" })
768        .args([
769            "install",
770            "--ignore-scripts",
771            "--no-audit",
772            "--no-fund",
773            "--save-exact",
774            &format!("@earendil-works/pi-coding-agent@{PINNED_PI_SDK_VERSION}"),
775        ])
776        .current_dir(root)
777        .status()
778        .map_err(|error| DevelopmentError::Process(format!("failed to start npm: {error}")))?;
779    if !status.success() {
780        return Err(DevelopmentError::Process(format!(
781            "managed Pi SDK installation exited {status}"
782        )));
783    }
784    Ok(())
785}
786
787fn run_pi_login(selected: &SelectedPiRuntime) -> DevelopmentResult<()> {
788    let managed_cli = managed_pi_root()?
789        .join("node_modules")
790        .join(".bin")
791        .join(if cfg!(windows) { "pi.cmd" } else { "pi" });
792    let cli = if managed_cli.is_file() {
793        managed_cli
794    } else {
795        find_on_path(if cfg!(windows) { "pi.cmd" } else { "pi" })
796            .ok_or_else(|| DevelopmentError::NotFound("Pi CLI for interactive `/login`".into()))?
797    };
798    eprintln!(
799        "Glass is opening Pi with its selected credential directory. Run `/login`, then exit Pi to return to Glass."
800    );
801    let status = Command::new(cli)
802        .env("PI_CODING_AGENT_DIR", &selected.agent_dir)
803        .status()
804        .map_err(|error| DevelopmentError::Process(format!("failed to open Pi login: {error}")))?;
805    if !status.success() {
806        return Err(DevelopmentError::Process(format!(
807            "Pi login session exited {status}"
808        )));
809    }
810    Ok(())
811}
812
813fn sdk_version(entry: &Path) -> Option<String> {
814    let package = entry.parent()?.parent()?.join("package.json");
815    let value: Value = serde_json::from_slice(&fs::read(package).ok()?).ok()?;
816    value.get("version")?.as_str().map(str::to_string)
817}
818
819fn parse_version(value: &str) -> Option<(u64, u64, u64)> {
820    let core = value
821        .trim()
822        .trim_start_matches('v')
823        .split(['-', '+'])
824        .next()?;
825    let mut parts = core.split('.');
826    Some((
827        parts.next()?.parse().ok()?,
828        parts.next()?.parse().ok()?,
829        parts.next()?.parse().ok()?,
830    ))
831}
832
833fn canonical_directory(path: &Path, label: &str) -> DevelopmentResult<PathBuf> {
834    let canonical = fs::canonicalize(path).map_err(|error| {
835        DevelopmentError::Process(format!(
836            "{label} is unavailable at {}: {error}",
837            path.display()
838        ))
839    })?;
840    if !canonical.is_dir() {
841        return Err(DevelopmentError::Process(format!(
842            "{label} is not a directory: {}",
843            canonical.display()
844        )));
845    }
846    Ok(canonical)
847}
848
849fn canonical_file(path: PathBuf, label: &str) -> DevelopmentResult<PathBuf> {
850    let canonical = fs::canonicalize(&path).map_err(|error| {
851        DevelopmentError::Process(format!(
852            "{label} is unavailable at {}: {error}",
853            path.display()
854        ))
855    })?;
856    if !canonical.is_file() {
857        return Err(DevelopmentError::Process(format!(
858            "{label} is not a file: {}",
859            canonical.display()
860        )));
861    }
862    Ok(canonical)
863}
864
865fn find_on_path(name: &str) -> Option<PathBuf> {
866    std::env::var_os("PATH").and_then(|path| {
867        std::env::split_paths(&path)
868            .map(|directory| directory.join(name))
869            .find(|candidate| candidate.is_file())
870    })
871}
872
873fn validate_options(options: &PiRuntimeOptions) -> DevelopmentResult<()> {
874    if options.session_dir.as_os_str().is_empty() {
875        return Err(DevelopmentError::InvalidInput(
876            "Pi session directory is required".into(),
877        ));
878    }
879    for (label, value, limit) in [
880        ("Pi session name", options.name.as_deref(), 1024),
881        ("Pi model", options.model.as_deref(), 1024),
882        ("Pi thinking level", options.thinking.as_deref(), 128),
883        (
884            "Pi system prompt",
885            options.additional_system_prompt.as_deref(),
886            128 * 1024,
887        ),
888    ] {
889        if value.is_some_and(|value| value.len() > limit || value.contains('\0')) {
890            return Err(DevelopmentError::InvalidInput(format!("invalid {label}")));
891        }
892    }
893    Ok(())
894}
895
896#[cfg(test)]
897mod tests {
898    use super::*;
899
900    fn response(runtime: &mut GlassPiRuntime, request: PiSessionRequest) -> Value {
901        let id = runtime.start_request(request).unwrap();
902        loop {
903            let value = runtime
904                .recv_event_timeout(Duration::from_secs(10))
905                .unwrap()
906                .expect("native SDK response");
907            if value.get("type").and_then(Value::as_str) == Some("response")
908                && value.get("id").and_then(Value::as_str) == Some(&id)
909            {
910                return value;
911            }
912        }
913    }
914
915    #[test]
916    fn request_mapping_uses_native_sdk_operations() {
917        assert_eq!(request_parts(PiSessionRequest::Hello).0, "hello");
918        assert_eq!(
919            request_parts(PiSessionRequest::FollowUp {
920                text: "next".into()
921            })
922            .0,
923            "followUp"
924        );
925        assert_eq!(request_parts(PiSessionRequest::SessionStats).0, "stats");
926    }
927
928    #[test]
929    fn runtime_asset_never_invokes_pi_rpc_cli() {
930        assert!(!RUNTIME_SOURCE.contains("--mode"));
931        assert!(!RUNTIME_SOURCE.contains("--mode rpc"));
932        assert!(RUNTIME_SOURCE.contains("createAgentSession"));
933        assert!(RUNTIME_SOURCE.contains("SessionManager"));
934    }
935
936    #[test]
937    fn readiness_version_and_expiry_checks_are_deterministic() {
938        assert_eq!(parse_version("v22.19.0"), Some((22, 19, 0)));
939        assert_eq!(parse_version("0.84.1-beta.1"), Some((0, 84, 1)));
940        assert_eq!(parse_version("invalid"), None);
941        assert!(credential_expired(&serde_json::json!({"expires":1})));
942        assert!(!credential_expired(&serde_json::json!({
943            "expires":9_999_999_999_u64
944        })));
945        assert!(!credential_expired(&serde_json::json!({"type":"api_key"})));
946    }
947
948    #[test]
949    fn native_sdk_starts_and_reports_capabilities_when_installed() {
950        if locate_sdk_entry().is_err() {
951            return;
952        }
953        let root =
954            std::env::temp_dir().join(format!("glass-pi-native-sdk-test-{}", std::process::id()));
955        let sessions = root.join("sessions");
956        fs::create_dir_all(&root).unwrap();
957        let mut runtime = GlassPiRuntime::spawn(
958            &root,
959            PiRuntimeOptions {
960                session_dir: sessions,
961                name: Some("native SDK contract test".into()),
962                ..PiRuntimeOptions::default()
963            },
964        )
965        .unwrap();
966        let hello = response(&mut runtime, PiSessionRequest::Hello);
967        assert_eq!(hello.get("ok").and_then(Value::as_bool), Some(true));
968        assert_eq!(
969            hello.pointer("/result/protocol").and_then(Value::as_str),
970            Some("glass-pi-sdk-v1")
971        );
972        let named = response(
973            &mut runtime,
974            PiSessionRequest::SetSessionName {
975                name: "renamed SDK session".into(),
976            },
977        );
978        assert_eq!(named.get("ok").and_then(Value::as_bool), Some(true));
979        assert_eq!(
980            response(&mut runtime, PiSessionRequest::SessionStats)
981                .get("ok")
982                .and_then(Value::as_bool),
983            Some(true)
984        );
985        assert!(
986            response(&mut runtime, PiSessionRequest::Tree)
987                .pointer("/result")
988                .is_some()
989        );
990        assert!(
991            response(&mut runtime, PiSessionRequest::Messages)
992                .pointer("/result")
993                .is_some()
994        );
995        let cloned = response(&mut runtime, PiSessionRequest::CloneSession);
996        assert_eq!(
997            cloned.get("ok").and_then(Value::as_bool),
998            Some(false),
999            "{cloned}"
1000        );
1001        assert!(
1002            cloned
1003                .get("error")
1004                .and_then(Value::as_str)
1005                .is_some_and(|error| error.contains("empty or invalid"))
1006        );
1007        assert_eq!(
1008            response(&mut runtime, PiSessionRequest::NewSession)
1009                .get("ok")
1010                .and_then(Value::as_bool),
1011            Some(true)
1012        );
1013        assert!(
1014            response(&mut runtime, PiSessionRequest::ListSessions)
1015                .pointer("/result")
1016                .and_then(Value::as_array)
1017                .is_some()
1018        );
1019        let rejected = response(
1020            &mut runtime,
1021            PiSessionRequest::SwitchSession {
1022                path: root.join("outside.jsonl").display().to_string(),
1023            },
1024        );
1025        assert_eq!(rejected.get("ok").and_then(Value::as_bool), Some(false));
1026        drop(runtime);
1027        fs::remove_dir_all(&root).unwrap();
1028    }
1029}