Skip to main content

glass_dev/
lib.rs

1//! Glass Development Environment runtime.
2//!
3//! This crate owns the resident software-development workspace used by the
4//! `glass` product. Browser intelligence remains provided by the one-way
5//! `glass-browser` dependency.
6//!
7//! The interactive TUI separates terminal rendering from workspace work. A
8//! snapshot worker hydrates resident projections and executes governed browser,
9//! Git, agent, and project operations off the input loop. The UI applies
10//! versioned snapshots, keeps drafts and modal state local, and restores the
11//! terminal without waiting for an active bounded job.
12//!
13//! ## Public API
14//!
15//! [`DevelopmentWorkspace`] owns the resident project runtime and its trust
16//! boundary. [`SharedDevelopmentWorkspace`] is the thread-safe handle used by
17//! the TUI, daemon, MCP, and agent services. [`DevelopmentToolRouter`] exposes
18//! governed tool execution, while [`PiReadiness`] and [`PiSessionRequest`]
19//! describe the managed Pi runtime surface.
20//!
21//! The focused browser-only API lives in
22//! [`glass_browser`](https://docs.rs/glass-browser).
23//!
24//! The docs.rs page documents the Rust library API; installed command behavior
25//! is specified in the [CLI reference](https://github.com/wanazhar/glass/blob/main/docs/cli.md).
26//!
27//! ## Quick start
28//!
29//! ```rust,no_run
30//! use glass_dev::DevelopmentWorkspace;
31//!
32//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
33//! let workspace = DevelopmentWorkspace::open(".")?;
34//! println!("{}", workspace.root().display());
35//! # Ok(())
36//! # }
37//! ```
38//!
39//! ## Modules
40//!
41//! [`agents`] owns resident Pi scheduling and evidence. [`browser`] provides
42//! the development browser service. [`development`] contains files, editors,
43//! processes, language services, and project execution. [`tools`] and
44//! [`trust`] enforce governed operations, while [`tui`] and [`workspace`]
45//! connect those services to the interactive product.
46
47pub mod agents;
48pub mod browser;
49pub mod cli;
50pub mod customization;
51pub mod daemon;
52pub mod debugger;
53pub mod development;
54pub mod experiments;
55pub mod git;
56pub mod intelligence;
57pub mod kernels;
58pub mod lsp;
59pub mod mcp;
60pub mod pi_runtime;
61pub mod tasks;
62pub mod testing;
63pub mod tools;
64pub mod trust;
65pub mod tui;
66pub mod workspace;
67
68use glass_browser::cli::args::Cli;
69
70pub use agents::{
71    AgentEvent, AgentId, AgentRegistry, AgentSnapshot, AgentSpec, AgentStatus, ResidentAgentBroker,
72};
73pub use browser::{BrowserRuntimeState, BrowserService, BrowserStartConfig};
74pub use customization::{Customization, GlassConfig, Skill};
75pub use experiments::{
76    ExperimentComparison, ExperimentEvidence, ExperimentManager, ExperimentRanking,
77    ExperimentSnapshot, ExperimentState, ExperimentTrustPolicy, ExperimentWeights,
78};
79pub use intelligence::{
80    CausalPath, DevelopmentEdge, DevelopmentIntelligence, DevelopmentNode, DevelopmentNodeKind,
81    ObservableDevelopmentEvent, ObservableEventInput, ReplayDiff,
82};
83pub use lsp::{LanguageServerConfig, LanguageService, LanguageServiceEvent};
84pub use pi_runtime::{
85    PINNED_PI_SDK_VERSION, PiReadiness, PiReadinessComponent, PiReadinessState, PiSessionRequest,
86};
87pub use tasks::{
88    RetryPolicy, TaskBudget, TaskEvidence, TaskId, TaskScheduler, TaskSnapshot, TaskSpec,
89    TaskState, VerificationRequirement,
90};
91pub use tools::{DevelopmentToolContext, DevelopmentToolRouter};
92pub use trust::{LocalTrustDecision, WorkspaceIdentity, WorkspaceTrust, WorkspaceTrustStore};
93pub use workspace::{DevelopmentWorkspace, SharedDevelopmentWorkspace};
94
95/// Dispatch the full Glass Development Environment.
96///
97/// Resident development commands are handled here. Browser-only commands use
98/// the public browser runtime through the one-way crate dependency.
99pub async fn dispatch(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
100    if cli.mcp {
101        let backend = std::sync::Arc::new(mcp::DevelopmentMcpBackend::open(
102            std::env::current_dir()?,
103            cli.yolo,
104        )?);
105        return glass_browser::mcp::server::run_mcp_server_with_backend(&cli, backend).await;
106    }
107    if let Some(glass_browser::cli::args::Commands::Agent { action }) = &cli.command
108        && matches!(
109            action,
110            glass_browser::cli::args::AgentCommand::Tool { .. }
111                | glass_browser::cli::args::AgentCommand::ToolFile { .. }
112        )
113    {
114        let result = dispatch_external_tool(action, cli.yolo).await?;
115        println!("{}", serde_json::to_string_pretty(&result)?);
116        return Ok(());
117    }
118    if let Some(glass_browser::cli::args::Commands::Agent { action }) = &cli.command {
119        enforce_legacy_development_trust(&cli)?;
120        return cli::dispatch_agent(action, cli.yolo);
121    }
122    if let Some(glass_browser::cli::args::Commands::Daemon { action }) = &cli.command {
123        return daemon::dispatch(action).await;
124    }
125    if let Some(glass_browser::cli::args::Commands::Project { action }) = &cli.command {
126        enforce_legacy_development_trust(&cli)?;
127        return cli::dispatch_project(action);
128    }
129    if cli.command.is_none() && cli.prompt.is_none() && !cli.mcp {
130        let visual_options = tui::TuiVisualOptions {
131            mode: cli.tui_live,
132            backend: cli.tui_live_backend,
133            quality: cli.tui_live_quality,
134            fit: cli.tui_live_fit,
135        };
136        return tui::run(std::env::current_dir()?, cli.tui_layout, visual_options);
137    }
138    enforce_legacy_development_trust(&cli)?;
139    glass_browser::cli::runner::dispatch(cli).await
140}
141
142fn enforce_legacy_development_trust(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
143    use glass_browser::cli::args::{AgentCommand, AgentHarness, Commands, ProjectCommand};
144
145    let (root, safe_static) = match cli.command.as_ref() {
146        Some(Commands::Project { action }) => {
147            let root = match action {
148                ProjectCommand::Inspect { root }
149                | ProjectCommand::Files { root }
150                | ProjectCommand::Search { root, .. }
151                | ProjectCommand::Read { root, .. }
152                | ProjectCommand::Edit { root, .. }
153                | ProjectCommand::Mkdir { root, .. }
154                | ProjectCommand::Rename { root, .. }
155                | ProjectCommand::Delete { root, .. }
156                | ProjectCommand::Diagnostics { root, .. }
157                | ProjectCommand::Run { root, .. }
158                | ProjectCommand::Test { root }
159                | ProjectCommand::Lint { root }
160                | ProjectCommand::Process { root, .. }
161                | ProjectCommand::Diff { root }
162                | ProjectCommand::Link { root, .. }
163                | ProjectCommand::Graph { root, .. }
164                | ProjectCommand::Breakpoint { root, .. }
165                | ProjectCommand::Timeline { root }
166                | ProjectCommand::Replay { root, .. }
167                | ProjectCommand::Neovim { root, .. }
168                | ProjectCommand::Experiment { root, .. }
169                | ProjectCommand::Attach { root, .. } => root,
170            };
171            let safe = matches!(
172                action,
173                ProjectCommand::Inspect { .. }
174                    | ProjectCommand::Files { .. }
175                    | ProjectCommand::Search { .. }
176                    | ProjectCommand::Read { .. }
177                    | ProjectCommand::Diff { .. }
178                    | ProjectCommand::Graph { .. }
179                    | ProjectCommand::Breakpoint { .. }
180                    | ProjectCommand::Timeline { .. }
181                    | ProjectCommand::Replay { .. }
182            );
183            (root, safe)
184        }
185        Some(Commands::Agent { action }) => {
186            let (root, safe) = match action {
187                AgentCommand::Doctor | AgentCommand::Setup { .. } | AgentCommand::Status => {
188                    return Ok(());
189                }
190                AgentCommand::Hello { root, harness } => {
191                    (root, matches!(harness, AgentHarness::Local))
192                }
193                AgentCommand::Prompt { root, harness, .. } => {
194                    (root, matches!(harness, AgentHarness::Local))
195                }
196                AgentCommand::Tool { .. } | AgentCommand::ToolFile { .. } => return Ok(()),
197                AgentCommand::Steer { root, .. }
198                | AgentCommand::FollowUp { root, .. }
199                | AgentCommand::Models { root }
200                | AgentCommand::SetModel { root, .. }
201                | AgentCommand::Thinking { root, .. }
202                | AgentCommand::Abort { root }
203                | AgentCommand::NewSession { root } => (root, false),
204            };
205            (root, safe)
206        }
207        _ => return Ok(()),
208    };
209    let workspace = DevelopmentWorkspace::open(root)?;
210    if workspace.trust() == WorkspaceTrust::Untrusted && !safe_static {
211        return Err(format!(
212            "repository-controlled development execution is blocked for {}; open the TUI to inspect and trust this workspace",
213            workspace.root().display()
214        )
215        .into());
216    }
217    Ok(())
218}
219
220async fn dispatch_external_tool(
221    action: &glass_browser::cli::args::AgentCommand,
222    unrestricted: bool,
223) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
224    use crate::development::{Actor, ToolAuthorization, ToolCall};
225    use glass_browser::cli::args::AgentCommand;
226
227    let (call, root, allow_mutation, confirmed) = match action {
228        AgentCommand::Tool {
229            call,
230            root,
231            allow_mutation,
232            yes,
233        } => (
234            serde_json::from_str::<ToolCall>(call)?,
235            root,
236            *allow_mutation || unrestricted,
237            *yes || unrestricted,
238        ),
239        AgentCommand::ToolFile {
240            path,
241            root,
242            allow_mutation,
243            yes,
244        } if std::env::var_os("GLASS_DEV_DAEMON_SOCKET").is_some() => {
245            return daemon::forward_resident_tool_file(
246                path,
247                root,
248                *allow_mutation || unrestricted,
249                *yes || unrestricted,
250            )
251            .await;
252        }
253        AgentCommand::ToolFile {
254            path,
255            root,
256            allow_mutation,
257            yes,
258        } => (
259            daemon::read_private_tool_call(path)?,
260            root,
261            *allow_mutation || unrestricted,
262            *yes || unrestricted,
263        ),
264        _ => return Err("expected an external agent tool action".into()),
265    };
266    let mut workspace = DevelopmentWorkspace::open(root)?;
267    let context = DevelopmentToolContext {
268        authorization: ToolAuthorization {
269            actor: Actor::external("cli"),
270            allow_mutation,
271            confirmed,
272        },
273        initiator: None,
274        expected_generation: workspace.generation(),
275        expected_project_revision: workspace.project().revision(),
276    };
277    Ok(workspace.execute_tool(&call, &context)?)
278}