glass-dev 0.3.9

Glass terminal-native development and browser workspace
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
//! Glass-owned host for Pi's native `AgentSession` SDK runtime.

use crate::agents::ResidentAgentBroker;
use crate::development::{DevelopmentError, DevelopmentResult, ToolCall};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
const EVENT_CAPACITY: usize = 256;
const RUNTIME_SOURCE: &str = include_str!("../assets/pi-runtime.mjs");
pub const PINNED_PI_SDK_VERSION: &str = "0.84.1";
const MINIMUM_NODE_VERSION: (u64, u64, u64) = (22, 19, 0);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PiReadinessState {
    Ready,
    Missing,
    Incompatible,
    Expired,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PiReadinessComponent {
    pub state: PiReadinessState,
    pub version: Option<String>,
    pub path: Option<PathBuf>,
    pub detail: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PiReadiness {
    pub ready: bool,
    pub node: PiReadinessComponent,
    pub sdk: PiReadinessComponent,
    pub authentication: PiReadinessComponent,
    pub provider: Option<String>,
    pub model: Option<String>,
    pub session: Option<String>,
    pub agent_dir: PathBuf,
    pub managed_root: PathBuf,
    pub remediation: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SelectedPiRuntime {
    sdk_entry: PathBuf,
    agent_dir: PathBuf,
}

#[derive(Debug, Clone)]
pub enum PiSessionRequest {
    Hello,
    Prompt { text: String },
    Steer { text: String },
    FollowUp { text: String },
    Abort,
    State,
    Models,
    SetModel { provider: String, model_id: String },
    SetThinking { level: String },
    NewSession,
    Compact { instructions: Option<String> },
    CloneSession,
    Fork { entry_id: String },
    SwitchSession { path: String },
    ListSessions,
    Entries { since: Option<String> },
    Tree,
    Messages,
    SessionStats,
    SetSessionName { name: String },
}

#[derive(Debug, Clone, Default)]
pub struct PiRuntimeOptions {
    pub unrestricted: bool,
    pub session_dir: PathBuf,
    pub name: Option<String>,
    pub model: Option<String>,
    pub thinking: Option<String>,
    pub broker: Option<ResidentAgentBroker>,
    pub additional_system_prompt: Option<String>,
    pub resume: bool,
}

pub struct GlassPiRuntime {
    child: Child,
    input: ChildStdin,
    output: Receiver<Result<Value, String>>,
    root: PathBuf,
    broker: Option<ResidentAgentBroker>,
    unrestricted: bool,
    next_id: u64,
}

impl std::fmt::Debug for GlassPiRuntime {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("GlassPiRuntime")
            .field("pid", &self.child.id())
            .field("root", &self.root)
            .finish_non_exhaustive()
    }
}

impl GlassPiRuntime {
    pub fn spawn(root: &Path, options: PiRuntimeOptions) -> DevelopmentResult<Self> {
        validate_options(&options)?;
        let root = fs::canonicalize(root)?;
        fs::create_dir_all(&options.session_dir)?;
        let session_dir = fs::canonicalize(&options.session_dir)?;
        let runtime_path = materialize_runtime()?;
        let sdk_entry = locate_sdk_entry()?;
        let agent_dir = active_agent_dir(&sdk_entry)?;
        fs::create_dir_all(&agent_dir)?;

        let mut command = Command::new("node");
        command
            .arg(&runtime_path)
            .env("GLASS_PI_SDK_ENTRY", sdk_entry)
            .env("GLASS_PI_CWD", &root)
            .env("GLASS_PI_SESSION_DIR", &session_dir)
            .env("GLASS_PI_AGENT_DIR", &agent_dir)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit());
        for (key, value) in [
            ("GLASS_PI_SESSION_NAME", options.name.as_deref()),
            ("GLASS_PI_MODEL", options.model.as_deref()),
            ("GLASS_PI_THINKING", options.thinking.as_deref()),
            (
                "GLASS_PI_SYSTEM_PROMPT",
                options.additional_system_prompt.as_deref(),
            ),
        ] {
            if let Some(value) = value {
                command.env(key, value);
            }
        }
        if options.resume {
            command.env("GLASS_PI_RESUME", "1");
        }

        let mut child = command.spawn().map_err(|error| {
            DevelopmentError::Process(format!("failed to start Glass Pi SDK runtime: {error}"))
        })?;
        let input = child
            .stdin
            .take()
            .ok_or_else(|| DevelopmentError::Process("Pi runtime stdin is unavailable".into()))?;
        let output_stream = child
            .stdout
            .take()
            .ok_or_else(|| DevelopmentError::Process("Pi runtime stdout is unavailable".into()))?;
        let (sender, output) = mpsc::sync_channel(EVENT_CAPACITY);
        thread::Builder::new()
            .name("glass-pi-sdk-output".into())
            .spawn(move || read_frames(output_stream, sender))?;

        let mut runtime = Self {
            child,
            input,
            output,
            root,
            broker: options.broker,
            unrestricted: options.unrestricted,
            next_id: 1,
        };
        match runtime.recv_raw(Duration::from_secs(15))? {
            Some(value) if value.get("type").and_then(Value::as_str) == Some("ready") => {
                Ok(runtime)
            }
            Some(value) => Err(DevelopmentError::Process(format!(
                "Pi SDK runtime emitted an unexpected startup frame: {value}"
            ))),
            None => Err(DevelopmentError::Process(
                "Pi SDK runtime did not become ready within 15 seconds".into(),
            )),
        }
    }

    pub fn start_request(&mut self, request: PiSessionRequest) -> DevelopmentResult<String> {
        let (operation, params) = request_parts(request);
        let id = format!("glass-{}", self.next_id);
        self.next_id = self.next_id.saturating_add(1);
        self.send(&json!({"id": id, "operation": operation, "params": params}))?;
        Ok(id)
    }

    pub fn recv_event_timeout(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
        let deadline = Instant::now() + timeout;
        loop {
            let Some(value) = self.recv_raw(deadline.saturating_duration_since(Instant::now()))?
            else {
                return Ok(None);
            };
            if value.get("type").and_then(Value::as_str) == Some("toolCall") {
                self.handle_tool_call(&value)?;
                continue;
            }
            return Ok(Some(value));
        }
    }

    fn recv_raw(&mut self, timeout: Duration) -> DevelopmentResult<Option<Value>> {
        match self.output.recv_timeout(timeout) {
            Ok(Ok(value)) => Ok(Some(value)),
            Ok(Err(error)) => Err(DevelopmentError::Process(error)),
            Err(RecvTimeoutError::Timeout) => Ok(None),
            Err(RecvTimeoutError::Disconnected) => Err(DevelopmentError::Process(
                "Pi SDK runtime event stream closed".into(),
            )),
        }
    }

    fn handle_tool_call(&mut self, value: &Value) -> DevelopmentResult<()> {
        let frame_id = value
            .get("id")
            .and_then(Value::as_str)
            .ok_or_else(|| DevelopmentError::Serialization("Pi tool frame has no id".into()))?;
        let call: ToolCall =
            serde_json::from_value(value.get("call").cloned().ok_or_else(|| {
                DevelopmentError::Serialization("Pi tool frame has no call".into())
            })?)?;
        let result = match &self.broker {
            Some(broker) => {
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_io()
                    .build()
                    .map_err(DevelopmentError::Io)?;
                runtime.block_on(crate::daemon::forward_resident_tool_call_with_context(
                    broker,
                    &call,
                    &self.root,
                    self.unrestricted,
                    self.unrestricted,
                ))
            }
            None => Err("resident Pi has no authoritative Glass daemon broker".into()),
        };
        let response = match result {
            Ok(result) => json!({
                "operation": "toolResult", "id": frame_id, "ok": true, "result": result,
            }),
            Err(error) => json!({
                "operation": "toolResult", "id": frame_id, "ok": false,
                "error": error.to_string(),
            }),
        };
        self.send(&response)
    }

    fn send(&mut self, value: &Value) -> DevelopmentResult<()> {
        let encoded = serde_json::to_vec(value)?;
        if encoded.is_empty() || encoded.len() > MAX_FRAME_BYTES {
            return Err(DevelopmentError::InvalidInput(
                "Pi SDK command exceeds the framed protocol limit".into(),
            ));
        }
        self.input
            .write_all(&(encoded.len() as u32).to_be_bytes())?;
        self.input.write_all(&encoded)?;
        self.input.flush()?;
        Ok(())
    }
}

impl Drop for GlassPiRuntime {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

fn request_parts(request: PiSessionRequest) -> (&'static str, Value) {
    match request {
        PiSessionRequest::Hello => ("hello", Value::Null),
        PiSessionRequest::Prompt { text } => ("prompt", json!({"text": text})),
        PiSessionRequest::Steer { text } => ("steer", json!({"text": text})),
        PiSessionRequest::FollowUp { text } => ("followUp", json!({"text": text})),
        PiSessionRequest::Abort => ("abort", Value::Null),
        PiSessionRequest::State => ("state", Value::Null),
        PiSessionRequest::Models => ("models", Value::Null),
        PiSessionRequest::SetModel { provider, model_id } => (
            "setModel",
            json!({"provider": provider, "modelId": model_id}),
        ),
        PiSessionRequest::SetThinking { level } => ("setThinking", json!({"level": level})),
        PiSessionRequest::NewSession => ("newSession", Value::Null),
        PiSessionRequest::Compact { instructions } => {
            ("compact", json!({"instructions": instructions}))
        }
        PiSessionRequest::CloneSession => ("cloneSession", Value::Null),
        PiSessionRequest::Fork { entry_id } => ("fork", json!({"entryId": entry_id})),
        PiSessionRequest::SwitchSession { path } => ("switchSession", json!({"path": path})),
        PiSessionRequest::ListSessions => ("listSessions", Value::Null),
        PiSessionRequest::Entries { since } => ("entries", json!({"since": since})),
        PiSessionRequest::Tree => ("tree", Value::Null),
        PiSessionRequest::Messages => ("messages", Value::Null),
        PiSessionRequest::SessionStats => ("stats", Value::Null),
        PiSessionRequest::SetSessionName { name } => ("setName", json!({"name": name})),
    }
}

fn read_frames(mut stream: impl Read, sender: mpsc::SyncSender<Result<Value, String>>) {
    loop {
        let mut header = [0_u8; 4];
        if let Err(error) = stream.read_exact(&mut header) {
            let _ = sender.send(Err(format!("Pi SDK runtime frame header failed: {error}")));
            return;
        }
        let length = u32::from_be_bytes(header) as usize;
        if length == 0 || length > MAX_FRAME_BYTES {
            let _ = sender.send(Err("Pi SDK runtime emitted an invalid frame length".into()));
            return;
        }
        let mut encoded = vec![0_u8; length];
        if let Err(error) = stream.read_exact(&mut encoded) {
            let _ = sender.send(Err(format!("Pi SDK runtime frame body failed: {error}")));
            return;
        }
        let value = serde_json::from_slice(&encoded).map_err(|error| error.to_string());
        if sender.send(value).is_err() {
            return;
        }
    }
}

pub fn pi_readiness() -> DevelopmentResult<PiReadiness> {
    let managed_root = managed_pi_root()?;
    let node = node_readiness();
    let sdk_candidate = locate_sdk_candidate();
    let (sdk, agent_dir) = match sdk_candidate {
        Ok((path, source)) => {
            let version = sdk_version(&path);
            let compatible = version
                .as_deref()
                .and_then(parse_version)
                .is_some_and(|version| version >= (0, 84, 1));
            let state = if compatible {
                PiReadinessState::Ready
            } else {
                PiReadinessState::Incompatible
            };
            let agent_dir = active_agent_dir(&path)?;
            (
                PiReadinessComponent {
                    state,
                    version,
                    path: Some(path),
                    detail: if compatible {
                        format!("compatible {source} Pi SDK")
                    } else {
                        format!("{source} Pi SDK version is missing or older than 0.84.1")
                    },
                },
                agent_dir,
            )
        }
        Err(error) => (
            PiReadinessComponent {
                state: PiReadinessState::Missing,
                version: None,
                path: None,
                detail: error.to_string(),
            },
            managed_agent_dir()?,
        ),
    };
    let (authentication, provider) = authentication_readiness(&agent_dir);
    let ready = node.state == PiReadinessState::Ready
        && sdk.state == PiReadinessState::Ready
        && authentication.state == PiReadinessState::Ready;
    let mut remediation = Vec::new();
    if node.state != PiReadinessState::Ready {
        remediation.push(format!(
            "Install Node {}.{}.{} or newer, then run `glass agent setup`.",
            MINIMUM_NODE_VERSION.0, MINIMUM_NODE_VERSION.1, MINIMUM_NODE_VERSION.2
        ));
    }
    if sdk.state != PiReadinessState::Ready {
        remediation.push("Run `glass agent setup` to install the pinned managed Pi SDK, or select an existing SDK with `--sdk-entry`.".into());
    }
    if authentication.state != PiReadinessState::Ready {
        remediation.push("Run `glass agent setup --login`, use Pi `/login`, or configure a supported provider API-key environment variable.".into());
    }
    Ok(PiReadiness {
        ready,
        node,
        sdk,
        authentication,
        provider,
        model: None,
        session: newest_session(&agent_dir),
        agent_dir,
        managed_root,
        remediation,
    })
}

pub fn setup_pi_runtime(
    sdk_entry: Option<&Path>,
    agent_dir: Option<&Path>,
    update: bool,
    login: bool,
) -> DevelopmentResult<PiReadiness> {
    let node = node_readiness();
    if node.state != PiReadinessState::Ready {
        return Err(DevelopmentError::Process(node.detail));
    }
    let managed_root = managed_pi_root()?;
    fs::create_dir_all(&managed_root)?;
    let selected = if let Some(entry) = sdk_entry {
        let entry = canonical_file(entry.to_path_buf(), "selected Pi SDK")?;
        let agent_dir = match agent_dir {
            Some(path) => canonical_directory(path, "selected Pi agent directory")?,
            None => default_pi_agent_dir()?,
        };
        SelectedPiRuntime {
            sdk_entry: entry,
            agent_dir,
        }
    } else {
        let entry = managed_sdk_entry()?;
        let installed = sdk_version(&entry).as_deref() == Some(PINNED_PI_SDK_VERSION);
        if update || !installed {
            install_managed_sdk(&managed_root)?;
        }
        SelectedPiRuntime {
            sdk_entry: canonical_file(managed_sdk_entry()?, "managed Pi SDK")?,
            agent_dir: managed_agent_dir()?,
        }
    };
    fs::create_dir_all(&selected.agent_dir)?;
    write_selected_runtime(&selected)?;
    if login {
        run_pi_login(&selected)?;
    }
    pi_readiness()
}

fn node_readiness() -> PiReadinessComponent {
    let path = find_on_path(if cfg!(windows) { "node.exe" } else { "node" });
    let Some(path) = path else {
        return PiReadinessComponent {
            state: PiReadinessState::Missing,
            version: None,
            path: None,
            detail: "Node is not available on PATH".into(),
        };
    };
    match Command::new(&path).arg("--version").output() {
        Ok(output) if output.status.success() => {
            let version = String::from_utf8_lossy(&output.stdout)
                .trim()
                .trim_start_matches('v')
                .to_string();
            let compatible =
                parse_version(&version).is_some_and(|value| value >= MINIMUM_NODE_VERSION);
            PiReadinessComponent {
                state: if compatible {
                    PiReadinessState::Ready
                } else {
                    PiReadinessState::Incompatible
                },
                version: Some(version.clone()),
                path: Some(path),
                detail: if compatible {
                    "compatible Node runtime".into()
                } else {
                    format!("Node {version} is older than 22.19.0")
                },
            }
        }
        Ok(output) => PiReadinessComponent {
            state: PiReadinessState::Unknown,
            version: None,
            path: Some(path),
            detail: format!("Node version check exited {}", output.status),
        },
        Err(error) => PiReadinessComponent {
            state: PiReadinessState::Unknown,
            version: None,
            path: Some(path),
            detail: format!("Node version check failed: {error}"),
        },
    }
}

fn authentication_readiness(agent_dir: &Path) -> (PiReadinessComponent, Option<String>) {
    const PROVIDER_KEYS: [(&str, &str); 10] = [
        ("ANTHROPIC_API_KEY", "anthropic"),
        ("OPENAI_API_KEY", "openai"),
        ("GEMINI_API_KEY", "google"),
        ("GOOGLE_API_KEY", "google"),
        ("MISTRAL_API_KEY", "mistral"),
        ("GROQ_API_KEY", "groq"),
        ("XAI_API_KEY", "xai"),
        ("OPENROUTER_API_KEY", "openrouter"),
        ("ZAI_API_KEY", "zai"),
        ("AWS_BEARER_TOKEN_BEDROCK", "amazon-bedrock"),
    ];
    if let Some((_, provider)) = PROVIDER_KEYS
        .iter()
        .find(|(key, _)| std::env::var_os(key).is_some())
    {
        return (
            PiReadinessComponent {
                state: PiReadinessState::Ready,
                version: None,
                path: None,
                detail: format!("{provider} authentication is available from the environment"),
            },
            Some((*provider).into()),
        );
    }
    let path = agent_dir.join("auth.json");
    let encoded = match fs::read(&path) {
        Ok(encoded) => encoded,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return (
                PiReadinessComponent {
                    state: PiReadinessState::Missing,
                    version: None,
                    path: Some(path),
                    detail: "no Pi credentials are configured".into(),
                },
                None,
            );
        }
        Err(error) => {
            return (
                PiReadinessComponent {
                    state: PiReadinessState::Unknown,
                    version: None,
                    path: Some(path),
                    detail: format!("Pi credential metadata is unreadable: {error}"),
                },
                None,
            );
        }
    };
    let value: Value = match serde_json::from_slice(&encoded) {
        Ok(value) => value,
        Err(error) => {
            return (
                PiReadinessComponent {
                    state: PiReadinessState::Unknown,
                    version: None,
                    path: Some(path),
                    detail: format!("Pi credential metadata is invalid JSON: {error}"),
                },
                None,
            );
        }
    };
    let providers = value
        .as_object()
        .map(|items| items.keys().take(8).cloned().collect::<Vec<_>>())
        .unwrap_or_default();
    if providers.is_empty() {
        return (
            PiReadinessComponent {
                state: PiReadinessState::Missing,
                version: None,
                path: Some(path),
                detail: "Pi credential file contains no providers".into(),
            },
            None,
        );
    }
    let expired = value
        .as_object()
        .is_some_and(|items| items.values().all(credential_expired));
    let state = if expired {
        PiReadinessState::Expired
    } else {
        PiReadinessState::Ready
    };
    (
        PiReadinessComponent {
            state,
            version: None,
            path: Some(path),
            detail: if expired {
                "all stored Pi credentials appear expired".into()
            } else {
                format!("stored Pi credentials for {}", providers.join(", "))
            },
        },
        providers.first().cloned(),
    )
}

fn credential_expired(value: &Value) -> bool {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    ["expires", "expiresAt", "expires_at", "expiration"]
        .iter()
        .find_map(|key| value.get(key))
        .and_then(|value| value.as_u64().or_else(|| value.as_str()?.parse().ok()))
        .is_some_and(|expires| {
            let seconds = if expires > 10_000_000_000 {
                expires / 1_000
            } else {
                expires
            };
            seconds <= now
        })
}

fn newest_session(agent_dir: &Path) -> Option<String> {
    let sessions = agent_dir.join("sessions");
    let mut newest = None;
    for entry in fs::read_dir(sessions).ok()? {
        let entry = entry.ok()?;
        let modified = entry.metadata().ok()?.modified().ok()?;
        if newest
            .as_ref()
            .is_none_or(|(current, _)| modified > *current)
        {
            newest = Some((modified, entry.file_name().to_string_lossy().into_owned()));
        }
    }
    newest.map(|(_, name)| name)
}

fn materialize_runtime() -> DevelopmentResult<PathBuf> {
    let base = dirs::cache_dir()
        .ok_or_else(|| DevelopmentError::Process("user cache directory is unavailable".into()))?
        .join("glass")
        .join("pi-sdk-v1");
    fs::create_dir_all(&base)?;
    let path = base.join("runtime.mjs");
    if fs::read_to_string(&path).ok().as_deref() != Some(RUNTIME_SOURCE) {
        let temporary = base.join(format!("runtime-{}.tmp", std::process::id()));
        fs::write(&temporary, RUNTIME_SOURCE)?;
        fs::rename(temporary, &path)?;
    }
    Ok(path)
}

fn locate_sdk_entry() -> DevelopmentResult<PathBuf> {
    locate_sdk_candidate().map(|(path, _)| path)
}

fn locate_sdk_candidate() -> DevelopmentResult<(PathBuf, &'static str)> {
    if let Some(path) = std::env::var_os("GLASS_PI_SDK_ENTRY") {
        return canonical_file(PathBuf::from(path), "GLASS_PI_SDK_ENTRY")
            .map(|path| (path, "environment-selected"));
    }
    if let Some(selected) = read_selected_runtime()
        && let Ok(path) = canonical_file(selected.sdk_entry, "selected Pi SDK")
    {
        return Ok((path, "Glass-selected"));
    }
    let managed = managed_sdk_entry()?;
    if managed.is_file() {
        return fs::canonicalize(managed)
            .map(|path| (path, "Glass-managed"))
            .map_err(DevelopmentError::Io);
    }
    let local = Path::new(env!("CARGO_MANIFEST_DIR")).join(
        "../../packages/pi-runtime/node_modules/@earendil-works/pi-coding-agent/dist/index.js",
    );
    if local.is_file() {
        return fs::canonicalize(local)
            .map(|path| (path, "repository"))
            .map_err(DevelopmentError::Io);
    }
    let pi = find_on_path("pi").ok_or_else(|| {
        DevelopmentError::NotFound(
            "Pi SDK is not ready; run `glass agent setup` or select an existing installation"
                .into(),
        )
    })?;
    let cli = fs::canonicalize(pi)?;
    canonical_file(cli.with_file_name("index.js"), "installed Pi SDK").map(|path| (path, "system"))
}

fn active_agent_dir(sdk_entry: &Path) -> DevelopmentResult<PathBuf> {
    if let Some(path) = std::env::var_os("GLASS_PI_AGENT_DIR") {
        let path = PathBuf::from(path);
        fs::create_dir_all(&path)?;
        return fs::canonicalize(path).map_err(DevelopmentError::Io);
    }
    if let Some(selected) = read_selected_runtime()
        && canonical_file(selected.sdk_entry, "selected Pi SDK")
            .is_ok_and(|selected| selected == sdk_entry)
    {
        fs::create_dir_all(&selected.agent_dir)?;
        return fs::canonicalize(selected.agent_dir).map_err(DevelopmentError::Io);
    }
    managed_agent_dir()
}

fn managed_pi_root() -> DevelopmentResult<PathBuf> {
    dirs::data_local_dir()
        .ok_or_else(|| DevelopmentError::Process("user local-data directory is unavailable".into()))
        .map(|root| root.join("glass").join("runtime").join("pi"))
}

fn managed_agent_dir() -> DevelopmentResult<PathBuf> {
    Ok(managed_pi_root()?.join("agent"))
}

fn default_pi_agent_dir() -> DevelopmentResult<PathBuf> {
    dirs::home_dir()
        .ok_or_else(|| DevelopmentError::Process("user home directory is unavailable".into()))
        .map(|home| home.join(".pi").join("agent"))
}

fn managed_sdk_entry() -> DevelopmentResult<PathBuf> {
    Ok(managed_pi_root()?
        .join("node_modules")
        .join("@earendil-works")
        .join("pi-coding-agent")
        .join("dist")
        .join("index.js"))
}

fn selected_runtime_path() -> DevelopmentResult<PathBuf> {
    Ok(managed_pi_root()?.join("selected-runtime.json"))
}

fn read_selected_runtime() -> Option<SelectedPiRuntime> {
    let path = selected_runtime_path().ok()?;
    serde_json::from_slice(&fs::read(path).ok()?).ok()
}

fn write_selected_runtime(selected: &SelectedPiRuntime) -> DevelopmentResult<()> {
    let path = selected_runtime_path()?;
    let parent = path.parent().ok_or_else(|| {
        DevelopmentError::Process("selected Pi runtime path has no parent".into())
    })?;
    fs::create_dir_all(parent)?;
    let temporary = parent.join(format!("selected-runtime-{}.tmp", std::process::id()));
    fs::write(&temporary, serde_json::to_vec_pretty(selected)?)?;
    fs::rename(temporary, path)?;
    Ok(())
}

fn install_managed_sdk(root: &Path) -> DevelopmentResult<()> {
    let manifest = serde_json::json!({
        "name":"@glass-dev/managed-pi-runtime",
        "private":true,
        "dependencies":{"@earendil-works/pi-coding-agent":PINNED_PI_SDK_VERSION}
    });
    fs::write(
        root.join("package.json"),
        serde_json::to_vec_pretty(&manifest)?,
    )?;
    let status = Command::new(if cfg!(windows) { "npm.cmd" } else { "npm" })
        .args([
            "install",
            "--ignore-scripts",
            "--no-audit",
            "--no-fund",
            "--save-exact",
            &format!("@earendil-works/pi-coding-agent@{PINNED_PI_SDK_VERSION}"),
        ])
        .current_dir(root)
        .status()
        .map_err(|error| DevelopmentError::Process(format!("failed to start npm: {error}")))?;
    if !status.success() {
        return Err(DevelopmentError::Process(format!(
            "managed Pi SDK installation exited {status}"
        )));
    }
    Ok(())
}

fn run_pi_login(selected: &SelectedPiRuntime) -> DevelopmentResult<()> {
    let managed_cli = managed_pi_root()?
        .join("node_modules")
        .join(".bin")
        .join(if cfg!(windows) { "pi.cmd" } else { "pi" });
    let cli = if managed_cli.is_file() {
        managed_cli
    } else {
        find_on_path(if cfg!(windows) { "pi.cmd" } else { "pi" })
            .ok_or_else(|| DevelopmentError::NotFound("Pi CLI for interactive `/login`".into()))?
    };
    eprintln!(
        "Glass is opening Pi with its selected credential directory. Run `/login`, then exit Pi to return to Glass."
    );
    let status = Command::new(cli)
        .env("PI_CODING_AGENT_DIR", &selected.agent_dir)
        .status()
        .map_err(|error| DevelopmentError::Process(format!("failed to open Pi login: {error}")))?;
    if !status.success() {
        return Err(DevelopmentError::Process(format!(
            "Pi login session exited {status}"
        )));
    }
    Ok(())
}

fn sdk_version(entry: &Path) -> Option<String> {
    let package = entry.parent()?.parent()?.join("package.json");
    let value: Value = serde_json::from_slice(&fs::read(package).ok()?).ok()?;
    value.get("version")?.as_str().map(str::to_string)
}

fn parse_version(value: &str) -> Option<(u64, u64, u64)> {
    let core = value
        .trim()
        .trim_start_matches('v')
        .split(['-', '+'])
        .next()?;
    let mut parts = core.split('.');
    Some((
        parts.next()?.parse().ok()?,
        parts.next()?.parse().ok()?,
        parts.next()?.parse().ok()?,
    ))
}

fn canonical_directory(path: &Path, label: &str) -> DevelopmentResult<PathBuf> {
    let canonical = fs::canonicalize(path).map_err(|error| {
        DevelopmentError::Process(format!(
            "{label} is unavailable at {}: {error}",
            path.display()
        ))
    })?;
    if !canonical.is_dir() {
        return Err(DevelopmentError::Process(format!(
            "{label} is not a directory: {}",
            canonical.display()
        )));
    }
    Ok(canonical)
}

fn canonical_file(path: PathBuf, label: &str) -> DevelopmentResult<PathBuf> {
    let canonical = fs::canonicalize(&path).map_err(|error| {
        DevelopmentError::Process(format!(
            "{label} is unavailable at {}: {error}",
            path.display()
        ))
    })?;
    if !canonical.is_file() {
        return Err(DevelopmentError::Process(format!(
            "{label} is not a file: {}",
            canonical.display()
        )));
    }
    Ok(canonical)
}

fn find_on_path(name: &str) -> Option<PathBuf> {
    std::env::var_os("PATH").and_then(|path| {
        std::env::split_paths(&path)
            .map(|directory| directory.join(name))
            .find(|candidate| candidate.is_file())
    })
}

fn validate_options(options: &PiRuntimeOptions) -> DevelopmentResult<()> {
    if options.session_dir.as_os_str().is_empty() {
        return Err(DevelopmentError::InvalidInput(
            "Pi session directory is required".into(),
        ));
    }
    for (label, value, limit) in [
        ("Pi session name", options.name.as_deref(), 1024),
        ("Pi model", options.model.as_deref(), 1024),
        ("Pi thinking level", options.thinking.as_deref(), 128),
        (
            "Pi system prompt",
            options.additional_system_prompt.as_deref(),
            128 * 1024,
        ),
    ] {
        if value.is_some_and(|value| value.len() > limit || value.contains('\0')) {
            return Err(DevelopmentError::InvalidInput(format!("invalid {label}")));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn response(runtime: &mut GlassPiRuntime, request: PiSessionRequest) -> Value {
        let id = runtime.start_request(request).unwrap();
        loop {
            let value = runtime
                .recv_event_timeout(Duration::from_secs(10))
                .unwrap()
                .expect("native SDK response");
            if value.get("type").and_then(Value::as_str) == Some("response")
                && value.get("id").and_then(Value::as_str) == Some(&id)
            {
                return value;
            }
        }
    }

    #[test]
    fn request_mapping_uses_native_sdk_operations() {
        assert_eq!(request_parts(PiSessionRequest::Hello).0, "hello");
        assert_eq!(
            request_parts(PiSessionRequest::FollowUp {
                text: "next".into()
            })
            .0,
            "followUp"
        );
        assert_eq!(request_parts(PiSessionRequest::SessionStats).0, "stats");
    }

    #[test]
    fn runtime_asset_never_invokes_pi_rpc_cli() {
        assert!(!RUNTIME_SOURCE.contains("--mode"));
        assert!(!RUNTIME_SOURCE.contains("--mode rpc"));
        assert!(RUNTIME_SOURCE.contains("createAgentSession"));
        assert!(RUNTIME_SOURCE.contains("SessionManager"));
    }

    #[test]
    fn readiness_version_and_expiry_checks_are_deterministic() {
        assert_eq!(parse_version("v22.19.0"), Some((22, 19, 0)));
        assert_eq!(parse_version("0.84.1-beta.1"), Some((0, 84, 1)));
        assert_eq!(parse_version("invalid"), None);
        assert!(credential_expired(&serde_json::json!({"expires":1})));
        assert!(!credential_expired(&serde_json::json!({
            "expires":9_999_999_999_u64
        })));
        assert!(!credential_expired(&serde_json::json!({"type":"api_key"})));
    }

    #[test]
    fn native_sdk_starts_and_reports_capabilities_when_installed() {
        if locate_sdk_entry().is_err() {
            return;
        }
        let root =
            std::env::temp_dir().join(format!("glass-pi-native-sdk-test-{}", std::process::id()));
        let sessions = root.join("sessions");
        fs::create_dir_all(&root).unwrap();
        let mut runtime = GlassPiRuntime::spawn(
            &root,
            PiRuntimeOptions {
                session_dir: sessions,
                name: Some("native SDK contract test".into()),
                ..PiRuntimeOptions::default()
            },
        )
        .unwrap();
        let hello = response(&mut runtime, PiSessionRequest::Hello);
        assert_eq!(hello.get("ok").and_then(Value::as_bool), Some(true));
        assert_eq!(
            hello.pointer("/result/protocol").and_then(Value::as_str),
            Some("glass-pi-sdk-v1")
        );
        let named = response(
            &mut runtime,
            PiSessionRequest::SetSessionName {
                name: "renamed SDK session".into(),
            },
        );
        assert_eq!(named.get("ok").and_then(Value::as_bool), Some(true));
        assert_eq!(
            response(&mut runtime, PiSessionRequest::SessionStats)
                .get("ok")
                .and_then(Value::as_bool),
            Some(true)
        );
        assert!(
            response(&mut runtime, PiSessionRequest::Tree)
                .pointer("/result")
                .is_some()
        );
        assert!(
            response(&mut runtime, PiSessionRequest::Messages)
                .pointer("/result")
                .is_some()
        );
        let cloned = response(&mut runtime, PiSessionRequest::CloneSession);
        assert_eq!(
            cloned.get("ok").and_then(Value::as_bool),
            Some(false),
            "{cloned}"
        );
        assert!(
            cloned
                .get("error")
                .and_then(Value::as_str)
                .is_some_and(|error| error.contains("empty or invalid"))
        );
        assert_eq!(
            response(&mut runtime, PiSessionRequest::NewSession)
                .get("ok")
                .and_then(Value::as_bool),
            Some(true)
        );
        assert!(
            response(&mut runtime, PiSessionRequest::ListSessions)
                .pointer("/result")
                .and_then(Value::as_array)
                .is_some()
        );
        let rejected = response(
            &mut runtime,
            PiSessionRequest::SwitchSession {
                path: root.join("outside.jsonl").display().to_string(),
            },
        );
        assert_eq!(rejected.get("ok").and_then(Value::as_bool), Some(false));
        drop(runtime);
        fs::remove_dir_all(&root).unwrap();
    }
}