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
47/// Resident Pi agent scheduling, evidence, and lifecycle control.
48pub mod agents;
49/// Development-browser service owned by the resident workspace worker.
50pub mod browser;
51/// Command-line argument and dispatch support for Glass Dev.
52pub mod cli;
53/// User and project customization loading.
54pub mod customization;
55/// Resident development daemon integration.
56pub mod daemon;
57/// Debugging and semantic breakpoint support.
58pub mod debugger;
59/// Files, editors, processes, language services, and project execution.
60pub mod development;
61/// Experiment orchestration and comparison.
62pub mod experiments;
63/// One-shot adapters for installed external coding agents.
64pub mod external_agents;
65/// Governed Git workspace operations.
66pub mod git;
67/// GitHub status, review, and pull-request shipping operations.
68pub mod github;
69/// Discovery and safe handoff of installed coding harnesses.
70pub mod harness;
71/// Development graph and causal intelligence projections.
72pub mod intelligence;
73/// Kernel process and runtime integration.
74pub mod kernels;
75/// LSP-facing language service integration.
76pub mod lsp;
77/// MCP server and tool integration.
78pub mod mcp;
79/// Managed Pi runtime readiness and sessions.
80pub mod pi_runtime;
81/// Task scheduling, evidence, and verification requirements.
82pub mod tasks;
83/// Test execution and result collection.
84pub mod testing;
85/// Governed development-tool routing.
86pub mod tools;
87/// Workspace trust decisions and persistence.
88pub mod trust;
89/// Interactive Glass Dev terminal application.
90pub mod tui;
91/// Workspace ownership and shared handles.
92pub mod workspace;
93
94use glass_browser::cli::args::Cli;
95
96/// Resident Pi agent types and scheduler handles.
97pub use agents::{
98    AgentEvent, AgentId, AgentRegistry, AgentSnapshot, AgentSpec, AgentStatus, ResidentAgentBroker,
99};
100/// Development browser configuration, state, and service handle.
101pub use browser::{BrowserRuntimeState, BrowserService, BrowserStartConfig};
102/// User-facing customization and skill configuration.
103pub use customization::{Customization, GlassConfig, Skill};
104/// Experiment management and comparison types.
105pub use experiments::{
106    ExperimentComparison, ExperimentEvidence, ExperimentManager, ExperimentRanking,
107    ExperimentSnapshot, ExperimentState, ExperimentTrustPolicy, ExperimentWeights,
108};
109/// Development intelligence graph and replay types.
110pub use intelligence::{
111    CausalPath, DevelopmentEdge, DevelopmentIntelligence, DevelopmentNode, DevelopmentNodeKind,
112    ObservableDevelopmentEvent, ObservableEventInput, ReplayDiff,
113};
114/// Language-service configuration and event types.
115pub use lsp::{LanguageServerConfig, LanguageService, LanguageServiceEvent};
116/// Pi readiness and managed-session request types.
117pub use pi_runtime::{
118    PINNED_PI_SDK_VERSION, PiReadiness, PiReadinessComponent, PiReadinessState, PiSessionRequest,
119};
120/// Task scheduling, retry, evidence, and verification types.
121pub use tasks::{
122    RetryPolicy, TaskBudget, TaskEvidence, TaskId, TaskScheduler, TaskSnapshot, TaskSpec,
123    TaskState, VerificationRequirement,
124};
125/// Governed tool execution context and router.
126pub use tools::{DevelopmentToolContext, DevelopmentToolRouter};
127/// Workspace trust identities, decisions, and persistence.
128pub use trust::{LocalTrustDecision, WorkspaceIdentity, WorkspaceTrust, WorkspaceTrustStore};
129/// Workspace owners and thread-safe handles.
130pub use workspace::{DevelopmentWorkspace, SharedDevelopmentWorkspace};
131
132/// Dispatch the full Glass Development Environment.
133///
134/// Resident development commands are handled here. Browser-only commands use
135/// the public browser runtime through the one-way crate dependency.
136pub async fn dispatch(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
137    if cli.mcp {
138        let backend = std::sync::Arc::new(mcp::DevelopmentMcpBackend::open(
139            std::env::current_dir()?,
140            cli.yolo,
141        )?);
142        return glass_browser::mcp::server::run_mcp_server_with_backend(&cli, backend).await;
143    }
144    if let Some(glass_browser::cli::args::Commands::Agent { action }) = &cli.command
145        && matches!(
146            action,
147            glass_browser::cli::args::AgentCommand::Tool { .. }
148                | glass_browser::cli::args::AgentCommand::ToolFile { .. }
149        )
150    {
151        let result = dispatch_external_tool(action, cli.yolo).await?;
152        println!("{}", serde_json::to_string_pretty(&result)?);
153        return Ok(());
154    }
155    if let Some(glass_browser::cli::args::Commands::Agent { action }) = &cli.command {
156        enforce_legacy_development_trust(&cli)?;
157        return cli::dispatch_agent(action, cli.yolo);
158    }
159    if let Some(glass_browser::cli::args::Commands::Harness { action }) = &cli.command {
160        enforce_legacy_development_trust(&cli)?;
161        return cli::dispatch_harness(action);
162    }
163    if let Some(glass_browser::cli::args::Commands::Daemon { action }) = &cli.command {
164        return daemon::dispatch(action).await;
165    }
166    if let Some(glass_browser::cli::args::Commands::Project { action }) = &cli.command {
167        enforce_legacy_development_trust(&cli)?;
168        return cli::dispatch_project(action);
169    }
170    if cli.prompt.is_none()
171        && matches!(
172            cli.command.as_ref(),
173            Some(glass_browser::cli::args::Commands::Tui)
174        )
175    {
176        return run_development_tui(&cli);
177    }
178    if cli.command.is_none() && cli.prompt.is_none() && !cli.mcp {
179        return run_development_tui(&cli);
180    }
181    enforce_legacy_development_trust(&cli)?;
182    glass_browser::cli::runner::dispatch(cli).await
183}
184
185fn run_development_tui(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
186    let visual_options = tui::TuiVisualOptions {
187        mode: cli.tui_live,
188        backend: cli.tui_live_backend,
189        quality: cli.tui_live_quality,
190        fit: cli.tui_live_fit,
191    };
192    tui::run(
193        std::env::current_dir()?,
194        cli.tui_layout,
195        visual_options,
196        cli.yolo,
197        cli.policy,
198    )
199}
200
201fn enforce_legacy_development_trust(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
202    use glass_browser::cli::args::{
203        AgentCommand, AgentHarness, Commands, HarnessCommand, ProjectCommand,
204    };
205
206    let (root, safe_static) = match cli.command.as_ref() {
207        Some(Commands::Project { action }) => {
208            let root = match action {
209                ProjectCommand::Inspect { root }
210                | ProjectCommand::Files { root }
211                | ProjectCommand::Search { root, .. }
212                | ProjectCommand::Read { root, .. }
213                | ProjectCommand::Edit { root, .. }
214                | ProjectCommand::Mkdir { root, .. }
215                | ProjectCommand::Rename { root, .. }
216                | ProjectCommand::Delete { root, .. }
217                | ProjectCommand::Diagnostics { root, .. }
218                | ProjectCommand::Run { root, .. }
219                | ProjectCommand::Test { root }
220                | ProjectCommand::Lint { root }
221                | ProjectCommand::Process { root, .. }
222                | ProjectCommand::Diff { root }
223                | ProjectCommand::Link { root, .. }
224                | ProjectCommand::Graph { root, .. }
225                | ProjectCommand::Breakpoint { root, .. }
226                | ProjectCommand::Timeline { root }
227                | ProjectCommand::Replay { root, .. }
228                | ProjectCommand::Neovim { root, .. }
229                | ProjectCommand::Experiment { root, .. }
230                | ProjectCommand::Attach { root, .. } => root,
231            };
232            let safe = matches!(
233                action,
234                ProjectCommand::Inspect { .. }
235                    | ProjectCommand::Files { .. }
236                    | ProjectCommand::Search { .. }
237                    | ProjectCommand::Read { .. }
238                    | ProjectCommand::Diff { .. }
239                    | ProjectCommand::Graph { .. }
240                    | ProjectCommand::Breakpoint { .. }
241                    | ProjectCommand::Timeline { .. }
242                    | ProjectCommand::Replay { .. }
243            );
244            (root, safe)
245        }
246        Some(Commands::Harness { action }) => match action {
247            HarnessCommand::List => return Ok(()),
248            HarnessCommand::Start { root, .. } => (root, false),
249        },
250        Some(Commands::Agent { action }) => {
251            let (root, safe) = match action {
252                AgentCommand::Doctor | AgentCommand::Setup { .. } | AgentCommand::Status => {
253                    return Ok(());
254                }
255                AgentCommand::Hello { root, harness } => {
256                    (root, matches!(harness, AgentHarness::Local))
257                }
258                AgentCommand::Prompt { root, harness, .. } => {
259                    (root, matches!(harness, AgentHarness::Local))
260                }
261                AgentCommand::Delegate { root, sandbox, .. } => (
262                    root,
263                    matches!(
264                        sandbox,
265                        glass_browser::cli::args::ExternalAgentSandbox::ReadOnly
266                    ),
267                ),
268                AgentCommand::Tool { .. } | AgentCommand::ToolFile { .. } => return Ok(()),
269                AgentCommand::Steer { root, .. }
270                | AgentCommand::FollowUp { root, .. }
271                | AgentCommand::Models { root }
272                | AgentCommand::SetModel { root, .. }
273                | AgentCommand::Thinking { root, .. }
274                | AgentCommand::Abort { root }
275                | AgentCommand::NewSession { root } => (root, false),
276            };
277            (root, safe)
278        }
279        _ => return Ok(()),
280    };
281    let workspace = DevelopmentWorkspace::open(root)?;
282    if workspace.trust() == WorkspaceTrust::Untrusted && !safe_static {
283        return Err(format!(
284            "repository-controlled development execution is blocked for {}; open the TUI to inspect and trust this workspace",
285            workspace.root().display()
286        )
287        .into());
288    }
289    Ok(())
290}
291
292async fn dispatch_external_tool(
293    action: &glass_browser::cli::args::AgentCommand,
294    unrestricted: bool,
295) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
296    use crate::development::{Actor, ToolAuthorization, ToolCall};
297    use glass_browser::cli::args::AgentCommand;
298
299    let (call, root, allow_mutation, confirmed) = match action {
300        AgentCommand::Tool {
301            call,
302            root,
303            allow_mutation,
304            yes,
305        } => (
306            serde_json::from_str::<ToolCall>(call)?,
307            root,
308            *allow_mutation || unrestricted,
309            *yes || unrestricted,
310        ),
311        AgentCommand::ToolFile {
312            path,
313            root,
314            allow_mutation,
315            yes,
316        } if std::env::var_os("GLASS_DEV_DAEMON_SOCKET").is_some() => {
317            return daemon::forward_resident_tool_file(
318                path,
319                root,
320                *allow_mutation || unrestricted,
321                *yes || unrestricted,
322            )
323            .await;
324        }
325        AgentCommand::ToolFile {
326            path,
327            root,
328            allow_mutation,
329            yes,
330        } => (
331            daemon::read_private_tool_call(path)?,
332            root,
333            *allow_mutation || unrestricted,
334            *yes || unrestricted,
335        ),
336        _ => return Err("expected an external agent tool action".into()),
337    };
338    let mut workspace = DevelopmentWorkspace::open(root)?;
339    let context = DevelopmentToolContext {
340        authorization: ToolAuthorization {
341            actor: Actor::external("cli"),
342            allow_mutation,
343            confirmed,
344        },
345        initiator: None,
346        expected_generation: workspace.generation(),
347        expected_project_revision: workspace.project().revision(),
348    };
349    Ok(workspace.execute_tool(&call, &context)?)
350}