1use crate::agents::AgentSpec;
4use crate::browser::BrowserStartConfig;
5use crate::debugger::{DebugAdapterConfig, SourceBreakpoint};
6use crate::development::{
7 AgentToolGateway, DevelopmentError, DevelopmentResult, ToolAuthorization, ToolCall,
8 ToolDescriptor,
9};
10use crate::kernels::KernelKind;
11use crate::pi_runtime::PiSessionRequest;
12use crate::tasks::{TaskId, TaskSpec};
13use crate::workspace::DevelopmentWorkspace;
14use crate::{DevelopmentNode, DevelopmentNodeKind, ObservableEventInput, WorkspaceTrust};
15use glass_browser::browser::session::{
16 SemanticObservationLevel, WorkflowRecordingSession, record_semantic_events,
17};
18use glass_browser::workspace::{WorkspaceId, WorkspaceStore};
19use serde_json::Value;
20use std::path::PathBuf;
21use std::time::Duration;
22
23const RESULT_LIMIT: usize = 512 * 1024;
24
25#[derive(Debug, Clone)]
26pub struct DevelopmentToolContext {
27 pub authorization: ToolAuthorization,
28 pub initiator: Option<crate::development::Actor>,
29 pub expected_generation: u64,
30 pub expected_project_revision: u64,
31}
32
33#[derive(Debug, Clone)]
35pub struct DevelopmentToolRouter {
36 core: AgentToolGateway,
37 descriptors: Vec<ToolDescriptor>,
38}
39
40impl Default for DevelopmentToolRouter {
41 fn default() -> Self {
42 let core = AgentToolGateway::default();
43 let service = service_descriptors();
44 let mut descriptors = core
45 .descriptors()
46 .into_iter()
47 .filter(|descriptor| {
48 !service
49 .iter()
50 .any(|candidate| candidate.name == descriptor.name)
51 })
52 .collect::<Vec<_>>();
53 descriptors.extend(service);
54 Self { core, descriptors }
55 }
56}
57
58impl DevelopmentToolRouter {
59 pub fn with_customization(customization: &crate::Customization, trust: WorkspaceTrust) -> Self {
60 let mut router = Self::default();
61 let custom = customization.descriptors(trust);
62 router
63 .descriptors
64 .retain(|descriptor| !custom.iter().any(|item| item.name == descriptor.name));
65 router.descriptors.extend(custom);
66 router
67 }
68
69 pub fn descriptors(&self) -> Vec<ToolDescriptor> {
70 self.descriptors.clone()
71 }
72
73 pub fn execute(
74 &self,
75 workspace: &mut DevelopmentWorkspace,
76 call: &ToolCall,
77 context: &DevelopmentToolContext,
78 ) -> DevelopmentResult<Value> {
79 if workspace.generation() != context.expected_generation {
80 return Err(DevelopmentError::Conflict(format!(
81 "stale workspace generation {}; current generation is {}",
82 context.expected_generation,
83 workspace.generation()
84 )));
85 }
86 if workspace.project().revision() != context.expected_project_revision {
87 return Err(DevelopmentError::Conflict(format!(
88 "stale project revision {}; current revision is {}",
89 context.expected_project_revision,
90 workspace.project().revision()
91 )));
92 }
93 let descriptor = self
94 .descriptors
95 .iter()
96 .find(|descriptor| descriptor.name == call.name)
97 .ok_or_else(|| DevelopmentError::NotFound(format!("tool {}", call.name)))?;
98 if !descriptor.available {
99 return Err(DevelopmentError::Conflict(
100 descriptor
101 .unavailable_reason
102 .clone()
103 .unwrap_or_else(|| format!("tool {} is unavailable", call.name)),
104 ));
105 }
106 if workspace.trust() == WorkspaceTrust::Untrusted && !untrusted_tool_allowed(&call.name) {
107 return Err(DevelopmentError::Conflict(format!(
108 "tool {} is blocked until the workspace is trusted",
109 call.name
110 )));
111 }
112 if descriptor.mutating
113 && (!context.authorization.allow_mutation || !context.authorization.confirmed)
114 {
115 return Err(DevelopmentError::Conflict(format!(
116 "tool {} requires mutation authority and confirmation",
117 call.name
118 )));
119 }
120 let actor_id = context.authorization.actor.id.clone();
121 let initiator_id = context
122 .initiator
123 .as_ref()
124 .map(|actor| actor.id.as_str())
125 .unwrap_or(actor_id.as_str());
126 let project_revision = workspace.project().revision();
127 let resource = format!("tool:{}", call.id);
128 let argument_bytes = serde_json::to_vec(&call.arguments)?.len();
129 workspace.intelligence_mut().upsert_node(DevelopmentNode {
130 id: resource.clone(),
131 kind: DevelopmentNodeKind::ToolCall,
132 label: call.name.clone(),
133 revision: project_revision,
134 stale: false,
135 evidence: serde_json::json!({
136 "toolCallId":call.id,
137 "name":call.name,
138 "mutating":descriptor.mutating,
139 "argumentBytes":argument_bytes
140 }),
141 })?;
142 workspace.intelligence_mut().link(
143 "repository:root",
144 &resource,
145 "receivedToolCall",
146 project_revision,
147 &actor_id,
148 serde_json::json!({"name":call.name,"initiator":initiator_id,"executor":actor_id}),
149 )?;
150 workspace.intelligence_mut().record(ObservableEventInput {
151 actor: &actor_id,
152 subsystem: "tool",
153 kind: "called",
154 resource: Some(&resource),
155 workspace_revision: project_revision,
156 evidence: serde_json::json!({"name":call.name,"mutating":descriptor.mutating,"initiator":initiator_id,"executor":actor_id}),
157 rationale: None,
158 })?;
159 if workspace.trust().permits_project_execution() {
160 workspace.customization().run_hooks(
161 "tool.before",
162 &serde_json::json!({"id":call.id,"name":call.name,"actor":&actor_id}),
163 workspace.trust(),
164 &actor_id,
165 )?;
166 }
167 let result = if service_descriptors()
168 .iter()
169 .any(|descriptor| descriptor.name == call.name)
170 {
171 self.execute_service(workspace, call, context)
172 } else if workspace.customization().custom_tool(&call.name).is_some() {
173 workspace.customization().execute_tool(
174 &call.name,
175 &call.arguments,
176 workspace.trust(),
177 &actor_id,
178 )
179 } else if let Some(name) = call.name.strip_prefix("glass.command.") {
180 workspace
181 .customization()
182 .execute_command(name, workspace.trust(), &actor_id)
183 } else {
184 self.core
185 .execute(workspace.project_mut(), call, &context.authorization)
186 };
187 match result {
188 Ok(result) => {
189 if workspace.trust().permits_project_execution() {
190 workspace.customization().run_hooks(
191 "tool.after",
192 &serde_json::json!({"id":call.id,"name":call.name,"actor":&actor_id,"ok":true}),
193 workspace.trust(),
194 &actor_id,
195 )?;
196 }
197 let result_bytes = serde_json::to_vec(&result)?.len();
198 if result_bytes > RESULT_LIMIT {
199 return Err(DevelopmentError::InvalidInput(format!(
200 "tool result exceeds the {RESULT_LIMIT} byte limit"
201 )));
202 }
203 let resulting_revision = workspace.project().revision();
204 project_observable_result(
205 workspace,
206 call,
207 &actor_id,
208 project_revision,
209 resulting_revision,
210 &result,
211 )?;
212 workspace.intelligence_mut().record(ObservableEventInput {
213 actor: &actor_id,
214 subsystem: "tool",
215 kind: "completed",
216 resource: Some(&resource),
217 workspace_revision: resulting_revision,
218 evidence: serde_json::json!({"name":call.name,"resultBytes":result_bytes}),
219 rationale: None,
220 })?;
221 Ok(result)
222 }
223 Err(error) => {
224 if workspace.trust().permits_project_execution() {
225 workspace.customization().run_hooks(
226 "tool.after",
227 &serde_json::json!({"id":call.id,"name":call.name,"actor":&actor_id,"ok":false,"error":error.to_string()}),
228 workspace.trust(),
229 &actor_id,
230 )?;
231 }
232 let resulting_revision = workspace.project().revision();
233 workspace.intelligence_mut().record(ObservableEventInput {
234 actor: &actor_id,
235 subsystem: "tool",
236 kind: "failed",
237 resource: Some(&resource),
238 workspace_revision: resulting_revision,
239 evidence: serde_json::json!({"name":call.name,"error":error.to_string()}),
240 rationale: None,
241 })?;
242 Err(error)
243 }
244 }
245 }
246
247 fn execute_service(
248 &self,
249 workspace: &mut DevelopmentWorkspace,
250 call: &ToolCall,
251 context: &DevelopmentToolContext,
252 ) -> DevelopmentResult<Value> {
253 let string = |name: &str| required_string(call, name);
254 let actor = normalized_actor_id(&context.authorization.actor.id);
255 match call.name.as_str() {
256 "glass.agent.delegate" => {
257 let sandbox = crate::external_agents::ExternalSandbox::parse(
258 optional_string(call, "sandbox").unwrap_or("read-only"),
259 )
260 .map_err(DevelopmentError::InvalidInput)?;
261 if sandbox == crate::external_agents::ExternalSandbox::WorkspaceWrite
262 && (!context.authorization.allow_mutation
263 || !context.authorization.confirmed)
264 {
265 return Err(DevelopmentError::Conflict(
266 "workspace-write delegation requires explicit mutation authority and confirmation"
267 .into(),
268 ));
269 }
270 let timeout = call
271 .arguments
272 .get("timeoutSeconds")
273 .and_then(Value::as_u64)
274 .unwrap_or(crate::external_agents::DEFAULT_TIMEOUT_SECS);
275 let result = crate::external_agents::delegate(
276 crate::external_agents::ExternalAgentRequest {
277 harness: string("harness")?.into(),
278 root: workspace.root().to_path_buf(),
279 prompt: string("prompt")?.into(),
280 sandbox,
281 timeout: Duration::from_secs(timeout),
282 allow_mutation: context.authorization.allow_mutation
283 && context.authorization.confirmed,
284 },
285 )
286 .map_err(DevelopmentError::Process)?;
287 Ok(serde_json::to_value(result)?)
288 }
289 "glass.editor.open" => map_service(
290 workspace
291 .project_mut()
292 .open_buffer(string("path")?, context.authorization.actor.clone()),
293 ),
294 "glass.editor.selection" => {
295 let path = string("path")?;
296 let buffer = workspace
297 .project()
298 .buffer(path)
299 .cloned()
300 .ok_or_else(|| DevelopmentError::NotFound(format!("buffer {path}")))?;
301 let selected_text = workspace.project().selected_editor_text(path)?;
302 Ok(serde_json::json!({
303 "path":buffer.path,
304 "line":buffer.cursor_line,
305 "column":buffer.cursor_column,
306 "selection":buffer.selection,
307 "selectedText":selected_text,
308 "actor":buffer.actor,
309 "dirty":buffer.dirty
310 }))
311 }
312 "glass.editor.replace_selection" => {
313 let buffer = workspace.project_mut().replace_buffer_selection(
314 string("path")?,
315 string("replacement")?.to_string(),
316 context.authorization.actor.clone(),
317 )?;
318 Ok(serde_json::to_value(buffer)?)
319 }
320 "glass.editor.replace" => {
321 let matches = workspace.project_mut().replace_in_buffer(
322 string("path")?,
323 string("oldText")?,
324 string("newText")?,
325 context.authorization.actor.clone(),
326 )?;
327 Ok(serde_json::json!({"replacements":matches}))
328 }
329 "glass.editor.save" => {
330 map_service(workspace.project_mut().save_buffer(string("path")?))
331 }
332 "glass.editor.diff" => map_service(workspace.project_mut().diff()),
333 "glass.editor.buffers" => Ok(serde_json::to_value(
334 workspace.project().buffers().cloned().collect::<Vec<_>>(),
335 )?),
336 "glass.editor.comments" => Ok(serde_json::to_value(
337 workspace.project().editor_comments(optional_string(call, "path")),
338 )?),
339 "glass.editor.proposals" => Ok(serde_json::to_value(
340 workspace.project().editor_proposals(),
341 )?),
342 "glass.editor.checkpoints" => Ok(serde_json::to_value(
343 workspace.project().editor_checkpoints(),
344 )?),
345 "glass.editor.comment.add" => map_service(workspace.project_mut().add_editor_comment(
346 string("path")?,
347 u32_value(call, "startLine")?,
348 u32_value(call, "endLine")?,
349 string("text")?.to_string(),
350 context.authorization.actor.clone(),
351 )),
352 "glass.editor.comment.resolve" => map_service(
353 workspace
354 .project_mut()
355 .resolve_editor_comment(string("id")?, context.authorization.actor.clone()),
356 ),
357 "glass.editor.proposal.create" => map_service(
358 workspace.project_mut().propose_editor_change(
359 string("path")?,
360 string("original")?.to_string(),
361 string("proposed")?.to_string(),
362 string("summary")?.to_string(),
363 context.authorization.actor.clone(),
364 ),
365 ),
366 "glass.editor.proposal.accept" => map_service(
367 workspace
368 .project_mut()
369 .accept_editor_proposal(string("id")?, context.authorization.actor.clone()),
370 ),
371 "glass.editor.proposal.reject" => map_service(
372 workspace
373 .project_mut()
374 .reject_editor_proposal(string("id")?, context.authorization.actor.clone()),
375 ),
376 "glass.editor.checkpoint.create" => map_service(
377 workspace
378 .project_mut()
379 .create_editor_checkpoint(
380 string("name")?.to_string(),
381 context.authorization.actor.clone(),
382 ),
383 ),
384 "glass.editor.checkpoint.restore" => map_service(
385 workspace
386 .project_mut()
387 .restore_editor_checkpoint(string("id")?, context.authorization.actor.clone()),
388 ),
389 "glass.process.start" => map_service(workspace.project_mut().start_process(
390 string("name")?,
391 required_string(call, "command")?,
392 )),
393 "glass.process.stop" => {
394 map_service(workspace.project_mut().stop_process(string("name")?))
395 }
396 "glass.process.logs" => {
397 let name = string("name")?;
398 let processes = workspace.project_mut().processes();
399 processes.poll()?;
400 Ok(serde_json::json!({
401 "name": name,
402 "output": processes.output(name)?,
403 }))
404 }
405 "glass.process.list" => {
406 map_service(workspace.project_mut().processes().list_checked())
407 }
408
409 "glass.process.restart" => {
410 map_service(workspace.project_mut().processes().restart(string("name")?))
411 }
412 "glass.process.input" => {
413 workspace
414 .project_mut()
415 .processes()
416 .send_input(string("name")?, string("input")?)?;
417 Ok(serde_json::json!({"sent":true}))
418 }
419 "glass.process.resize" => {
420 let cols = u16_value(call, "cols")?;
421 let rows = u16_value(call, "rows")?;
422 workspace
423 .project_mut()
424 .processes()
425 .resize(string("name")?, cols, rows)?;
426 Ok(serde_json::json!({"resized":true,"cols":cols,"rows":rows}))
427 }
428 "glass.process.health" => {
429 let name = string("name")?;
430 let snapshot = workspace
431 .project_mut()
432 .processes()
433 .list_checked()?
434 .into_iter()
435 .find(|snapshot| snapshot.name == name)
436 .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
437 Ok(serde_json::json!({
438 "name":snapshot.name,
439 "pid":snapshot.pid,
440 "state":snapshot.state,
441 "health":snapshot.health,
442 "detectedUrls":snapshot.detected_urls
443 }))
444 }
445 "glass.process.ports" => {
446 let snapshots = workspace.project_mut().processes().list_checked()?;
447 Ok(serde_json::json!({
448 "processes":snapshots.into_iter().map(|snapshot| serde_json::json!({
449 "name":snapshot.name,
450 "pid":snapshot.pid,
451 "urls":snapshot.detected_urls
452 })).collect::<Vec<_>>()
453 }))
454 }
455 "glass.browser.start" => {
456 let config: BrowserStartConfig = serde_json::from_value(call.arguments.clone())?;
457 workspace.browser().start(config)
458 }
459 "glass.browser.stop" => workspace.browser().stop(),
460 "glass.browser.attach" => {
461 let mut config: BrowserStartConfig = serde_json::from_value(call.arguments.clone())?;
462 config.attach = true;
463 workspace.browser().start(config)
464 }
465 "glass.browser.reconnect" => workspace.browser().reconnect(),
466 "glass.browser.state" => workspace.browser().state(),
467 "glass.browser.observe" => workspace.browser().observe(),
468 "glass.browser.snapshot" => workspace.browser().snapshot(),
469 "glass.browser.semantic" => workspace.browser().semantic(match optional_string(call, "level").unwrap_or("structured") {
470 "summary" => SemanticObservationLevel::Summary,
471 "interactive" => SemanticObservationLevel::Interactive,
472 "structured" => SemanticObservationLevel::Structured,
473 "detailed" => SemanticObservationLevel::Detailed,
474 "raw" => SemanticObservationLevel::Raw,
475 _ => return Err(DevelopmentError::InvalidInput("browser semantic level must be summary, interactive, structured, detailed, or raw".into())),
476 }),
477 "glass.browser.web_ir" => workspace.browser().web_ir(),
478 "glass.browser.diff" => workspace.browser().diff(),
479 "glass.browser.targets" => workspace.browser().targets(),
480 "glass.browser.target.select" => workspace
481 .browser()
482 .select_target(string("targetId")?.into()),
483 "glass.browser.navigate" => workspace.browser().navigate(
484 string("url")?.into(),
485 unsigned(call, "browserRevision", 0)?,
486 timeout(call, 180)?.unwrap_or(Duration::from_secs(30)),
487 ),
488 "glass.browser.act" => {
489 let revision = unsigned(call, "browserRevision", 0)?;
490 match string("action")? {
491 "back" => workspace.browser().back(revision),
492 "forward" => workspace.browser().forward(revision),
493 "reload" => workspace.browser().reload(revision),
494 "stopLoading" => workspace.browser().stop_loading(revision),
495 "click" => workspace
496 .browser()
497 .click(string("target")?.into(), revision),
498 "type" => workspace.browser().type_text(
499 string("text")?.into(),
500 optional_string(call, "target").map(str::to_string),
501 revision,
502 ),
503 "scroll" => workspace.browser().scroll(
504 number(call, "dx", 0.0)?,
505 number(call, "dy", 0.0)?,
506 revision,
507 ),
508 action => Err(DevelopmentError::InvalidInput(format!(
509 "unsupported browser action {action}; expected back, forward, reload, stopLoading, click, type, or scroll"
510 ))),
511 }
512 }
513 "glass.browser.screenshot" => workspace.browser().screenshot(),
514 "glass.browser.remote-view.open" => workspace.browser().open_remote_view(),
515 "glass.browser.remote-view.status" => workspace.browser().remote_view_status(),
516 "glass.browser.remote-view.revoke" => workspace.browser().revoke_remote_view(),
517 "glass.workflow.list" => workspace.browser().list_workflows(),
518 "glass.workflow.run" => workspace.browser().run_workflow(
519 required_value(call, "definition")?.clone(),
520 value_map(call, "inputs")?,
521 ),
522 "glass.workflow.pause" => workspace.browser().pause_workflow(),
523 "glass.workflow.resume" => workspace.browser().resume_workflow(
524 required_value(call, "definition")?.clone(),
525 value_map(call, "inputs")?,
526 required_value(call, "checkpoint")?.clone(),
527 ),
528 "glass.workflow.cancel" => workspace.browser().cancel_workflow(),
529 "glass.workflow.verify" => workspace.browser().verify_workflow(),
530 "glass.workflow.record" => {
531 let session: WorkflowRecordingSession = serde_json::from_value(
532 required_value(call, "session")?.clone(),
533 )?;
534 Ok(serde_json::to_value(record_semantic_events(session).map_err(|error| {
535 DevelopmentError::InvalidInput(error.to_string())
536 })?)?)
537 }
538 "glass.memory.retrieve" => {
539 if let Some(record_id) = optional_string(call, "recordId") {
540 Ok(serde_json::to_value(
541 workspace
542 .knowledge()
543 .get(record_id)
544 .ok_or_else(|| DevelopmentError::NotFound(format!("memory record {record_id}")))?,
545 )?)
546 } else {
547 Ok(serde_json::json!({
548 "records":workspace.knowledge().records(),
549 "stats":workspace.knowledge().stats().map_err(|error| DevelopmentError::Process(error.to_string()))?
550 }))
551 }
552 }
553 "glass.memory.explain" => {
554 let record_id = string("recordId")?;
555 let record = workspace
556 .knowledge()
557 .get(record_id)
558 .ok_or_else(|| DevelopmentError::NotFound(format!("memory record {record_id}")))?;
559 Ok(serde_json::json!({
560 "record":record,
561 "advisory":true,
562 "authority":"fresh browser evidence remains authoritative"
563 }))
564 }
565 "glass.memory.forget" => {
566 let record_id = string("recordId")?;
567 let change = workspace
568 .knowledge_mut()
569 .remove(record_id)
570 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
571 Ok(serde_json::to_value(change)?)
572 }
573 "glass.semantic.diff" => workspace.browser().diff(),
574 "glass.semantic.links" => Ok(serde_json::json!({
575 "nodes":workspace.intelligence().nodes().collect::<Vec<_>>(),
576 "edges":workspace.intelligence().edges().collect::<Vec<_>>()
577 })),
578 "glass.github.review" => Ok(serde_json::to_value(crate::github::review(
579 workspace.root(),
580 )?)?),
581 "glass.github.ship" => {
582 let request: crate::github::GitHubShipRequest =
583 serde_json::from_value(call.arguments.clone())?;
584 Ok(serde_json::to_value(crate::github::ship(
585 workspace.root(),
586 &request,
587 )?)?)
588 }
589 "glass.git.status" => git_value(workspace.git(), |git| git.status()),
590 "glass.git.diff" => git_value(workspace.git(), |git| {
591 git.diff(
592 boolean(call, "staged", false),
593 optional_string(call, "path"),
594 )
595 }),
596 "glass.git.stage" => {
597 let paths = string_array(call, "paths")?;
598 git_mutation(workspace.git(), |git| git.stage(&paths))?;
599 Ok(serde_json::json!({"staged":paths}))
600 }
601 "glass.git.unstage" => {
602 let paths = string_array(call, "paths")?;
603 git_mutation(workspace.git(), |git| git.unstage(&paths))?;
604 Ok(serde_json::json!({"unstaged":paths}))
605 }
606 "glass.git.discard" => {
607 let paths = string_array(call, "paths")?;
608 git_mutation(workspace.git(), |git| git.discard(&paths))?;
609 Ok(serde_json::json!({"discarded":paths}))
610 }
611 "glass.git.push" => {
612 git_mutation(workspace.git(), |git| {
613 git.push(optional_string(call, "remote"), optional_string(call, "branch"))
614 })?;
615 Ok(serde_json::json!({"pushed":true}))
616 }
617 "glass.git.commit" => {
618 let message = string("message")?;
619 git_value(workspace.git(), |git| git.commit(message))
620 }
621 "glass.git.branches" => git_value(workspace.git(), |git| git.branches()),
622 "glass.git.branch.create" => {
623 let name = string("name")?;
624 let start_point = optional_string(call, "startPoint");
625 git_mutation(workspace.git(), |git| git.create_branch(name, start_point))?;
626 Ok(serde_json::json!({"created":name}))
627 }
628 "glass.git.branch.switch" => {
629 let name = string("name")?;
630 let create = boolean(call, "create", false);
631 git_mutation(workspace.git(), |git| git.switch_branch(name, create))?;
632 Ok(serde_json::json!({"current":name}))
633 }
634 "glass.git.blame" => {
635 let path = string("path")?;
636 let start = unsigned(call, "startLine", 1)?;
637 let end = unsigned(call, "endLine", 1)?;
638 git_value(workspace.git(), |git| git.blame(path, start, end))
639 }
640 "glass.git.conflicts" => git_value(workspace.git(), |git| git.conflicts()),
641 "glass.git.stash.list" => git_value(workspace.git(), |git| git.stash_list()),
642 "glass.git.stash.push" => {
643 let message = string("message")?;
644 let include_untracked = boolean(call, "includeUntracked", false);
645 git_mutation(workspace.git(), |git| {
646 git.stash_push(message, include_untracked)
647 })?;
648 Ok(serde_json::json!({"stashed":true}))
649 }
650 "glass.git.stash.pop" => {
651 let reference = string("reference")?;
652 git_mutation(workspace.git(), |git| git.stash_pop(reference))?;
653 Ok(serde_json::json!({"restored":reference}))
654 }
655 "glass.git.worktree.list" => git_value(workspace.git(), |git| git.worktrees()),
656 "glass.git.worktree.create" => {
657 let path = PathBuf::from(string("path")?);
658 let branch = string("branch")?;
659 let create_branch = boolean(call, "createBranch", true);
660 git_mutation(workspace.git(), |git| {
661 git.create_worktree(&path, branch, create_branch)
662 })?;
663 Ok(serde_json::json!({"path":path,"created":true}))
664 }
665 "glass.git.worktree.remove" => {
666 let path = PathBuf::from(string("path")?);
667 git_mutation(workspace.git(), |git| {
668 git.remove_worktree(&path, boolean(call, "force", false))
669 })?;
670 Ok(serde_json::json!({"path":path,"removed":true}))
671 }
672 "glass.test.discover" => Ok(serde_json::to_value(
673 workspace.tests().suites().collect::<Vec<_>>(),
674 )?),
675 "glass.test.run" => {
676 let revision = workspace.project().revision();
677 map_service(workspace.tests_mut().start(
678 string("runId")?,
679 string("suiteId")?,
680 &actor,
681 revision,
682 timeout(call, 3_600)?,
683 ))
684 }
685 "glass.test.run-affected" => {
686 let paths = string_array(call, "changedPaths")?;
687 let suite_ids = workspace
688 .tests()
689 .affected_suites(paths.iter().map(String::as_str))
690 .into_iter()
691 .map(|suite| suite.id.clone())
692 .collect::<Vec<_>>();
693 let revision = workspace.project().revision();
694 let prefix = optional_string(call, "runPrefix").unwrap_or("affected");
695 let mut runs = Vec::new();
696 for (index, suite_id) in suite_ids.into_iter().enumerate() {
697 runs.push(map_service(workspace.tests_mut().start(
698 &format!("{prefix}-{index}"),
699 &suite_id,
700 &actor,
701 revision,
702 timeout(call, 3_600)?,
703 ))?);
704 }
705 Ok(serde_json::to_value(runs)?)
706 }
707 "glass.test.cancel" => {
708 map_service(workspace.tests_mut().cancel(string("runId")?))?;
709 Ok(serde_json::json!({"cancelled":string("runId")?}))
710 }
711 "glass.test.results" => {
712 let finished = map_service(workspace.tests_mut().poll())?;
713 Ok(serde_json::json!({
714 "finished":finished,
715 "running":workspace.tests().running().collect::<Vec<_>>(),
716 "results":workspace.tests().results().collect::<Vec<_>>()
717 }))
718 }
719 "glass.test.watch" => {
720 let revision = workspace.project().revision();
721 map_service(workspace.tests_mut().watch(string("suiteId")?, revision))?;
722 Ok(serde_json::json!({"watching":string("suiteId")?}))
723 }
724 "glass.eval.start" => {
725 let kind = parse_kernel_kind(string("kind")?)?;
726 let name = string("name")?;
727 let capabilities = string_array_or_empty(call, "capabilities")?;
728 let mutation_authority = boolean(call, "mutationAuthority", false)
729 && context.authorization.allow_mutation
730 && context.authorization.confirmed;
731 map_service(workspace.kernels_mut().start_governed(
732 name,
733 kind,
734 &format!("kernel:{name}"),
735 &capabilities,
736 mutation_authority,
737 ))?;
738 Ok(serde_json::json!({"started":name,"kind":kind,"capabilities":capabilities,"mutationAuthority":mutation_authority}))
739 }
740 "glass.eval.execute" => {
741 map_service(workspace.execute_kernel(
742 string("name")?,
743 string("code")?,
744 &context.authorization,
745 timeout(call, 600)?,
746 ))
747 }
748 "glass.eval.list" => Ok(serde_json::to_value(
749 workspace.kernels().snapshots().collect::<Vec<_>>(),
750 )?),
751 "glass.eval.reset" => {
752 map_service(workspace.kernels_mut().reset(string("name")?, &actor))?;
753 Ok(serde_json::json!({"reset":string("name")?}))
754 }
755 "glass.eval.cancel" => map_service(workspace.kernels_mut().cancel(string("name")?)),
756 "glass.eval.stop" => map_service(workspace.kernels_mut().stop(string("name")?)),
757 "glass.lsp.start" => {
758 let server = string("server")?;
759 let configured = workspace.customization().config().lsp.get(server).cloned();
760 let config = match (optional_string(call, "command"), configured) {
761 (Some(command), _) => crate::lsp::LanguageServerConfig {
762 command: command.to_string(),
763 arguments: string_array_or_empty(call, "arguments")?,
764 },
765 (None, Some(config)) => crate::lsp::LanguageServerConfig {
766 command: config.command,
767 arguments: config.args,
768 },
769 (None, None) => return Err(DevelopmentError::InvalidInput(
770 "lsp start requires command or a matching glass.toml lsp entry".into(),
771 )),
772 };
773 map_service(workspace.language().start(server, &config))?;
774 Ok(serde_json::json!({"started":server}))
775 }
776 "glass.lsp.stop" => {
777 map_service(workspace.language().stop(string("server")?))?;
778 Ok(serde_json::json!({"stopped":string("server")?}))
779 }
780 "glass.lsp.list" => Ok(serde_json::json!({
781 "servers":workspace.language().names().collect::<Vec<_>>()
782 })),
783 "glass.lsp.events" => Ok(serde_json::to_value(
784 workspace.language().events(unsigned(call, "since", 0)?),
785 )?),
786 "glass.lsp.raw" => map_service(workspace.language().raw_request(
787 string("server")?,
788 &actor,
789 string("method")?,
790 call.arguments
791 .get("params")
792 .cloned()
793 .unwrap_or_else(|| serde_json::json!({})),
794 timeout(call, 60)?.unwrap_or(Duration::from_secs(10)),
795 )),
796 "glass.lsp.diagnostics" => map_service(workspace.language().diagnostics(
797 string("server")?,
798 &actor,
799 string("path")?,
800 )),
801 "glass.lsp.hover" => map_service(workspace.language().hover(
802 string("server")?,
803 &actor,
804 string("path")?,
805 unsigned(call, "line", 1)? as u32,
806 unsigned(call, "character", 1)? as u32,
807 )),
808 "glass.lsp.completion" => map_service(workspace.language().completion(
809 string("server")?,
810 &actor,
811 string("path")?,
812 unsigned(call, "line", 1)? as u32,
813 unsigned(call, "character", 1)? as u32,
814 )),
815 "glass.lsp.definition" => map_service(workspace.language().definition(
816 string("server")?,
817 &actor,
818 string("path")?,
819 u32_value(call, "line")?,
820 u32_value(call, "character")?,
821 )),
822 "glass.lsp.declaration" => map_service(workspace.language().declaration(
823 string("server")?,
824 &actor,
825 string("path")?,
826 u32_value(call, "line")?,
827 u32_value(call, "character")?,
828 )),
829 "glass.lsp.implementation" => map_service(workspace.language().implementation(
830 string("server")?,
831 &actor,
832 string("path")?,
833 u32_value(call, "line")?,
834 u32_value(call, "character")?,
835 )),
836 "glass.lsp.references" => map_service(workspace.language().references(
837 string("server")?,
838 &actor,
839 string("path")?,
840 u32_value(call, "line")?,
841 u32_value(call, "character")?,
842 )),
843 "glass.lsp.document_symbols" => map_service(workspace.language().document_symbols(
844 string("server")?,
845 &actor,
846 string("path")?,
847 )),
848 "glass.lsp.workspace_symbols" => map_service(workspace.language().workspace_symbols(
849 string("server")?,
850 &actor,
851 string("query")?,
852 )),
853 "glass.lsp.signature_help" => map_service(workspace.language().signature_help(
854 string("server")?,
855 &actor,
856 string("path")?,
857 u32_value(call, "line")?,
858 u32_value(call, "character")?,
859 )),
860 "glass.lsp.code_actions" => map_service(workspace.language().code_actions(
861 string("server")?,
862 &actor,
863 string("path")?,
864 position(call, "start")?,
865 position(call, "end")?,
866 value_array_or_empty(call, "diagnostics")?,
867 )),
868 "glass.lsp.formatting" => map_service(workspace.language().formatting(
869 string("server")?,
870 &actor,
871 string("path")?,
872 )),
873 "glass.lsp.range_formatting" => map_service(workspace.language().range_formatting(
874 string("server")?,
875 &actor,
876 string("path")?,
877 position(call, "start")?,
878 position(call, "end")?,
879 )),
880 "glass.lsp.semantic_tokens" => map_service(workspace.language().semantic_tokens(
881 string("server")?,
882 &actor,
883 string("path")?,
884 )),
885 "glass.lsp.rename" => map_service(workspace.language().rename(
886 string("server")?,
887 &actor,
888 string("path")?,
889 u32_value(call, "line")?,
890 u32_value(call, "character")?,
891 string("newName")?,
892 )),
893 "glass.debug.start" => {
894 let session = string("session")?;
895 let configured = workspace.customization().config().dap.get(session).cloned();
896 let (mut config, configured_tcp, configured_connect_timeout_ms) =
897 match (optional_string(call, "command"), configured) {
898 (Some(command), _) => (
899 DebugAdapterConfig::new(
900 command,
901 string_array_or_empty(call, "arguments")?,
902 ),
903 None,
904 5_000,
905 ),
906 (None, Some(config)) => (
907 DebugAdapterConfig::new(config.command, config.args),
908 config.tcp_address,
909 config.connect_timeout_ms,
910 ),
911 (None, None) => return Err(DevelopmentError::InvalidInput(
912 "debug start requires command or a matching glass.toml dap entry".into(),
913 )),
914 };
915 if let Some(address) = optional_string(call, "tcpAddress")
916 .map(str::to_string)
917 .or(configured_tcp)
918 {
919 let address = address.parse().map_err(|_| {
920 DevelopmentError::InvalidInput(
921 "debug tcpAddress must be a loopback IP socket address".into(),
922 )
923 })?;
924 config = config.with_tcp(
925 address,
926 Duration::from_millis(unsigned(
927 call,
928 "connectTimeoutMs",
929 configured_connect_timeout_ms,
930 )?),
931 );
932 }
933 map_debug(workspace.start_debugger(
934 session,
935 &config,
936 Duration::from_secs(unsigned(call, "timeoutSeconds", 30)?),
937 ))?;
938 Ok(serde_json::json!({"started":session}))
939 }
940 "glass.debug.launch" => map_debug(
941 debugger(workspace, string("session")?)?.launch(
942 call.arguments
943 .get("configuration")
944 .cloned()
945 .unwrap_or(Value::Null),
946 ),
947 ),
948 "glass.debug.attach" => map_debug(
949 debugger(workspace, string("session")?)?.attach(
950 call.arguments
951 .get("configuration")
952 .cloned()
953 .unwrap_or(Value::Null),
954 ),
955 ),
956 "glass.debug.configuration_done" => {
957 map_debug(debugger(workspace, string("session")?)?.configuration_done())
958 }
959 "glass.debug.restart" => map_debug(
960 debugger(workspace, string("session")?)?.restart(
961 call.arguments
962 .get("configuration")
963 .cloned()
964 .unwrap_or_else(|| serde_json::json!({})),
965 ),
966 ),
967 "glass.debug.breakpoint.set" => {
968 let lines = unsigned_array(call, "lines")?;
969 let breakpoints = lines
970 .iter()
971 .copied()
972 .map(SourceBreakpoint::line)
973 .collect::<Vec<_>>();
974 map_debug(
975 debugger(workspace, string("session")?)?
976 .set_source_breakpoints(&PathBuf::from(string("path")?), &breakpoints),
977 )
978 }
979 "glass.debug.breakpoint.remove" => map_debug(
980 debugger(workspace, string("session")?)?
981 .set_source_breakpoints(&PathBuf::from(string("path")?), &[]),
982 ),
983 "glass.debug.exception.set" => map_debug(
984 debugger(workspace, string("session")?)?
985 .set_exception_breakpoints(&string_array_or_empty(call, "filters")?),
986 ),
987 "glass.debug.continue" => map_debug(
988 debugger(workspace, string("session")?)?
989 .continue_thread(integer(call, "threadId")?),
990 ),
991 "glass.debug.pause" => map_debug(
992 debugger(workspace, string("session")?)?.pause(integer(call, "threadId")?),
993 ),
994 "glass.debug.step" => {
995 let debugger = debugger(workspace, string("session")?)?;
996 let thread = integer(call, "threadId")?;
997 match string("kind")? {
998 "over" => map_debug(debugger.next(thread)),
999 "in" => map_debug(debugger.step_in(thread)),
1000 "out" => map_debug(debugger.step_out(thread)),
1001 _ => Err(DevelopmentError::InvalidInput(
1002 "debug step kind must be over, in, or out".into(),
1003 )),
1004 }
1005 }
1006 "glass.debug.threads" => map_debug(debugger(workspace, string("session")?)?.threads()),
1007 "glass.debug.stack" => map_debug(
1008 debugger(workspace, string("session")?)?.stack_trace(integer(call, "threadId")?),
1009 ),
1010 "glass.debug.scopes" => map_debug(
1011 debugger(workspace, string("session")?)?.scopes(integer(call, "frameId")?),
1012 ),
1013 "glass.debug.variables" => map_debug(
1014 debugger(workspace, string("session")?)?
1015 .variables(integer(call, "variablesReference")?),
1016 ),
1017 "glass.debug.evaluate" => map_debug(debugger(workspace, string("session")?)?.evaluate(
1018 string("expression")?,
1019 call.arguments.get("frameId").and_then(Value::as_i64),
1020 optional_string(call, "context").unwrap_or("repl"),
1021 )),
1022 "glass.debug.events" => {
1023 map_debug(debugger(workspace, string("session")?)?.poll_events())
1024 }
1025 "glass.debug.inspect" => {
1026 map_debug(debugger(workspace, string("session")?)?.snapshot())
1027 }
1028 "glass.debug.processes" => map_debug(
1029 debugger(workspace, string("session")?)?.debuggee_processes(),
1030 ),
1031 "glass.debug.disconnect" => map_debug(
1032 debugger(workspace, string("session")?)?
1033 .disconnect(boolean(call, "terminateDebuggee", false)),
1034 ),
1035 "glass.debug.terminate" => map_debug(
1036 debugger(workspace, string("session")?)?
1037 .terminate(boolean(call, "restart", false)),
1038 ),
1039 "glass.debug.stop" => {
1040 map_debug(workspace.stop_debugger(string("session")?))?;
1041 Ok(serde_json::json!({"stopped":string("session")?}))
1042 }
1043 "glass.agent.list" => map_service(workspace.agents().list()),
1044 "glass.agent.setup" => map_service(crate::pi_runtime::setup_pi_runtime(
1045 None,
1046 None,
1047 boolean(call, "update", false),
1048 boolean(call, "login", false),
1049 )),
1050 "glass.agent.spawn" => {
1051 let spec: AgentSpec =
1052 serde_json::from_value(call.arguments.get("spec").cloned().ok_or_else(
1053 || DevelopmentError::InvalidInput("agent spawn requires spec".into()),
1054 )?)?;
1055 map_service(workspace.agents().create(spec))
1056 }
1057 "glass.agent.prompt" => {
1058 let id = agent_id(workspace, string("agentId")?)?;
1059 let text = string("text")?;
1060 map_service(workspace.agents().prompt_with_context(
1061 &id,
1062 text,
1063 call.arguments.get("context").cloned(),
1064 ))?;
1065 Ok(serde_json::json!({"queued":true}))
1066 }
1067 "glass.agent.send" => {
1068 let text = string("text")?;
1069 let context = call.arguments.get("context").cloned();
1070 let mode = optional_string(call, "mode").unwrap_or("follow-up");
1071 let selected = optional_string(call, "agentId")
1072 .map(|value| agent_id(workspace, value))
1073 .transpose()?;
1074 let agent = selected.or_else(|| {
1075 workspace
1076 .agents()
1077 .list()
1078 .ok()?
1079 .into_iter()
1080 .find(|item| {
1081 !matches!(
1082 item.status,
1083 crate::AgentStatus::Completed
1084 | crate::AgentStatus::Failed
1085 | crate::AgentStatus::Cancelled
1086 )
1087 })
1088 .map(|item| item.id)
1089 });
1090 let agent = match agent {
1091 Some(agent) => agent,
1092 None => {
1093 let readiness = crate::pi_runtime::pi_readiness()?;
1094 if !readiness.ready {
1095 return Err(DevelopmentError::Conflict(
1096 "Pi is not ready; use Agent [s] to install the runtime and [l] to sign in"
1097 .into(),
1098 ));
1099 }
1100 let id = workspace
1101 .agents()
1102 .create(AgentSpec::new(
1103 "assistant",
1104 "interactive Glass Agent session",
1105 ))?;
1106 map_service(workspace.agents().prompt_with_context(&id, text, context))?;
1107 return Ok(serde_json::json!({"queued":true,"agentId":id}));
1108 }
1109 };
1110 let mut status = workspace.agents().snapshot(&agent)?.status;
1111 let restarted = matches!(
1112 status,
1113 crate::AgentStatus::Failed | crate::AgentStatus::Cancelled
1114 );
1115 if restarted {
1116 workspace.agents().restart(&agent)?;
1117 status = workspace.agents().snapshot(&agent)?.status;
1118 }
1119 if mode == "steer" && status == crate::AgentStatus::Working {
1120 map_service(workspace.agents().steer_with_context(&agent, text, context.clone()))?;
1121 } else if mode == "follow-up" && status == crate::AgentStatus::Working {
1122 map_service(workspace.agents().follow_up_with_context(&agent, text, context.clone()))?;
1123 } else {
1124 map_service(workspace.agents().prompt_with_context(&agent, text, context))?;
1125 }
1126 let mut response = serde_json::json!({"queued":true,"agentId":agent});
1127 if restarted {
1128 response["restarted"] = Value::Bool(true);
1129 }
1130 Ok(response)
1131 }
1132 "glass.agent.steer" => {
1133 let id = agent_id(workspace, string("agentId")?)?;
1134 let text = string("text")?;
1135 map_service(workspace.agents().steer_with_context(
1136 &id,
1137 text,
1138 call.arguments.get("context").cloned(),
1139 ))?;
1140 Ok(serde_json::json!({"queued":true}))
1141 }
1142 "glass.agent.follow-up" => {
1143 let id = agent_id(workspace, string("agentId")?)?;
1144 let text = string("text")?;
1145 map_service(workspace.agents().follow_up_with_context(
1146 &id,
1147 text,
1148 call.arguments.get("context").cloned(),
1149 ))?;
1150 Ok(serde_json::json!({"queued":true}))
1151 }
1152 "glass.agent.approve" => {
1153 let id = agent_id(workspace, string("agentId")?)?;
1154 map_service(workspace.agents().approve_tool(
1155 &id,
1156 string("frameId")?,
1157 boolean(call, "approved", false),
1158 ))?;
1159 Ok(serde_json::json!({"queued":true}))
1160 }
1161 "glass.agent.abort" => {
1162 let id = agent_id(workspace, string("agentId")?)?;
1163 map_service(workspace.agents().cancel(&id))?;
1164 Ok(serde_json::json!({"cancelled":true}))
1165 }
1166 "glass.agent.compact" => {
1167 let id = agent_id(workspace, string("agentId")?)?;
1168 map_service(workspace.agents().request(
1169 &id,
1170 PiSessionRequest::Compact {
1171 instructions: optional_string(call, "instructions").map(str::to_string),
1172 },
1173 ))?;
1174 Ok(serde_json::json!({"queued":true}))
1175 }
1176 "glass.agent.model" => {
1177 let id = agent_id(workspace, string("agentId")?)?;
1178 map_service(workspace.agents().request(
1179 &id,
1180 PiSessionRequest::SetModel {
1181 provider: string("provider")?.into(),
1182 model_id: string("modelId")?.into(),
1183 },
1184 ))?;
1185 Ok(serde_json::json!({"queued":true}))
1186 }
1187 "glass.agent.thinking" => {
1188 let id = agent_id(workspace, string("agentId")?)?;
1189 map_service(workspace.agents().request(
1190 &id,
1191 PiSessionRequest::SetThinking {
1192 level: string("level")?.into(),
1193 },
1194 ))?;
1195 Ok(serde_json::json!({"queued":true}))
1196 }
1197 "glass.agent.new-session" => {
1198 agent_request(workspace, call, PiSessionRequest::NewSession)
1199 }
1200 "glass.agent.clone-session" => {
1201 agent_request(workspace, call, PiSessionRequest::CloneSession)
1202 }
1203 "glass.agent.rewind" => agent_request(
1204 workspace,
1205 call,
1206 PiSessionRequest::Rewind {
1207 entry_id: string("entryId")?.into(),
1208 },
1209 ),
1210 "glass.agent.fork" => agent_request(
1211 workspace,
1212 call,
1213 PiSessionRequest::Fork {
1214 entry_id: string("entryId")?.into(),
1215 },
1216 ),
1217 "glass.agent.switch-session" => agent_request(
1218 workspace,
1219 call,
1220 PiSessionRequest::SwitchSession {
1221 path: string("path")?.into(),
1222 },
1223 ),
1224 "glass.agent.sessions" => agent_request(workspace, call, PiSessionRequest::ListSessions),
1225 "glass.agent.tree" => agent_request(workspace, call, PiSessionRequest::Tree),
1226 "glass.agent.messages" => agent_request(workspace, call, PiSessionRequest::Messages),
1227 "glass.agent.entries" => agent_request(
1228 workspace,
1229 call,
1230 PiSessionRequest::Entries {
1231 since: optional_string(call, "since").map(str::to_string),
1232 },
1233 ),
1234 "glass.agent.stats" => agent_request(workspace, call, PiSessionRequest::SessionStats),
1235 "glass.agent.name" => agent_request(
1236 workspace,
1237 call,
1238 PiSessionRequest::SetSessionName {
1239 name: string("name")?.into(),
1240 },
1241 ),
1242 "glass.task.create" => {
1243 let spec = serde_json::from_value::<TaskSpec>(call.arguments.clone())?;
1244 Ok(serde_json::to_value(workspace.create_task(spec)?)?)
1245 }
1246 "glass.task.list" => Ok(serde_json::to_value(workspace.tasks()?)?),
1247 "glass.task.get" | "glass.task.inspect" => {
1248 let id = TaskId::parse(string("taskId")?)?;
1249 Ok(serde_json::to_value(workspace.task(&id)?)?)
1250 }
1251 "glass.task.pause" => task_action(workspace, call, |workspace, id| {
1252 workspace.pause_task(id)
1253 }),
1254 "glass.task.resume" => task_action(workspace, call, |workspace, id| {
1255 workspace.resume_task(id)
1256 }),
1257 "glass.task.cancel" => task_action(workspace, call, |workspace, id| {
1258 workspace.cancel_task(id)
1259 }),
1260 "glass.task.retry" => task_action(workspace, call, |workspace, id| {
1261 workspace.retry_task(id)
1262 }),
1263 "glass.task.override-blocked" => task_action(workspace, call, |workspace, id| {
1264 workspace.override_blocked_task(id)
1265 }),
1266 "glass.task.reassign" => {
1267 let id = TaskId::parse(string("taskId")?)?;
1268 workspace.reassign_task(
1269 &id,
1270 string("role")?.into(),
1271 optional_string(call, "model").map(str::to_string),
1272 optional_string(call, "thinking").map(str::to_string),
1273 )?;
1274 Ok(serde_json::json!({"reassigned":true}))
1275 }
1276 "glass.task.evidence" | "glass.task.verify" => {
1277 let id = TaskId::parse(string("taskId")?)?;
1278 workspace.submit_task_evidence(
1279 &id,
1280 string("kind")?.into(),
1281 context.authorization.actor.id.clone(),
1282 boolean(call, "passed", false),
1283 call.arguments
1284 .get("details")
1285 .cloned()
1286 .unwrap_or(Value::Null),
1287 )?;
1288 Ok(serde_json::json!({"recorded":true}))
1289 }
1290 "glass.experiment.create" => {
1291 let port = call
1292 .arguments
1293 .get("port")
1294 .and_then(Value::as_u64)
1295 .map(u16::try_from)
1296 .transpose()
1297 .map_err(|_| DevelopmentError::InvalidInput("invalid experiment port".into()))?;
1298 Ok(serde_json::to_value(workspace.experiments()?.create(
1299 string("id")?,
1300 string("branch")?,
1301 port,
1302 )?)?)
1303 }
1304 "glass.experiment.collect" => Ok(serde_json::to_value(
1305 workspace
1306 .experiments()?
1307 .collect_automatic(string("id")?)?,
1308 )?),
1309 "glass.experiment.list" => Ok(serde_json::to_value(
1310 workspace.experiments()?.snapshots(),
1311 )?),
1312 "glass.experiment.compare" => Ok(serde_json::to_value(
1313 workspace.experiments()?.compare(),
1314 )?),
1315 "glass.experiment.select" => Ok(serde_json::to_value(
1316 workspace.experiments()?.select(string("id")?)?,
1317 )?),
1318 "glass.experiment.remove" => {
1319 workspace
1320 .experiments()?
1321 .remove(string("id")?, boolean(call, "force", false))?;
1322 Ok(serde_json::json!({"removed":true}))
1323 }
1324 "glass.graph.query" => Ok(serde_json::to_value(
1325 workspace.intelligence().node(string("id")?),
1326 )?),
1327 "glass.graph.source" => {
1328 let line = call
1329 .arguments
1330 .get("line")
1331 .and_then(Value::as_u64)
1332 .map(u32::try_from)
1333 .transpose()
1334 .map_err(|_| DevelopmentError::InvalidInput("invalid graph line".into()))?;
1335 Ok(serde_json::to_value(
1336 workspace
1337 .project()
1338 .graph()
1339 .entities_for_source(string("path")?, line),
1340 )?)
1341 }
1342 "glass.graph.path" | "glass.graph.explain" => Ok(serde_json::to_value(
1343 workspace
1344 .intelligence()
1345 .path(string("from")?, string("to")?)?,
1346 )?),
1347 "glass.graph.link" => {
1348 let revision = workspace.project().revision();
1349 let edge = workspace.intelligence_mut().link(
1350 string("from")?,
1351 string("to")?,
1352 string("relation")?,
1353 revision,
1354 &actor,
1355 call.arguments
1356 .get("evidence")
1357 .cloned()
1358 .unwrap_or(Value::Null),
1359 )?;
1360 workspace.intelligence_mut().record(ObservableEventInput {
1361 actor: &actor,
1362 subsystem: "graph",
1363 kind: "linked",
1364 resource: None,
1365 workspace_revision: revision,
1366 evidence: serde_json::json!({"edgeId":edge,"from":string("from")?,"to":string("to")?,"relation":string("relation")?}),
1367 rationale: None,
1368 })?;
1369 Ok(serde_json::json!({"edgeId":edge}))
1370 }
1371 "glass.replay.list" | "glass.replay.inspect" => {
1372 Ok(serde_json::to_value(workspace.intelligence().replay(
1373 unsigned(call, "since", 0)?,
1374 usize::try_from(unsigned(call, "limit", 128)?).unwrap_or(4096),
1375 )?)?)
1376 }
1377 "glass.replay.diff" => Ok(serde_json::to_value(
1378 workspace
1379 .intelligence()
1380 .replay_diff(unsigned(call, "from", 0)?, unsigned(call, "to", 1)?)?,
1381 )?),
1382 "glass.workspace.list" => {
1383 let store = WorkspaceStore::open_default()
1384 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1385 Ok(serde_json::to_value(store.list().map_err(|error| {
1386 DevelopmentError::Process(error.to_string())
1387 })?)?)
1388 }
1389 "glass.workspace.inspect" => {
1390 let id = WorkspaceId::new(string("id")?)
1391 .map_err(|error| DevelopmentError::InvalidInput(error.to_string()))?;
1392 let store = WorkspaceStore::open_default()
1393 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1394 Ok(serde_json::to_value(
1395 store
1396 .open(&id)
1397 .map_err(|error| DevelopmentError::Process(error.to_string()))?,
1398 )?)
1399 }
1400 "glass.workspace.suspend" | "glass.workspace.resume" => {
1401 let id = WorkspaceId::new(string("id")?)
1402 .map_err(|error| DevelopmentError::InvalidInput(error.to_string()))?;
1403 let store = WorkspaceStore::open_default()
1404 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1405 let workspace = if call.name.ends_with("suspend") {
1406 store.suspend(&id)
1407 } else {
1408 store.resume(&id)
1409 }
1410 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1411 Ok(serde_json::to_value(workspace)?)
1412 }
1413 "glass.workspace.delete" => {
1414 let id = WorkspaceId::new(string("id")?)
1415 .map_err(|error| DevelopmentError::InvalidInput(error.to_string()))?;
1416 let store = WorkspaceStore::open_default()
1417 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1418 store
1419 .delete(&id)
1420 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1421 Ok(serde_json::json!({"id":id,"deleted":true}))
1422 }
1423 "glass.daemon.start" => {
1424 let runtime = tokio::runtime::Builder::new_current_thread()
1425 .enable_all()
1426 .build()
1427 .map_err(|error| DevelopmentError::Process(error.to_string()))?;
1428 map_service(runtime.block_on(crate::daemon::start(None, None)))
1429 }
1430 "glass.daemon.status" | "glass.daemon.doctor" => map_service(
1431 crate::daemon::read_status_checked(None, None)
1432 .map_err(|error| DevelopmentError::Process(error.to_string())),
1433 ),
1434 "glass.daemon.stop" => map_service(
1435 crate::daemon::stop(None, None)
1436 .map(|_| serde_json::json!({"status":"stopped"}))
1437 .map_err(|error| DevelopmentError::Process(error.to_string())),
1438 ),
1439 "glass.daemon.logs" => map_service(
1440 crate::daemon::log_tail(None)
1441 .map_err(|error| DevelopmentError::Process(error.to_string())),
1442 ),
1443 "glass.agent.hello" | "glass.agent.models" => {
1444 let id = optional_string(call, "agentId")
1445 .map(|value| agent_id(workspace, value))
1446 .transpose()?
1447 .or_else(|| active_agent_id(workspace))
1448 .ok_or_else(|| {
1449 DevelopmentError::Conflict(
1450 "start an interactive agent session before requesting Pi state"
1451 .into(),
1452 )
1453 })?;
1454 let request = if call.name.ends_with("hello") {
1455 PiSessionRequest::Hello
1456 } else {
1457 PiSessionRequest::Models
1458 };
1459 map_service(workspace.agents().request(&id, request))?;
1460 Ok(serde_json::json!({"queued":true,"agentId":id.as_str()}))
1461 }
1462 "glass.project.attach" => {
1463 let actor = crate::development::Actor::external(string("actor")?);
1464 workspace.project_mut().attach_actor(actor.clone())?;
1465 Ok(serde_json::to_value(actor)?)
1466 }
1467 "glass.workspace.trust.status" => Ok(serde_json::json!({
1468 "trust":workspace.trust(),
1469 "identity":workspace.trust_identity(),
1470 "store":workspace.trust_store_path(),
1471 "localDecisionRequired":true
1472 })),
1473 "glass.workspace.trust.inspect" => Ok(serde_json::json!({
1474 "trust":workspace.trust(),
1475 "items":workspace.trust_inspection(),
1476 "localDecisionRequired":true
1477 })),
1478 _ => Err(DevelopmentError::NotFound(format!("tool {}", call.name))),
1479 }
1480 }
1481}
1482
1483fn service_descriptors() -> Vec<ToolDescriptor> {
1484 const READ: &[&str] = &[
1485 "glass.process.list",
1486 "glass.process.logs",
1487 "glass.github.review",
1488 "glass.git.status",
1489 "glass.git.branches",
1490 "glass.git.blame",
1491 "glass.git.conflicts",
1492 "glass.git.diff",
1493 "glass.git.stash.list",
1494 "glass.git.worktree.list",
1495 "glass.editor.selection",
1496 "glass.editor.diff",
1497 "glass.editor.buffers",
1498 "glass.editor.comments",
1499 "glass.editor.proposals",
1500 "glass.editor.checkpoints",
1501 "glass.eval.list",
1502 "glass.lsp.diagnostics",
1503 "glass.workspace.list",
1504 "glass.workspace.inspect",
1505 "glass.daemon.status",
1506 "glass.daemon.doctor",
1507 "glass.daemon.logs",
1508 "glass.agent.hello",
1509 "glass.agent.models",
1510 "glass.workspace.trust.status",
1511 "glass.workspace.trust.inspect",
1512 "glass.lsp.list",
1513 "glass.lsp.events",
1514 "glass.lsp.raw",
1515 "glass.lsp.hover",
1516 "glass.lsp.completion",
1517 "glass.lsp.definition",
1518 "glass.lsp.declaration",
1519 "glass.lsp.implementation",
1520 "glass.lsp.references",
1521 "glass.lsp.document_symbols",
1522 "glass.lsp.workspace_symbols",
1523 "glass.lsp.signature_help",
1524 "glass.lsp.code_actions",
1525 "glass.lsp.formatting",
1526 "glass.lsp.range_formatting",
1527 "glass.lsp.semantic_tokens",
1528 "glass.lsp.rename",
1529 "glass.agent.list",
1530 "glass.agent.sessions",
1531 "glass.agent.tree",
1532 "glass.agent.messages",
1533 "glass.agent.entries",
1534 "glass.agent.stats",
1535 "glass.debug.events",
1536 "glass.debug.inspect",
1537 "glass.debug.processes",
1538 "glass.debug.threads",
1539 "glass.graph.source",
1540 "glass.task.list",
1541 "glass.task.get",
1542 "glass.task.inspect",
1543 "glass.test.results",
1544 "glass.test.discover",
1545 "glass.experiment.list",
1546 "glass.experiment.compare",
1547 "glass.graph.query",
1548 "glass.graph.path",
1549 "glass.graph.explain",
1550 "glass.replay.list",
1551 "glass.replay.inspect",
1552 "glass.replay.diff",
1553 "glass.process.health",
1554 "glass.process.ports",
1555 "glass.browser.state",
1556 "glass.browser.observe",
1557 "glass.browser.snapshot",
1558 "glass.browser.semantic",
1559 "glass.browser.web_ir",
1560 "glass.browser.diff",
1561 "glass.browser.targets",
1562 "glass.browser.screenshot",
1563 "glass.browser.remote-view.status",
1564 "glass.workflow.list",
1565 "glass.workflow.verify",
1566 "glass.workflow.record",
1567 "glass.memory.retrieve",
1568 "glass.memory.explain",
1569 "glass.semantic.diff",
1570 "glass.semantic.links",
1571 ];
1572 const MUTATE: &[&str] = &[
1573 "glass.workspace.suspend",
1574 "glass.workspace.resume",
1575 "glass.workspace.delete",
1576 "glass.daemon.start",
1577 "glass.daemon.stop",
1578 "glass.project.attach",
1579 "glass.github.ship",
1580 "glass.git.stage",
1581 "glass.git.discard",
1582 "glass.git.push",
1583 "glass.git.commit",
1584 "glass.git.branch.create",
1585 "glass.git.branch.switch",
1586 "glass.git.stash.push",
1587 "glass.git.stash.pop",
1588 "glass.git.worktree.create",
1589 "glass.git.worktree.remove",
1590 "glass.graph.link",
1591 "glass.test.run",
1592 "glass.test.run-affected",
1593 "glass.test.cancel",
1594 "glass.test.watch",
1595 "glass.eval.start",
1596 "glass.eval.execute",
1597 "glass.eval.cancel",
1598 "glass.eval.reset",
1599 "glass.eval.stop",
1600 "glass.debug.start",
1601 "glass.lsp.start",
1602 "glass.lsp.stop",
1603 "glass.debug.launch",
1604 "glass.debug.attach",
1605 "glass.debug.configuration_done",
1606 "glass.debug.restart",
1607 "glass.debug.breakpoint.set",
1608 "glass.debug.breakpoint.remove",
1609 "glass.debug.exception.set",
1610 "glass.debug.continue",
1611 "glass.debug.pause",
1612 "glass.debug.step",
1613 "glass.debug.disconnect",
1614 "glass.debug.terminate",
1615 "glass.debug.stop",
1616 "glass.agent.spawn",
1617 "glass.agent.setup",
1618 "glass.agent.delegate",
1619 "glass.agent.prompt",
1620 "glass.agent.send",
1621 "glass.agent.steer",
1622 "glass.agent.follow-up",
1623 "glass.agent.approve",
1624 "glass.agent.abort",
1625 "glass.agent.compact",
1626 "glass.agent.model",
1627 "glass.agent.thinking",
1628 "glass.agent.new-session",
1629 "glass.agent.clone-session",
1630 "glass.agent.rewind",
1631 "glass.agent.fork",
1632 "glass.agent.switch-session",
1633 "glass.agent.name",
1634 "glass.task.create",
1635 "glass.task.pause",
1636 "glass.task.resume",
1637 "glass.task.cancel",
1638 "glass.task.retry",
1639 "glass.task.reassign",
1640 "glass.task.override-blocked",
1641 "glass.task.evidence",
1642 "glass.task.verify",
1643 "glass.experiment.create",
1644 "glass.experiment.collect",
1645 "glass.experiment.select",
1646 "glass.experiment.remove",
1647 "glass.editor.open",
1648 "glass.editor.replace",
1649 "glass.editor.replace_selection",
1650 "glass.editor.save",
1651 "glass.editor.comment.add",
1652 "glass.editor.comment.resolve",
1653 "glass.editor.proposal.create",
1654 "glass.editor.proposal.accept",
1655 "glass.editor.proposal.reject",
1656 "glass.editor.checkpoint.create",
1657 "glass.editor.checkpoint.restore",
1658 "glass.process.start",
1659 "glass.process.stop",
1660 "glass.process.restart",
1661 "glass.process.input",
1662 "glass.process.resize",
1663 "glass.browser.start",
1664 "glass.browser.attach",
1665 "glass.browser.reconnect",
1666 "glass.browser.stop",
1667 "glass.browser.target.select",
1668 "glass.browser.navigate",
1669 "glass.browser.act",
1670 "glass.browser.remote-view.open",
1671 "glass.browser.remote-view.revoke",
1672 "glass.workflow.run",
1673 "glass.workflow.pause",
1674 "glass.workflow.resume",
1675 "glass.workflow.cancel",
1676 "glass.memory.forget",
1677 ];
1678 READ.iter()
1679 .map(|name| service_descriptor(name, false))
1680 .chain(MUTATE.iter().map(|name| service_descriptor(name, true)))
1681 .collect()
1682}
1683
1684pub(crate) fn tool_requires_mutation(name: &str) -> bool {
1685 static MUTATING: std::sync::LazyLock<Vec<String>> = std::sync::LazyLock::new(|| {
1686 service_descriptors()
1687 .into_iter()
1688 .filter(|descriptor| descriptor.mutating)
1689 .map(|descriptor| descriptor.name)
1690 .collect()
1691 });
1692 MUTATING.iter().any(|candidate| candidate == name)
1693}
1694
1695fn untrusted_tool_allowed(name: &str) -> bool {
1696 matches!(
1697 name,
1698 "glass.file.read"
1699 | "glass.file.list"
1700 | "glass.file.search"
1701 | "glass.file.grep"
1702 | "glass.file.find"
1703 | "glass.github.review"
1704 | "glass.git.status"
1705 | "glass.git.diff"
1706 | "glass.git.branches"
1707 | "glass.git.blame"
1708 | "glass.git.conflicts"
1709 | "glass.git.stash.list"
1710 | "glass.git.worktree.list"
1711 | "glass.browser.start"
1712 | "glass.browser.attach"
1713 | "glass.browser.reconnect"
1714 | "glass.browser.stop"
1715 | "glass.browser.state"
1716 | "glass.browser.observe"
1717 | "glass.browser.snapshot"
1718 | "glass.browser.semantic"
1719 | "glass.browser.web_ir"
1720 | "glass.browser.diff"
1721 | "glass.browser.targets"
1722 | "glass.browser.target.select"
1723 | "glass.browser.navigate"
1724 | "glass.browser.act"
1725 | "glass.browser.screenshot"
1726 | "glass.browser.remote-view.open"
1727 | "glass.browser.remote-view.status"
1728 | "glass.browser.remote-view.revoke"
1729 | "glass.agent.setup"
1730 | "glass.agent.list"
1731 | "glass.agent.sessions"
1732 | "glass.agent.tree"
1733 | "glass.agent.messages"
1734 | "glass.agent.entries"
1735 | "glass.agent.stats"
1736 | "glass.graph.source"
1737 | "glass.agent.hello"
1738 | "glass.agent.models"
1739 | "glass.editor.open"
1740 | "glass.editor.selection"
1741 | "glass.editor.diff"
1742 | "glass.editor.buffers"
1743 | "glass.editor.comments"
1744 | "glass.editor.proposals"
1745 | "glass.editor.checkpoints"
1746 | "glass.daemon.logs"
1747 | "glass.neovim.probe"
1748 | "glass.memory.retrieve"
1749 | "glass.memory.explain"
1750 | "glass.semantic.inspect"
1751 | "glass.semantic.diff"
1752 | "glass.semantic.links"
1753 | "glass.graph.query"
1754 | "glass.graph.path"
1755 | "glass.graph.explain"
1756 | "glass.replay.list"
1757 | "glass.replay.inspect"
1758 | "glass.replay.diff"
1759 | "glass.process.logs"
1760 | "glass.process.list"
1761 | "glass.process.health"
1762 | "glass.process.ports"
1763 | "glass.workspace.trust.status"
1764 | "glass.workspace.trust.inspect"
1765 | "glass.task.list"
1766 | "glass.task.get"
1767 | "glass.task.inspect"
1768 )
1769}
1770
1771fn service_descriptor(name: &str, mutating: bool) -> ToolDescriptor {
1772 let (description, input_schema) = if name == "glass.agent.delegate" {
1773 (
1774 "Delegate one bounded prompt to a temporary installed external agent".to_string(),
1775 serde_json::json!({
1776 "type": "object",
1777 "properties": {
1778 "harness": {"type": "string", "enum": ["codex", "claude", "opencode"]},
1779 "prompt": {"type": "string", "minLength": 1, "maxLength": 65536},
1780 "sandbox": {"type": "string", "enum": ["read-only", "workspace-write"]},
1781 "timeoutSeconds": {"type": "integer", "minimum": 1, "maximum": 3600}
1782 },
1783 "required": ["harness", "prompt"],
1784 "additionalProperties": false
1785 }),
1786 )
1787 } else {
1788 (
1789 format!("Resident Glass Dev operation {name}"),
1790 serde_json::json!({"type": "object"}),
1791 )
1792 };
1793 ToolDescriptor {
1794 name: name.into(),
1795 description,
1796 input_schema,
1797 mutating,
1798 available: true,
1799 unavailable_reason: None,
1800 }
1801}
1802
1803fn required_string<'a>(call: &'a ToolCall, name: &str) -> DevelopmentResult<&'a str> {
1804 call.arguments
1805 .get(name)
1806 .and_then(Value::as_str)
1807 .filter(|value| !value.is_empty() && value.len() <= 64 * 1024 && !value.contains('\0'))
1808 .ok_or_else(|| {
1809 DevelopmentError::InvalidInput(format!("{} requires bounded string {name}", call.name))
1810 })
1811}
1812
1813fn optional_string<'a>(call: &'a ToolCall, name: &str) -> Option<&'a str> {
1814 call.arguments.get(name).and_then(Value::as_str)
1815}
1816
1817fn required_value<'a>(call: &'a ToolCall, name: &str) -> DevelopmentResult<&'a Value> {
1818 call.arguments
1819 .get(name)
1820 .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))
1821}
1822
1823fn value_map(
1824 call: &ToolCall,
1825 name: &str,
1826) -> DevelopmentResult<std::collections::BTreeMap<String, Value>> {
1827 match call.arguments.get(name) {
1828 None => Ok(std::collections::BTreeMap::new()),
1829 Some(value) => serde_json::from_value(value.clone()).map_err(DevelopmentError::from),
1830 }
1831}
1832
1833fn boolean(call: &ToolCall, name: &str, default: bool) -> bool {
1834 call.arguments
1835 .get(name)
1836 .and_then(Value::as_bool)
1837 .unwrap_or(default)
1838}
1839
1840fn unsigned(call: &ToolCall, name: &str, default: u64) -> DevelopmentResult<u64> {
1841 let value = call
1842 .arguments
1843 .get(name)
1844 .and_then(Value::as_u64)
1845 .unwrap_or(default);
1846 (value <= i64::MAX as u64).then_some(value).ok_or_else(|| {
1847 DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1848 })
1849}
1850
1851fn integer(call: &ToolCall, name: &str) -> DevelopmentResult<i64> {
1852 call.arguments
1853 .get(name)
1854 .and_then(Value::as_i64)
1855 .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))
1856}
1857
1858fn u32_value(call: &ToolCall, name: &str) -> DevelopmentResult<u32> {
1859 u32::try_from(unsigned(call, name, 0)?).map_err(|_| {
1860 DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1861 })
1862}
1863
1864fn u16_value(call: &ToolCall, name: &str) -> DevelopmentResult<u16> {
1865 let value = u16::try_from(unsigned(call, name, 0)?).map_err(|_| {
1866 DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1867 })?;
1868 (value > 0).then_some(value).ok_or_else(|| {
1869 DevelopmentError::InvalidInput(format!("{}.{} must be non-zero", call.name, name))
1870 })
1871}
1872
1873fn position(
1874 call: &ToolCall,
1875 name: &str,
1876) -> DevelopmentResult<crate::development::DiagnosticPosition> {
1877 serde_json::from_value(required_value(call, name)?.clone()).map_err(DevelopmentError::from)
1878}
1879
1880fn value_array_or_empty(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<Value>> {
1881 match call.arguments.get(name) {
1882 None => Ok(Vec::new()),
1883 Some(Value::Array(values)) if values.len() <= 512 => Ok(values.clone()),
1884 Some(_) => Err(DevelopmentError::InvalidInput(format!(
1885 "{}.{} must be an array of at most 512 values",
1886 call.name, name
1887 ))),
1888 }
1889}
1890
1891fn number(call: &ToolCall, name: &str, default: f64) -> DevelopmentResult<f64> {
1892 let value = call
1893 .arguments
1894 .get(name)
1895 .and_then(Value::as_f64)
1896 .unwrap_or(default);
1897 value.is_finite().then_some(value).ok_or_else(|| {
1898 DevelopmentError::InvalidInput(format!("{}.{} must be finite", call.name, name))
1899 })
1900}
1901
1902fn string_array(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<String>> {
1903 let values = call
1904 .arguments
1905 .get(name)
1906 .and_then(Value::as_array)
1907 .filter(|values| !values.is_empty() && values.len() <= 256)
1908 .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))?;
1909 values
1910 .iter()
1911 .map(|value| {
1912 value
1913 .as_str()
1914 .filter(|value| !value.is_empty() && value.len() <= 4096 && !value.contains('\0'))
1915 .map(str::to_string)
1916 .ok_or_else(|| DevelopmentError::InvalidInput(format!("invalid {name} item")))
1917 })
1918 .collect()
1919}
1920
1921fn string_array_or_empty(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<String>> {
1922 if call.arguments.get(name).is_none() {
1923 Ok(Vec::new())
1924 } else {
1925 string_array(call, name)
1926 }
1927}
1928
1929fn unsigned_array(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<u64>> {
1930 call.arguments
1931 .get(name)
1932 .and_then(Value::as_array)
1933 .filter(|values| !values.is_empty() && values.len() <= 512)
1934 .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))?
1935 .iter()
1936 .map(|value| {
1937 value
1938 .as_u64()
1939 .filter(|value| *value > 0)
1940 .ok_or_else(|| DevelopmentError::InvalidInput(format!("invalid {name} item")))
1941 })
1942 .collect()
1943}
1944
1945fn timeout(call: &ToolCall, maximum_seconds: u64) -> DevelopmentResult<Option<Duration>> {
1946 call.arguments
1947 .get("timeoutSeconds")
1948 .map(|_| unsigned(call, "timeoutSeconds", maximum_seconds))
1949 .transpose()?
1950 .map(|seconds| {
1951 if seconds == 0 || seconds > maximum_seconds {
1952 Err(DevelopmentError::InvalidInput(format!(
1953 "timeoutSeconds must be 1..={maximum_seconds}"
1954 )))
1955 } else {
1956 Ok(Duration::from_secs(seconds))
1957 }
1958 })
1959 .transpose()
1960}
1961
1962fn parse_kernel_kind(value: &str) -> DevelopmentResult<KernelKind> {
1963 match value {
1964 "python" => Ok(KernelKind::Python),
1965 "javascript" => Ok(KernelKind::JavaScript),
1966 "shell" => Ok(KernelKind::Shell),
1967 "sql" => Ok(KernelKind::Sql),
1968 _ => Err(DevelopmentError::InvalidInput(
1969 "kernel kind must be python, javascript, shell, or sql".into(),
1970 )),
1971 }
1972}
1973
1974fn normalized_actor_id(value: &str) -> String {
1975 let normalized: String = value
1976 .chars()
1977 .filter(|character| character.is_ascii_alphanumeric() || "-_.".contains(*character))
1978 .take(128)
1979 .collect();
1980 if normalized.is_empty() {
1981 "actor".into()
1982 } else {
1983 normalized
1984 }
1985}
1986
1987fn agent_id(
1988 workspace: &mut DevelopmentWorkspace,
1989 value: &str,
1990) -> DevelopmentResult<crate::agents::AgentId> {
1991 workspace
1992 .agents()
1993 .list()?
1994 .into_iter()
1995 .find(|snapshot| snapshot.id.as_str() == value)
1996 .map(|snapshot| snapshot.id)
1997 .ok_or_else(|| DevelopmentError::NotFound(format!("agent {value}")))
1998}
1999fn active_agent_id(workspace: &mut DevelopmentWorkspace) -> Option<crate::agents::AgentId> {
2000 workspace
2001 .agents()
2002 .list()
2003 .ok()?
2004 .into_iter()
2005 .find(|snapshot| {
2006 !matches!(
2007 snapshot.status,
2008 crate::agents::AgentStatus::Completed
2009 | crate::agents::AgentStatus::Failed
2010 | crate::agents::AgentStatus::Cancelled
2011 )
2012 })
2013 .map(|snapshot| snapshot.id)
2014}
2015
2016fn agent_request(
2017 workspace: &mut DevelopmentWorkspace,
2018 call: &ToolCall,
2019 request: PiSessionRequest,
2020) -> DevelopmentResult<Value> {
2021 let id = agent_id(workspace, required_string(call, "agentId")?)?;
2022 map_service(workspace.agents().request(&id, request))?;
2023 Ok(serde_json::json!({"queued":true}))
2024}
2025
2026fn task_action(
2027 workspace: &mut DevelopmentWorkspace,
2028 call: &ToolCall,
2029 action: impl FnOnce(&mut DevelopmentWorkspace, &TaskId) -> DevelopmentResult<()>,
2030) -> DevelopmentResult<Value> {
2031 let id = TaskId::parse(required_string(call, "taskId")?)?;
2032 action(workspace, &id)?;
2033 Ok(serde_json::json!({"updated":true}))
2034}
2035
2036fn map_service<T: serde::Serialize, E: std::fmt::Display>(
2037 result: Result<T, E>,
2038) -> DevelopmentResult<Value> {
2039 result
2040 .map_err(|error| DevelopmentError::Process(error.to_string()))
2041 .and_then(|value| serde_json::to_value(value).map_err(DevelopmentError::from))
2042}
2043
2044fn map_debug<T: serde::Serialize>(
2045 result: crate::debugger::DebugResult<T>,
2046) -> DevelopmentResult<Value> {
2047 map_service(result)
2048}
2049
2050fn debugger<'a>(
2051 workspace: &'a mut DevelopmentWorkspace,
2052 name: &str,
2053) -> DevelopmentResult<&'a mut crate::debugger::DebuggerSession> {
2054 workspace
2055 .debugger_mut(name)
2056 .map_err(|error| DevelopmentError::Process(error.to_string()))
2057}
2058
2059fn git_value<T: serde::Serialize>(
2060 git: Option<&crate::git::GitService>,
2061 operation: impl FnOnce(&crate::git::GitService) -> crate::git::GitResult<T>,
2062) -> DevelopmentResult<Value> {
2063 map_service(operation(git.ok_or_else(|| {
2064 DevelopmentError::NotFound("Git repository".into())
2065 })?))
2066}
2067
2068fn git_mutation(
2069 git: Option<&crate::git::GitService>,
2070 operation: impl FnOnce(&crate::git::GitService) -> crate::git::GitResult<()>,
2071) -> DevelopmentResult<()> {
2072 operation(git.ok_or_else(|| DevelopmentError::NotFound("Git repository".into()))?)
2073 .map_err(|error| DevelopmentError::Process(error.to_string()))
2074}
2075
2076fn project_observable_result(
2077 workspace: &mut DevelopmentWorkspace,
2078 call: &ToolCall,
2079 actor: &str,
2080 before_revision: u64,
2081 after_revision: u64,
2082 result: &Value,
2083) -> DevelopmentResult<()> {
2084 let tool_node = format!("tool:{}", call.id);
2085 let result_bytes = serde_json::to_vec(result)?.len();
2086 let summary = serde_json::json!({
2087 "tool":call.name,
2088 "callId":call.id,
2089 "beforeRevision":before_revision,
2090 "afterRevision":after_revision,
2091 "resultBytes":result_bytes,
2092 });
2093 let argument = |name: &str| {
2094 call.arguments.get(name).and_then(|value| {
2095 value
2096 .as_str()
2097 .map(str::to_string)
2098 .or_else(|| value.as_u64().map(|value| value.to_string()))
2099 .or_else(|| value.as_i64().map(|value| value.to_string()))
2100 })
2101 };
2102 let resource_name = |preferred: &[&str], fallback: &str| {
2103 preferred
2104 .iter()
2105 .find_map(|name| argument(name).filter(|value| !value.is_empty()))
2106 .unwrap_or_else(|| fallback.to_string())
2107 };
2108 let mut observed = Vec::<(String, DevelopmentNodeKind, String, String)>::new();
2109
2110 if call.name.starts_with("glass.file.") || call.name.starts_with("glass.editor.") {
2111 let path = resource_name(&["path", "from", "to"], &call.id);
2112 let file = format!("file:{}", id_component(&path));
2113 observed.push((
2114 file.clone(),
2115 DevelopmentNodeKind::File,
2116 path,
2117 "referencesFile".into(),
2118 ));
2119 if call.name.starts_with("glass.editor.") {
2120 observed.push((
2121 format!("editorRevision:{}", id_component(&call.id)),
2122 DevelopmentNodeKind::EditorRevision,
2123 format!("editor revision {after_revision}"),
2124 "producedEditorRevision".into(),
2125 ));
2126 }
2127 }
2128 if call.name.starts_with("glass.lsp.") {
2129 let path = resource_name(&["path"], &call.id);
2130 if call.name == "glass.lsp.diagnostics" || call.name == "glass.diagnostics.run" {
2131 observed.push((
2132 format!("diagnostic:{}", id_component(&call.id)),
2133 DevelopmentNodeKind::Diagnostic,
2134 path,
2135 "reportedDiagnostic".into(),
2136 ));
2137 } else if !matches!(
2138 call.name.as_str(),
2139 "glass.lsp.start" | "glass.lsp.stop" | "glass.lsp.list" | "glass.lsp.events"
2140 ) {
2141 observed.push((
2142 format!("symbol:{}", id_component(&call.id)),
2143 DevelopmentNodeKind::Symbol,
2144 path,
2145 "resolvedSymbol".into(),
2146 ));
2147 }
2148 }
2149 if call.name.starts_with("glass.git.") {
2150 let kind = if call.name == "glass.git.commit" {
2151 DevelopmentNodeKind::GitCommit
2152 } else {
2153 DevelopmentNodeKind::GitChange
2154 };
2155 observed.push((
2156 format!("gitChange:{}", id_component(&call.id)),
2157 kind,
2158 call.name.clone(),
2159 "observedGitChange".into(),
2160 ));
2161 }
2162 if call.name.starts_with("glass.process.") {
2163 let name = resource_name(&["name"], &call.id);
2164 observed.push((
2165 format!("process:{}", id_component(&name)),
2166 DevelopmentNodeKind::Process,
2167 name,
2168 "observedProcess".into(),
2169 ));
2170 if let Some(port) = find_scalar(result, &["port", "debugPort", "assignedPort"], 0) {
2171 observed.push((
2172 format!("port:{}", id_component(&port)),
2173 DevelopmentNodeKind::Port,
2174 port,
2175 "observedPort".into(),
2176 ));
2177 }
2178 }
2179 if call.name.starts_with("glass.debug.") {
2180 let session = resource_name(&["session"], &call.id);
2181 observed.push((
2182 format!("debugger:{}", id_component(&session)),
2183 DevelopmentNodeKind::Debugger,
2184 session.clone(),
2185 "observedDebugSession".into(),
2186 ));
2187 if call.name.contains("breakpoint") {
2188 observed.push((
2189 format!("breakpoint:{}", id_component(&call.id)),
2190 DevelopmentNodeKind::Breakpoint,
2191 resource_name(&["path"], &call.id),
2192 "configuredBreakpoint".into(),
2193 ));
2194 }
2195 if let Some(thread) = argument("threadId").or_else(|| find_scalar(result, &["threadId"], 0))
2196 {
2197 observed.push((
2198 format!(
2199 "thread:{}:{}",
2200 id_component(&session),
2201 id_component(&thread)
2202 ),
2203 DevelopmentNodeKind::Thread,
2204 thread,
2205 "observedThread".into(),
2206 ));
2207 }
2208 if let Some(frame) =
2209 argument("frameId").or_else(|| find_scalar(result, &["frameId", "id"], 0))
2210 {
2211 observed.push((
2212 format!(
2213 "stackFrame:{}:{}",
2214 id_component(&session),
2215 id_component(&frame)
2216 ),
2217 DevelopmentNodeKind::StackFrame,
2218 frame,
2219 "observedStackFrame".into(),
2220 ));
2221 }
2222 }
2223 if call.name.starts_with("glass.browser.") {
2224 let target = argument("targetId")
2225 .or_else(|| find_scalar(result, &["targetId", "id"], 0))
2226 .unwrap_or_else(|| "active".into());
2227 observed.push((
2228 format!("browserTarget:{}", id_component(&target)),
2229 DevelopmentNodeKind::BrowserTarget,
2230 target,
2231 "observedBrowserTarget".into(),
2232 ));
2233 if let Some(revision) = find_scalar(result, &["revision", "browserRevision"], 0) {
2234 observed.push((
2235 format!("browserRevision:{}", id_component(&revision)),
2236 DevelopmentNodeKind::BrowserRevision,
2237 revision,
2238 "observedBrowserRevision".into(),
2239 ));
2240 }
2241 }
2242 if call.name.starts_with("glass.semantic.")
2243 || call.name.starts_with("glass.web_ir.")
2244 || call.name == "glass.browser.web_ir"
2245 {
2246 observed.push((
2247 format!("webIr:{}", id_component(&call.id)),
2248 DevelopmentNodeKind::WebIrEntity,
2249 call.name.clone(),
2250 "observedWebIr".into(),
2251 ));
2252 }
2253 if call.name.starts_with("glass.workflow.") {
2254 let run = resource_name(&["runId", "id", "name"], &call.id);
2255 observed.push((
2256 format!("workflow:{}", id_component(&run)),
2257 DevelopmentNodeKind::Workflow,
2258 run,
2259 "observedWorkflow".into(),
2260 ));
2261 }
2262 if call.name.starts_with("glass.test.") {
2263 let run = resource_name(&["runId", "suiteId"], &call.id);
2264 observed.push((
2265 format!("test:{}", id_component(&run)),
2266 DevelopmentNodeKind::Test,
2267 run,
2268 "observedTest".into(),
2269 ));
2270 }
2271 if call.name.starts_with("glass.eval.") {
2272 let name = resource_name(&["name"], &call.id);
2273 observed.push((
2274 format!("kernel:{}", id_component(&name)),
2275 DevelopmentNodeKind::Kernel,
2276 name,
2277 "observedKernel".into(),
2278 ));
2279 }
2280 if call.name.starts_with("glass.agent.") {
2281 let agent = argument("agentId")
2282 .or_else(|| find_scalar(result, &["agentId", "id"], 0))
2283 .unwrap_or_else(|| call.id.clone());
2284 observed.push((
2285 format!("agent:{}", id_component(&agent)),
2286 DevelopmentNodeKind::Agent,
2287 agent,
2288 "observedAgent".into(),
2289 ));
2290 }
2291 if call.name.starts_with("glass.task.") {
2292 let task = resource_name(&["taskId", "id"], &call.id);
2293 observed.push((
2294 format!("task:{}", id_component(&task)),
2295 DevelopmentNodeKind::Task,
2296 task,
2297 "observedTask".into(),
2298 ));
2299 }
2300 if call.name.starts_with("glass.experiment.") {
2301 let experiment = resource_name(&["id"], &call.id);
2302 observed.push((
2303 format!("experiment:{}", id_component(&experiment)),
2304 DevelopmentNodeKind::Experiment,
2305 experiment,
2306 "observedExperiment".into(),
2307 ));
2308 }
2309
2310 let mut previous: Option<String> = None;
2311 for (id, kind, label, relation) in observed {
2312 workspace.intelligence_mut().upsert_node(DevelopmentNode {
2313 id: id.clone(),
2314 kind,
2315 label,
2316 revision: after_revision,
2317 stale: false,
2318 evidence: summary.clone(),
2319 })?;
2320 workspace.intelligence_mut().link(
2321 previous.as_deref().unwrap_or(&tool_node),
2322 &id,
2323 &relation,
2324 after_revision,
2325 actor,
2326 summary.clone(),
2327 )?;
2328 workspace.intelligence_mut().record(ObservableEventInput {
2329 actor,
2330 subsystem: subsystem_for_tool(&call.name),
2331 kind: "observed",
2332 resource: Some(&id),
2333 workspace_revision: after_revision,
2334 evidence: summary.clone(),
2335 rationale: None,
2336 })?;
2337 previous = Some(id);
2338 }
2339 Ok(())
2340}
2341
2342fn subsystem_for_tool(tool: &str) -> &str {
2343 tool.strip_prefix("glass.")
2344 .and_then(|value| value.split('.').next())
2345 .unwrap_or("project")
2346}
2347
2348fn id_component(value: &str) -> String {
2349 value
2350 .chars()
2351 .map(|character| {
2352 if character.is_control() {
2353 '_'
2354 } else {
2355 character
2356 }
2357 })
2358 .take(240)
2359 .collect()
2360}
2361
2362fn find_scalar(value: &Value, keys: &[&str], depth: usize) -> Option<String> {
2363 if depth > 6 {
2364 return None;
2365 }
2366 match value {
2367 Value::Object(values) => {
2368 for key in keys {
2369 if let Some(value) = values.get(*key) {
2370 if let Some(value) = value.as_str() {
2371 return Some(value.to_string());
2372 }
2373 if let Some(value) = value.as_u64() {
2374 return Some(value.to_string());
2375 }
2376 }
2377 }
2378 values
2379 .values()
2380 .find_map(|value| find_scalar(value, keys, depth + 1))
2381 }
2382 Value::Array(values) => values
2383 .iter()
2384 .find_map(|value| find_scalar(value, keys, depth + 1)),
2385 _ => None,
2386 }
2387}
2388
2389#[cfg(test)]
2390mod tests {
2391 use super::*;
2392 use crate::development::Actor;
2393 use serde_json::json;
2394 use std::sync::atomic::{AtomicU64, Ordering};
2395
2396 static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2397
2398 fn workspace() -> DevelopmentWorkspace {
2399 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2400 let root = std::env::temp_dir().join(format!(
2401 "glass-tool-router-{}-{sequence}",
2402 std::process::id()
2403 ));
2404 std::fs::create_dir_all(&root).unwrap();
2405 std::fs::write(
2406 root.join("Cargo.toml"),
2407 "[package]\nname='x'\nversion='0.1.0'\n",
2408 )
2409 .unwrap();
2410 let mut workspace = DevelopmentWorkspace::open(root).unwrap();
2411 workspace
2412 .apply_local_trust_decision(crate::LocalTrustDecision::TrustOnce)
2413 .unwrap();
2414 workspace
2415 }
2416
2417 fn context(workspace: &DevelopmentWorkspace, mutate: bool) -> DevelopmentToolContext {
2418 DevelopmentToolContext {
2419 authorization: ToolAuthorization {
2420 actor: Actor::embedded(),
2421 allow_mutation: mutate,
2422 confirmed: mutate,
2423 },
2424 initiator: None,
2425 expected_generation: workspace.generation(),
2426 expected_project_revision: workspace.project().revision(),
2427 }
2428 }
2429
2430 #[test]
2431 fn root_file_listing_with_empty_path_keeps_tool_successful() {
2432 let mut workspace = workspace();
2433 let router = DevelopmentToolRouter::default();
2434 let call = ToolCall {
2435 id: "list-root".into(),
2436 name: "glass.file.list".into(),
2437 arguments: json!({"path":""}),
2438 };
2439 let read_only = context(&workspace, false);
2440 let result = router
2441 .execute(&mut workspace, &call, &read_only)
2442 .expect("listing the project root must succeed");
2443 assert!(result["entries"].is_array());
2444 assert_eq!(
2445 workspace
2446 .intelligence()
2447 .node("file:list-root")
2448 .unwrap()
2449 .label,
2450 "list-root"
2451 );
2452 }
2453
2454 #[test]
2455 fn router_rejects_stale_or_unauthorized_mutations() {
2456 let mut workspace = workspace();
2457 let router = DevelopmentToolRouter::default();
2458 let call = ToolCall {
2459 id: "write-1".into(),
2460 name: "glass.file.write".into(),
2461 arguments: serde_json::json!({"path":"src/lib.rs","content":"pub fn ok() {}\n"}),
2462 };
2463 let read_only = context(&workspace, false);
2464 assert!(router.execute(&mut workspace, &call, &read_only).is_err());
2465 let mut stale = context(&workspace, true);
2466 stale.expected_project_revision = stale.expected_project_revision.saturating_add(1);
2467 assert!(router.execute(&mut workspace, &call, &stale).is_err());
2468 let valid = context(&workspace, true);
2469 workspace.execute_tool(&call, &valid).unwrap();
2470 assert!(workspace.root().join("src/lib.rs").exists());
2471 let replay = workspace.intelligence().replay(0, 16).unwrap();
2472 assert_eq!(
2473 replay
2474 .iter()
2475 .map(|event| event.kind.as_str())
2476 .collect::<Vec<_>>(),
2477 vec!["called", "observed", "completed"]
2478 );
2479 assert!(
2480 workspace
2481 .intelligence()
2482 .path("repository:root", "tool:write-1")
2483 .is_ok()
2484 );
2485 }
2486
2487 #[test]
2488 fn router_uses_resident_kernel_and_test_services() {
2489 let mut workspace = workspace();
2490 let router = DevelopmentToolRouter::default();
2491 let start = ToolCall {
2492 id: "kernel-1".into(),
2493 name: "glass.eval.start".into(),
2494 arguments: serde_json::json!({"name":"analysis","kind":"sql"}),
2495 };
2496 let mutation = context(&workspace, true);
2497 router.execute(&mut workspace, &start, &mutation).unwrap();
2498 let execute = ToolCall {
2499 id: "kernel-2".into(),
2500 name: "glass.eval.execute".into(),
2501 arguments: serde_json::json!({"name":"analysis","code":"SELECT 40 + 2 AS answer"}),
2502 };
2503 let result = router.execute(&mut workspace, &execute, &mutation).unwrap();
2504 assert_eq!(result["value"][0]["answer"], 42);
2505 assert!(
2506 router
2507 .descriptors()
2508 .iter()
2509 .any(|descriptor| descriptor.name == "glass.debug.launch")
2510 );
2511 }
2512
2513 #[test]
2514 fn kernel_bindings_reenter_the_same_router_with_dual_provenance() {
2515 let mut workspace = workspace();
2516 std::fs::write(workspace.root().join("evidence.txt"), "governed\n").unwrap();
2517 let router = DevelopmentToolRouter::default();
2518 let mutation = context(&workspace, true);
2519 router
2520 .execute(
2521 &mut workspace,
2522 &ToolCall {
2523 id: "kernel-binding-start".into(),
2524 name: "glass.eval.start".into(),
2525 arguments: serde_json::json!({
2526 "name":"analysis",
2527 "kind":"sql",
2528 "capabilities":["glass.file.read","glass.file.write"]
2529 }),
2530 },
2531 &mutation,
2532 )
2533 .unwrap();
2534 let result = router
2535 .execute(
2536 &mut workspace,
2537 &ToolCall {
2538 id: "kernel-binding-execute".into(),
2539 name: "glass.eval.execute".into(),
2540 arguments: serde_json::json!({
2541 "name":"analysis",
2542 "code":r#"GLASS CALL {"id":"sql-1","tool":"glass.file.read","arguments":{"path":"evidence.txt"}}"#
2543 }),
2544 },
2545 &mutation,
2546 )
2547 .unwrap();
2548 assert_eq!(result["value"]["content"], "governed\n");
2549 assert_eq!(result["initiatorId"], "embedded:glass-agent");
2550 assert_eq!(result["executorId"], "kernel:analysis");
2551 let replay = workspace.intelligence().replay(0, 32).unwrap();
2552 let nested = replay
2553 .iter()
2554 .find(|event| event.resource.as_deref() == Some("tool:kernel-analysis-sql-1"))
2555 .unwrap();
2556 assert_eq!(nested.actor, "kernel:analysis");
2557 assert_eq!(nested.evidence["initiator"], "embedded:glass-agent");
2558 assert_eq!(nested.evidence["executor"], "kernel:analysis");
2559
2560 let denied = router.execute(
2561 &mut workspace,
2562 &ToolCall {
2563 id: "kernel-binding-denied".into(),
2564 name: "glass.eval.execute".into(),
2565 arguments: serde_json::json!({
2566 "name":"analysis",
2567 "code":r#"GLASS CALL {"id":"sql-2","tool":"glass.file.write","arguments":{"path":"denied.txt","content":"no"}}"#
2568 }),
2569 },
2570 &mutation,
2571 );
2572 assert!(denied.unwrap_err().to_string().contains("mutation"));
2573 assert!(!workspace.root().join("denied.txt").exists());
2574 }
2575
2576 #[test]
2577 fn governed_python_queries_browser_tests_and_graph_before_approved_mutation() {
2578 let mut workspace = workspace();
2579 let router = DevelopmentToolRouter::default();
2580 let mutation = context(&workspace, true);
2581 router
2582 .execute(
2583 &mut workspace,
2584 &ToolCall {
2585 id: "governed-python-start".into(),
2586 name: "glass.eval.start".into(),
2587 arguments: serde_json::json!({
2588 "name":"analysis",
2589 "kind":"python",
2590 "capabilities":[
2591 "glass.browser.state",
2592 "glass.test.results",
2593 "glass.graph.path",
2594 "glass.file.write"
2595 ]
2596 }),
2597 },
2598 &mutation,
2599 )
2600 .unwrap();
2601
2602 for (id, code, expected) in [
2603 (
2604 "governed-python-browser",
2605 "glass.call('glass.browser.state')",
2606 "'connected': False",
2607 ),
2608 (
2609 "governed-python-tests",
2610 "glass.call('glass.test.results')",
2611 "results",
2612 ),
2613 (
2614 "governed-python-graph",
2615 "glass.call('glass.graph.path', {'from': 'repository:root', 'to': 'tool:kernel-analysis-python-1'})",
2616 "repository:root",
2617 ),
2618 ] {
2619 let result = router
2620 .execute(
2621 &mut workspace,
2622 &ToolCall {
2623 id: id.into(),
2624 name: "glass.eval.execute".into(),
2625 arguments: serde_json::json!({"name":"analysis","code":code}),
2626 },
2627 &mutation,
2628 )
2629 .unwrap();
2630 assert!(
2631 result["value"].as_str().unwrap().contains(expected),
2632 "{id} must return governed {expected} evidence: {result}"
2633 );
2634 assert_eq!(result["initiatorId"], "embedded:glass-agent");
2635 assert_eq!(result["executorId"], "kernel:analysis");
2636 }
2637
2638 let denied = router.execute(
2639 &mut workspace,
2640 &ToolCall {
2641 id: "governed-python-denied".into(),
2642 name: "glass.eval.execute".into(),
2643 arguments: serde_json::json!({
2644 "name":"analysis",
2645 "code":"glass.call('glass.file.write', {'path': 'denied.py', 'content': 'no'})"
2646 }),
2647 },
2648 &mutation,
2649 );
2650 assert!(denied.unwrap_err().to_string().contains("mutation"));
2651 assert!(!workspace.root().join("denied.py").exists());
2652
2653 router
2654 .execute(
2655 &mut workspace,
2656 &ToolCall {
2657 id: "approved-python-start".into(),
2658 name: "glass.eval.start".into(),
2659 arguments: serde_json::json!({
2660 "name":"approved",
2661 "kind":"python",
2662 "capabilities":["glass.file.write"],
2663 "mutationAuthority":true
2664 }),
2665 },
2666 &mutation,
2667 )
2668 .unwrap();
2669 let approved = router
2670 .execute(
2671 &mut workspace,
2672 &ToolCall {
2673 id: "approved-python-write".into(),
2674 name: "glass.eval.execute".into(),
2675 arguments: serde_json::json!({
2676 "name":"approved",
2677 "code":"glass.call('glass.file.write', {'path': 'approved.py', 'content': 'approved\\n'})"
2678 }),
2679 },
2680 &mutation,
2681 )
2682 .unwrap();
2683 assert_eq!(approved["initiatorId"], "embedded:glass-agent");
2684 assert_eq!(approved["executorId"], "kernel:approved");
2685 assert_eq!(
2686 std::fs::read_to_string(workspace.root().join("approved.py")).unwrap(),
2687 "approved\n"
2688 );
2689
2690 let replay = workspace.intelligence().replay(0, 128).unwrap();
2691 for resource in [
2692 "tool:kernel-analysis-python-1",
2693 "tool:kernel-analysis-python-2",
2694 "tool:kernel-analysis-python-3",
2695 "tool:kernel-approved-python-1",
2696 ] {
2697 let nested = replay
2698 .iter()
2699 .find(|event| event.resource.as_deref() == Some(resource))
2700 .unwrap_or_else(|| panic!("missing provenance for {resource}"));
2701 assert_eq!(nested.evidence["initiator"], "embedded:glass-agent");
2702 assert!(
2703 nested.evidence["executor"]
2704 .as_str()
2705 .unwrap()
2706 .starts_with("kernel:")
2707 );
2708 }
2709 }
2710
2711 #[test]
2712 fn router_exposes_shared_editor_process_browser_and_complete_lsp_tools() {
2713 let mut workspace = workspace();
2714 std::fs::create_dir_all(workspace.root().join("src")).unwrap();
2715 std::fs::write(workspace.root().join("src/lib.rs"), "pub fn old() {}\n").unwrap();
2716 let router = DevelopmentToolRouter::default();
2717 let descriptors = router.descriptors();
2718 for name in [
2719 "glass.editor.open",
2720 "glass.editor.selection",
2721 "glass.editor.replace",
2722 "glass.editor.replace_selection",
2723 "glass.editor.save",
2724 "glass.editor.comments",
2725 "glass.editor.proposals",
2726 "glass.editor.checkpoints",
2727 "glass.editor.comment.add",
2728 "glass.editor.comment.resolve",
2729 "glass.editor.proposal.create",
2730 "glass.editor.proposal.accept",
2731 "glass.editor.proposal.reject",
2732 "glass.editor.checkpoint.create",
2733 "glass.editor.checkpoint.restore",
2734 "glass.process.list",
2735 "glass.process.logs",
2736 "glass.process.start",
2737 "glass.github.review",
2738 "glass.github.ship",
2739 "glass.process.stop",
2740 "glass.process.restart",
2741 "glass.browser.observe",
2742 "glass.browser.snapshot",
2743 "glass.browser.attach",
2744 "glass.browser.reconnect",
2745 "glass.browser.semantic",
2746 "glass.browser.web_ir",
2747 "glass.browser.diff",
2748 "glass.browser.navigate",
2749 "glass.browser.act",
2750 "glass.workflow.list",
2751 "glass.workflow.run",
2752 "glass.workflow.pause",
2753 "glass.workflow.resume",
2754 "glass.workflow.cancel",
2755 "glass.workflow.verify",
2756 "glass.workflow.record",
2757 "glass.memory.retrieve",
2758 "glass.memory.explain",
2759 "glass.memory.forget",
2760 "glass.semantic.inspect",
2761 "glass.semantic.diff",
2762 "glass.semantic.links",
2763 "glass.lsp.start",
2764 "glass.lsp.stop",
2765 "glass.lsp.list",
2766 "glass.lsp.events",
2767 "glass.lsp.definition",
2768 "glass.lsp.declaration",
2769 "glass.lsp.implementation",
2770 "glass.lsp.references",
2771 "glass.lsp.document_symbols",
2772 "glass.lsp.workspace_symbols",
2773 "glass.lsp.signature_help",
2774 "glass.lsp.code_actions",
2775 "glass.lsp.formatting",
2776 "glass.lsp.range_formatting",
2777 "glass.lsp.semantic_tokens",
2778 "glass.lsp.rename",
2779 "glass.lsp.raw",
2780 "glass.debug.configuration_done",
2781 "glass.debug.restart",
2782 "glass.debug.breakpoint.remove",
2783 "glass.debug.exception.set",
2784 "glass.debug.threads",
2785 "glass.debug.disconnect",
2786 "glass.debug.terminate",
2787 "glass.agent.model",
2788 "glass.agent.thinking",
2789 "glass.agent.new-session",
2790 "glass.agent.clone-session",
2791 "glass.agent.rewind",
2792 "glass.agent.fork",
2793 "glass.agent.switch-session",
2794 "glass.agent.sessions",
2795 "glass.agent.tree",
2796 "glass.agent.messages",
2797 "glass.agent.entries",
2798 "glass.agent.stats",
2799 "glass.agent.name",
2800 "glass.task.create",
2801 "glass.task.list",
2802 "glass.task.get",
2803 "glass.task.inspect",
2804 "glass.task.pause",
2805 "glass.task.resume",
2806 "glass.task.cancel",
2807 "glass.task.retry",
2808 "glass.task.reassign",
2809 "glass.task.override-blocked",
2810 "glass.task.evidence",
2811 "glass.task.verify",
2812 "glass.experiment.create",
2813 "glass.experiment.collect",
2814 "glass.experiment.list",
2815 "glass.experiment.compare",
2816 "glass.experiment.select",
2817 "glass.experiment.remove",
2818 ] {
2819 let descriptor = descriptors
2820 .iter()
2821 .find(|descriptor| descriptor.name == name)
2822 .unwrap_or_else(|| panic!("missing {name}"));
2823 assert!(
2824 descriptor.available,
2825 "{name} must execute, not be a placeholder"
2826 );
2827 }
2828 let semantic_descriptors = descriptors
2829 .iter()
2830 .filter(|descriptor| descriptor.name == "glass.semantic.inspect")
2831 .collect::<Vec<_>>();
2832 assert_eq!(semantic_descriptors.len(), 1);
2833 assert_eq!(
2834 semantic_descriptors[0].input_schema["required"],
2835 serde_json::json!(["entity"])
2836 );
2837
2838 for (id, name, arguments) in [
2839 (
2840 "open",
2841 "glass.editor.open",
2842 serde_json::json!({"path":"src/lib.rs"}),
2843 ),
2844 (
2845 "replace",
2846 "glass.editor.replace",
2847 serde_json::json!({"path":"src/lib.rs","oldText":"old","newText":"resident"}),
2848 ),
2849 (
2850 "save",
2851 "glass.editor.save",
2852 serde_json::json!({"path":"src/lib.rs"}),
2853 ),
2854 ] {
2855 let call = ToolCall {
2856 id: id.into(),
2857 name: name.into(),
2858 arguments,
2859 };
2860 let authorized = context(&workspace, true);
2861 router.execute(&mut workspace, &call, &authorized).unwrap();
2862 }
2863 assert_eq!(
2864 std::fs::read_to_string(workspace.root().join("src/lib.rs")).unwrap(),
2865 "pub fn resident() {}\n"
2866 );
2867 }
2868 #[test]
2869 fn editor_selection_tool_returns_text_and_replaces_only_that_range() {
2870 let mut workspace = workspace();
2871 std::fs::create_dir_all(workspace.root().join("src")).unwrap();
2872 std::fs::write(workspace.root().join("src/lib.rs"), "alpha\nbeta\n").unwrap();
2873 let router = DevelopmentToolRouter::default();
2874 let authorized = context(&workspace, true);
2875 router
2876 .execute(
2877 &mut workspace,
2878 &ToolCall {
2879 id: "selection-open".into(),
2880 name: "glass.editor.open".into(),
2881 arguments: serde_json::json!({"path":"src/lib.rs"}),
2882 },
2883 &authorized,
2884 )
2885 .unwrap();
2886 workspace
2887 .project_mut()
2888 .set_buffer_selection(
2889 "src/lib.rs",
2890 Some(crate::development::TextSelection {
2891 anchor: crate::development::TextPosition { line: 1, column: 2 },
2892 active: crate::development::TextPosition { line: 2, column: 3 },
2893 }),
2894 crate::development::Actor::local(),
2895 )
2896 .unwrap();
2897 let read_only = context(&workspace, false);
2898 let selection = router
2899 .execute(
2900 &mut workspace,
2901 &ToolCall {
2902 id: "selection-read".into(),
2903 name: "glass.editor.selection".into(),
2904 arguments: serde_json::json!({"path":"src/lib.rs"}),
2905 },
2906 &read_only,
2907 )
2908 .unwrap();
2909 assert_eq!(selection["selectedText"], "lpha\nbe");
2910 let authorized = context(&workspace, true);
2911 router
2912 .execute(
2913 &mut workspace,
2914 &ToolCall {
2915 id: "selection-replace".into(),
2916 name: "glass.editor.replace_selection".into(),
2917 arguments: serde_json::json!({
2918 "path":"src/lib.rs",
2919 "replacement":"X\nY"
2920 }),
2921 },
2922 &authorized,
2923 )
2924 .unwrap();
2925 assert_eq!(
2926 workspace.project().buffer("src/lib.rs").unwrap().content,
2927 "aX\nYta\n"
2928 );
2929 assert!(
2930 workspace
2931 .project()
2932 .buffer("src/lib.rs")
2933 .unwrap()
2934 .selection
2935 .is_none()
2936 );
2937 }
2938
2939 #[test]
2940 fn live_web_ir_route_is_read_only_and_requires_browser() {
2941 let mut workspace = workspace();
2942 let router = DevelopmentToolRouter::default();
2943 let descriptor = router
2944 .descriptors()
2945 .into_iter()
2946 .find(|descriptor| descriptor.name == "glass.browser.web_ir")
2947 .expect("live Web IR descriptor");
2948 assert!(descriptor.available);
2949 assert!(!descriptor.mutating);
2950
2951 let read_only = context(&workspace, false);
2952 let error = router
2953 .execute(
2954 &mut workspace,
2955 &ToolCall {
2956 id: "web-ir-disconnected".into(),
2957 name: "glass.browser.web_ir".into(),
2958 arguments: json!({}),
2959 },
2960 &read_only,
2961 )
2962 .unwrap_err();
2963 assert!(error.to_string().contains("glass.browser.start"));
2964 }
2965
2966 #[test]
2967 fn observable_projection_populates_every_issue_35_graph_resource_kind() {
2968 let mut workspace = workspace();
2969 let samples = vec![
2970 ("glass.editor.save", json!({"path":"src/lib.rs"}), json!({})),
2971 ("glass.lsp.hover", json!({"path":"src/lib.rs"}), json!({})),
2972 (
2973 "glass.lsp.diagnostics",
2974 json!({"path":"src/lib.rs"}),
2975 json!([]),
2976 ),
2977 ("glass.git.diff", json!({}), json!({"changed":true})),
2978 (
2979 "glass.process.ports",
2980 json!({"name":"web"}),
2981 json!({"port":8080}),
2982 ),
2983 (
2984 "glass.debug.stack",
2985 json!({"session":"rust","threadId":3}),
2986 json!({"stackFrames":[{"id":9}]}),
2987 ),
2988 (
2989 "glass.browser.state",
2990 json!({}),
2991 json!({"targetId":"page-1","revision":12}),
2992 ),
2993 ("glass.web_ir.inspect", json!({}), json!({"entities":[]})),
2994 (
2995 "glass.browser.web_ir",
2996 json!({}),
2997 json!({"targetId":"page-1","revision":12,"entityCount":3}),
2998 ),
2999 (
3000 "glass.workflow.verify",
3001 json!({"runId":"checkout"}),
3002 json!({"passed":false}),
3003 ),
3004 (
3005 "glass.test.results",
3006 json!({"runId":"unit"}),
3007 json!({"passed":true}),
3008 ),
3009 (
3010 "glass.eval.execute",
3011 json!({"name":"analysis"}),
3012 json!({"value":42}),
3013 ),
3014 ("glass.agent.list", json!({}), json!({"agentId":"agent-1"})),
3015 (
3016 "glass.task.get",
3017 json!({"taskId":"task-1"}),
3018 json!({"state":"failed"}),
3019 ),
3020 (
3021 "glass.experiment.collect",
3022 json!({"id":"approach-a"}),
3023 json!({"measured":true}),
3024 ),
3025 ];
3026 for (index, (name, arguments, result)) in samples.into_iter().enumerate() {
3027 let call = ToolCall {
3028 id: format!("projection-{index}"),
3029 name: name.into(),
3030 arguments,
3031 };
3032 let tool_node = format!("tool:{}", call.id);
3033 workspace
3034 .intelligence_mut()
3035 .upsert_node(DevelopmentNode {
3036 id: tool_node.clone(),
3037 kind: DevelopmentNodeKind::ToolCall,
3038 label: call.name.clone(),
3039 revision: 1,
3040 stale: false,
3041 evidence: Value::Null,
3042 })
3043 .unwrap();
3044 workspace
3045 .intelligence_mut()
3046 .link(
3047 "repository:root",
3048 &tool_node,
3049 "receivedToolCall",
3050 1,
3051 "test",
3052 Value::Null,
3053 )
3054 .unwrap();
3055 project_observable_result(&mut workspace, &call, "test", 1, 1, &result).unwrap();
3056 }
3057 assert!(
3058 workspace
3059 .intelligence()
3060 .query_kind(DevelopmentNodeKind::WebIrEntity)
3061 .iter()
3062 .any(|node| node.id == "webIr:projection-8"),
3063 "live browser Web IR must be projected into the graph"
3064 );
3065 for kind in [
3066 DevelopmentNodeKind::Repository,
3067 DevelopmentNodeKind::File,
3068 DevelopmentNodeKind::Symbol,
3069 DevelopmentNodeKind::EditorRevision,
3070 DevelopmentNodeKind::GitChange,
3071 DevelopmentNodeKind::Process,
3072 DevelopmentNodeKind::Port,
3073 DevelopmentNodeKind::Diagnostic,
3074 DevelopmentNodeKind::Debugger,
3075 DevelopmentNodeKind::Thread,
3076 DevelopmentNodeKind::StackFrame,
3077 DevelopmentNodeKind::BrowserTarget,
3078 DevelopmentNodeKind::BrowserRevision,
3079 DevelopmentNodeKind::WebIrEntity,
3080 DevelopmentNodeKind::Workflow,
3081 DevelopmentNodeKind::Test,
3082 DevelopmentNodeKind::Kernel,
3083 DevelopmentNodeKind::Agent,
3084 DevelopmentNodeKind::Task,
3085 DevelopmentNodeKind::Experiment,
3086 DevelopmentNodeKind::ToolCall,
3087 ] {
3088 assert!(
3089 !workspace.intelligence().query_kind(kind).is_empty(),
3090 "missing {kind:?}"
3091 );
3092 }
3093 let router = DevelopmentToolRouter::default();
3094 for (index, (from, to, relation)) in [
3095 ("file:src/lib.rs", "gitChange:projection-3", "changedBy"),
3096 ("gitChange:projection-3", "test:unit", "verifiedBy"),
3097 ("test:unit", "webIr:projection-7", "observedRegression"),
3098 ]
3099 .into_iter()
3100 .enumerate()
3101 {
3102 let context = context(&workspace, true);
3103 router
3104 .execute(
3105 &mut workspace,
3106 &ToolCall {
3107 id: format!("causal-link-{index}"),
3108 name: "glass.graph.link".into(),
3109 arguments: json!({
3110 "from":from,
3111 "to":to,
3112 "relation":relation,
3113 "evidence":{"source":"resident-verification"}
3114 }),
3115 },
3116 &context,
3117 )
3118 .unwrap();
3119 }
3120 let path = workspace
3121 .intelligence()
3122 .path("file:src/lib.rs", "webIr:projection-7")
3123 .unwrap();
3124 assert_eq!(
3125 path.edges
3126 .iter()
3127 .map(|edge| edge.relation.as_str())
3128 .collect::<Vec<_>>(),
3129 vec!["changedBy", "verifiedBy", "observedRegression"]
3130 );
3131 assert!(path.edges.iter().all(|edge| !edge.provenance.is_empty()));
3132 let replay = workspace.intelligence().replay(0, 128).unwrap();
3133 assert!(replay.iter().any(|event| event.subsystem == "task"));
3134 assert!(replay.iter().all(|event| event.rationale.is_none()));
3135 }
3136
3137 #[test]
3138 fn external_delegate_is_registered_as_approval_gated_capability() {
3139 let descriptor = DevelopmentToolRouter::default()
3140 .descriptors()
3141 .into_iter()
3142 .find(|descriptor| descriptor.name == "glass.agent.delegate")
3143 .expect("external delegate descriptor");
3144 assert!(descriptor.mutating);
3145 assert_eq!(
3146 descriptor.input_schema["properties"]["sandbox"]["enum"],
3147 json!(["read-only", "workspace-write"])
3148 );
3149 assert!(tool_requires_mutation("glass.agent.delegate"));
3150 }
3151}