Skip to main content

glass_dev/
daemon.rs

1//! Local authenticated daemon that owns complete development workspaces.
2
3use crate::development::{Actor, ToolAuthorization, ToolCall};
4use crate::{
5    DevelopmentToolContext, DevelopmentWorkspace, ResidentAgentBroker, WorkspaceTrustStore,
6};
7use glass_browser::cli::args::DaemonCommand;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use std::cell::RefCell;
11use std::collections::{BTreeMap, VecDeque};
12use std::path::{Path, PathBuf};
13use std::rc::Rc;
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
17
18const PROTOCOL_VERSION: u32 = 1;
19const MAX_REQUEST_BYTES: usize = 1024 * 1024;
20const MAX_RESPONSE_BYTES: usize = 1024 * 1024;
21const MAX_WORKSPACES: usize = 8;
22const MAX_CLIENTS: usize = 16;
23const WORKSPACE_COMMAND_CAPACITY: usize = 64;
24const WORKSPACE_EVENT_CAPACITY: usize = 512;
25const MAX_EVENT_BATCH: usize = 256;
26const DAEMON_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
27const OPERATION_CAPACITY: usize = 128;
28const OPERATION_EVENT_CAPACITY: usize = 512;
29
30type WorkspaceRegistry = Rc<RefCell<BTreeMap<String, WorkspaceActorHandle>>>;
31type QueuedOperation = (String, ToolCall, Box<DevelopmentToolContext>);
32type OperationExecution = (
33    DevelopmentWorkspace,
34    String,
35    String,
36    u64,
37    Result<Value, String>,
38);
39type OperationCompletion = Result<OperationExecution, tokio::task::JoinError>;
40
41#[derive(Clone)]
42struct WorkspaceActorHandle {
43    sender: tokio::sync::mpsc::Sender<WorkspaceCommand>,
44    summary: Value,
45    operations: Arc<Mutex<OperationRegistry>>,
46}
47
48enum WorkspaceCommand {
49    Inspect {
50        response: tokio::sync::oneshot::Sender<Result<Value, String>>,
51    },
52    Tool {
53        call: ToolCall,
54        context: Box<DevelopmentToolContext>,
55        response: tokio::sync::oneshot::Sender<Result<Value, String>>,
56    },
57    SubmitOperation {
58        operation_id: String,
59        call: ToolCall,
60        context: Box<DevelopmentToolContext>,
61    },
62    Events {
63        since: u64,
64        limit: usize,
65        response: tokio::sync::oneshot::Sender<Value>,
66    },
67    Shutdown {
68        response: tokio::sync::oneshot::Sender<()>,
69    },
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73#[serde(rename_all = "camelCase")]
74pub struct DevelopmentDaemonStatus {
75    pub protocol_version: u32,
76    pub state: String,
77    pub pid: u32,
78    pub socket: PathBuf,
79    pub status_path: PathBuf,
80    pub token_path: PathBuf,
81    pub started_at_ms: u128,
82    pub workspace_count: usize,
83    pub client_count: usize,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88pub struct DevelopmentDaemonRequest {
89    pub id: String,
90    pub token: String,
91    pub operation: String,
92    pub workspace_id: Option<String>,
93    pub root: Option<PathBuf>,
94    pub call: Option<ToolCall>,
95    pub expected_generation: Option<u64>,
96    pub expected_project_revision: Option<u64>,
97    #[serde(default)]
98    pub allow_mutation: bool,
99    #[serde(default)]
100    pub confirmed: bool,
101    pub actor: Option<String>,
102    #[serde(default)]
103    pub since: Option<u64>,
104    #[serde(default)]
105    pub limit: Option<usize>,
106    pub operation_id: Option<String>,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub enum DevelopmentOperationState {
112    Queued,
113    Running,
114    Succeeded,
115    Failed,
116    Cancelled,
117    Indeterminate,
118}
119
120impl DevelopmentOperationState {
121    fn terminal(self) -> bool {
122        matches!(
123            self,
124            Self::Succeeded | Self::Failed | Self::Cancelled | Self::Indeterminate
125        )
126    }
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131pub struct DevelopmentOperation {
132    pub id: String,
133    pub workspace_id: String,
134    pub actor: String,
135    pub operation_type: String,
136    pub state: DevelopmentOperationState,
137    pub submitted_at_ms: u128,
138    pub started_at_ms: Option<u128>,
139    pub completed_at_ms: Option<u128>,
140    pub revision_before: u64,
141    pub revision_after: Option<u64>,
142    pub result_ref: Option<String>,
143    pub result: Option<Value>,
144    pub failure_reason: Option<String>,
145    pub retry_safe: bool,
146    pub indeterminate: bool,
147    pub cancellation_requested: bool,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub struct DevelopmentOperationEvent {
153    pub sequence: u64,
154    pub operation_id: String,
155    pub timestamp_ms: u128,
156    pub state: DevelopmentOperationState,
157    pub message: String,
158}
159
160struct OperationRegistry {
161    workspace_id: String,
162    records: BTreeMap<String, DevelopmentOperation>,
163    order: VecDeque<String>,
164    idempotency: BTreeMap<String, String>,
165    events: VecDeque<DevelopmentOperationEvent>,
166    next_operation: u64,
167    next_event: u64,
168}
169
170impl OperationRegistry {
171    fn new(workspace_id: String) -> Self {
172        Self {
173            workspace_id,
174            records: BTreeMap::new(),
175            order: VecDeque::new(),
176            idempotency: BTreeMap::new(),
177            events: VecDeque::new(),
178            next_operation: 1,
179            next_event: 1,
180        }
181    }
182
183    fn submit(
184        &mut self,
185        request_id: &str,
186        actor: String,
187        operation_type: String,
188        revision_before: u64,
189        retry_safe: bool,
190    ) -> Result<(DevelopmentOperation, bool), String> {
191        if let Some(operation_id) = self.idempotency.get(request_id) {
192            return self
193                .records
194                .get(operation_id)
195                .cloned()
196                .map(|record| (record, false))
197                .ok_or_else(|| "operation idempotency record is inconsistent".into());
198        }
199        self.prune_terminal();
200        if self.records.len() >= OPERATION_CAPACITY {
201            return Err("workspace operation retention limit reached".into());
202        }
203        let id = format!("{}-op-{:06}", self.workspace_id, self.next_operation);
204        self.next_operation = self.next_operation.saturating_add(1);
205        let record = DevelopmentOperation {
206            id: id.clone(),
207            workspace_id: self.workspace_id.clone(),
208            actor,
209            operation_type,
210            state: DevelopmentOperationState::Queued,
211            submitted_at_ms: now_ms(),
212            started_at_ms: None,
213            completed_at_ms: None,
214            revision_before,
215            revision_after: None,
216            result_ref: None,
217            result: None,
218            failure_reason: None,
219            retry_safe,
220            indeterminate: false,
221            cancellation_requested: false,
222        };
223        self.records.insert(id.clone(), record.clone());
224        self.order.push_back(id.clone());
225        self.idempotency.insert(request_id.into(), id.clone());
226        self.event(&id, DevelopmentOperationState::Queued, "operation accepted");
227        Ok((record, true))
228    }
229
230    fn prune_terminal(&mut self) {
231        while self.records.len() >= OPERATION_CAPACITY {
232            let Some(id) = self.order.iter().find_map(|id| {
233                self.records
234                    .get(id)
235                    .is_some_and(|record| record.state.terminal())
236                    .then(|| id.clone())
237            }) else {
238                break;
239            };
240            self.order.retain(|operation_id| operation_id != &id);
241            self.records.remove(&id);
242            self.idempotency
243                .retain(|_, operation_id| operation_id != &id);
244        }
245    }
246
247    fn event(&mut self, id: &str, state: DevelopmentOperationState, message: &str) {
248        if self.events.len() == OPERATION_EVENT_CAPACITY {
249            self.events.pop_front();
250        }
251        self.events.push_back(DevelopmentOperationEvent {
252            sequence: self.next_event,
253            operation_id: id.into(),
254            timestamp_ms: now_ms(),
255            state,
256            message: message.into(),
257        });
258        self.next_event = self.next_event.saturating_add(1);
259    }
260
261    fn start(&mut self, id: &str) -> bool {
262        let Some(record) = self.records.get_mut(id) else {
263            return false;
264        };
265        if record.cancellation_requested {
266            record.state = DevelopmentOperationState::Cancelled;
267            record.completed_at_ms = Some(now_ms());
268            self.event(
269                id,
270                DevelopmentOperationState::Cancelled,
271                "cancelled before start",
272            );
273            return false;
274        }
275        record.state = DevelopmentOperationState::Running;
276        record.started_at_ms = Some(now_ms());
277        self.event(id, DevelopmentOperationState::Running, "operation started");
278        true
279    }
280
281    fn finish(&mut self, id: &str, revision_after: u64, result: Result<Value, String>) {
282        let Some(record) = self.records.get_mut(id) else {
283            return;
284        };
285        record.revision_after = Some(revision_after);
286        record.completed_at_ms = Some(now_ms());
287        let (state, message) = if record.cancellation_requested {
288            record.state = DevelopmentOperationState::Cancelled;
289            record.result = None;
290            record.failure_reason =
291                Some("operation completed after cancellation was requested".into());
292            (DevelopmentOperationState::Cancelled, "operation cancelled")
293        } else {
294            match result {
295                Ok(value) => {
296                    record.state = DevelopmentOperationState::Succeeded;
297                    record.result_ref =
298                        Some(format!("operation://{}/{}/result", self.workspace_id, id));
299                    record.result = Some(value);
300                    (DevelopmentOperationState::Succeeded, "operation succeeded")
301                }
302                Err(error) => {
303                    record.state = DevelopmentOperationState::Failed;
304                    record.failure_reason = Some(error);
305                    (DevelopmentOperationState::Failed, "operation failed")
306                }
307            }
308        };
309        self.event(id, state, message);
310    }
311
312    fn indeterminate(&mut self, id: &str, error: String) {
313        if let Some(record) = self.records.get_mut(id) {
314            record.state = DevelopmentOperationState::Indeterminate;
315            record.indeterminate = true;
316            record.failure_reason = Some(error);
317            record.completed_at_ms = Some(now_ms());
318        }
319        self.event(
320            id,
321            DevelopmentOperationState::Indeterminate,
322            "operation outcome is indeterminate",
323        );
324    }
325
326    fn cancel(&mut self, id: &str) -> Result<DevelopmentOperation, String> {
327        let (state, record) = {
328            let record = self
329                .records
330                .get_mut(id)
331                .ok_or_else(|| "unknown workspace operation".to_string())?;
332            if !record.state.terminal() {
333                record.cancellation_requested = true;
334                if record.state == DevelopmentOperationState::Queued {
335                    record.state = DevelopmentOperationState::Cancelled;
336                    record.completed_at_ms = Some(now_ms());
337                }
338            }
339            (record.state, record.clone())
340        };
341        self.event(id, state, "cancellation requested");
342        Ok(record)
343    }
344}
345
346#[derive(Debug, Clone, Serialize, Deserialize)]
347#[serde(rename_all = "camelCase")]
348pub struct DevelopmentDaemonEvent {
349    pub sequence: u64,
350    pub timestamp_ms: u128,
351    pub kind: String,
352    pub workspace_id: String,
353    pub tool_call_id: Option<String>,
354    pub success: bool,
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
358#[serde(rename_all = "camelCase")]
359pub struct DevelopmentDaemonResponse {
360    pub id: String,
361    pub ok: bool,
362    pub result: Value,
363    pub error: Option<String>,
364}
365
366pub async fn dispatch(action: &DaemonCommand) -> Result<(), Box<dyn std::error::Error>> {
367    match action {
368        DaemonCommand::Start { socket, status } => {
369            println!(
370                "{}",
371                serde_json::to_string_pretty(&start(socket.as_deref(), status.as_deref()).await?)?
372            );
373        }
374        DaemonCommand::Status { socket, status } | DaemonCommand::Doctor { socket, status } => {
375            println!(
376                "{}",
377                serde_json::to_string_pretty(&read_status_checked(
378                    socket.as_deref(),
379                    status.as_deref()
380                )?)?
381            );
382        }
383        DaemonCommand::Stop { socket, status } => {
384            stop(socket.as_deref(), status.as_deref())?;
385            println!("{{\"status\":\"stopped\"}}");
386        }
387        DaemonCommand::Logs { status } => {
388            let (_, default_status) = default_paths();
389            let status = status.as_deref().unwrap_or(&default_status);
390            print!("{}", bounded_log(status)?);
391        }
392        DaemonCommand::AcknowledgeRecovery { .. } => {
393            println!("{{\"status\":\"no-recovery-required\"}}");
394        }
395        DaemonCommand::Serve { socket, status } => serve(socket, status).await?,
396    }
397    Ok(())
398}
399
400pub fn default_paths() -> (PathBuf, PathBuf) {
401    #[cfg(windows)]
402    let base =
403        dirs::data_local_dir().unwrap_or_else(|| std::env::temp_dir().join("glass-current-user"));
404    #[cfg(not(windows))]
405    let base = std::env::var_os("XDG_RUNTIME_DIR")
406        .map(PathBuf::from)
407        .or_else(|| std::env::var_os("XDG_DATA_HOME").map(PathBuf::from))
408        .unwrap_or_else(|| std::env::temp_dir().join(format!("glass-{}", effective_uid())));
409    let root = base.join("glass-dev");
410    #[cfg(windows)]
411    {
412        use std::hash::{Hash, Hasher};
413        let mut hasher = std::hash::DefaultHasher::new();
414        root.hash(&mut hasher);
415        let endpoint = PathBuf::from(format!(r"\\.\pipe\glass-dev-{:016x}", hasher.finish()));
416        (endpoint, root.join("glassd.json"))
417    }
418    #[cfg(not(windows))]
419    {
420        (root.join("glassd.sock"), root.join("glassd.json"))
421    }
422}
423
424pub async fn start(
425    socket: Option<&Path>,
426    status_path: Option<&Path>,
427) -> Result<DevelopmentDaemonStatus, Box<dyn std::error::Error>> {
428    #[cfg(not(any(unix, windows)))]
429    {
430        let _ = (socket, status_path);
431        return Err("the durable development daemon currently requires Unix local sockets".into());
432    }
433    #[cfg(unix)]
434    {
435        let (default_socket, default_status) = default_paths();
436        let socket = socket.unwrap_or(&default_socket);
437        let status_path = status_path.unwrap_or(&default_status);
438        if let Ok(existing) = read_status(status_path)
439            && process_alive(existing.pid)
440        {
441            return Err(
442                format!("development daemon is already running as {}", existing.pid).into(),
443            );
444        }
445        remove_socket_if_safe(socket)?;
446        if status_path.exists() {
447            std::fs::remove_file(status_path)?;
448        }
449        std::fs::create_dir_all(socket.parent().unwrap_or_else(|| Path::new(".")))?;
450        std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
451        let log = log_path(status_path);
452        let stdout = std::fs::OpenOptions::new()
453            .create(true)
454            .append(true)
455            .open(&log)?;
456        let stderr = stdout.try_clone()?;
457        std::process::Command::new(std::env::current_exe()?)
458            .args(["daemon", "serve"])
459            .arg("--socket")
460            .arg(socket)
461            .arg("--status")
462            .arg(status_path)
463            .stdin(std::process::Stdio::null())
464            .stdout(std::process::Stdio::from(stdout))
465            .stderr(std::process::Stdio::from(stderr))
466            .spawn()?;
467        let deadline = std::time::Instant::now() + Duration::from_secs(3);
468        loop {
469            if let Ok(status) = read_status(status_path)
470                && process_alive(status.pid)
471                && status.socket == socket
472            {
473                return Ok(status);
474            }
475            if std::time::Instant::now() >= deadline {
476                return Err("development daemon did not become ready within three seconds".into());
477            }
478            tokio::time::sleep(Duration::from_millis(25)).await;
479        }
480    }
481    #[cfg(windows)]
482    {
483        let (default_socket, default_status) = default_paths();
484        let socket = socket.unwrap_or(&default_socket);
485        let status_path = status_path.unwrap_or(&default_status);
486        validate_windows_pipe_name(socket)?;
487        if let Ok(existing) = read_status(status_path)
488            && process_alive(existing.pid)
489        {
490            return Err(
491                format!("development daemon is already running as {}", existing.pid).into(),
492            );
493        }
494        if status_path.exists() {
495            std::fs::remove_file(status_path)?;
496        }
497        std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
498        let log = log_path(status_path);
499        let stdout = std::fs::OpenOptions::new()
500            .create(true)
501            .append(true)
502            .open(&log)?;
503        let stderr = stdout.try_clone()?;
504        std::process::Command::new(std::env::current_exe()?)
505            .args(["daemon", "serve"])
506            .arg("--socket")
507            .arg(socket)
508            .arg("--status")
509            .arg(status_path)
510            .stdin(std::process::Stdio::null())
511            .stdout(std::process::Stdio::from(stdout))
512            .stderr(std::process::Stdio::from(stderr))
513            .spawn()?;
514        let deadline = std::time::Instant::now() + Duration::from_secs(3);
515        loop {
516            if let Ok(status) = read_status(status_path)
517                && process_alive(status.pid)
518                && status.socket == socket
519            {
520                return Ok(status);
521            }
522            if std::time::Instant::now() >= deadline {
523                return Err("development daemon did not become ready within three seconds".into());
524            }
525            tokio::time::sleep(Duration::from_millis(25)).await;
526        }
527    }
528}
529
530pub fn read_status_checked(
531    socket: Option<&Path>,
532    status_path: Option<&Path>,
533) -> Result<DevelopmentDaemonStatus, Box<dyn std::error::Error>> {
534    let (default_socket, default_status) = default_paths();
535    let expected_socket = socket.unwrap_or(&default_socket);
536    let status_path = status_path.unwrap_or(&default_status);
537    let mut status = read_status(status_path)?;
538    validate_status(&status, status_path)?;
539    if status.socket != expected_socket {
540        return Err("daemon status socket does not match the requested socket".into());
541    }
542    if !process_alive(status.pid) {
543        status.state = "stopped".into();
544    }
545    Ok(status)
546}
547
548pub fn stop(
549    socket: Option<&Path>,
550    status_path: Option<&Path>,
551) -> Result<(), Box<dyn std::error::Error>> {
552    #[cfg(not(any(unix, windows)))]
553    {
554        let _ = (socket, status_path);
555        return Err("the durable development daemon currently requires Unix".into());
556    }
557    #[cfg(unix)]
558    {
559        let status = read_status_checked(socket, status_path)?;
560        if status.pid == std::process::id() {
561            return Err("refusing to stop the calling process".into());
562        }
563        let result = unsafe { libc::kill(status.pid as i32, libc::SIGTERM) };
564        if result != 0 {
565            return Err(std::io::Error::last_os_error().into());
566        }
567        Ok(())
568    }
569    #[cfg(windows)]
570    {
571        use windows_sys::Win32::System::Threading::{
572            OpenProcess, PROCESS_TERMINATE, TerminateProcess,
573        };
574        let status = read_status_checked(socket, status_path)?;
575        if status.pid == std::process::id() {
576            return Err("refusing to stop the calling process".into());
577        }
578        let process = unsafe { OpenProcess(PROCESS_TERMINATE, 0, status.pid) };
579        if process.is_null() {
580            return Err(std::io::Error::last_os_error().into());
581        }
582        let terminated = unsafe { TerminateProcess(process, 0) };
583        unsafe { windows_sys::Win32::Foundation::CloseHandle(process) };
584        if terminated == 0 {
585            return Err(std::io::Error::last_os_error().into());
586        }
587        Ok(())
588    }
589}
590
591pub async fn serve(socket: &Path, status_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
592    serve_with_store(
593        socket,
594        status_path,
595        WorkspaceTrustStore::platform_default()?,
596    )
597    .await
598}
599
600async fn serve_with_store(
601    socket: &Path,
602    status_path: &Path,
603    trust_store: WorkspaceTrustStore,
604) -> Result<(), Box<dyn std::error::Error>> {
605    #[cfg(not(any(unix, windows)))]
606    {
607        let _ = (socket, status_path);
608        return Err("the durable development daemon currently requires Unix".into());
609    }
610    #[cfg(unix)]
611    {
612        use std::os::unix::fs::PermissionsExt;
613        use tokio::net::UnixListener;
614        use tokio::signal::unix::{SignalKind, signal};
615
616        remove_socket_if_safe(socket)?;
617        std::fs::create_dir_all(socket.parent().unwrap_or_else(|| Path::new(".")))?;
618        std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
619        let listener = UnixListener::bind(socket)?;
620        std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))?;
621        let token_path = token_path(status_path);
622        let token = create_token()?;
623        write_private(&token_path, token.as_bytes())?;
624        let status = DevelopmentDaemonStatus {
625            protocol_version: PROTOCOL_VERSION,
626            state: "running".into(),
627            pid: std::process::id(),
628            socket: socket.to_path_buf(),
629            status_path: status_path.to_path_buf(),
630            token_path: token_path.clone(),
631            started_at_ms: now_ms(),
632            workspace_count: 0,
633            client_count: 0,
634        };
635        write_status(status_path, &status)?;
636        let workspaces: WorkspaceRegistry = Rc::new(RefCell::new(BTreeMap::new()));
637        let clients = std::rc::Rc::new(std::cell::Cell::new(0_usize));
638        let local = tokio::task::LocalSet::new();
639        let mut terminate = signal(SignalKind::terminate())?;
640        local
641            .run_until(async {
642                loop {
643                    let (stream, _) = tokio::select! {
644                        accepted = listener.accept() => accepted?,
645                        _ = terminate.recv() => break,
646                    };
647                    authorize_local_peer(&stream)?;
648                    if clients.get() >= MAX_CLIENTS {
649                        continue;
650                    }
651                    clients.set(clients.get() + 1);
652                    update_counts(status_path, workspaces.borrow().len(), clients.get())?;
653                    let workspaces = Rc::clone(&workspaces);
654                    let clients = Rc::clone(&clients);
655                    let token = token.clone();
656                    let status_path = status_path.to_path_buf();
657                    let socket = socket.to_path_buf();
658                    let trust_store = trust_store.clone();
659                    tokio::task::spawn_local(async move {
660                        if let Err(error) =
661                            handle_client(stream, &token, &socket, &workspaces, &trust_store).await
662                        {
663                            tracing::warn!(%error, "development daemon client failed");
664                        }
665                        clients.set(clients.get().saturating_sub(1));
666                        let workspace_count = workspaces.borrow().len();
667                        let _ = update_counts(&status_path, workspace_count, clients.get());
668                    });
669                }
670                Ok::<(), Box<dyn std::error::Error>>(())
671            })
672            .await?;
673        let _ = std::fs::remove_file(status_path);
674        let _ = std::fs::remove_file(token_path);
675        remove_socket_if_safe(socket)?;
676        Ok(())
677    }
678    #[cfg(windows)]
679    {
680        use tokio::net::windows::named_pipe::ServerOptions;
681
682        validate_windows_pipe_name(socket)?;
683        std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
684        let token_path = token_path(status_path);
685        let token = create_token()?;
686        write_private(&token_path, token.as_bytes())?;
687        let status = DevelopmentDaemonStatus {
688            protocol_version: PROTOCOL_VERSION,
689            state: "running".into(),
690            pid: std::process::id(),
691            socket: socket.to_path_buf(),
692            status_path: status_path.to_path_buf(),
693            token_path: token_path.clone(),
694            started_at_ms: now_ms(),
695            workspace_count: 0,
696            client_count: 0,
697        };
698        write_status(status_path, &status)?;
699        let workspaces: WorkspaceRegistry = Rc::new(RefCell::new(BTreeMap::new()));
700        let clients = Rc::new(std::cell::Cell::new(0_usize));
701        let local = tokio::task::LocalSet::new();
702        let pipe_name = socket.to_string_lossy().to_string();
703        local
704            .run_until(async {
705                let mut first = true;
706                loop {
707                    let server = ServerOptions::new()
708                        .first_pipe_instance(first)
709                        .reject_remote_clients(true)
710                        .create(&pipe_name)?;
711                    first = false;
712                    tokio::select! {
713                        connected = server.connect() => connected?,
714                        _ = tokio::signal::ctrl_c() => break,
715                    }
716                    if clients.get() >= MAX_CLIENTS {
717                        continue;
718                    }
719                    clients.set(clients.get() + 1);
720                    update_counts(status_path, workspaces.borrow().len(), clients.get())?;
721                    let workspaces = Rc::clone(&workspaces);
722                    let clients = Rc::clone(&clients);
723                    let token = token.clone();
724                    let status_path = status_path.to_path_buf();
725                    let socket = socket.to_path_buf();
726                    let trust_store = trust_store.clone();
727                    tokio::task::spawn_local(async move {
728                        if let Err(error) =
729                            handle_stream(server, &token, &socket, &workspaces, &trust_store).await
730                        {
731                            tracing::warn!(%error, "development daemon named-pipe client failed");
732                        }
733                        clients.set(clients.get().saturating_sub(1));
734                        let _ =
735                            update_counts(&status_path, workspaces.borrow().len(), clients.get());
736                    });
737                }
738                Ok::<(), Box<dyn std::error::Error>>(())
739            })
740            .await?;
741        let _ = std::fs::remove_file(status_path);
742        let _ = std::fs::remove_file(token_path);
743        Ok(())
744    }
745}
746
747#[cfg(unix)]
748async fn handle_client(
749    stream: tokio::net::UnixStream,
750    token: &str,
751    socket: &Path,
752    workspaces: &WorkspaceRegistry,
753    trust_store: &WorkspaceTrustStore,
754) -> Result<(), Box<dyn std::error::Error>> {
755    handle_stream(stream, token, socket, workspaces, trust_store).await
756}
757
758async fn handle_stream<S>(
759    stream: S,
760    token: &str,
761    socket: &Path,
762    workspaces: &WorkspaceRegistry,
763    trust_store: &WorkspaceTrustStore,
764) -> Result<(), Box<dyn std::error::Error>>
765where
766    S: AsyncRead + AsyncWrite + Unpin,
767{
768    let (read, mut write) = tokio::io::split(stream);
769    let mut lines = BufReader::new(read).lines();
770    while let Some(line) = lines.next_line().await? {
771        let response = if line.len() > MAX_REQUEST_BYTES {
772            DevelopmentDaemonResponse {
773                id: "oversized".into(),
774                ok: false,
775                result: Value::Null,
776                error: Some("daemon request exceeds the size limit".into()),
777            }
778        } else {
779            match serde_json::from_str::<DevelopmentDaemonRequest>(&line) {
780                Ok(request) => {
781                    execute_request(request, token, socket, workspaces, trust_store).await
782                }
783                Err(error) => DevelopmentDaemonResponse {
784                    id: "invalid".into(),
785                    ok: false,
786                    result: Value::Null,
787                    error: Some(format!("invalid daemon request: {error}")),
788                },
789            }
790        };
791        let encoded = serde_json::to_vec(&response)?;
792        if encoded.len() > MAX_RESPONSE_BYTES {
793            return Err("daemon response exceeds the size limit".into());
794        }
795        write.write_all(&encoded).await?;
796        write.write_all(b"\n").await?;
797        write.flush().await?;
798    }
799    Ok(())
800}
801
802async fn execute_request(
803    request: DevelopmentDaemonRequest,
804    token: &str,
805    socket: &Path,
806    workspaces: &WorkspaceRegistry,
807    trust_store: &WorkspaceTrustStore,
808) -> DevelopmentDaemonResponse {
809    let id = request.id.clone();
810    let result = async {
811        validate_request(&request, token)?;
812        match request.operation.as_str() {
813            "ping" => Ok(serde_json::json!({"protocolVersion":PROTOCOL_VERSION})),
814            "workspace.list" => Ok(Value::Array(
815                workspaces
816                    .borrow()
817                    .values()
818                    .map(|handle| handle.summary.clone())
819                    .collect(),
820            )),
821            "workspace.open" => {
822                let workspace_id = required_workspace_id(&request)?;
823                let root = request
824                    .root
825                    .as_deref()
826                    .ok_or("workspace.open requires root")?;
827                if workspaces.borrow().contains_key(workspace_id) {
828                    return Err("workspace identity is already open".into());
829                }
830                if workspaces.borrow().len() >= MAX_WORKSPACES {
831                    return Err("daemon workspace quota reached".into());
832                }
833                let mut workspace =
834                    DevelopmentWorkspace::open_with_store(root, trust_store.clone())
835                        .map_err(|error| error.to_string())?;
836                workspace
837                    .agents()
838                    .set_resident_broker(ResidentAgentBroker {
839                        socket: socket.to_path_buf(),
840                        token: token.to_string(),
841                        workspace_id: workspace_id.to_string(),
842                    })
843                    .map_err(|error| error.to_string())?;
844                let result = workspace_summary(workspace_id, &workspace);
845                let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
846                let operations = Arc::new(Mutex::new(OperationRegistry::new(workspace_id.into())));
847                tokio::task::spawn_local(run_workspace_actor(
848                    workspace_id.into(),
849                    workspace,
850                    receiver,
851                    Arc::clone(&operations),
852                ));
853                let mut state = workspaces.borrow_mut();
854                if state.contains_key(workspace_id) || state.len() >= MAX_WORKSPACES {
855                    return Err("daemon workspace registry changed while opening".into());
856                }
857                state.insert(
858                    workspace_id.into(),
859                    WorkspaceActorHandle {
860                        sender,
861                        summary: result.clone(),
862                        operations,
863                    },
864                );
865                Ok(result)
866            }
867            "workspace.inspect" => {
868                let workspace_id = required_workspace_id(&request)?;
869                workspace_inspect(workspace_handle(workspaces, workspace_id)?).await
870            }
871            "workspace.tool" => {
872                let workspace_id = required_workspace_id(&request)?;
873                let call = request
874                    .call
875                    .as_ref()
876                    .ok_or("workspace.tool requires call")?;
877                if request.allow_mutation || long_operation_tool(&call.name) {
878                    return Err(
879                        "mutating or long-running tools require operation.submit so clients can reconnect and reconcile"
880                            .into(),
881                    );
882                }
883                let context = request_tool_context(&request, "workspace.tool")?;
884                workspace_tool(
885                    workspace_handle(workspaces, workspace_id)?,
886                    call.clone(),
887                    context,
888                )
889                .await
890            }
891            "operation.submit" => {
892                let workspace_id = required_workspace_id(&request)?;
893                let call = request
894                    .call
895                    .as_ref()
896                    .ok_or("operation.submit requires call")?;
897                let context = request_tool_context(&request, "operation.submit")?;
898                let handle = workspace_handle(workspaces, workspace_id)?;
899                let actor = request.actor.clone().unwrap_or_else(|| "local".into());
900                let (operation, created) = handle
901                    .operations
902                    .lock()
903                    .map_err(|_| "workspace operation registry is poisoned")?
904                    .submit(
905                        &request.id,
906                        actor,
907                        call.name.clone(),
908                        context.expected_project_revision,
909                        !request.allow_mutation,
910                    )?;
911                if created
912                    && handle
913                        .sender
914                        .try_send(WorkspaceCommand::SubmitOperation {
915                            operation_id: operation.id.clone(),
916                            call: call.clone(),
917                            context: Box::new(context),
918                        })
919                        .is_err()
920                {
921                    if let Ok(mut registry) = handle.operations.lock() {
922                        registry.indeterminate(
923                            &operation.id,
924                            "workspace actor command queue closed".into(),
925                        );
926                    }
927                    return Err("workspace actor command queue closed".into());
928                }
929                Ok(serde_json::json!({"accepted":true,"created":created,"operation":operation}))
930            }
931            "operation.inspect" | "operation.reconcile" => {
932                let workspace_id = required_workspace_id(&request)?;
933                let operation_id = required_operation_id(&request)?;
934                let handle = workspace_handle(workspaces, workspace_id)?;
935                let operation = handle
936                    .operations
937                    .lock()
938                    .map_err(|_| "workspace operation registry is poisoned")?
939                    .records
940                    .get(operation_id)
941                    .cloned()
942                    .ok_or("unknown workspace operation")?;
943                let reconciled = operation.state.terminal();
944                let retry_safe = matches!(
945                    operation.state,
946                    DevelopmentOperationState::Failed
947                        | DevelopmentOperationState::Cancelled
948                        | DevelopmentOperationState::Indeterminate
949                ) && operation.retry_safe;
950                Ok(serde_json::json!({
951                    "operation":operation,
952                    "reconciled":reconciled,
953                    "retrySafe":retry_safe,
954                }))
955            }
956            "operation.list" => {
957                let workspace_id = required_workspace_id(&request)?;
958                let handle = workspace_handle(workspaces, workspace_id)?;
959                let registry = handle
960                    .operations
961                    .lock()
962                    .map_err(|_| "workspace operation registry is poisoned")?;
963                let operations = registry
964                    .order
965                    .iter()
966                    .filter_map(|id| registry.records.get(id).cloned())
967                    .collect::<Vec<_>>();
968                Ok(serde_json::json!({"operations":operations,"capacity":OPERATION_CAPACITY}))
969            }
970            "operation.cancel" => {
971                let workspace_id = required_workspace_id(&request)?;
972                let operation_id = required_operation_id(&request)?;
973                let handle = workspace_handle(workspaces, workspace_id)?;
974                let operation = handle
975                    .operations
976                    .lock()
977                    .map_err(|_| "workspace operation registry is poisoned")?
978                    .cancel(operation_id)?;
979                Ok(serde_json::json!({"operation":operation}))
980            }
981            "operation.events" => {
982                let workspace_id = required_workspace_id(&request)?;
983                let operation_id = request.operation_id.as_deref();
984                if let Some(operation_id) = operation_id {
985                    validate_identifier(operation_id, "operation")?;
986                }
987                let limit = request.limit.unwrap_or(128);
988                if limit == 0 || limit > MAX_EVENT_BATCH {
989                    return Err(format!(
990                        "operation event limit must be 1..={MAX_EVENT_BATCH}"
991                    ));
992                }
993                let handle = workspace_handle(workspaces, workspace_id)?;
994                let registry = handle
995                    .operations
996                    .lock()
997                    .map_err(|_| "workspace operation registry is poisoned")?;
998                let since = request.since.unwrap_or(0);
999                let events = registry
1000                    .events
1001                    .iter()
1002                    .filter(|event| event.sequence > since)
1003                    .filter(|event| operation_id.is_none_or(|id| event.operation_id == id))
1004                    .take(limit)
1005                    .cloned()
1006                    .collect::<Vec<_>>();
1007                Ok(serde_json::json!({
1008                    "events":events,
1009                    "newestSequence":registry.events.back().map_or(0, |event| event.sequence),
1010                    "capacity":OPERATION_EVENT_CAPACITY,
1011                }))
1012            }
1013            "workspace.events" => {
1014                let workspace_id = required_workspace_id(&request)?;
1015                workspace_events(
1016                    workspace_handle(workspaces, workspace_id)?,
1017                    request.since.unwrap_or(0),
1018                    request.limit.unwrap_or(128),
1019                )
1020                .await
1021            }
1022            "workspace.close" => {
1023                let workspace_id = required_workspace_id(&request)?;
1024                let handle = workspaces.borrow_mut().remove(workspace_id);
1025                if let Some(handle) = handle {
1026                    let (response, received) = tokio::sync::oneshot::channel();
1027                    handle
1028                        .sender
1029                        .send(WorkspaceCommand::Shutdown { response })
1030                        .await
1031                        .map_err(|_| "workspace actor command queue closed")?;
1032                    received.await.map_err(|_| "workspace actor did not stop")?;
1033                    Ok(serde_json::json!({"closed":true}))
1034                } else {
1035                    Ok(serde_json::json!({"closed":false}))
1036                }
1037            }
1038            _ => Err("unknown daemon operation".into()),
1039        }
1040    }
1041    .await;
1042    match result {
1043        Ok(result) => DevelopmentDaemonResponse {
1044            id,
1045            ok: true,
1046            result,
1047            error: None,
1048        },
1049        Err(error) => DevelopmentDaemonResponse {
1050            id,
1051            ok: false,
1052            result: Value::Null,
1053            error: Some(error),
1054        },
1055    }
1056}
1057
1058fn workspace_handle(
1059    workspaces: &WorkspaceRegistry,
1060    workspace_id: &str,
1061) -> Result<WorkspaceActorHandle, String> {
1062    workspaces
1063        .borrow()
1064        .get(workspace_id)
1065        .cloned()
1066        .ok_or_else(|| "unknown durable workspace".into())
1067}
1068
1069async fn workspace_inspect(handle: WorkspaceActorHandle) -> Result<Value, String> {
1070    let (response, received) = tokio::sync::oneshot::channel();
1071    handle
1072        .sender
1073        .send(WorkspaceCommand::Inspect { response })
1074        .await
1075        .map_err(|_| "workspace actor command queue closed")?;
1076    received
1077        .await
1078        .map_err(|_| "workspace actor dropped its inspect response")?
1079}
1080
1081async fn workspace_tool(
1082    handle: WorkspaceActorHandle,
1083    call: ToolCall,
1084    context: DevelopmentToolContext,
1085) -> Result<Value, String> {
1086    let (response, received) = tokio::sync::oneshot::channel();
1087    handle
1088        .sender
1089        .send(WorkspaceCommand::Tool {
1090            call,
1091            context: Box::new(context),
1092            response,
1093        })
1094        .await
1095        .map_err(|_| "workspace actor command queue closed")?;
1096    received
1097        .await
1098        .map_err(|_| "workspace actor dropped its tool response")?
1099}
1100
1101async fn workspace_events(
1102    handle: WorkspaceActorHandle,
1103    since: u64,
1104    limit: usize,
1105) -> Result<Value, String> {
1106    if limit == 0 || limit > MAX_EVENT_BATCH {
1107        return Err(format!(
1108            "workspace event limit must be 1..={MAX_EVENT_BATCH}"
1109        ));
1110    }
1111    let (response, received) = tokio::sync::oneshot::channel();
1112    handle
1113        .sender
1114        .send(WorkspaceCommand::Events {
1115            since,
1116            limit,
1117            response,
1118        })
1119        .await
1120        .map_err(|_| "workspace actor command queue closed")?;
1121    received
1122        .await
1123        .map_err(|_| "workspace actor dropped its event response".into())
1124}
1125
1126async fn run_workspace_actor(
1127    workspace_id: String,
1128    workspace: DevelopmentWorkspace,
1129    mut commands: tokio::sync::mpsc::Receiver<WorkspaceCommand>,
1130    operations: Arc<Mutex<OperationRegistry>>,
1131) {
1132    let mut workspace = Some(workspace);
1133    let mut queued_operations: VecDeque<QueuedOperation> = VecDeque::new();
1134    let (completion_tx, mut completions) = tokio::sync::mpsc::channel::<OperationCompletion>(1);
1135    let mut operation_running = false;
1136    let mut command_channel_open = true;
1137    let mut closing: Option<tokio::sync::oneshot::Sender<()>> = None;
1138    let mut events = VecDeque::with_capacity(WORKSPACE_EVENT_CAPACITY);
1139    let mut next_event = 1_u64;
1140    let mut dropped_events = 0_u64;
1141    push_workspace_event(
1142        &workspace_id,
1143        &mut events,
1144        &mut next_event,
1145        &mut dropped_events,
1146        "workspace.opened",
1147        None,
1148        true,
1149    );
1150    let mut tick = tokio::time::interval(Duration::from_millis(50));
1151    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1152    loop {
1153        if closing.is_none() && !operation_running && workspace.is_some() {
1154            while let Some((operation_id, call, context)) = queued_operations.pop_front() {
1155                let should_start = operations
1156                    .lock()
1157                    .map(|mut registry| registry.start(&operation_id))
1158                    .unwrap_or(false);
1159                if !should_start {
1160                    continue;
1161                }
1162                let mut owned_workspace = workspace
1163                    .take()
1164                    .expect("workspace operation start owns the workspace");
1165                let completion = completion_tx.clone();
1166                operation_running = true;
1167                tokio::task::spawn_local(async move {
1168                    let joined = tokio::task::spawn_blocking(move || {
1169                        let result = owned_workspace
1170                            .execute_tool(&call, &context)
1171                            .map_err(|error| error.to_string());
1172                        let revision_after = owned_workspace.project().revision();
1173                        (
1174                            owned_workspace,
1175                            operation_id,
1176                            call.id,
1177                            revision_after,
1178                            result,
1179                        )
1180                    })
1181                    .await;
1182                    let _ = completion.send(joined).await;
1183                });
1184                break;
1185            }
1186        }
1187        if closing.is_some() && !operation_running {
1188            if let Some(response) = closing.take() {
1189                let _ = response.send(());
1190            }
1191            break;
1192        }
1193        tokio::select! {
1194            biased;
1195            completion = completions.recv(), if operation_running => {
1196                operation_running = false;
1197                match completion {
1198                    Some(Ok((returned_workspace, operation_id, call_id, revision_after, result))) => {
1199                        workspace = Some(returned_workspace);
1200                        if let Ok(mut registry) = operations.lock() {
1201                            registry.finish(&operation_id, revision_after, result.clone());
1202                        }
1203                        push_workspace_event(
1204                            &workspace_id,
1205                            &mut events,
1206                            &mut next_event,
1207                            &mut dropped_events,
1208                            "operation.completed",
1209                            Some(call_id),
1210                            result.is_ok(),
1211                        );
1212                    }
1213                    Some(Err(error)) => {
1214                        let running_id = operations.lock().ok().and_then(|registry| {
1215                            registry.records.values().find(|record| {
1216                                record.state == DevelopmentOperationState::Running
1217                            }).map(|record| record.id.clone())
1218                        });
1219                        if let Some(operation_id) = running_id
1220                            && let Ok(mut registry) = operations.lock()
1221                        {
1222                            registry.indeterminate(
1223                                &operation_id,
1224                                format!("workspace operation worker failed: {error}"),
1225                            );
1226                        }
1227                        tracing::error!(workspace_id, %error, "workspace operation worker failed");
1228                        if let Some(response) = closing.take() {
1229                            let _ = response.send(());
1230                        }
1231                        break;
1232                    }
1233                    None => break,
1234                }
1235            }
1236            command = commands.recv(), if command_channel_open => match command {
1237                Some(WorkspaceCommand::Inspect { response }) => {
1238                    let result = workspace.as_mut().map_or_else(
1239                        || Err("workspace is busy with a recoverable operation; inspect the operation ID".into()),
1240                        |workspace| inspect_workspace(&workspace_id, workspace),
1241                    );
1242                    let _ = response.send(result);
1243                }
1244                Some(WorkspaceCommand::Tool { call, context, response }) => {
1245                    let Some(mut owned_workspace) = workspace.take() else {
1246                        let _ = response.send(Err(
1247                            "workspace is busy; submit long work with operation.submit and inspect its ID".into(),
1248                        ));
1249                        continue;
1250                    };
1251                    let kind = daemon_event_kind(&call.name);
1252                    let execution = tokio::task::spawn_blocking(move || {
1253                        let result = owned_workspace
1254                            .execute_tool(&call, &context)
1255                            .map_err(|error| error.to_string());
1256                        (owned_workspace, call.id, result)
1257                    })
1258                    .await;
1259                    let (returned_workspace, call_id, result) = match execution {
1260                        Ok(execution) => execution,
1261                        Err(error) => {
1262                            let _ = response.send(Err(format!(
1263                                "workspace actor tool execution failed: {error}"
1264                            )));
1265                            break;
1266                        }
1267                    };
1268                    workspace = Some(returned_workspace);
1269                    push_workspace_event(
1270                        &workspace_id,
1271                        &mut events,
1272                        &mut next_event,
1273                        &mut dropped_events,
1274                        kind,
1275                        Some(call_id),
1276                        result.is_ok(),
1277                    );
1278                    let _ = response.send(result);
1279                }
1280                Some(WorkspaceCommand::SubmitOperation { operation_id, call, context }) => {
1281                    queued_operations.push_back((operation_id, call, context));
1282                }
1283                Some(WorkspaceCommand::Events { since, limit, response }) => {
1284                    let _ = response.send(workspace_event_batch(
1285                        &events,
1286                        next_event,
1287                        dropped_events,
1288                        since,
1289                        limit,
1290                    ));
1291                }
1292                Some(WorkspaceCommand::Shutdown { response }) => {
1293                    if let Ok(mut registry) = operations.lock() {
1294                        let active = registry
1295                            .records
1296                            .values()
1297                            .filter(|record| !record.state.terminal())
1298                            .map(|record| record.id.clone())
1299                            .collect::<Vec<_>>();
1300                        for id in active {
1301                            let _ = registry.cancel(&id);
1302                        }
1303                    }
1304                    queued_operations.clear();
1305                    closing = Some(response);
1306                }
1307                None => {
1308                    command_channel_open = false;
1309                    if let Ok(mut registry) = operations.lock() {
1310                        let active = registry
1311                            .records
1312                            .values()
1313                            .filter(|record| !record.state.terminal())
1314                            .map(|record| record.id.clone())
1315                            .collect::<Vec<_>>();
1316                        for id in active {
1317                            let _ = registry.cancel(&id);
1318                        }
1319                    }
1320                    queued_operations.clear();
1321                    if !operation_running {
1322                        break;
1323                    }
1324                },
1325            },
1326            _ = tick.tick() => {
1327                if let Some(workspace) = workspace.as_mut()
1328                    && let Err(error) = workspace.tasks()
1329                {
1330                    tracing::warn!(workspace_id, %error, "workspace task scheduler tick failed");
1331                }
1332            }
1333        }
1334    }
1335}
1336
1337fn workspace_event_batch(
1338    events: &VecDeque<DevelopmentDaemonEvent>,
1339    next_event: u64,
1340    dropped_events: u64,
1341    since: u64,
1342    limit: usize,
1343) -> Value {
1344    let oldest = events
1345        .front()
1346        .map(|event| event.sequence)
1347        .unwrap_or(next_event);
1348    let newest = events.back().map(|event| event.sequence).unwrap_or(0);
1349    let selected = events
1350        .iter()
1351        .filter(|event| event.sequence > since)
1352        .take(limit)
1353        .cloned()
1354        .collect::<Vec<_>>();
1355    serde_json::json!({
1356        "events": selected,
1357        "oldestSequence": oldest,
1358        "newestSequence": newest,
1359        "lostBefore": (since.saturating_add(1) < oldest).then_some(oldest),
1360        "droppedEvents": dropped_events,
1361        "capacity": WORKSPACE_EVENT_CAPACITY,
1362    })
1363}
1364
1365fn push_workspace_event(
1366    workspace_id: &str,
1367    events: &mut VecDeque<DevelopmentDaemonEvent>,
1368    next_event: &mut u64,
1369    dropped_events: &mut u64,
1370    kind: &str,
1371    tool_call_id: Option<String>,
1372    success: bool,
1373) {
1374    if events.len() == WORKSPACE_EVENT_CAPACITY {
1375        events.pop_front();
1376        *dropped_events = dropped_events.saturating_add(1);
1377    }
1378    events.push_back(DevelopmentDaemonEvent {
1379        sequence: *next_event,
1380        timestamp_ms: now_ms(),
1381        kind: kind.into(),
1382        workspace_id: workspace_id.into(),
1383        tool_call_id,
1384        success,
1385    });
1386    *next_event = next_event.saturating_add(1);
1387}
1388
1389fn daemon_event_kind(tool: &str) -> &'static str {
1390    if tool.starts_with("glass.agent.") {
1391        "agent.event"
1392    } else if tool.starts_with("glass.task.") {
1393        "task.changed"
1394    } else if tool.starts_with("glass.process.") {
1395        "process.output"
1396    } else if tool.starts_with("glass.browser.") || tool.starts_with("glass.web.") {
1397        "browser.revision"
1398    } else if tool.starts_with("glass.lsp.") {
1399        "lsp.diagnostics"
1400    } else if tool.starts_with("glass.debug.") {
1401        "debugger.stopped"
1402    } else if tool.starts_with("glass.test.") || tool.starts_with("glass.workflow.") {
1403        "test.completed"
1404    } else if tool.starts_with("glass.git.") {
1405        "git.changed"
1406    } else if tool.starts_with("glass.experiment.") {
1407        "experiment.changed"
1408    } else {
1409        "workspace.changed"
1410    }
1411}
1412
1413fn long_operation_tool(name: &str) -> bool {
1414    [
1415        "glass.process.",
1416        "glass.test.",
1417        "glass.eval.",
1418        "glass.debug.",
1419        "glass.git.",
1420        "glass.workflow.",
1421        "glass.experiment.",
1422        "glass.agent.",
1423        "glass.task.",
1424        "glass.browser.start",
1425        "glass.browser.stop",
1426        "glass.browser.reconnect",
1427    ]
1428    .iter()
1429    .any(|prefix| name.starts_with(prefix))
1430}
1431
1432fn inspect_workspace(
1433    workspace_id: &str,
1434    workspace: &mut DevelopmentWorkspace,
1435) -> Result<Value, String> {
1436    let agents = workspace
1437        .agents()
1438        .list()
1439        .map_err(|error| error.to_string())?;
1440    let tasks = workspace.tasks().map_err(|error| error.to_string())?;
1441    let processes = workspace
1442        .project_mut()
1443        .processes()
1444        .list_checked()
1445        .map_err(|error| error.to_string())?;
1446    Ok(serde_json::json!({
1447        "workspace":workspace_summary(workspace_id, workspace),
1448        "processes":processes,
1449        "agents":agents,
1450        "tasks":tasks,
1451        "kernels":workspace.kernels().snapshots().collect::<Vec<_>>(),
1452        "debuggers":workspace.debugger_names().collect::<Vec<_>>(),
1453        "browser":workspace.browser().state().map_err(|error| error.to_string())?
1454    }))
1455}
1456
1457#[cfg(unix)]
1458pub async fn request(
1459    socket: &Path,
1460    request: &DevelopmentDaemonRequest,
1461) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>> {
1462    let stream = tokio::net::UnixStream::connect(socket).await?;
1463    bounded_request_stream(stream, request).await
1464}
1465
1466#[cfg(windows)]
1467pub async fn request(
1468    socket: &Path,
1469    request: &DevelopmentDaemonRequest,
1470) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>> {
1471    use tokio::net::windows::named_pipe::ClientOptions;
1472    validate_windows_pipe_name(socket)?;
1473    let deadline = std::time::Instant::now() + Duration::from_secs(3);
1474    let pipe_name = socket.to_string_lossy();
1475    let stream = loop {
1476        match ClientOptions::new().open(pipe_name.as_ref()) {
1477            Ok(stream) => break stream,
1478            Err(error)
1479                if error.raw_os_error() == Some(231) && std::time::Instant::now() < deadline =>
1480            {
1481                tokio::time::sleep(Duration::from_millis(10)).await;
1482            }
1483            Err(error) => return Err(error.into()),
1484        }
1485    };
1486    bounded_request_stream(stream, request).await
1487}
1488
1489async fn bounded_request_stream<S>(
1490    stream: S,
1491    request: &DevelopmentDaemonRequest,
1492) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>>
1493where
1494    S: AsyncRead + AsyncWrite + Unpin,
1495{
1496    tokio::time::timeout(DAEMON_REQUEST_TIMEOUT, request_stream(stream, request))
1497        .await
1498        .map_err(|_| {
1499            format!(
1500                "daemon operation {} timed out after {} seconds",
1501                request.operation,
1502                DAEMON_REQUEST_TIMEOUT.as_secs()
1503            )
1504        })?
1505}
1506
1507async fn request_stream<S>(
1508    stream: S,
1509    request: &DevelopmentDaemonRequest,
1510) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>>
1511where
1512    S: AsyncRead + AsyncWrite + Unpin,
1513{
1514    let (read, mut write) = tokio::io::split(stream);
1515    let encoded = serde_json::to_vec(request)?;
1516    if encoded.len() > MAX_REQUEST_BYTES {
1517        return Err("daemon request exceeds the size limit".into());
1518    }
1519    write.write_all(&encoded).await?;
1520    write.write_all(b"\n").await?;
1521    write.flush().await?;
1522    let mut line = String::new();
1523    BufReader::new(read).read_line(&mut line).await?;
1524    Ok(serde_json::from_str(&line)?)
1525}
1526
1527#[cfg(not(any(unix, windows)))]
1528pub async fn request(
1529    _socket: &Path,
1530    _request: &DevelopmentDaemonRequest,
1531) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>> {
1532    Err("the local development daemon requires Unix-domain sockets on this platform".into())
1533}
1534
1535pub async fn forward_resident_tool_file(
1536    path: &Path,
1537    root: &Path,
1538    allow_mutation: bool,
1539    confirmed: bool,
1540) -> Result<Value, Box<dyn std::error::Error>> {
1541    let socket = PathBuf::from(
1542        std::env::var_os("GLASS_DEV_DAEMON_SOCKET")
1543            .ok_or("resident Pi broker socket is missing")?,
1544    );
1545    let token = std::env::var("GLASS_DEV_DAEMON_TOKEN")
1546        .map_err(|_| "resident Pi broker token is missing")?;
1547    let workspace_id = std::env::var("GLASS_DEV_DAEMON_WORKSPACE")
1548        .map_err(|_| "resident Pi broker workspace is missing")?;
1549    forward_resident_tool_file_with_context(
1550        &socket,
1551        &token,
1552        &workspace_id,
1553        path,
1554        root,
1555        allow_mutation,
1556        confirmed,
1557    )
1558    .await
1559}
1560
1561async fn forward_resident_tool_file_with_context(
1562    socket: &Path,
1563    token: &str,
1564    workspace_id: &str,
1565    path: &Path,
1566    root: &Path,
1567    allow_mutation: bool,
1568    confirmed: bool,
1569) -> Result<Value, Box<dyn std::error::Error>> {
1570    let call = read_private_tool_call(path)?;
1571    forward_resident_tool_call(
1572        socket,
1573        token,
1574        workspace_id,
1575        &call,
1576        root,
1577        allow_mutation,
1578        confirmed,
1579    )
1580    .await
1581}
1582
1583pub(crate) async fn forward_resident_tool_call_with_context(
1584    broker: &ResidentAgentBroker,
1585    call: &ToolCall,
1586    root: &Path,
1587    allow_mutation: bool,
1588    confirmed: bool,
1589) -> Result<Value, Box<dyn std::error::Error>> {
1590    forward_resident_tool_call(
1591        &broker.socket,
1592        &broker.token,
1593        &broker.workspace_id,
1594        call,
1595        root,
1596        allow_mutation,
1597        confirmed,
1598    )
1599    .await
1600}
1601
1602async fn forward_resident_tool_call(
1603    socket: &Path,
1604    token: &str,
1605    workspace_id: &str,
1606    call: &ToolCall,
1607    root: &Path,
1608    allow_mutation: bool,
1609    confirmed: bool,
1610) -> Result<Value, Box<dyn std::error::Error>> {
1611    let inspect = request(
1612        socket,
1613        &DevelopmentDaemonRequest {
1614            id: format!("inspect-{}", call.id),
1615            token: token.to_string(),
1616            operation: "workspace.inspect".into(),
1617            workspace_id: Some(workspace_id.to_string()),
1618            root: None,
1619            call: None,
1620            expected_generation: None,
1621            expected_project_revision: None,
1622            allow_mutation: false,
1623            confirmed: false,
1624            actor: Some("pi".into()),
1625            since: None,
1626            limit: None,
1627            operation_id: None,
1628        },
1629    )
1630    .await?;
1631    if !inspect.ok {
1632        return Err(inspect
1633            .error
1634            .unwrap_or_else(|| "workspace inspect failed".into())
1635            .into());
1636    }
1637    let expected_root = std::fs::canonicalize(root)?;
1638    let observed_root = inspect
1639        .result
1640        .pointer("/workspace/root")
1641        .and_then(Value::as_str);
1642    if observed_root != expected_root.to_str() {
1643        return Err("resident Pi broker root does not match the durable workspace".into());
1644    }
1645    let generation = inspect
1646        .result
1647        .pointer("/workspace/generation")
1648        .and_then(Value::as_u64)
1649        .ok_or("durable workspace generation is missing")?;
1650    let revision = inspect
1651        .result
1652        .pointer("/workspace/projectRevision")
1653        .and_then(Value::as_u64)
1654        .ok_or("durable workspace revision is missing")?;
1655    let mut response = request(
1656        socket,
1657        &DevelopmentDaemonRequest {
1658            id: format!("tool-{}", call.id),
1659            token: token.to_string(),
1660            operation: "operation.submit".into(),
1661            workspace_id: Some(workspace_id.to_string()),
1662            root: None,
1663            call: Some(call.clone()),
1664            expected_generation: Some(generation),
1665            expected_project_revision: Some(revision),
1666            allow_mutation,
1667            confirmed,
1668            actor: Some("pi".into()),
1669            since: None,
1670            limit: None,
1671            operation_id: None,
1672        },
1673    )
1674    .await?;
1675    if !response.ok {
1676        return Err(response
1677            .error
1678            .unwrap_or_else(|| "resident operation submission failed".into())
1679            .into());
1680    }
1681    let operation_id = response
1682        .result
1683        .pointer("/operation/id")
1684        .and_then(Value::as_str)
1685        .ok_or("daemon operation submission returned no operation ID")?
1686        .to_string();
1687    loop {
1688        let state = response
1689            .result
1690            .pointer("/operation/state")
1691            .and_then(Value::as_str);
1692        if state == Some("succeeded") {
1693            return response
1694                .result
1695                .pointer("/operation/result")
1696                .cloned()
1697                .ok_or_else(|| "successful daemon operation returned no result".into());
1698        }
1699        if matches!(state, Some("failed" | "cancelled" | "indeterminate")) {
1700            let reason = response
1701                .result
1702                .pointer("/operation/failureReason")
1703                .and_then(Value::as_str)
1704                .unwrap_or("resident operation did not succeed");
1705            return Err(reason.into());
1706        }
1707        tokio::time::sleep(Duration::from_millis(50)).await;
1708        response = request(
1709            socket,
1710            &DevelopmentDaemonRequest {
1711                id: format!("inspect-operation-{}", call.id),
1712                token: token.to_string(),
1713                operation: "operation.inspect".into(),
1714                workspace_id: Some(workspace_id.to_string()),
1715                root: None,
1716                call: None,
1717                expected_generation: None,
1718                expected_project_revision: None,
1719                allow_mutation: false,
1720                confirmed: false,
1721                actor: Some("pi".into()),
1722                since: None,
1723                limit: None,
1724                operation_id: Some(operation_id.clone()),
1725            },
1726        )
1727        .await?;
1728        if !response.ok {
1729            return Err(response
1730                .error
1731                .unwrap_or_else(|| "resident operation inspection failed".into())
1732                .into());
1733        }
1734    }
1735}
1736
1737pub(crate) fn read_private_tool_call(path: &Path) -> Result<ToolCall, Box<dyn std::error::Error>> {
1738    use std::io::Read;
1739    const MAX_CALL_BYTES: u64 = 256 * 1024;
1740    let canonical = path.canonicalize()?;
1741    let temporary_root = std::env::temp_dir().canonicalize()?;
1742    if canonical.parent() != Some(temporary_root.as_path())
1743        || !canonical
1744            .file_name()
1745            .and_then(|name| name.to_str())
1746            .is_some_and(|name| name.starts_with("glass-pi-call-") && name.ends_with(".json"))
1747    {
1748        return Err("Pi broker requests must use a private Glass temporary file".into());
1749    }
1750    let mut options = std::fs::OpenOptions::new();
1751    options.read(true);
1752    #[cfg(unix)]
1753    {
1754        use std::os::unix::fs::OpenOptionsExt;
1755        options.custom_flags(libc::O_NOFOLLOW);
1756    }
1757    let file = options.open(&canonical)?;
1758    let metadata = file.metadata()?;
1759    if !metadata.is_file() || metadata.len() > MAX_CALL_BYTES {
1760        return Err("invalid Pi broker request file".into());
1761    }
1762    #[cfg(unix)]
1763    {
1764        use std::os::unix::fs::{MetadataExt, PermissionsExt};
1765        if metadata.uid() != unsafe { libc::geteuid() }
1766            || metadata.permissions().mode() & 0o077 != 0
1767        {
1768            return Err("Pi broker request must be owned by this user with mode 0600".into());
1769        }
1770    }
1771    let mut encoded = Vec::with_capacity(metadata.len() as usize);
1772    file.take(MAX_CALL_BYTES + 1).read_to_end(&mut encoded)?;
1773    std::fs::remove_file(&canonical)?;
1774    if encoded.len() as u64 > MAX_CALL_BYTES {
1775        return Err("Pi broker request exceeds the size limit".into());
1776    }
1777    Ok(serde_json::from_slice(&encoded)?)
1778}
1779
1780fn workspace_summary(id: &str, workspace: &DevelopmentWorkspace) -> Value {
1781    serde_json::json!({
1782        "id":id,
1783        "root":workspace.root(),
1784        "trust":workspace.trust(),
1785        "generation":workspace.generation(),
1786        "projectRevision":workspace.project().revision()
1787    })
1788}
1789
1790fn validate_request(request: &DevelopmentDaemonRequest, token: &str) -> Result<(), String> {
1791    if request.token.as_bytes() != token.as_bytes() {
1792        return Err("invalid daemon authentication token".into());
1793    }
1794    validate_identifier(&request.id, "request")?;
1795    if request.operation.is_empty()
1796        || request.operation.len() > 128
1797        || request.operation.chars().any(char::is_control)
1798    {
1799        return Err("invalid daemon operation".into());
1800    }
1801    Ok(())
1802}
1803
1804fn required_workspace_id(request: &DevelopmentDaemonRequest) -> Result<&str, String> {
1805    let id = request
1806        .workspace_id
1807        .as_deref()
1808        .ok_or("daemon request requires workspaceId")?;
1809    validate_identifier(id, "workspace")?;
1810    Ok(id)
1811}
1812
1813fn required_operation_id(request: &DevelopmentDaemonRequest) -> Result<&str, String> {
1814    let id = request
1815        .operation_id
1816        .as_deref()
1817        .ok_or("daemon request requires operationId")?;
1818    validate_identifier(id, "operation")?;
1819    Ok(id)
1820}
1821
1822fn request_tool_context(
1823    request: &DevelopmentDaemonRequest,
1824    operation: &str,
1825) -> Result<DevelopmentToolContext, String> {
1826    let actor = request
1827        .actor
1828        .as_deref()
1829        .map(Actor::external)
1830        .unwrap_or_else(Actor::local);
1831    Ok(DevelopmentToolContext {
1832        authorization: ToolAuthorization {
1833            actor,
1834            allow_mutation: request.allow_mutation,
1835            confirmed: request.confirmed,
1836        },
1837        initiator: None,
1838        expected_generation: request
1839            .expected_generation
1840            .ok_or_else(|| format!("{operation} requires expectedGeneration"))?,
1841        expected_project_revision: request
1842            .expected_project_revision
1843            .ok_or_else(|| format!("{operation} requires expectedProjectRevision"))?,
1844    })
1845}
1846
1847fn validate_identifier(value: &str, description: &str) -> Result<(), String> {
1848    if value.is_empty()
1849        || value.len() > 128
1850        || !value
1851            .chars()
1852            .all(|character| character.is_ascii_alphanumeric() || "-_.".contains(character))
1853    {
1854        return Err(format!("invalid {description} identifier"));
1855    }
1856    Ok(())
1857}
1858
1859fn read_status(path: &Path) -> Result<DevelopmentDaemonStatus, Box<dyn std::error::Error>> {
1860    let bytes = std::fs::read(path)?;
1861    if bytes.len() > 64 * 1024 {
1862        return Err("daemon status exceeds the size limit".into());
1863    }
1864    Ok(serde_json::from_slice(&bytes)?)
1865}
1866
1867fn validate_status(
1868    status: &DevelopmentDaemonStatus,
1869    path: &Path,
1870) -> Result<(), Box<dyn std::error::Error>> {
1871    if status.protocol_version != PROTOCOL_VERSION || status.status_path != path {
1872        return Err("invalid development daemon status contract".into());
1873    }
1874    if status.workspace_count > MAX_WORKSPACES || status.client_count > MAX_CLIENTS {
1875        return Err("daemon status exceeds resource quotas".into());
1876    }
1877    Ok(())
1878}
1879
1880fn write_status(
1881    path: &Path,
1882    status: &DevelopmentDaemonStatus,
1883) -> Result<(), Box<dyn std::error::Error>> {
1884    let encoded = serde_json::to_vec_pretty(status)?;
1885    write_private(path, &encoded)
1886}
1887
1888fn update_counts(
1889    status_path: &Path,
1890    workspace_count: usize,
1891    client_count: usize,
1892) -> Result<(), Box<dyn std::error::Error>> {
1893    let mut status = read_status(status_path)?;
1894    status.workspace_count = workspace_count;
1895    status.client_count = client_count;
1896    write_status(status_path, &status)
1897}
1898
1899fn write_private(path: &Path, bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
1900    use std::io::Write;
1901    #[cfg(unix)]
1902    use std::os::unix::fs::OpenOptionsExt;
1903    let temporary = path.with_extension(format!("tmp-{}", std::process::id()));
1904    let mut options = std::fs::OpenOptions::new();
1905    options.create_new(true).write(true);
1906    #[cfg(unix)]
1907    options.mode(0o600);
1908    let mut file = options.open(&temporary)?;
1909    file.write_all(bytes)?;
1910    file.sync_all()?;
1911    std::fs::rename(temporary, path)?;
1912    Ok(())
1913}
1914
1915fn create_token() -> Result<String, Box<dyn std::error::Error>> {
1916    let mut bytes = [0_u8; 32];
1917    getrandom::fill(&mut bytes)?;
1918    Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
1919}
1920
1921fn token_path(status: &Path) -> PathBuf {
1922    status.with_extension("token")
1923}
1924
1925fn log_path(status: &Path) -> PathBuf {
1926    status.with_extension("log")
1927}
1928
1929fn bounded_log(status: &Path) -> Result<String, Box<dyn std::error::Error>> {
1930    use std::io::{Read, Seek, SeekFrom};
1931    let mut file = std::fs::File::open(log_path(status))?;
1932    let length = file.metadata()?.len();
1933    let start = length.saturating_sub(64 * 1024);
1934    file.seek(SeekFrom::Start(start))?;
1935    let mut output = String::new();
1936    file.read_to_string(&mut output)?;
1937    Ok(output)
1938}
1939
1940#[cfg(unix)]
1941fn authorize_local_peer(stream: &tokio::net::UnixStream) -> Result<(), Box<dyn std::error::Error>> {
1942    #[cfg(target_os = "linux")]
1943    {
1944        use std::os::fd::AsRawFd;
1945        let mut credentials = libc::ucred {
1946            pid: 0,
1947            uid: 0,
1948            gid: 0,
1949        };
1950        let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
1951        let result = unsafe {
1952            libc::getsockopt(
1953                stream.as_raw_fd(),
1954                libc::SOL_SOCKET,
1955                libc::SO_PEERCRED,
1956                (&mut credentials as *mut libc::ucred).cast(),
1957                &mut length,
1958            )
1959        };
1960        if result != 0 || credentials.uid != unsafe { libc::geteuid() } {
1961            return Err("daemon rejected a non-local-user peer".into());
1962        }
1963    }
1964    Ok(())
1965}
1966
1967#[cfg(unix)]
1968fn remove_socket_if_safe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1969    use std::os::unix::fs::FileTypeExt;
1970    match std::fs::symlink_metadata(path) {
1971        Ok(metadata) if metadata.file_type().is_socket() => std::fs::remove_file(path)?,
1972        Ok(_) => return Err(format!("refusing to replace non-socket {}", path.display()).into()),
1973        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1974        Err(error) => return Err(error.into()),
1975    }
1976    Ok(())
1977}
1978
1979#[cfg(not(unix))]
1980fn remove_socket_if_safe(_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1981    Ok(())
1982}
1983
1984fn process_alive(pid: u32) -> bool {
1985    #[cfg(unix)]
1986    {
1987        unsafe { libc::kill(pid as i32, 0) == 0 }
1988    }
1989    #[cfg(windows)]
1990    {
1991        use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
1992        use windows_sys::Win32::System::Threading::{
1993            GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
1994        };
1995        let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
1996        if process.is_null() {
1997            return false;
1998        }
1999        let mut exit_code = 0_u32;
2000        let success = unsafe { GetExitCodeProcess(process, &mut exit_code) } != 0;
2001        unsafe { CloseHandle(process) };
2002        success && exit_code == STILL_ACTIVE as u32
2003    }
2004    #[cfg(not(any(unix, windows)))]
2005    {
2006        let _ = pid;
2007        false
2008    }
2009}
2010
2011#[cfg(windows)]
2012fn validate_windows_pipe_name(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
2013    let value = path
2014        .to_str()
2015        .ok_or("Windows named-pipe endpoint must be Unicode")?;
2016    if !valid_windows_pipe_name(value) {
2017        return Err("invalid Windows Glass daemon pipe name".into());
2018    }
2019    Ok(())
2020}
2021
2022#[cfg(any(windows, test))]
2023fn valid_windows_pipe_name(value: &str) -> bool {
2024    value
2025        .strip_prefix(r"\\.\pipe\glass-dev-")
2026        .is_some_and(|name| {
2027            !name.is_empty()
2028                && name.len() <= 64
2029                && name
2030                    .chars()
2031                    .all(|character| character.is_ascii_alphanumeric() || character == '-')
2032        })
2033}
2034
2035fn effective_uid() -> u32 {
2036    #[cfg(unix)]
2037    {
2038        unsafe { libc::geteuid() }
2039    }
2040    #[cfg(not(unix))]
2041    {
2042        0
2043    }
2044}
2045
2046fn now_ms() -> u128 {
2047    SystemTime::now()
2048        .duration_since(UNIX_EPOCH)
2049        .unwrap_or_default()
2050        .as_millis()
2051}
2052
2053#[cfg(test)]
2054mod tests {
2055    use super::*;
2056    use std::sync::atomic::{AtomicU64, Ordering};
2057
2058    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2059
2060    #[test]
2061    fn windows_pipe_names_are_local_and_glass_owned() {
2062        assert!(valid_windows_pipe_name(
2063            r"\\.\pipe\glass-dev-0123456789abcdef"
2064        ));
2065        assert!(!valid_windows_pipe_name(r"\\server\pipe\glass-dev-test"));
2066        assert!(!valid_windows_pipe_name(r"\\.\pipe\other-product"));
2067        assert!(!valid_windows_pipe_name(r"\\.\pipe\glass-dev-bad/name"));
2068    }
2069
2070    fn test_context() -> DevelopmentToolContext {
2071        DevelopmentToolContext {
2072            authorization: ToolAuthorization {
2073                actor: Actor::external("daemon-concurrency-test"),
2074                allow_mutation: true,
2075                confirmed: true,
2076            },
2077            initiator: None,
2078            expected_generation: 1,
2079            expected_project_revision: 0,
2080        }
2081    }
2082
2083    async fn submit_and_wait(
2084        socket: &Path,
2085        request_value: &DevelopmentDaemonRequest,
2086    ) -> DevelopmentDaemonResponse {
2087        let mut submission = request_value.clone();
2088        submission.operation = "operation.submit".into();
2089        let accepted = request(socket, &submission).await.unwrap();
2090        if !accepted.ok {
2091            return accepted;
2092        }
2093        let operation_id = accepted.result["operation"]["id"]
2094            .as_str()
2095            .unwrap()
2096            .to_string();
2097        for sequence in 0..2_000 {
2098            let mut inspect = submission.clone();
2099            inspect.id = format!("inspect-{}-{sequence}", submission.id);
2100            inspect.operation = "operation.inspect".into();
2101            inspect.call = None;
2102            inspect.expected_generation = None;
2103            inspect.expected_project_revision = None;
2104            inspect.allow_mutation = false;
2105            inspect.confirmed = false;
2106            inspect.operation_id = Some(operation_id.clone());
2107            let response = request(socket, &inspect).await.unwrap();
2108            if !response.ok {
2109                return response;
2110            }
2111            match response.result["operation"]["state"].as_str() {
2112                Some("succeeded") => {
2113                    return DevelopmentDaemonResponse {
2114                        id: submission.id,
2115                        ok: true,
2116                        result: response.result["operation"]["result"].clone(),
2117                        error: None,
2118                    };
2119                }
2120                Some("failed" | "cancelled" | "indeterminate") => {
2121                    return DevelopmentDaemonResponse {
2122                        id: submission.id,
2123                        ok: false,
2124                        result: Value::Null,
2125                        error: response.result["operation"]["failureReason"]
2126                            .as_str()
2127                            .map(str::to_string)
2128                            .or_else(|| Some("operation did not succeed".into())),
2129                    };
2130                }
2131                _ => tokio::time::sleep(Duration::from_millis(10)).await,
2132            }
2133        }
2134        DevelopmentDaemonResponse {
2135            id: submission.id,
2136            ok: false,
2137            result: Value::Null,
2138            error: Some("operation did not settle in the test deadline".into()),
2139        }
2140    }
2141
2142    #[tokio::test(flavor = "current_thread")]
2143    async fn workspace_actors_do_not_serialize_unrelated_long_operations() {
2144        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2145        let base = std::env::temp_dir().join(format!(
2146            "glassd-actor-concurrency-{}-{sequence}",
2147            std::process::id()
2148        ));
2149        let first_root = base.join("first");
2150        let second_root = base.join("second");
2151        std::fs::create_dir_all(&first_root).unwrap();
2152        std::fs::create_dir_all(&second_root).unwrap();
2153        for root in [&first_root, &second_root] {
2154            std::fs::write(
2155                root.join("Cargo.toml"),
2156                "[package]\nname='stress-fixture'\nversion='0.1.0'\n",
2157            )
2158            .unwrap();
2159        }
2160        let dap_adapter = second_root.join("stress_dap.py");
2161        std::fs::write(
2162            &dap_adapter,
2163            r#"import json, sys
2164while True:
2165    line = sys.stdin.buffer.readline()
2166    if not line:
2167        break
2168    if not line.lower().startswith(b'content-length:'):
2169        continue
2170    length = int(line.split(b':', 1)[1])
2171    while sys.stdin.buffer.readline() not in (b'\r\n', b'\n', b''):
2172        pass
2173    request = json.loads(sys.stdin.buffer.read(length))
2174    response = {'seq': request['seq'] + 1000, 'type': 'response', 'request_seq': request['seq'], 'command': request['command'], 'success': True, 'body': {}}
2175    body = json.dumps(response).encode()
2176    sys.stdout.buffer.write(f'Content-Length: {len(body)}\r\n\r\n'.encode() + body)
2177    sys.stdout.buffer.flush()
2178"#,
2179        )
2180        .unwrap();
2181        let store = WorkspaceTrustStore::at(base.join("trust.json"));
2182        for root in [&first_root, &second_root] {
2183            store
2184                .trust_project(&crate::WorkspaceIdentity::inspect(root).unwrap())
2185                .unwrap();
2186        }
2187        let local = tokio::task::LocalSet::new();
2188        local
2189            .run_until(async {
2190                let actor = |id: &str, root: &Path| {
2191                    let workspace =
2192                        DevelopmentWorkspace::open_with_store(root, store.clone()).unwrap();
2193                    let summary = workspace_summary(id, &workspace);
2194                    let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2195                    let operations = Arc::new(Mutex::new(OperationRegistry::new(id.into())));
2196                    tokio::task::spawn_local(run_workspace_actor(
2197                        id.into(),
2198                        workspace,
2199                        receiver,
2200                        Arc::clone(&operations),
2201                    ));
2202                    WorkspaceActorHandle {
2203                        sender,
2204                        summary,
2205                        operations,
2206                    }
2207                };
2208                let first = actor("first", &first_root);
2209                let second = actor("second", &second_root);
2210                let python = ["python3", "python"]
2211                    .into_iter()
2212                    .find(|program| {
2213                        std::process::Command::new(program)
2214                            .arg("--version")
2215                            .output()
2216                            .is_ok_and(|output| output.status.success())
2217                    })
2218                    .expect("full-suite stress requires Python for the fixture DAP adapter");
2219                workspace_tool(
2220                    second.clone(),
2221                    ToolCall {
2222                        id: "debug-start".into(),
2223                        name: "glass.debug.start".into(),
2224                        arguments: serde_json::json!({
2225                            "session":"stress",
2226                            "command":python,
2227                            "arguments":[dap_adapter],
2228                            "timeoutSeconds":3
2229                        }),
2230                    },
2231                    test_context(),
2232                )
2233                .await
2234                .unwrap();
2235                let (kernel_kind, kernel_code) = if cfg!(windows) {
2236                    ("python", "import time; time.sleep(1); print('complete')")
2237                } else {
2238                    ("shell", "sleep 1; echo complete")
2239                };
2240                workspace_tool(
2241                    first.clone(),
2242                    ToolCall {
2243                        id: "shell-start".into(),
2244                        name: "glass.eval.start".into(),
2245                        arguments: serde_json::json!({"name":"slow","kind":kernel_kind}),
2246                    },
2247                    test_context(),
2248                )
2249                .await
2250                .unwrap();
2251                let slow = tokio::task::spawn_local(workspace_tool(
2252                    first.clone(),
2253                    ToolCall {
2254                        id: "shell-slow".into(),
2255                        name: "glass.eval.execute".into(),
2256                        arguments: serde_json::json!({
2257                            "name":"slow",
2258                            "code":kernel_code,
2259                            "timeoutSeconds":3
2260                        }),
2261                    },
2262                    test_context(),
2263                ));
2264                tokio::time::sleep(Duration::from_millis(50)).await;
2265                let started = std::time::Instant::now();
2266                let (inspect, browser, lsp, debug, tests, processes) = tokio::join!(
2267                    workspace_inspect(second.clone()),
2268                    workspace_tool(
2269                        second.clone(),
2270                        ToolCall {
2271                            id: "browser-state".into(),
2272                            name: "glass.browser.state".into(),
2273                            arguments: serde_json::json!({}),
2274                        },
2275                        test_context(),
2276                    ),
2277                    workspace_tool(
2278                        second.clone(),
2279                        ToolCall {
2280                            id: "lsp-list".into(),
2281                            name: "glass.lsp.list".into(),
2282                            arguments: serde_json::json!({}),
2283                        },
2284                        test_context(),
2285                    ),
2286                    workspace_tool(
2287                        second.clone(),
2288                        ToolCall {
2289                            id: "debug-events".into(),
2290                            name: "glass.debug.events".into(),
2291                            arguments: serde_json::json!({"session":"stress"}),
2292                        },
2293                        test_context(),
2294                    ),
2295                    workspace_tool(
2296                        second.clone(),
2297                        ToolCall {
2298                            id: "test-discover".into(),
2299                            name: "glass.test.discover".into(),
2300                            arguments: serde_json::json!({}),
2301                        },
2302                        test_context(),
2303                    ),
2304                    workspace_tool(
2305                        second.clone(),
2306                        ToolCall {
2307                            id: "process-list".into(),
2308                            name: "glass.process.list".into(),
2309                            arguments: serde_json::json!({}),
2310                        },
2311                        test_context(),
2312                    ),
2313                );
2314                let elapsed = started.elapsed();
2315                let inspect = inspect.unwrap();
2316                assert_eq!(inspect["workspace"]["id"], "second");
2317                assert!(browser.is_ok());
2318                assert!(lsp.is_ok());
2319                assert!(debug.is_ok());
2320                assert!(tests.is_ok());
2321                assert!(processes.is_ok());
2322                assert!(
2323                    elapsed < Duration::from_millis(300),
2324                    "unrelated workspace inspect waited {elapsed:?}"
2325                );
2326                assert!(slow.await.unwrap().is_ok());
2327                for handle in [first, second] {
2328                    let (response, received) = tokio::sync::oneshot::channel();
2329                    handle
2330                        .sender
2331                        .send(WorkspaceCommand::Shutdown { response })
2332                        .await
2333                        .unwrap();
2334                    received.await.unwrap();
2335                }
2336            })
2337            .await;
2338        std::fs::remove_dir_all(base).unwrap();
2339    }
2340
2341    #[tokio::test(flavor = "current_thread")]
2342    async fn long_operations_reconnect_reconcile_and_cancel_by_stable_id() {
2343        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2344        let root = std::env::temp_dir().join(format!(
2345            "glassd-operation-lifecycle-{}-{sequence}",
2346            std::process::id()
2347        ));
2348        std::fs::create_dir_all(&root).unwrap();
2349        let store = WorkspaceTrustStore::at(root.join("trust.json"));
2350        store
2351            .trust_project(&crate::WorkspaceIdentity::inspect(&root).unwrap())
2352            .unwrap();
2353        let local = tokio::task::LocalSet::new();
2354        local
2355            .run_until(async {
2356                let workspace =
2357                    DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
2358                let summary = workspace_summary("operations", &workspace);
2359                let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2360                let operations = Arc::new(Mutex::new(OperationRegistry::new("operations".into())));
2361                tokio::task::spawn_local(run_workspace_actor(
2362                    "operations".into(),
2363                    workspace,
2364                    receiver,
2365                    Arc::clone(&operations),
2366                ));
2367                let handle = WorkspaceActorHandle {
2368                    sender: sender.clone(),
2369                    summary: summary.clone(),
2370                    operations: Arc::clone(&operations),
2371                };
2372                let (kernel_kind, slow_code) = if cfg!(windows) {
2373                    ("python", "import time; time.sleep(0.2); print('complete')")
2374                } else {
2375                    ("shell", "sleep 0.2; echo complete")
2376                };
2377                workspace_tool(
2378                    handle.clone(),
2379                    ToolCall {
2380                        id: "operation-kernel-start".into(),
2381                        name: "glass.eval.start".into(),
2382                        arguments: serde_json::json!({"name":"operation","kind":kernel_kind}),
2383                    },
2384                    test_context(),
2385                )
2386                .await
2387                .unwrap();
2388
2389                let (first, created) = operations
2390                    .lock()
2391                    .unwrap()
2392                    .submit(
2393                        "stable-request",
2394                        "test-client".into(),
2395                        "glass.eval.execute".into(),
2396                        0,
2397                        true,
2398                    )
2399                    .unwrap();
2400                assert!(created);
2401                sender
2402                    .send(WorkspaceCommand::SubmitOperation {
2403                        operation_id: first.id.clone(),
2404                        call: ToolCall {
2405                            id: "operation-slow".into(),
2406                            name: "glass.eval.execute".into(),
2407                            arguments: serde_json::json!({
2408                                "name":"operation",
2409                                "code":slow_code,
2410                                "timeoutSeconds":2
2411                            }),
2412                        },
2413                        context: Box::new(test_context()),
2414                    })
2415                    .await
2416                    .unwrap();
2417
2418                // A fresh handle models a disconnected client recovering the same operation.
2419                let reconnected = WorkspaceActorHandle {
2420                    sender: sender.clone(),
2421                    summary,
2422                    operations: Arc::clone(&operations),
2423                };
2424                let immediate = reconnected.operations.lock().unwrap().records[&first.id].clone();
2425                assert!(matches!(
2426                    immediate.state,
2427                    DevelopmentOperationState::Queued | DevelopmentOperationState::Running
2428                ));
2429                let duplicate = operations
2430                    .lock()
2431                    .unwrap()
2432                    .submit(
2433                        "stable-request",
2434                        "test-client".into(),
2435                        "glass.eval.execute".into(),
2436                        0,
2437                        true,
2438                    )
2439                    .unwrap();
2440                assert!(!duplicate.1);
2441                assert_eq!(duplicate.0.id, first.id);
2442                for _ in 0..100 {
2443                    if operations.lock().unwrap().records[&first.id].state
2444                        == DevelopmentOperationState::Succeeded
2445                    {
2446                        break;
2447                    }
2448                    tokio::time::sleep(Duration::from_millis(10)).await;
2449                }
2450                let finished = operations.lock().unwrap().records[&first.id].clone();
2451                assert_eq!(finished.state, DevelopmentOperationState::Succeeded);
2452                assert!(finished.result.is_some());
2453                assert_eq!(finished.revision_after, Some(0));
2454
2455                let (cancelled, _) = operations
2456                    .lock()
2457                    .unwrap()
2458                    .submit(
2459                        "cancel-request",
2460                        "test-client".into(),
2461                        "glass.eval.execute".into(),
2462                        0,
2463                        true,
2464                    )
2465                    .unwrap();
2466                sender
2467                    .send(WorkspaceCommand::SubmitOperation {
2468                        operation_id: cancelled.id.clone(),
2469                        call: ToolCall {
2470                            id: "operation-cancel".into(),
2471                            name: "glass.eval.execute".into(),
2472                            arguments: serde_json::json!({
2473                                "name":"operation",
2474                                "code":slow_code,
2475                                "timeoutSeconds":2
2476                            }),
2477                        },
2478                        context: Box::new(test_context()),
2479                    })
2480                    .await
2481                    .unwrap();
2482                for _ in 0..100 {
2483                    if operations.lock().unwrap().records[&cancelled.id].state
2484                        == DevelopmentOperationState::Running
2485                    {
2486                        break;
2487                    }
2488                    tokio::time::sleep(Duration::from_millis(5)).await;
2489                }
2490                let cancelling = operations.lock().unwrap().cancel(&cancelled.id).unwrap();
2491                assert!(cancelling.cancellation_requested);
2492                for _ in 0..100 {
2493                    if operations.lock().unwrap().records[&cancelled.id].state
2494                        == DevelopmentOperationState::Cancelled
2495                    {
2496                        break;
2497                    }
2498                    tokio::time::sleep(Duration::from_millis(10)).await;
2499                }
2500                assert_eq!(
2501                    operations.lock().unwrap().records[&cancelled.id].state,
2502                    DevelopmentOperationState::Cancelled
2503                );
2504                assert!(
2505                    operations
2506                        .lock()
2507                        .unwrap()
2508                        .events
2509                        .iter()
2510                        .any(|event| event.operation_id == first.id
2511                            && event.state == DevelopmentOperationState::Succeeded)
2512                );
2513
2514                let (response, received) = tokio::sync::oneshot::channel();
2515                reconnected
2516                    .sender
2517                    .send(WorkspaceCommand::Shutdown { response })
2518                    .await
2519                    .unwrap();
2520                received.await.unwrap();
2521            })
2522            .await;
2523        std::fs::remove_dir_all(root).unwrap();
2524    }
2525
2526    #[tokio::test(flavor = "current_thread")]
2527    async fn workspace_event_cursors_survive_client_reconnects() {
2528        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2529        let root = std::env::temp_dir().join(format!(
2530            "glassd-event-cursor-{}-{sequence}",
2531            std::process::id()
2532        ));
2533        std::fs::create_dir_all(&root).unwrap();
2534        let local = tokio::task::LocalSet::new();
2535        local
2536            .run_until(async {
2537                let workspace = DevelopmentWorkspace::open(&root).unwrap();
2538                let summary = workspace_summary("events", &workspace);
2539                let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2540                let operations = Arc::new(Mutex::new(OperationRegistry::new("events".into())));
2541                tokio::task::spawn_local(run_workspace_actor(
2542                    "events".into(),
2543                    workspace,
2544                    receiver,
2545                    Arc::clone(&operations),
2546                ));
2547                let first_client = WorkspaceActorHandle {
2548                    sender: sender.clone(),
2549                    summary: summary.clone(),
2550                    operations: Arc::clone(&operations),
2551                };
2552                workspace_tool(
2553                    first_client,
2554                    ToolCall {
2555                        id: "task-list".into(),
2556                        name: "glass.task.list".into(),
2557                        arguments: serde_json::json!({}),
2558                    },
2559                    test_context(),
2560                )
2561                .await
2562                .unwrap();
2563                let first = workspace_events(
2564                    WorkspaceActorHandle {
2565                        sender: sender.clone(),
2566                        summary: summary.clone(),
2567                        operations: Arc::clone(&operations),
2568                    },
2569                    0,
2570                    16,
2571                )
2572                .await
2573                .unwrap();
2574                assert_eq!(first["events"][0]["kind"], "workspace.opened");
2575                assert_eq!(first["events"][1]["kind"], "task.changed");
2576                let cursor = first["newestSequence"].as_u64().unwrap();
2577
2578                // A fresh handle models a client reconnecting to the same actor.
2579                let reconnected = WorkspaceActorHandle {
2580                    sender,
2581                    summary,
2582                    operations,
2583                };
2584                workspace_tool(
2585                    reconnected.clone(),
2586                    ToolCall {
2587                        id: "task-list-after-reconnect".into(),
2588                        name: "glass.task.list".into(),
2589                        arguments: serde_json::json!({}),
2590                    },
2591                    test_context(),
2592                )
2593                .await
2594                .unwrap();
2595                let resumed = workspace_events(reconnected, cursor, 16).await.unwrap();
2596                assert_eq!(resumed["events"].as_array().unwrap().len(), 1);
2597                assert_eq!(resumed["events"][0]["kind"], "task.changed");
2598                assert_eq!(resumed["lostBefore"], Value::Null);
2599            })
2600            .await;
2601        std::fs::remove_dir_all(root).unwrap();
2602    }
2603
2604    #[test]
2605    fn workspace_event_overflow_is_bounded_and_observable() {
2606        let mut events = VecDeque::with_capacity(WORKSPACE_EVENT_CAPACITY);
2607        let mut next = 1;
2608        let mut dropped = 0;
2609        for index in 0..=WORKSPACE_EVENT_CAPACITY {
2610            push_workspace_event(
2611                "bounded",
2612                &mut events,
2613                &mut next,
2614                &mut dropped,
2615                "workspace.changed",
2616                Some(format!("call-{index}")),
2617                true,
2618            );
2619        }
2620        let batch = workspace_event_batch(&events, next, dropped, 0, MAX_EVENT_BATCH);
2621        assert_eq!(events.len(), WORKSPACE_EVENT_CAPACITY);
2622        assert_eq!(batch["droppedEvents"], 1);
2623        assert_eq!(batch["lostBefore"], 2);
2624        assert_eq!(batch["events"].as_array().unwrap().len(), MAX_EVENT_BATCH);
2625    }
2626
2627    #[tokio::test(flavor = "current_thread")]
2628    #[cfg(unix)]
2629    async fn daemon_preserves_resources_across_client_disconnects() {
2630        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2631        let base =
2632            std::env::temp_dir().join(format!("glassd-test-{}-{sequence}", std::process::id()));
2633        let project = base.join("project");
2634        std::fs::create_dir_all(&project).unwrap();
2635        std::fs::write(
2636            project.join("Cargo.toml"),
2637            "[package]\nname='x'\nversion='0.1.0'\n",
2638        )
2639        .unwrap();
2640        let trust_store = WorkspaceTrustStore::at(base.join("trust.json"));
2641        trust_store
2642            .trust_project(&crate::WorkspaceIdentity::inspect(&project).unwrap())
2643            .unwrap();
2644        let socket = base.join("glassd.sock");
2645        let status = base.join("glassd.json");
2646        let local = tokio::task::LocalSet::new();
2647        local
2648            .run_until(async {
2649                let server_socket = socket.clone();
2650                let server_status = status.clone();
2651                let server_trust_store = trust_store.clone();
2652                let server = tokio::task::spawn_local(async move {
2653                    serve_with_store(&server_socket, &server_status, server_trust_store)
2654                        .await
2655                        .unwrap()
2656                });
2657                for _ in 0..100 {
2658                    if status.exists() && socket.exists() {
2659                        break;
2660                    }
2661                    tokio::time::sleep(Duration::from_millis(10)).await;
2662                }
2663                let token = std::fs::read_to_string(token_path(&status)).unwrap();
2664                let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2665                    id: id.into(),
2666                    token: token.clone(),
2667                    operation: operation.into(),
2668                    workspace_id: Some("fixture".into()),
2669                    root: None,
2670                    call: None,
2671                    expected_generation: None,
2672                    expected_project_revision: None,
2673                    allow_mutation: false,
2674                    confirmed: false,
2675                    actor: Some("test-client".into()),
2676                    since: None,
2677                    limit: None,
2678                    operation_id: None,
2679                };
2680                let mut open = base_request("open", "workspace.open");
2681                open.root = Some(project.clone());
2682                assert!(request(&socket, &open).await.unwrap().ok);
2683                let mut start = base_request("start", "operation.submit");
2684                start.call = Some(ToolCall {
2685                    id: "kernel-start".into(),
2686                    name: "glass.eval.start".into(),
2687                    arguments: serde_json::json!({"name":"durable","kind":"sql"}),
2688                });
2689                start.expected_generation = Some(1);
2690                start.expected_project_revision = Some(0);
2691                start.allow_mutation = true;
2692                start.confirmed = true;
2693                assert!(submit_and_wait(&socket, &start).await.ok);
2694                let mut process_start = base_request("process-start", "operation.submit");
2695                process_start.call = Some(ToolCall {
2696                    id: "process-start".into(),
2697                    name: "glass.process.start".into(),
2698                    arguments: serde_json::json!({"name":"durable-process","command":"sleep 30"}),
2699                });
2700                process_start.expected_generation = Some(1);
2701                process_start.expected_project_revision = Some(0);
2702                process_start.allow_mutation = true;
2703                process_start.confirmed = true;
2704                assert!(submit_and_wait(&socket, &process_start).await.ok);
2705                let pi_available = std::process::Command::new("pi")
2706                    .arg("--version")
2707                    .output()
2708                    .is_ok();
2709                if pi_available {
2710                    let mut agent_start = base_request("agent-start", "operation.submit");
2711                    agent_start.call = Some(ToolCall {
2712                        id: "agent-start".into(),
2713                        name: "glass.agent.spawn".into(),
2714                        arguments: serde_json::json!({"spec":{
2715                            "role":"durability-probe",
2716                            "task":"Remain idle while the client reconnects",
2717                            "dependencies":[],
2718                            "model":null,
2719                            "thinking":null,
2720                            "worktree":null,
2721                            "unrestricted":false,
2722                            "maxRuntimeSeconds":60,
2723                            "maxEvents":100
2724                        }}),
2725                    });
2726                    agent_start.expected_generation = Some(1);
2727                    agent_start.expected_project_revision = Some(1);
2728                    agent_start.allow_mutation = true;
2729                    agent_start.confirmed = true;
2730                    let agent_response = submit_and_wait(&socket, &agent_start).await;
2731                    assert!(agent_response.ok, "{:?}", agent_response.error);
2732                }
2733                let browser_e2e = std::env::var("GLASS_E2E").as_deref() == Ok("1")
2734                    && std::env::var_os("GLASS_CHROME_PATH").is_some();
2735                if browser_e2e {
2736                    let port_probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2737                    let browser_port = port_probe.local_addr().unwrap().port();
2738                    drop(port_probe);
2739                    let mut browser_start = base_request("browser-start", "operation.submit");
2740                    browser_start.call = Some(ToolCall {
2741                        id: "browser-start".into(),
2742                        name: "glass.browser.start".into(),
2743                        arguments: serde_json::json!({
2744                            "port":browser_port,
2745                            "incognito":true,
2746                            "chromePath":std::env::var("GLASS_CHROME_PATH").unwrap()
2747                        }),
2748                    });
2749                    browser_start.expected_generation = Some(1);
2750                    browser_start.expected_project_revision = Some(1);
2751                    browser_start.allow_mutation = true;
2752                    browser_start.confirmed = true;
2753                    let response = submit_and_wait(&socket, &browser_start).await;
2754                    assert!(response.ok, "{:?}", response.error);
2755                }
2756                // The Pi-style broker opens a new process/socket and still
2757                // executes against the same daemon-owned kernel.
2758                let call = ToolCall {
2759                    id: "kernel-execute".into(),
2760                    name: "glass.eval.execute".into(),
2761                    arguments: serde_json::json!({"name":"durable","code":"SELECT 42 AS answer"}),
2762                };
2763                let call_path = std::env::temp_dir().join(format!(
2764                    "glass-pi-call-{}-{sequence}.json",
2765                    std::process::id()
2766                ));
2767                write_private(&call_path, &serde_json::to_vec(&call).unwrap()).unwrap();
2768                let result = forward_resident_tool_file_with_context(
2769                    &socket, &token, "fixture", &call_path, &project, true, true,
2770                )
2771                .await
2772                .unwrap();
2773                assert_eq!(result["value"][0]["answer"], 42);
2774                // A fresh socket observes the process and optional Pi worker
2775                // created by earlier, disconnected clients.
2776                let inspect = request(
2777                    &socket,
2778                    &base_request("inspect-reconnected", "workspace.inspect"),
2779                )
2780                .await
2781                .unwrap();
2782                assert!(inspect.ok);
2783                assert!(
2784                    inspect.result["processes"]
2785                        .as_array()
2786                        .unwrap()
2787                        .iter()
2788                        .any(|process| process["name"] == "durable-process")
2789                );
2790                assert!(
2791                    inspect.result["kernels"]
2792                        .as_array()
2793                        .unwrap()
2794                        .iter()
2795                        .any(|kernel| kernel["name"] == "durable")
2796                );
2797                if pi_available {
2798                    assert!(!inspect.result["agents"].as_array().unwrap().is_empty());
2799                }
2800                assert_eq!(inspect.result["browser"]["connected"], browser_e2e);
2801                let mut process_stop = base_request("process-stop", "operation.submit");
2802                process_stop.call = Some(ToolCall {
2803                    id: "process-stop".into(),
2804                    name: "glass.process.stop".into(),
2805                    arguments: serde_json::json!({"name":"durable-process"}),
2806                });
2807                process_stop.expected_generation = Some(1);
2808                process_stop.expected_project_revision = Some(1);
2809                process_stop.allow_mutation = true;
2810                process_stop.confirmed = true;
2811                assert!(submit_and_wait(&socket, &process_stop).await.ok);
2812                if browser_e2e {
2813                    let mut browser_stop = base_request("browser-stop", "operation.submit");
2814                    browser_stop.call = Some(ToolCall {
2815                        id: "browser-stop".into(),
2816                        name: "glass.browser.stop".into(),
2817                        arguments: serde_json::json!({}),
2818                    });
2819                    browser_stop.expected_generation = Some(1);
2820                    browser_stop.expected_project_revision = Some(2);
2821                    browser_stop.allow_mutation = true;
2822                    browser_stop.confirmed = true;
2823                    assert!(submit_and_wait(&socket, &browser_stop).await.ok);
2824                }
2825                server.abort();
2826            })
2827            .await;
2828        let _ = std::fs::remove_dir_all(base);
2829    }
2830
2831    #[tokio::test(flavor = "current_thread")]
2832    #[cfg(unix)]
2833    async fn daemon_reconnect_preserves_untrusted_state_and_cannot_elevate_it() {
2834        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2835        let base = std::env::temp_dir().join(format!(
2836            "glassd-trust-test-{}-{sequence}",
2837            std::process::id()
2838        ));
2839        let project = base.join("project");
2840        std::fs::create_dir_all(&project).unwrap();
2841        std::fs::write(
2842            project.join("glass.toml"),
2843            "[tools.hostile]\ndescription='hostile'\ncommand='echo unsafe'\n",
2844        )
2845        .unwrap();
2846        let socket = base.join("glassd.sock");
2847        let status = base.join("glassd.json");
2848        let local = tokio::task::LocalSet::new();
2849        local
2850            .run_until(async {
2851                let server_socket = socket.clone();
2852                let server_status = status.clone();
2853                let store = WorkspaceTrustStore::at(base.join("trust.json"));
2854                let server = tokio::task::spawn_local(async move {
2855                    serve_with_store(&server_socket, &server_status, store)
2856                        .await
2857                        .unwrap()
2858                });
2859                for _ in 0..100 {
2860                    if status.exists() && socket.exists() {
2861                        break;
2862                    }
2863                    tokio::time::sleep(Duration::from_millis(10)).await;
2864                }
2865                let token = std::fs::read_to_string(token_path(&status)).unwrap();
2866                let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2867                    id: id.into(),
2868                    token: token.clone(),
2869                    operation: operation.into(),
2870                    workspace_id: Some("untrusted".into()),
2871                    root: None,
2872                    call: None,
2873                    expected_generation: None,
2874                    expected_project_revision: None,
2875                    allow_mutation: false,
2876                    confirmed: false,
2877                    actor: Some("external-agent".into()),
2878                    since: None,
2879                    limit: None,
2880                    operation_id: None,
2881                };
2882                let mut open = base_request("open", "workspace.open");
2883                open.root = Some(project.clone());
2884                let opened = request(&socket, &open).await.unwrap();
2885                assert!(opened.ok);
2886                assert_eq!(opened.result["trust"], "untrusted");
2887
2888                // Each request creates a fresh client connection. Reconnecting
2889                // observes the same state but has no trust-mutation operation.
2890                let inspected = request(&socket, &base_request("inspect", "workspace.inspect"))
2891                    .await
2892                    .unwrap();
2893                assert!(inspected.ok);
2894                assert_eq!(inspected.result["workspace"]["trust"], "untrusted");
2895
2896                let mut tool = base_request("tool", "operation.submit");
2897                tool.call = Some(ToolCall {
2898                    id: "hostile".into(),
2899                    name: "glass.custom.hostile".into(),
2900                    arguments: serde_json::json!({}),
2901                });
2902                tool.expected_generation = Some(1);
2903                tool.expected_project_revision = Some(0);
2904                tool.allow_mutation = true;
2905                tool.confirmed = true;
2906                let denied = submit_and_wait(&socket, &tool).await;
2907                assert!(!denied.ok);
2908                assert!(denied.error.unwrap().contains("trust"));
2909                server.abort();
2910            })
2911            .await;
2912        let _ = std::fs::remove_dir_all(base);
2913    }
2914
2915    #[test]
2916    fn daemon_identifiers_and_status_quotas_fail_closed() {
2917        assert!(validate_identifier("workspace-1", "workspace").is_ok());
2918        assert!(validate_identifier("../escape", "workspace").is_err());
2919    }
2920}