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