1use crate::development::{
4 Actor, ExperimentManager, HarnessRequest, LinkProvenance, LocalHarness, PiHarness,
5 ProcessSnapshot, ProjectWorkspace, SemanticBreakpoint, SemanticSnapshot,
6};
7use glass_browser::cli::args::{
8 AgentCommand, AgentHarness, ExperimentCommand, ExternalAgentSandbox, HarnessCommand,
9 NeovimCommand, ProjectCommand, ProjectGraphCommand, ProjectProcessCommand,
10};
11use serde::Serialize;
12use std::io::Read;
13use std::time::Duration;
14
15type CliResult<T> = Result<T, Box<dyn std::error::Error>>;
16
17pub fn dispatch_agent(action: &AgentCommand, unrestricted: bool) -> CliResult<()> {
18 match action {
19 AgentCommand::Doctor | AgentCommand::Status => {
20 return print_json(&crate::pi_runtime::pi_readiness()?);
21 }
22 AgentCommand::Setup {
23 sdk_entry,
24 agent_dir,
25 update,
26 login,
27 } => {
28 return print_json(&crate::pi_runtime::setup_pi_runtime(
29 sdk_entry.as_deref(),
30 agent_dir.as_deref(),
31 *update,
32 *login,
33 )?);
34 }
35 _ => {}
36 }
37 if let AgentCommand::Delegate {
38 harness,
39 prompt,
40 root,
41 sandbox,
42 timeout_secs,
43 allow_mutation,
44 yes,
45 } = action
46 {
47 let sandbox = match sandbox {
48 ExternalAgentSandbox::ReadOnly => crate::external_agents::ExternalSandbox::ReadOnly,
49 ExternalAgentSandbox::WorkspaceWrite => {
50 if !(*allow_mutation || unrestricted) {
51 return Err(
52 "workspace-write delegation requires --allow-mutation (or --yolo)".into(),
53 );
54 }
55 if !(*yes || unrestricted) {
56 return Err(
57 "workspace-write delegation requires --yes for the exact request".into(),
58 );
59 }
60 crate::external_agents::ExternalSandbox::WorkspaceWrite
61 }
62 };
63 let prompt = if prompt == "-" {
64 let mut stdin_prompt = String::new();
65 std::io::stdin().read_to_string(&mut stdin_prompt)?;
66 stdin_prompt
67 } else {
68 prompt.clone()
69 };
70 let result =
71 crate::external_agents::delegate(crate::external_agents::ExternalAgentRequest {
72 harness: harness.clone(),
73 root: root.clone(),
74 prompt,
75 sandbox,
76 timeout: Duration::from_secs(*timeout_secs),
77 allow_mutation: *allow_mutation || unrestricted,
78 })?;
79 print_json(&result)?;
80 if !result.success {
81 let reason = if result.timed_out {
82 " after the configured timeout".into()
83 } else {
84 result
85 .status
86 .map(|status| format!(" with status {status}"))
87 .unwrap_or_else(|| " before a successful exit".into())
88 };
89 return Err(format!("{} delegation failed{reason}", result.harness).into());
90 }
91 return Ok(());
92 }
93 let (root, request, adapter) = match action {
94 AgentCommand::Tool { .. } | AgentCommand::ToolFile { .. } => {
95 return Err("agent tool calls use the resident broker path".into());
96 }
97 AgentCommand::Hello { root, harness } => (root, HarnessRequest::Hello, *harness),
98 AgentCommand::Prompt {
99 root,
100 text,
101 harness,
102 } => (
103 root,
104 HarnessRequest::Prompt { text: text.clone() },
105 *harness,
106 ),
107 AgentCommand::Steer {
108 root,
109 text,
110 harness,
111 } => (root, HarnessRequest::Steer { text: text.clone() }, *harness),
112 AgentCommand::FollowUp { root, text } => (
113 root,
114 HarnessRequest::FollowUp { text: text.clone() },
115 AgentHarness::Pi,
116 ),
117 AgentCommand::Models { root } => (root, HarnessRequest::Models, AgentHarness::Pi),
118 AgentCommand::SetModel {
119 root,
120 provider,
121 model_id,
122 } => (
123 root,
124 HarnessRequest::SetModel {
125 provider: provider.clone(),
126 model_id: model_id.clone(),
127 },
128 AgentHarness::Pi,
129 ),
130 AgentCommand::Thinking { root, level } => (
131 root,
132 HarnessRequest::SetThinking {
133 level: level.clone(),
134 },
135 AgentHarness::Pi,
136 ),
137 AgentCommand::Abort { root } => (root, HarnessRequest::Abort, AgentHarness::Pi),
138 AgentCommand::NewSession { root } => (root, HarnessRequest::NewSession, AgentHarness::Pi),
139 AgentCommand::Doctor | AgentCommand::Setup { .. } | AgentCommand::Status => {
140 unreachable!("readiness commands return before harness dispatch")
141 }
142 AgentCommand::Delegate { .. } => unreachable!("delegation returns before harness dispatch"),
143 };
144 let mut workspace = ProjectWorkspace::open(root)?;
145 match adapter {
146 AgentHarness::Local => {
147 let mut harness = LocalHarness::default();
148 print_json(&harness.handle(&mut workspace, request)?)?;
149 }
150 AgentHarness::Pi => {
151 let mut harness = PiHarness::spawn_with_unrestricted(workspace.root(), unrestricted)?;
152 print_json(&harness.request(request)?)?;
153 }
154 }
155 Ok(())
156}
157
158pub fn dispatch_harness(action: &HarnessCommand) -> CliResult<()> {
159 match action {
160 HarnessCommand::List => {
161 let harnesses = crate::harness::discover()
162 .into_iter()
163 .map(|status| {
164 serde_json::json!({
165 "id": status.spec.id,
166 "label": status.spec.label,
167 "binary": status.spec.binary,
168 "description": status.spec.description,
169 "installed": status.path.is_some(),
170 "path": status.path,
171 "temporaryDelegation": matches!(
172 status.spec.id,
173 "codex" | "claude" | "opencode"
174 ),
175 })
176 })
177 .collect::<Vec<_>>();
178 print_json(&serde_json::json!({"harnesses": harnesses}))?;
179 }
180 HarnessCommand::Start { name, root } => {
181 let resolved = crate::harness::resolve(name)?;
182 let status = crate::harness::launch_resolved(&resolved, root)?;
183 print_json(&serde_json::json!({
184 "harness": resolved.spec.id,
185 "label": resolved.spec.label,
186 "path": resolved.path,
187 "root": root,
188 "success": status.success(),
189 "status": status.code(),
190 }))?;
191 if !status.success() {
192 return Err(format!(
193 "{} exited{}",
194 resolved.spec.label,
195 status.code().map_or_else(
196 || " from a signal".into(),
197 |code| format!(" with status {code}")
198 )
199 )
200 .into());
201 }
202 }
203 }
204 Ok(())
205}
206
207pub fn dispatch_project(action: &ProjectCommand) -> CliResult<()> {
208 match action {
209 ProjectCommand::Inspect { root } => {
210 let workspace = ProjectWorkspace::open(root)?;
211 print_json(&serde_json::json!({
212 "schemaVersion": crate::development::DEVELOPMENT_SCHEMA_VERSION,
213 "root": workspace.root(),
214 "detection": workspace.detection(),
215 "config": workspace.config(),
216 "revision": workspace.revision(),
217 }))?;
218 }
219 ProjectCommand::Files { root } => {
220 let workspace = ProjectWorkspace::open(root)?;
221 print_json(&workspace.list_files_result()?)?;
222 }
223 ProjectCommand::Search { root, query, limit } => {
224 let mut workspace = ProjectWorkspace::open(root)?;
225 print_json(&workspace.search(query, *limit)?)?;
226 }
227 ProjectCommand::Read { root, path } => {
228 let mut workspace = ProjectWorkspace::open(root)?;
229 let content = workspace.read_file(path)?;
230 print_json(&serde_json::json!({"path": path, "content": content}))?;
231 }
232 ProjectCommand::Edit {
233 root,
234 path,
235 content,
236 input,
237 } => {
238 let content = match (content, input) {
239 (Some(content), None) => content.clone(),
240 (None, Some(input)) => std::fs::read_to_string(input)?,
241 (None, None) => {
242 return Err("project edit requires --content or --input".into());
243 }
244 (Some(_), Some(_)) => unreachable!("clap prevents conflicting edit inputs"),
245 };
246 let mut workspace = ProjectWorkspace::open(root)?;
247 workspace.edit_buffer(path, content, Actor::local())?;
248 print_json(&workspace.save_buffer(path)?)?;
249 }
250 ProjectCommand::Mkdir { root, path } => {
251 let mut workspace = ProjectWorkspace::open(root)?;
252 workspace.create_directory(path, Actor::local())?;
253 print_json(&serde_json::json!({"path": path, "created": true}))?;
254 }
255 ProjectCommand::Rename { root, from, to } => {
256 let mut workspace = ProjectWorkspace::open(root)?;
257 workspace.rename_path(from, to, Actor::local())?;
258 print_json(&serde_json::json!({"from": from, "to": to, "renamed": true}))?;
259 }
260 ProjectCommand::Delete { root, path, yes } => {
261 if !yes {
262 return Err("project delete requires --yes confirmation".into());
263 }
264 let mut workspace = ProjectWorkspace::open(root)?;
265 workspace.delete_path(path, Actor::local())?;
266 print_json(&serde_json::json!({"path": path, "deleted": true}))?;
267 }
268 ProjectCommand::Diagnostics { root, path } => {
269 let mut workspace = ProjectWorkspace::open(root)?;
270 print_json(&workspace.publish_rust_diagnostics(path)?)?;
271 }
272 ProjectCommand::Run {
273 root,
274 name,
275 command,
276 wait,
277 } => {
278 if !wait {
279 return Err("one-shot CLI process runs require --wait; use the TUI for persistent interactive processes".into());
280 }
281 let mut workspace = ProjectWorkspace::open(root)?;
282 let command = command
283 .clone()
284 .or_else(|| detected_command(workspace.detection(), name))
285 .ok_or_else(|| format!("no configured command for process {name}"))?;
286 #[cfg(windows)]
287 let snapshot = workspace.run_command_to_completion(
288 name,
289 &command,
290 std::time::Duration::from_secs(600),
291 )?;
292 #[cfg(not(windows))]
293 let snapshot = {
294 let snapshot = workspace.start_process(name, &command)?;
295 if *wait {
296 workspace.processes().close_input(name)?;
297 wait_for_project_process(&mut workspace, name)?
298 } else {
299 snapshot
300 }
301 };
302 print_json(&snapshot)?;
303 }
304 ProjectCommand::Test { root } => {
305 run_detected_command(root, "test", workspace_test_command)?;
306 }
307 ProjectCommand::Lint { root } => {
308 run_detected_command(root, "lint", workspace_lint_command)?;
309 }
310 ProjectCommand::Process { root, action } => {
311 let mut workspace = ProjectWorkspace::open(root)?;
312 match action {
313 ProjectProcessCommand::List => print_json(&workspace.processes().list_checked()?)?,
314 ProjectProcessCommand::Start {
315 name,
316 command,
317 wait,
318 } => {
319 if !wait {
320 return Err("one-shot CLI process starts require --wait; use the TUI for persistent interactive processes".into());
321 }
322 #[cfg(windows)]
323 let snapshot = workspace.run_command_to_completion(
324 name,
325 command,
326 std::time::Duration::from_secs(600),
327 )?;
328 #[cfg(not(windows))]
329 let snapshot = {
330 workspace.start_process(name, command)?;
331 if *wait {
332 workspace.processes().close_input(name)?;
333 wait_for_project_process(&mut workspace, name)?
334 } else {
335 workspace
336 .processes()
337 .list()
338 .into_iter()
339 .find(|process| process.name == *name)
340 .ok_or_else(|| format!("process {name} disappeared"))?
341 }
342 };
343 print_json(&snapshot)?;
344 }
345 ProjectProcessCommand::Stop { name } => {
346 print_json(&workspace.stop_process(name)?)?;
347 }
348 ProjectProcessCommand::Restart { name } => {
349 print_json(&workspace.processes().restart(name)?)?;
350 }
351 ProjectProcessCommand::Remove { name } => {
352 print_json(&workspace.processes().remove(name)?)?;
353 }
354 ProjectProcessCommand::Input { name, input } => {
355 workspace.processes().send_input(name, input)?;
356 print_json(&serde_json::json!({"name": name, "accepted": true}))?;
357 }
358 ProjectProcessCommand::Resize { name, cols, rows } => {
359 workspace.processes().resize(name, *cols, *rows)?;
360 print_json(&serde_json::json!({"name": name, "cols": cols, "rows": rows}))?;
361 }
362 ProjectProcessCommand::Output { name } => {
363 print_json(&serde_json::json!({
364 "name": name,
365 "output": workspace.processes().output(name)?,
366 }))?;
367 }
368 }
369 }
370 ProjectCommand::Diff { root } => {
371 let mut workspace = ProjectWorkspace::open(root)?;
372 print_json(&workspace.diff()?)?;
373 }
374 ProjectCommand::Link {
375 root,
376 entity,
377 path,
378 start_line,
379 end_line,
380 provenance,
381 confidence,
382 detail,
383 } => {
384 let mut workspace = ProjectWorkspace::open(root)?;
385 let provenance = parse_link_provenance(provenance)?;
386 let link = workspace.link_runtime_source(
387 entity,
388 path,
389 *start_line,
390 *end_line,
391 provenance,
392 detail,
393 *confidence,
394 Actor::local(),
395 )?;
396 print_json(&link)?;
397 }
398 ProjectCommand::Timeline { root } => {
399 let workspace = ProjectWorkspace::open(root)?;
400 print_json(&workspace.timeline().events().collect::<Vec<_>>())?;
401 }
402 ProjectCommand::Graph { root, action } => {
403 let mut workspace = ProjectWorkspace::open(root)?;
404 match action {
405 ProjectGraphCommand::Discover => print_json(&workspace.discover_runtime_links()?)?,
406 ProjectGraphCommand::Entity { entity } => {
407 print_json(&workspace.graph().links_for(entity))?
408 }
409 ProjectGraphCommand::Source { path, line } => {
410 print_json(&workspace.graph().entities_for_source(path, *line))?
411 }
412 }
413 }
414 ProjectCommand::Breakpoint {
415 root,
416 kind,
417 entity,
418 before,
419 after,
420 } => {
421 let mut workspace = ProjectWorkspace::open(root)?;
422 workspace.discover_runtime_links()?;
423 let before: SemanticSnapshot = serde_json::from_slice(&std::fs::read(before)?)?;
424 let after: SemanticSnapshot = serde_json::from_slice(&std::fs::read(after)?)?;
425 let breakpoint = match kind.as_str() {
426 "disappears" => SemanticBreakpoint::EntityDisappears { entity_id: entity.clone() },
427 "name-missing" => SemanticBreakpoint::AccessibleNameMissing { entity_id: Some(entity.clone()) },
428 "role-changes" => SemanticBreakpoint::RoleChanges { entity_id: entity.clone() },
429 "actionability-lost" => SemanticBreakpoint::ActionabilityLost { entity_id: entity.clone() },
430 _ => return Err("breakpoint kind must be disappears, name-missing, role-changes, or actionability-lost".into()),
431 };
432 print_json(&workspace.evaluate_semantic_breakpoints(
433 &[breakpoint],
434 &before,
435 &after,
436 )?)?;
437 }
438 ProjectCommand::Replay { root, start, limit } => {
439 let workspace = ProjectWorkspace::open(root)?;
440 print_json(&workspace.replay(*start, *limit)?)?;
441 }
442 ProjectCommand::Neovim { root, action } => {
443 let mut workspace = ProjectWorkspace::open(root)?;
444 match action {
445 NeovimCommand::Probe => print_json(&crate::development::probe_neovim()?)?,
446 NeovimCommand::Start { name, path } => {
447 print_json(&crate::development::start_neovim(
448 workspace.processes(),
449 name,
450 path.as_deref(),
451 )?)?
452 }
453 }
454 }
455 ProjectCommand::Experiment { root, action } => {
456 let manager = ExperimentManager::new(root)?;
457 match action {
458 ExperimentCommand::Create { name, port } => {
459 print_json(&manager.create(name, *port)?)?
460 }
461 }
462 }
463 ProjectCommand::Attach { root, actor } => {
464 let mut workspace = ProjectWorkspace::open(root)?;
465 let actor = Actor::external(actor);
466 workspace.attach_actor(actor.clone())?;
467 print_json(&actor)?;
468 }
469 }
470 Ok(())
471}
472
473fn detected_command(
474 detection: &crate::development::ProjectDetection,
475 name: &str,
476) -> Option<String> {
477 match name {
478 "dev" => detection.dev_command.clone(),
479 "test" => detection.test_command.clone(),
480 "lint" => detection.lint_command.clone(),
481 "build" => detection.build_command.clone(),
482 _ => None,
483 }
484}
485
486fn workspace_test_command(detection: &crate::development::ProjectDetection) -> Option<String> {
487 detection.test_command.clone()
488}
489
490fn workspace_lint_command(detection: &crate::development::ProjectDetection) -> Option<String> {
491 detection.lint_command.clone()
492}
493
494fn run_detected_command(
495 root: &std::path::Path,
496 name: &str,
497 command: fn(&crate::development::ProjectDetection) -> Option<String>,
498) -> CliResult<()> {
499 let mut workspace = ProjectWorkspace::open(root)?;
500 let command = command(workspace.detection())
501 .ok_or_else(|| format!("project has no detected {name} command"))?;
502 print_json(&workspace.run_verification(name, &command, Duration::from_secs(600))?)?;
503 Ok(())
504}
505
506fn wait_for_project_process(
507 workspace: &mut ProjectWorkspace,
508 name: &str,
509) -> CliResult<ProcessSnapshot> {
510 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600);
511 loop {
512 let snapshots = workspace.processes().poll()?;
513 let snapshot = snapshots
514 .into_iter()
515 .find(|process| process.name == name)
516 .ok_or_else(|| format!("process {name} disappeared"))?;
517 if !matches!(snapshot.state, crate::development::ProcessState::Running) {
518 return Ok(snapshot);
519 }
520 if std::time::Instant::now() >= deadline {
521 workspace.stop_process(name)?;
522 return Err(format!("process {name} exceeded 600 seconds").into());
523 }
524 std::thread::sleep(std::time::Duration::from_millis(20));
525 }
526}
527
528fn parse_link_provenance(value: &str) -> CliResult<LinkProvenance> {
529 match value {
530 "explicit-marker" => Ok(LinkProvenance::ExplicitMarker),
531 "runtime-observation" => Ok(LinkProvenance::RuntimeObservation),
532 "static-analysis" => Ok(LinkProvenance::StaticAnalysis),
533 "inferred" => Ok(LinkProvenance::Inferred),
534 _ => Err(
535 "provenance must be explicit-marker, runtime-observation, static-analysis, or inferred"
536 .into(),
537 ),
538 }
539}
540
541fn print_json<T: Serialize + ?Sized>(value: &T) -> CliResult<()> {
542 println!("{}", serde_json::to_string_pretty(value)?);
543 Ok(())
544}