Skip to main content

glass_dev/
tools.rs

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