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
1929pub fn log_tail(status_path: Option<&Path>) -> Result<String, Box<dyn std::error::Error>> {
1930    let (_, default_status) = default_paths();
1931    bounded_log(status_path.unwrap_or(&default_status))
1932}
1933
1934fn bounded_log(status: &Path) -> Result<String, Box<dyn std::error::Error>> {
1935    use std::io::{Read, Seek, SeekFrom};
1936    let mut file = std::fs::File::open(log_path(status))?;
1937    let length = file.metadata()?.len();
1938    let start = length.saturating_sub(64 * 1024);
1939    file.seek(SeekFrom::Start(start))?;
1940    let mut output = String::new();
1941    file.read_to_string(&mut output)?;
1942    Ok(output)
1943}
1944
1945#[cfg(unix)]
1946fn authorize_local_peer(
1947    _stream: &tokio::net::UnixStream,
1948) -> Result<(), Box<dyn std::error::Error>> {
1949    #[cfg(target_os = "linux")]
1950    {
1951        use std::os::fd::AsRawFd;
1952        let mut credentials = libc::ucred {
1953            pid: 0,
1954            uid: 0,
1955            gid: 0,
1956        };
1957        let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
1958        let result = unsafe {
1959            libc::getsockopt(
1960                _stream.as_raw_fd(),
1961                libc::SOL_SOCKET,
1962                libc::SO_PEERCRED,
1963                (&mut credentials as *mut libc::ucred).cast(),
1964                &mut length,
1965            )
1966        };
1967        if result != 0 || credentials.uid != unsafe { libc::geteuid() } {
1968            return Err("daemon rejected a non-local-user peer".into());
1969        }
1970    }
1971    Ok(())
1972}
1973
1974#[cfg(unix)]
1975fn remove_socket_if_safe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1976    use std::os::unix::fs::FileTypeExt;
1977    match std::fs::symlink_metadata(path) {
1978        Ok(metadata) if metadata.file_type().is_socket() => std::fs::remove_file(path)?,
1979        Ok(_) => return Err(format!("refusing to replace non-socket {}", path.display()).into()),
1980        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1981        Err(error) => return Err(error.into()),
1982    }
1983    Ok(())
1984}
1985
1986#[cfg(not(unix))]
1987fn remove_socket_if_safe(_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1988    Ok(())
1989}
1990
1991fn process_alive(pid: u32) -> bool {
1992    #[cfg(unix)]
1993    {
1994        unsafe { libc::kill(pid as i32, 0) == 0 }
1995    }
1996    #[cfg(windows)]
1997    {
1998        use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
1999        use windows_sys::Win32::System::Threading::{
2000            GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
2001        };
2002        let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
2003        if process.is_null() {
2004            return false;
2005        }
2006        let mut exit_code = 0_u32;
2007        let success = unsafe { GetExitCodeProcess(process, &mut exit_code) } != 0;
2008        unsafe { CloseHandle(process) };
2009        success && exit_code == STILL_ACTIVE as u32
2010    }
2011    #[cfg(not(any(unix, windows)))]
2012    {
2013        let _ = pid;
2014        false
2015    }
2016}
2017
2018#[cfg(windows)]
2019fn validate_windows_pipe_name(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
2020    let value = path
2021        .to_str()
2022        .ok_or("Windows named-pipe endpoint must be Unicode")?;
2023    if !valid_windows_pipe_name(value) {
2024        return Err("invalid Windows Glass daemon pipe name".into());
2025    }
2026    Ok(())
2027}
2028
2029#[cfg(any(windows, test))]
2030fn valid_windows_pipe_name(value: &str) -> bool {
2031    value
2032        .strip_prefix(r"\\.\pipe\glass-dev-")
2033        .is_some_and(|name| {
2034            !name.is_empty()
2035                && name.len() <= 64
2036                && name
2037                    .chars()
2038                    .all(|character| character.is_ascii_alphanumeric() || character == '-')
2039        })
2040}
2041
2042fn effective_uid() -> u32 {
2043    #[cfg(unix)]
2044    {
2045        unsafe { libc::geteuid() }
2046    }
2047    #[cfg(not(unix))]
2048    {
2049        0
2050    }
2051}
2052
2053fn now_ms() -> u128 {
2054    SystemTime::now()
2055        .duration_since(UNIX_EPOCH)
2056        .unwrap_or_default()
2057        .as_millis()
2058}
2059
2060#[cfg(test)]
2061mod tests {
2062    use super::*;
2063    use std::sync::atomic::{AtomicU64, Ordering};
2064
2065    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2066
2067    #[test]
2068    fn windows_pipe_names_are_local_and_glass_owned() {
2069        assert!(valid_windows_pipe_name(
2070            r"\\.\pipe\glass-dev-0123456789abcdef"
2071        ));
2072        assert!(!valid_windows_pipe_name(r"\\server\pipe\glass-dev-test"));
2073        assert!(!valid_windows_pipe_name(r"\\.\pipe\other-product"));
2074        assert!(!valid_windows_pipe_name(r"\\.\pipe\glass-dev-bad/name"));
2075    }
2076
2077    fn test_context() -> DevelopmentToolContext {
2078        DevelopmentToolContext {
2079            authorization: ToolAuthorization {
2080                actor: Actor::external("daemon-concurrency-test"),
2081                allow_mutation: true,
2082                confirmed: true,
2083            },
2084            initiator: None,
2085            expected_generation: 1,
2086            expected_project_revision: 0,
2087        }
2088    }
2089
2090    async fn wait_for_operation_state(
2091        operations: &Arc<Mutex<OperationRegistry>>,
2092        operation_id: &str,
2093        expected: DevelopmentOperationState,
2094    ) {
2095        let deadline =
2096            std::time::Instant::now() + Duration::from_secs(if cfg!(windows) { 20 } else { 5 });
2097        loop {
2098            let state = operations.lock().unwrap().records[operation_id].state;
2099            if state == expected {
2100                return;
2101            }
2102            assert!(
2103                std::time::Instant::now() < deadline,
2104                "operation {operation_id} remained {state:?}, expected {expected:?}; failure_reason={:?}",
2105                operations.lock().unwrap().records[operation_id].failure_reason
2106            );
2107            tokio::time::sleep(Duration::from_millis(10)).await;
2108        }
2109    }
2110
2111    async fn submit_and_wait(
2112        socket: &Path,
2113        request_value: &DevelopmentDaemonRequest,
2114    ) -> DevelopmentDaemonResponse {
2115        let mut submission = request_value.clone();
2116        submission.operation = "operation.submit".into();
2117        let accepted = request(socket, &submission).await.unwrap();
2118        if !accepted.ok {
2119            return accepted;
2120        }
2121        let operation_id = accepted.result["operation"]["id"]
2122            .as_str()
2123            .unwrap()
2124            .to_string();
2125        for sequence in 0..2_000 {
2126            let mut inspect = submission.clone();
2127            inspect.id = format!("inspect-{}-{sequence}", submission.id);
2128            inspect.operation = "operation.inspect".into();
2129            inspect.call = None;
2130            inspect.expected_generation = None;
2131            inspect.expected_project_revision = None;
2132            inspect.allow_mutation = false;
2133            inspect.confirmed = false;
2134            inspect.operation_id = Some(operation_id.clone());
2135            let response = request(socket, &inspect).await.unwrap();
2136            if !response.ok {
2137                return response;
2138            }
2139            match response.result["operation"]["state"].as_str() {
2140                Some("succeeded") => {
2141                    return DevelopmentDaemonResponse {
2142                        id: submission.id,
2143                        ok: true,
2144                        result: response.result["operation"]["result"].clone(),
2145                        error: None,
2146                    };
2147                }
2148                Some("failed" | "cancelled" | "indeterminate") => {
2149                    return DevelopmentDaemonResponse {
2150                        id: submission.id,
2151                        ok: false,
2152                        result: Value::Null,
2153                        error: response.result["operation"]["failureReason"]
2154                            .as_str()
2155                            .map(str::to_string)
2156                            .or_else(|| Some("operation did not succeed".into())),
2157                    };
2158                }
2159                _ => tokio::time::sleep(Duration::from_millis(10)).await,
2160            }
2161        }
2162        DevelopmentDaemonResponse {
2163            id: submission.id,
2164            ok: false,
2165            result: Value::Null,
2166            error: Some("operation did not settle in the test deadline".into()),
2167        }
2168    }
2169
2170    #[tokio::test(flavor = "current_thread")]
2171    async fn workspace_actors_do_not_serialize_unrelated_long_operations() {
2172        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2173        let base = std::env::temp_dir().join(format!(
2174            "glassd-actor-concurrency-{}-{sequence}",
2175            std::process::id()
2176        ));
2177        let first_root = base.join("first");
2178        let second_root = base.join("second");
2179        std::fs::create_dir_all(&first_root).unwrap();
2180        std::fs::create_dir_all(&second_root).unwrap();
2181        for root in [&first_root, &second_root] {
2182            std::fs::write(
2183                root.join("Cargo.toml"),
2184                "[package]\nname='stress-fixture'\nversion='0.1.0'\n",
2185            )
2186            .unwrap();
2187        }
2188        let dap_adapter = second_root.join("stress_dap.py");
2189        std::fs::write(
2190            &dap_adapter,
2191            r#"import json, sys
2192while True:
2193    line = sys.stdin.buffer.readline()
2194    if not line:
2195        break
2196    if not line.lower().startswith(b'content-length:'):
2197        continue
2198    length = int(line.split(b':', 1)[1])
2199    while sys.stdin.buffer.readline() not in (b'\r\n', b'\n', b''):
2200        pass
2201    request = json.loads(sys.stdin.buffer.read(length))
2202    response = {'seq': request['seq'] + 1000, 'type': 'response', 'request_seq': request['seq'], 'command': request['command'], 'success': True, 'body': {}}
2203    body = json.dumps(response).encode()
2204    sys.stdout.buffer.write(f'Content-Length: {len(body)}\r\n\r\n'.encode() + body)
2205    sys.stdout.buffer.flush()
2206"#,
2207        )
2208        .unwrap();
2209        let store = WorkspaceTrustStore::at(base.join("trust.json"));
2210        for root in [&first_root, &second_root] {
2211            store
2212                .trust_project(&crate::WorkspaceIdentity::inspect(root).unwrap())
2213                .unwrap();
2214        }
2215        let local = tokio::task::LocalSet::new();
2216        local
2217            .run_until(async {
2218                let actor = |id: &str, root: &Path| {
2219                    let workspace =
2220                        DevelopmentWorkspace::open_with_store(root, store.clone()).unwrap();
2221                    let summary = workspace_summary(id, &workspace);
2222                    let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2223                    let operations = Arc::new(Mutex::new(OperationRegistry::new(id.into())));
2224                    tokio::task::spawn_local(run_workspace_actor(
2225                        id.into(),
2226                        workspace,
2227                        receiver,
2228                        Arc::clone(&operations),
2229                    ));
2230                    WorkspaceActorHandle {
2231                        sender,
2232                        summary,
2233                        operations,
2234                    }
2235                };
2236                let first = actor("first", &first_root);
2237                let second = actor("second", &second_root);
2238                let python = ["python3", "python"]
2239                    .into_iter()
2240                    .find(|program| {
2241                        std::process::Command::new(program)
2242                            .arg("--version")
2243                            .output()
2244                            .is_ok_and(|output| output.status.success())
2245                    })
2246                    .expect("full-suite stress requires Python for the fixture DAP adapter");
2247                workspace_tool(
2248                    second.clone(),
2249                    ToolCall {
2250                        id: "debug-start".into(),
2251                        name: "glass.debug.start".into(),
2252                        arguments: serde_json::json!({
2253                            "session":"stress",
2254                            "command":python,
2255                            "arguments":[dap_adapter],
2256                            "timeoutSeconds":3
2257                        }),
2258                    },
2259                    test_context(),
2260                )
2261                .await
2262                .unwrap();
2263                let (kernel_kind, kernel_code) = if cfg!(windows) {
2264                    ("python", "import time; time.sleep(3); print('complete')")
2265                } else {
2266                    ("shell", "sleep 3; echo complete")
2267                };
2268                workspace_tool(
2269                    first.clone(),
2270                    ToolCall {
2271                        id: "shell-start".into(),
2272                        name: "glass.eval.start".into(),
2273                        arguments: serde_json::json!({"name":"slow","kind":kernel_kind}),
2274                    },
2275                    test_context(),
2276                )
2277                .await
2278                .unwrap();
2279                let slow = tokio::task::spawn_local(workspace_tool(
2280                    first.clone(),
2281                    ToolCall {
2282                        id: "shell-slow".into(),
2283                        name: "glass.eval.execute".into(),
2284                        arguments: serde_json::json!({
2285                            "name":"slow",
2286                            "code":kernel_code,
2287                            "timeoutSeconds":5
2288                        }),
2289                    },
2290                    test_context(),
2291                ));
2292                tokio::time::sleep(Duration::from_millis(50)).await;
2293                let (inspect, browser, lsp, debug, tests, processes) = tokio::join!(
2294                    workspace_inspect(second.clone()),
2295                    workspace_tool(
2296                        second.clone(),
2297                        ToolCall {
2298                            id: "browser-state".into(),
2299                            name: "glass.browser.state".into(),
2300                            arguments: serde_json::json!({}),
2301                        },
2302                        test_context(),
2303                    ),
2304                    workspace_tool(
2305                        second.clone(),
2306                        ToolCall {
2307                            id: "lsp-list".into(),
2308                            name: "glass.lsp.list".into(),
2309                            arguments: serde_json::json!({}),
2310                        },
2311                        test_context(),
2312                    ),
2313                    workspace_tool(
2314                        second.clone(),
2315                        ToolCall {
2316                            id: "debug-events".into(),
2317                            name: "glass.debug.events".into(),
2318                            arguments: serde_json::json!({"session":"stress"}),
2319                        },
2320                        test_context(),
2321                    ),
2322                    workspace_tool(
2323                        second.clone(),
2324                        ToolCall {
2325                            id: "test-discover".into(),
2326                            name: "glass.test.discover".into(),
2327                            arguments: serde_json::json!({}),
2328                        },
2329                        test_context(),
2330                    ),
2331                    workspace_tool(
2332                        second.clone(),
2333                        ToolCall {
2334                            id: "process-list".into(),
2335                            name: "glass.process.list".into(),
2336                            arguments: serde_json::json!({}),
2337                        },
2338                        test_context(),
2339                    ),
2340                );
2341                let inspect = inspect.unwrap();
2342                assert_eq!(inspect["workspace"]["id"], "second");
2343                assert!(browser.is_ok());
2344                assert!(lsp.is_ok());
2345                assert!(debug.is_ok());
2346                assert!(tests.is_ok());
2347                assert!(processes.is_ok());
2348                assert!(
2349                    !slow.is_finished(),
2350                    "unrelated workspace work waited for the slow operation"
2351                );
2352                assert!(slow.await.unwrap().is_ok());
2353                for handle in [first, second] {
2354                    let (response, received) = tokio::sync::oneshot::channel();
2355                    handle
2356                        .sender
2357                        .send(WorkspaceCommand::Shutdown { response })
2358                        .await
2359                        .unwrap();
2360                    received.await.unwrap();
2361                }
2362            })
2363            .await;
2364        std::fs::remove_dir_all(base).unwrap();
2365    }
2366
2367    #[tokio::test(flavor = "current_thread")]
2368    async fn long_operations_reconnect_reconcile_and_cancel_by_stable_id() {
2369        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2370        let root = std::env::temp_dir().join(format!(
2371            "glassd-operation-lifecycle-{}-{sequence}",
2372            std::process::id()
2373        ));
2374        std::fs::create_dir_all(&root).unwrap();
2375        let store = WorkspaceTrustStore::at(root.join("trust.json"));
2376        store
2377            .trust_project(&crate::WorkspaceIdentity::inspect(&root).unwrap())
2378            .unwrap();
2379        let local = tokio::task::LocalSet::new();
2380        local
2381            .run_until(async {
2382                let workspace =
2383                    DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
2384                let summary = workspace_summary("operations", &workspace);
2385                let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2386                let operations = Arc::new(Mutex::new(OperationRegistry::new("operations".into())));
2387                tokio::task::spawn_local(run_workspace_actor(
2388                    "operations".into(),
2389                    workspace,
2390                    receiver,
2391                    Arc::clone(&operations),
2392                ));
2393                let handle = WorkspaceActorHandle {
2394                    sender: sender.clone(),
2395                    summary: summary.clone(),
2396                    operations: Arc::clone(&operations),
2397                };
2398                let (kernel_kind, slow_code) = if cfg!(windows) {
2399                    ("python", "import time; time.sleep(0.2); print('complete')")
2400                } else {
2401                    ("shell", "sleep 0.2; echo complete")
2402                };
2403                workspace_tool(
2404                    handle.clone(),
2405                    ToolCall {
2406                        id: "operation-kernel-start".into(),
2407                        name: "glass.eval.start".into(),
2408                        arguments: serde_json::json!({"name":"operation","kind":kernel_kind}),
2409                    },
2410                    test_context(),
2411                )
2412                .await
2413                .unwrap();
2414                if cfg!(windows) {
2415                    workspace_tool(
2416                        handle.clone(),
2417                        ToolCall {
2418                            id: "operation-kernel-warmup".into(),
2419                            name: "glass.eval.execute".into(),
2420                            arguments: serde_json::json!({
2421                                "name":"operation",
2422                                "code":"print('ready')",
2423                                "timeoutSeconds":10
2424                            }),
2425                        },
2426                        test_context(),
2427                    )
2428                    .await
2429                    .unwrap();
2430                }
2431
2432                let (first, created) = operations
2433                    .lock()
2434                    .unwrap()
2435                    .submit(
2436                        "stable-request",
2437                        "test-client".into(),
2438                        "glass.eval.execute".into(),
2439                        0,
2440                        true,
2441                    )
2442                    .unwrap();
2443                assert!(created);
2444                sender
2445                    .send(WorkspaceCommand::SubmitOperation {
2446                        operation_id: first.id.clone(),
2447                        call: ToolCall {
2448                            id: "operation-slow".into(),
2449                            name: "glass.eval.execute".into(),
2450                            arguments: serde_json::json!({
2451                                "name":"operation",
2452                                "code":slow_code,
2453                                "timeoutSeconds":2
2454                            }),
2455                        },
2456                        context: Box::new(test_context()),
2457                    })
2458                    .await
2459                    .unwrap();
2460
2461                // A fresh handle models a disconnected client recovering the same operation.
2462                let reconnected = WorkspaceActorHandle {
2463                    sender: sender.clone(),
2464                    summary,
2465                    operations: Arc::clone(&operations),
2466                };
2467                let immediate = reconnected.operations.lock().unwrap().records[&first.id].clone();
2468                assert!(matches!(
2469                    immediate.state,
2470                    DevelopmentOperationState::Queued | DevelopmentOperationState::Running
2471                ));
2472                let duplicate = operations
2473                    .lock()
2474                    .unwrap()
2475                    .submit(
2476                        "stable-request",
2477                        "test-client".into(),
2478                        "glass.eval.execute".into(),
2479                        0,
2480                        true,
2481                    )
2482                    .unwrap();
2483                assert!(!duplicate.1);
2484                assert_eq!(duplicate.0.id, first.id);
2485                wait_for_operation_state(
2486                    &operations,
2487                    &first.id,
2488                    DevelopmentOperationState::Succeeded,
2489                )
2490                .await;
2491                let finished = operations.lock().unwrap().records[&first.id].clone();
2492                assert_eq!(finished.state, DevelopmentOperationState::Succeeded);
2493                assert!(finished.result.is_some());
2494                assert_eq!(finished.revision_after, Some(0));
2495
2496                let (cancelled, _) = operations
2497                    .lock()
2498                    .unwrap()
2499                    .submit(
2500                        "cancel-request",
2501                        "test-client".into(),
2502                        "glass.eval.execute".into(),
2503                        0,
2504                        true,
2505                    )
2506                    .unwrap();
2507                sender
2508                    .send(WorkspaceCommand::SubmitOperation {
2509                        operation_id: cancelled.id.clone(),
2510                        call: ToolCall {
2511                            id: "operation-cancel".into(),
2512                            name: "glass.eval.execute".into(),
2513                            arguments: serde_json::json!({
2514                                "name":"operation",
2515                                "code":if cfg!(windows) {
2516                                    "import time; time.sleep(2); print('cancel')"
2517                                } else {
2518                                    "sleep 2; echo cancel"
2519                                },
2520                                "timeoutSeconds":5
2521                            }),
2522                        },
2523                        context: Box::new(test_context()),
2524                    })
2525                    .await
2526                    .unwrap();
2527                wait_for_operation_state(
2528                    &operations,
2529                    &cancelled.id,
2530                    DevelopmentOperationState::Running,
2531                )
2532                .await;
2533                let cancelling = operations.lock().unwrap().cancel(&cancelled.id).unwrap();
2534                assert!(cancelling.cancellation_requested);
2535                wait_for_operation_state(
2536                    &operations,
2537                    &cancelled.id,
2538                    DevelopmentOperationState::Cancelled,
2539                )
2540                .await;
2541                assert_eq!(
2542                    operations.lock().unwrap().records[&cancelled.id].state,
2543                    DevelopmentOperationState::Cancelled
2544                );
2545                assert!(
2546                    operations
2547                        .lock()
2548                        .unwrap()
2549                        .events
2550                        .iter()
2551                        .any(|event| event.operation_id == first.id
2552                            && event.state == DevelopmentOperationState::Succeeded)
2553                );
2554
2555                let (response, received) = tokio::sync::oneshot::channel();
2556                reconnected
2557                    .sender
2558                    .send(WorkspaceCommand::Shutdown { response })
2559                    .await
2560                    .unwrap();
2561                received.await.unwrap();
2562            })
2563            .await;
2564        std::fs::remove_dir_all(root).unwrap();
2565    }
2566
2567    #[tokio::test(flavor = "current_thread")]
2568    async fn workspace_event_cursors_survive_client_reconnects() {
2569        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2570        let root = std::env::temp_dir().join(format!(
2571            "glassd-event-cursor-{}-{sequence}",
2572            std::process::id()
2573        ));
2574        std::fs::create_dir_all(&root).unwrap();
2575        let local = tokio::task::LocalSet::new();
2576        local
2577            .run_until(async {
2578                let workspace = DevelopmentWorkspace::open(&root).unwrap();
2579                let summary = workspace_summary("events", &workspace);
2580                let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2581                let operations = Arc::new(Mutex::new(OperationRegistry::new("events".into())));
2582                tokio::task::spawn_local(run_workspace_actor(
2583                    "events".into(),
2584                    workspace,
2585                    receiver,
2586                    Arc::clone(&operations),
2587                ));
2588                let first_client = WorkspaceActorHandle {
2589                    sender: sender.clone(),
2590                    summary: summary.clone(),
2591                    operations: Arc::clone(&operations),
2592                };
2593                workspace_tool(
2594                    first_client,
2595                    ToolCall {
2596                        id: "task-list".into(),
2597                        name: "glass.task.list".into(),
2598                        arguments: serde_json::json!({}),
2599                    },
2600                    test_context(),
2601                )
2602                .await
2603                .unwrap();
2604                let first = workspace_events(
2605                    WorkspaceActorHandle {
2606                        sender: sender.clone(),
2607                        summary: summary.clone(),
2608                        operations: Arc::clone(&operations),
2609                    },
2610                    0,
2611                    16,
2612                )
2613                .await
2614                .unwrap();
2615                assert_eq!(first["events"][0]["kind"], "workspace.opened");
2616                assert_eq!(first["events"][1]["kind"], "task.changed");
2617                let cursor = first["newestSequence"].as_u64().unwrap();
2618
2619                // A fresh handle models a client reconnecting to the same actor.
2620                let reconnected = WorkspaceActorHandle {
2621                    sender,
2622                    summary,
2623                    operations,
2624                };
2625                workspace_tool(
2626                    reconnected.clone(),
2627                    ToolCall {
2628                        id: "task-list-after-reconnect".into(),
2629                        name: "glass.task.list".into(),
2630                        arguments: serde_json::json!({}),
2631                    },
2632                    test_context(),
2633                )
2634                .await
2635                .unwrap();
2636                let resumed = workspace_events(reconnected, cursor, 16).await.unwrap();
2637                assert_eq!(resumed["events"].as_array().unwrap().len(), 1);
2638                assert_eq!(resumed["events"][0]["kind"], "task.changed");
2639                assert_eq!(resumed["lostBefore"], Value::Null);
2640            })
2641            .await;
2642        std::fs::remove_dir_all(root).unwrap();
2643    }
2644
2645    #[test]
2646    fn workspace_event_overflow_is_bounded_and_observable() {
2647        let mut events = VecDeque::with_capacity(WORKSPACE_EVENT_CAPACITY);
2648        let mut next = 1;
2649        let mut dropped = 0;
2650        for index in 0..=WORKSPACE_EVENT_CAPACITY {
2651            push_workspace_event(
2652                "bounded",
2653                &mut events,
2654                &mut next,
2655                &mut dropped,
2656                "workspace.changed",
2657                Some(format!("call-{index}")),
2658                true,
2659            );
2660        }
2661        let batch = workspace_event_batch(&events, next, dropped, 0, MAX_EVENT_BATCH);
2662        assert_eq!(events.len(), WORKSPACE_EVENT_CAPACITY);
2663        assert_eq!(batch["droppedEvents"], 1);
2664        assert_eq!(batch["lostBefore"], 2);
2665        assert_eq!(batch["events"].as_array().unwrap().len(), MAX_EVENT_BATCH);
2666    }
2667
2668    #[tokio::test(flavor = "current_thread")]
2669    #[cfg(unix)]
2670    async fn daemon_preserves_resources_across_client_disconnects() {
2671        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2672        let base =
2673            std::env::temp_dir().join(format!("glassd-test-{}-{sequence}", std::process::id()));
2674        let project = base.join("project");
2675        std::fs::create_dir_all(&project).unwrap();
2676        std::fs::write(
2677            project.join("Cargo.toml"),
2678            "[package]\nname='x'\nversion='0.1.0'\n",
2679        )
2680        .unwrap();
2681        let trust_store = WorkspaceTrustStore::at(base.join("trust.json"));
2682        trust_store
2683            .trust_project(&crate::WorkspaceIdentity::inspect(&project).unwrap())
2684            .unwrap();
2685        let socket = base.join("glassd.sock");
2686        let status = base.join("glassd.json");
2687        let local = tokio::task::LocalSet::new();
2688        local
2689            .run_until(async {
2690                let server_socket = socket.clone();
2691                let server_status = status.clone();
2692                let server_trust_store = trust_store.clone();
2693                let server = tokio::task::spawn_local(async move {
2694                    serve_with_store(&server_socket, &server_status, server_trust_store)
2695                        .await
2696                        .unwrap()
2697                });
2698                for _ in 0..100 {
2699                    if status.exists() && socket.exists() {
2700                        break;
2701                    }
2702                    tokio::time::sleep(Duration::from_millis(10)).await;
2703                }
2704                let token = std::fs::read_to_string(token_path(&status)).unwrap();
2705                let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2706                    id: id.into(),
2707                    token: token.clone(),
2708                    operation: operation.into(),
2709                    workspace_id: Some("fixture".into()),
2710                    root: None,
2711                    call: None,
2712                    expected_generation: None,
2713                    expected_project_revision: None,
2714                    allow_mutation: false,
2715                    confirmed: false,
2716                    actor: Some("test-client".into()),
2717                    since: None,
2718                    limit: None,
2719                    operation_id: None,
2720                };
2721                let mut open = base_request("open", "workspace.open");
2722                open.root = Some(project.clone());
2723                assert!(request(&socket, &open).await.unwrap().ok);
2724                let mut start = base_request("start", "operation.submit");
2725                start.call = Some(ToolCall {
2726                    id: "kernel-start".into(),
2727                    name: "glass.eval.start".into(),
2728                    arguments: serde_json::json!({"name":"durable","kind":"sql"}),
2729                });
2730                start.expected_generation = Some(1);
2731                start.expected_project_revision = Some(0);
2732                start.allow_mutation = true;
2733                start.confirmed = true;
2734                assert!(submit_and_wait(&socket, &start).await.ok);
2735                let mut process_start = base_request("process-start", "operation.submit");
2736                process_start.call = Some(ToolCall {
2737                    id: "process-start".into(),
2738                    name: "glass.process.start".into(),
2739                    arguments: serde_json::json!({"name":"durable-process","command":"sleep 30"}),
2740                });
2741                process_start.expected_generation = Some(1);
2742                process_start.expected_project_revision = Some(0);
2743                process_start.allow_mutation = true;
2744                process_start.confirmed = true;
2745                assert!(submit_and_wait(&socket, &process_start).await.ok);
2746                let pi_available = std::process::Command::new("pi")
2747                    .arg("--version")
2748                    .output()
2749                    .is_ok();
2750                if pi_available {
2751                    let mut agent_start = base_request("agent-start", "operation.submit");
2752                    agent_start.call = Some(ToolCall {
2753                        id: "agent-start".into(),
2754                        name: "glass.agent.spawn".into(),
2755                        arguments: serde_json::json!({"spec":{
2756                            "role":"durability-probe",
2757                            "task":"Remain idle while the client reconnects",
2758                            "dependencies":[],
2759                            "model":null,
2760                            "thinking":null,
2761                            "worktree":null,
2762                            "unrestricted":false,
2763                            "maxRuntimeSeconds":60,
2764                            "maxEvents":100
2765                        }}),
2766                    });
2767                    agent_start.expected_generation = Some(1);
2768                    agent_start.expected_project_revision = Some(1);
2769                    agent_start.allow_mutation = true;
2770                    agent_start.confirmed = true;
2771                    let agent_response = submit_and_wait(&socket, &agent_start).await;
2772                    assert!(agent_response.ok, "{:?}", agent_response.error);
2773                }
2774                let browser_e2e = std::env::var("GLASS_E2E").as_deref() == Ok("1")
2775                    && std::env::var_os("GLASS_CHROME_PATH").is_some();
2776                if browser_e2e {
2777                    let port_probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2778                    let browser_port = port_probe.local_addr().unwrap().port();
2779                    drop(port_probe);
2780                    let mut browser_start = base_request("browser-start", "operation.submit");
2781                    browser_start.call = Some(ToolCall {
2782                        id: "browser-start".into(),
2783                        name: "glass.browser.start".into(),
2784                        arguments: serde_json::json!({
2785                            "port":browser_port,
2786                            "incognito":true,
2787                            "chromePath":std::env::var("GLASS_CHROME_PATH").unwrap()
2788                        }),
2789                    });
2790                    browser_start.expected_generation = Some(1);
2791                    browser_start.expected_project_revision = Some(1);
2792                    browser_start.allow_mutation = true;
2793                    browser_start.confirmed = true;
2794                    let response = submit_and_wait(&socket, &browser_start).await;
2795                    assert!(response.ok, "{:?}", response.error);
2796                }
2797                // The Pi-style broker opens a new process/socket and still
2798                // executes against the same daemon-owned kernel.
2799                let call = ToolCall {
2800                    id: "kernel-execute".into(),
2801                    name: "glass.eval.execute".into(),
2802                    arguments: serde_json::json!({"name":"durable","code":"SELECT 42 AS answer"}),
2803                };
2804                let call_path = std::env::temp_dir().join(format!(
2805                    "glass-pi-call-{}-{sequence}.json",
2806                    std::process::id()
2807                ));
2808                write_private(&call_path, &serde_json::to_vec(&call).unwrap()).unwrap();
2809                let result = forward_resident_tool_file_with_context(
2810                    &socket, &token, "fixture", &call_path, &project, true, true,
2811                )
2812                .await
2813                .unwrap();
2814                assert_eq!(result["value"][0]["answer"], 42);
2815                // A fresh socket observes the process and optional Pi worker
2816                // created by earlier, disconnected clients.
2817                let inspect = request(
2818                    &socket,
2819                    &base_request("inspect-reconnected", "workspace.inspect"),
2820                )
2821                .await
2822                .unwrap();
2823                assert!(inspect.ok);
2824                assert!(
2825                    inspect.result["processes"]
2826                        .as_array()
2827                        .unwrap()
2828                        .iter()
2829                        .any(|process| process["name"] == "durable-process")
2830                );
2831                assert!(
2832                    inspect.result["kernels"]
2833                        .as_array()
2834                        .unwrap()
2835                        .iter()
2836                        .any(|kernel| kernel["name"] == "durable")
2837                );
2838                if pi_available {
2839                    assert!(!inspect.result["agents"].as_array().unwrap().is_empty());
2840                }
2841                assert_eq!(inspect.result["browser"]["connected"], browser_e2e);
2842                let mut process_stop = base_request("process-stop", "operation.submit");
2843                process_stop.call = Some(ToolCall {
2844                    id: "process-stop".into(),
2845                    name: "glass.process.stop".into(),
2846                    arguments: serde_json::json!({"name":"durable-process"}),
2847                });
2848                process_stop.expected_generation = Some(1);
2849                process_stop.expected_project_revision = Some(1);
2850                process_stop.allow_mutation = true;
2851                process_stop.confirmed = true;
2852                assert!(submit_and_wait(&socket, &process_stop).await.ok);
2853                if browser_e2e {
2854                    let mut browser_stop = base_request("browser-stop", "operation.submit");
2855                    browser_stop.call = Some(ToolCall {
2856                        id: "browser-stop".into(),
2857                        name: "glass.browser.stop".into(),
2858                        arguments: serde_json::json!({}),
2859                    });
2860                    browser_stop.expected_generation = Some(1);
2861                    browser_stop.expected_project_revision = Some(2);
2862                    browser_stop.allow_mutation = true;
2863                    browser_stop.confirmed = true;
2864                    assert!(submit_and_wait(&socket, &browser_stop).await.ok);
2865                }
2866                server.abort();
2867            })
2868            .await;
2869        let _ = std::fs::remove_dir_all(base);
2870    }
2871
2872    #[tokio::test(flavor = "current_thread")]
2873    #[cfg(unix)]
2874    async fn daemon_reconnect_preserves_untrusted_state_and_cannot_elevate_it() {
2875        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2876        let base = std::env::temp_dir().join(format!(
2877            "glassd-trust-test-{}-{sequence}",
2878            std::process::id()
2879        ));
2880        let project = base.join("project");
2881        std::fs::create_dir_all(&project).unwrap();
2882        std::fs::write(
2883            project.join("glass.toml"),
2884            "[tools.hostile]\ndescription='hostile'\ncommand='echo unsafe'\n",
2885        )
2886        .unwrap();
2887        let socket = base.join("glassd.sock");
2888        let status = base.join("glassd.json");
2889        let local = tokio::task::LocalSet::new();
2890        local
2891            .run_until(async {
2892                let server_socket = socket.clone();
2893                let server_status = status.clone();
2894                let store = WorkspaceTrustStore::at(base.join("trust.json"));
2895                let server = tokio::task::spawn_local(async move {
2896                    serve_with_store(&server_socket, &server_status, store)
2897                        .await
2898                        .unwrap()
2899                });
2900                for _ in 0..100 {
2901                    if status.exists() && socket.exists() {
2902                        break;
2903                    }
2904                    tokio::time::sleep(Duration::from_millis(10)).await;
2905                }
2906                let token = std::fs::read_to_string(token_path(&status)).unwrap();
2907                let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2908                    id: id.into(),
2909                    token: token.clone(),
2910                    operation: operation.into(),
2911                    workspace_id: Some("untrusted".into()),
2912                    root: None,
2913                    call: None,
2914                    expected_generation: None,
2915                    expected_project_revision: None,
2916                    allow_mutation: false,
2917                    confirmed: false,
2918                    actor: Some("external-agent".into()),
2919                    since: None,
2920                    limit: None,
2921                    operation_id: None,
2922                };
2923                let mut open = base_request("open", "workspace.open");
2924                open.root = Some(project.clone());
2925                let opened = request(&socket, &open).await.unwrap();
2926                assert!(opened.ok);
2927                assert_eq!(opened.result["trust"], "untrusted");
2928
2929                // Each request creates a fresh client connection. Reconnecting
2930                // observes the same state but has no trust-mutation operation.
2931                let inspected = request(&socket, &base_request("inspect", "workspace.inspect"))
2932                    .await
2933                    .unwrap();
2934                assert!(inspected.ok);
2935                assert_eq!(inspected.result["workspace"]["trust"], "untrusted");
2936
2937                let mut tool = base_request("tool", "operation.submit");
2938                tool.call = Some(ToolCall {
2939                    id: "hostile".into(),
2940                    name: "glass.custom.hostile".into(),
2941                    arguments: serde_json::json!({}),
2942                });
2943                tool.expected_generation = Some(1);
2944                tool.expected_project_revision = Some(0);
2945                tool.allow_mutation = true;
2946                tool.confirmed = true;
2947                let denied = submit_and_wait(&socket, &tool).await;
2948                assert!(!denied.ok);
2949                assert!(denied.error.unwrap().contains("trust"));
2950                server.abort();
2951            })
2952            .await;
2953        let _ = std::fs::remove_dir_all(base);
2954    }
2955
2956    #[test]
2957    fn daemon_identifiers_and_status_quotas_fail_closed() {
2958        assert!(validate_identifier("workspace-1", "workspace").is_ok());
2959        assert!(validate_identifier("../escape", "workspace").is_err());
2960    }
2961}