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.setup" => map_service(crate::pi_runtime::setup_pi_runtime(
920                None,
921                None,
922                false,
923                boolean(call, "login", false),
924            )),
925            "glass.agent.spawn" => {
926                let spec: AgentSpec =
927                    serde_json::from_value(call.arguments.get("spec").cloned().ok_or_else(
928                        || DevelopmentError::InvalidInput("agent spawn requires spec".into()),
929                    )?)?;
930                map_service(workspace.agents().create(spec))
931            }
932            "glass.agent.prompt" => {
933                let id = agent_id(workspace, string("agentId")?)?;
934                map_service(workspace.agents().prompt(&id, string("text")?))?;
935                Ok(serde_json::json!({"queued":true}))
936            }
937            "glass.agent.send" => {
938                let text = string("text")?;
939                let mode = optional_string(call, "mode").unwrap_or("follow-up");
940                let selected = optional_string(call, "agentId")
941                    .map(|value| agent_id(workspace, value))
942                    .transpose()?;
943                let agent = selected.or_else(|| {
944                    workspace
945                        .agents()
946                        .list()
947                        .ok()?
948                        .into_iter()
949                        .find(|item| {
950                            !matches!(
951                                item.status,
952                                crate::AgentStatus::Completed
953                                    | crate::AgentStatus::Failed
954                                    | crate::AgentStatus::Cancelled
955                            )
956                        })
957                        .map(|item| item.id)
958                });
959                let agent = match agent {
960                    Some(agent) => agent,
961                    None => {
962                        let id = map_service(workspace
963                            .agents()
964                            .create(crate::AgentSpec::new("assistant", text)))?;
965                        return Ok(serde_json::json!({"queued":true,"agentId":id}));
966                    }
967                };
968                let status = workspace.agents().snapshot(&agent)?.status;
969                if mode == "steer" && status == crate::AgentStatus::Working {
970                    map_service(workspace.agents().steer(&agent, text))?;
971                } else if mode == "follow-up" && status == crate::AgentStatus::Working {
972                    map_service(workspace.agents().follow_up(&agent, text))?;
973                } else {
974                    map_service(workspace.agents().prompt(&agent, text))?;
975                }
976                Ok(serde_json::json!({"queued":true,"agentId":agent}))
977            }
978            "glass.agent.steer" => {
979                let id = agent_id(workspace, string("agentId")?)?;
980                map_service(workspace.agents().steer(&id, string("text")?))?;
981                Ok(serde_json::json!({"queued":true}))
982            }
983            "glass.agent.follow-up" => {
984                let id = agent_id(workspace, string("agentId")?)?;
985                map_service(workspace.agents().follow_up(&id, string("text")?))?;
986                Ok(serde_json::json!({"queued":true}))
987            }
988            "glass.agent.abort" => {
989                let id = agent_id(workspace, string("agentId")?)?;
990                map_service(workspace.agents().cancel(&id))?;
991                Ok(serde_json::json!({"cancelled":true}))
992            }
993            "glass.agent.compact" => {
994                let id = agent_id(workspace, string("agentId")?)?;
995                map_service(workspace.agents().request(
996                    &id,
997                    PiSessionRequest::Compact {
998                        instructions: optional_string(call, "instructions").map(str::to_string),
999                    },
1000                ))?;
1001                Ok(serde_json::json!({"queued":true}))
1002            }
1003            "glass.agent.model" => {
1004                let id = agent_id(workspace, string("agentId")?)?;
1005                map_service(workspace.agents().request(
1006                    &id,
1007                    PiSessionRequest::SetModel {
1008                        provider: string("provider")?.into(),
1009                        model_id: string("modelId")?.into(),
1010                    },
1011                ))?;
1012                Ok(serde_json::json!({"queued":true}))
1013            }
1014            "glass.agent.thinking" => {
1015                let id = agent_id(workspace, string("agentId")?)?;
1016                map_service(workspace.agents().request(
1017                    &id,
1018                    PiSessionRequest::SetThinking {
1019                        level: string("level")?.into(),
1020                    },
1021                ))?;
1022                Ok(serde_json::json!({"queued":true}))
1023            }
1024            "glass.agent.new-session" => {
1025                agent_request(workspace, call, PiSessionRequest::NewSession)
1026            }
1027            "glass.agent.clone-session" => {
1028                agent_request(workspace, call, PiSessionRequest::CloneSession)
1029            }
1030            "glass.agent.fork" => agent_request(
1031                workspace,
1032                call,
1033                PiSessionRequest::Fork {
1034                    entry_id: string("entryId")?.into(),
1035                },
1036            ),
1037            "glass.agent.switch-session" => agent_request(
1038                workspace,
1039                call,
1040                PiSessionRequest::SwitchSession {
1041                    path: string("path")?.into(),
1042                },
1043            ),
1044            "glass.agent.messages" => agent_request(workspace, call, PiSessionRequest::Messages),
1045            "glass.agent.entries" => agent_request(
1046                workspace,
1047                call,
1048                PiSessionRequest::Entries {
1049                    since: optional_string(call, "since").map(str::to_string),
1050                },
1051            ),
1052            "glass.agent.stats" => agent_request(workspace, call, PiSessionRequest::SessionStats),
1053            "glass.agent.name" => agent_request(
1054                workspace,
1055                call,
1056                PiSessionRequest::SetSessionName {
1057                    name: string("name")?.into(),
1058                },
1059            ),
1060            "glass.task.create" => {
1061                let spec = serde_json::from_value::<TaskSpec>(call.arguments.clone())?;
1062                Ok(serde_json::to_value(workspace.create_task(spec)?)?)
1063            }
1064            "glass.task.list" => Ok(serde_json::to_value(workspace.tasks()?)?),
1065            "glass.task.get" | "glass.task.inspect" => {
1066                let id = TaskId::parse(string("taskId")?)?;
1067                Ok(serde_json::to_value(workspace.task(&id)?)?)
1068            }
1069            "glass.task.pause" => task_action(workspace, call, |workspace, id| {
1070                workspace.pause_task(id)
1071            }),
1072            "glass.task.resume" => task_action(workspace, call, |workspace, id| {
1073                workspace.resume_task(id)
1074            }),
1075            "glass.task.cancel" => task_action(workspace, call, |workspace, id| {
1076                workspace.cancel_task(id)
1077            }),
1078            "glass.task.retry" => task_action(workspace, call, |workspace, id| {
1079                workspace.retry_task(id)
1080            }),
1081            "glass.task.override-blocked" => task_action(workspace, call, |workspace, id| {
1082                workspace.override_blocked_task(id)
1083            }),
1084            "glass.task.reassign" => {
1085                let id = TaskId::parse(string("taskId")?)?;
1086                workspace.reassign_task(
1087                    &id,
1088                    string("role")?.into(),
1089                    optional_string(call, "model").map(str::to_string),
1090                    optional_string(call, "thinking").map(str::to_string),
1091                )?;
1092                Ok(serde_json::json!({"reassigned":true}))
1093            }
1094            "glass.task.evidence" | "glass.task.verify" => {
1095                let id = TaskId::parse(string("taskId")?)?;
1096                workspace.submit_task_evidence(
1097                    &id,
1098                    string("kind")?.into(),
1099                    context.authorization.actor.id.clone(),
1100                    boolean(call, "passed", false),
1101                    call.arguments
1102                        .get("details")
1103                        .cloned()
1104                        .unwrap_or(Value::Null),
1105                )?;
1106                Ok(serde_json::json!({"recorded":true}))
1107            }
1108            "glass.experiment.create" => {
1109                let port = call
1110                    .arguments
1111                    .get("port")
1112                    .and_then(Value::as_u64)
1113                    .map(u16::try_from)
1114                    .transpose()
1115                    .map_err(|_| DevelopmentError::InvalidInput("invalid experiment port".into()))?;
1116                Ok(serde_json::to_value(workspace.experiments()?.create(
1117                    string("id")?,
1118                    string("branch")?,
1119                    port,
1120                )?)?)
1121            }
1122            "glass.experiment.collect" => Ok(serde_json::to_value(
1123                workspace
1124                    .experiments()?
1125                    .collect_automatic(string("id")?)?,
1126            )?),
1127            "glass.experiment.list" => Ok(serde_json::to_value(
1128                workspace.experiments()?.snapshots(),
1129            )?),
1130            "glass.experiment.compare" => Ok(serde_json::to_value(
1131                workspace.experiments()?.compare(),
1132            )?),
1133            "glass.experiment.select" => Ok(serde_json::to_value(
1134                workspace.experiments()?.select(string("id")?)?,
1135            )?),
1136            "glass.experiment.remove" => {
1137                workspace
1138                    .experiments()?
1139                    .remove(string("id")?, boolean(call, "force", false))?;
1140                Ok(serde_json::json!({"removed":true}))
1141            }
1142            "glass.graph.query" => Ok(serde_json::to_value(
1143                workspace.intelligence().node(string("id")?),
1144            )?),
1145            "glass.graph.path" | "glass.graph.explain" => Ok(serde_json::to_value(
1146                workspace
1147                    .intelligence()
1148                    .path(string("from")?, string("to")?)?,
1149            )?),
1150            "glass.graph.link" => {
1151                let revision = workspace.project().revision();
1152                let edge = workspace.intelligence_mut().link(
1153                    string("from")?,
1154                    string("to")?,
1155                    string("relation")?,
1156                    revision,
1157                    &actor,
1158                    call.arguments
1159                        .get("evidence")
1160                        .cloned()
1161                        .unwrap_or(Value::Null),
1162                )?;
1163                workspace.intelligence_mut().record(ObservableEventInput {
1164                    actor: &actor,
1165                    subsystem: "graph",
1166                    kind: "linked",
1167                    resource: None,
1168                    workspace_revision: revision,
1169                    evidence: serde_json::json!({"edgeId":edge,"from":string("from")?,"to":string("to")?,"relation":string("relation")?}),
1170                    rationale: None,
1171                })?;
1172                Ok(serde_json::json!({"edgeId":edge}))
1173            }
1174            "glass.replay.list" | "glass.replay.inspect" => {
1175                Ok(serde_json::to_value(workspace.intelligence().replay(
1176                    unsigned(call, "since", 0)?,
1177                    usize::try_from(unsigned(call, "limit", 128)?).unwrap_or(4096),
1178                )?)?)
1179            }
1180            "glass.replay.diff" => Ok(serde_json::to_value(
1181                workspace
1182                    .intelligence()
1183                    .replay_diff(unsigned(call, "from", 0)?, unsigned(call, "to", 1)?)?,
1184            )?),
1185            "glass.workspace.trust.status" => Ok(serde_json::json!({
1186                "trust":workspace.trust(),
1187                "identity":workspace.trust_identity(),
1188                "store":workspace.trust_store_path(),
1189                "localDecisionRequired":true
1190            })),
1191            "glass.workspace.trust.inspect" => Ok(serde_json::json!({
1192                "trust":workspace.trust(),
1193                "items":workspace.trust_inspection(),
1194                "localDecisionRequired":true
1195            })),
1196            _ => Err(DevelopmentError::NotFound(format!("tool {}", call.name))),
1197        }
1198    }
1199}
1200
1201fn service_descriptors() -> Vec<ToolDescriptor> {
1202    const READ: &[&str] = &[
1203        "glass.git.status",
1204        "glass.git.diff",
1205        "glass.git.branches",
1206        "glass.git.blame",
1207        "glass.git.conflicts",
1208        "glass.git.stash.list",
1209        "glass.git.worktree.list",
1210        "glass.test.discover",
1211        "glass.test.results",
1212        "glass.eval.list",
1213        "glass.lsp.diagnostics",
1214        "glass.lsp.list",
1215        "glass.lsp.events",
1216        "glass.lsp.raw",
1217        "glass.lsp.hover",
1218        "glass.lsp.completion",
1219        "glass.lsp.definition",
1220        "glass.lsp.declaration",
1221        "glass.lsp.implementation",
1222        "glass.lsp.references",
1223        "glass.lsp.document_symbols",
1224        "glass.lsp.workspace_symbols",
1225        "glass.lsp.signature_help",
1226        "glass.lsp.code_actions",
1227        "glass.lsp.formatting",
1228        "glass.lsp.range_formatting",
1229        "glass.lsp.semantic_tokens",
1230        "glass.lsp.rename",
1231        "glass.debug.stack",
1232        "glass.debug.threads",
1233        "glass.debug.scopes",
1234        "glass.debug.variables",
1235        "glass.debug.evaluate",
1236        "glass.debug.events",
1237        "glass.debug.inspect",
1238        "glass.debug.processes",
1239        "glass.agent.list",
1240        "glass.agent.messages",
1241        "glass.agent.entries",
1242        "glass.agent.stats",
1243        "glass.task.list",
1244        "glass.task.get",
1245        "glass.task.inspect",
1246        "glass.experiment.list",
1247        "glass.experiment.compare",
1248        "glass.graph.query",
1249        "glass.graph.path",
1250        "glass.graph.explain",
1251        "glass.replay.list",
1252        "glass.replay.inspect",
1253        "glass.replay.diff",
1254        "glass.editor.selection",
1255        "glass.editor.diff",
1256        "glass.editor.buffers",
1257        "glass.process.health",
1258        "glass.process.ports",
1259        "glass.browser.state",
1260        "glass.browser.observe",
1261        "glass.browser.snapshot",
1262        "glass.browser.semantic",
1263        "glass.browser.diff",
1264        "glass.browser.targets",
1265        "glass.browser.screenshot",
1266        "glass.browser.remote-view.status",
1267        "glass.workflow.list",
1268        "glass.workflow.verify",
1269        "glass.workflow.record",
1270        "glass.memory.retrieve",
1271        "glass.memory.explain",
1272        "glass.semantic.inspect",
1273        "glass.semantic.diff",
1274        "glass.semantic.links",
1275        "glass.workspace.trust.status",
1276        "glass.workspace.trust.inspect",
1277    ];
1278    const MUTATE: &[&str] = &[
1279        "glass.git.stage",
1280        "glass.git.unstage",
1281        "glass.git.discard",
1282        "glass.git.push",
1283        "glass.git.commit",
1284        "glass.git.branch.create",
1285        "glass.git.branch.switch",
1286        "glass.git.stash.push",
1287        "glass.git.stash.pop",
1288        "glass.git.worktree.create",
1289        "glass.git.worktree.remove",
1290        "glass.graph.link",
1291        "glass.test.run",
1292        "glass.test.run-affected",
1293        "glass.test.cancel",
1294        "glass.test.watch",
1295        "glass.eval.start",
1296        "glass.eval.execute",
1297        "glass.eval.cancel",
1298        "glass.eval.reset",
1299        "glass.eval.stop",
1300        "glass.debug.start",
1301        "glass.lsp.start",
1302        "glass.lsp.stop",
1303        "glass.debug.launch",
1304        "glass.debug.attach",
1305        "glass.debug.configuration_done",
1306        "glass.debug.restart",
1307        "glass.debug.breakpoint.set",
1308        "glass.debug.breakpoint.remove",
1309        "glass.debug.exception.set",
1310        "glass.debug.continue",
1311        "glass.debug.pause",
1312        "glass.debug.step",
1313        "glass.debug.disconnect",
1314        "glass.debug.terminate",
1315        "glass.debug.stop",
1316        "glass.agent.spawn",
1317        "glass.agent.setup",
1318        "glass.agent.prompt",
1319        "glass.agent.send",
1320        "glass.agent.steer",
1321        "glass.agent.follow-up",
1322        "glass.agent.abort",
1323        "glass.agent.compact",
1324        "glass.agent.model",
1325        "glass.agent.thinking",
1326        "glass.agent.new-session",
1327        "glass.agent.clone-session",
1328        "glass.agent.fork",
1329        "glass.agent.switch-session",
1330        "glass.agent.name",
1331        "glass.task.create",
1332        "glass.task.pause",
1333        "glass.task.resume",
1334        "glass.task.cancel",
1335        "glass.task.retry",
1336        "glass.task.reassign",
1337        "glass.task.override-blocked",
1338        "glass.task.evidence",
1339        "glass.task.verify",
1340        "glass.experiment.create",
1341        "glass.experiment.collect",
1342        "glass.experiment.select",
1343        "glass.experiment.remove",
1344        "glass.editor.open",
1345        "glass.editor.replace",
1346        "glass.editor.save",
1347        "glass.process.restart",
1348        "glass.process.input",
1349        "glass.process.resize",
1350        "glass.browser.start",
1351        "glass.browser.attach",
1352        "glass.browser.reconnect",
1353        "glass.browser.stop",
1354        "glass.browser.target.select",
1355        "glass.browser.navigate",
1356        "glass.browser.act",
1357        "glass.browser.remote-view.open",
1358        "glass.browser.remote-view.revoke",
1359        "glass.workflow.run",
1360        "glass.workflow.pause",
1361        "glass.workflow.resume",
1362        "glass.workflow.cancel",
1363        "glass.memory.forget",
1364    ];
1365    READ.iter()
1366        .map(|name| service_descriptor(name, false))
1367        .chain(MUTATE.iter().map(|name| service_descriptor(name, true)))
1368        .collect()
1369}
1370
1371fn untrusted_tool_allowed(name: &str) -> bool {
1372    matches!(
1373        name,
1374        "glass.file.read"
1375            | "glass.file.list"
1376            | "glass.file.search"
1377            | "glass.file.grep"
1378            | "glass.file.find"
1379            | "glass.git.status"
1380            | "glass.git.diff"
1381            | "glass.git.branches"
1382            | "glass.git.blame"
1383            | "glass.git.conflicts"
1384            | "glass.git.stash.list"
1385            | "glass.git.worktree.list"
1386            | "glass.browser.start"
1387            | "glass.browser.attach"
1388            | "glass.browser.reconnect"
1389            | "glass.browser.stop"
1390            | "glass.browser.state"
1391            | "glass.browser.observe"
1392            | "glass.browser.snapshot"
1393            | "glass.browser.semantic"
1394            | "glass.browser.diff"
1395            | "glass.browser.targets"
1396            | "glass.browser.target.select"
1397            | "glass.browser.navigate"
1398            | "glass.browser.act"
1399            | "glass.browser.screenshot"
1400            | "glass.browser.remote-view.open"
1401            | "glass.browser.remote-view.status"
1402            | "glass.browser.remote-view.revoke"
1403            | "glass.memory.retrieve"
1404            | "glass.memory.explain"
1405            | "glass.semantic.inspect"
1406            | "glass.semantic.diff"
1407            | "glass.semantic.links"
1408            | "glass.graph.query"
1409            | "glass.graph.path"
1410            | "glass.graph.explain"
1411            | "glass.replay.list"
1412            | "glass.replay.inspect"
1413            | "glass.replay.diff"
1414            | "glass.editor.open"
1415            | "glass.editor.selection"
1416            | "glass.editor.diff"
1417            | "glass.editor.buffers"
1418            | "glass.process.logs"
1419            | "glass.process.list"
1420            | "glass.process.health"
1421            | "glass.process.ports"
1422            | "glass.workspace.trust.status"
1423            | "glass.workspace.trust.inspect"
1424            | "glass.task.list"
1425            | "glass.task.get"
1426            | "glass.task.inspect"
1427    )
1428}
1429
1430fn service_descriptor(name: &str, mutating: bool) -> ToolDescriptor {
1431    ToolDescriptor {
1432        name: name.into(),
1433        description: format!("Resident Glass Dev operation {name}"),
1434        input_schema: serde_json::json!({"type":"object"}),
1435        mutating,
1436        available: true,
1437        unavailable_reason: None,
1438    }
1439}
1440
1441fn required_string<'a>(call: &'a ToolCall, name: &str) -> DevelopmentResult<&'a str> {
1442    call.arguments
1443        .get(name)
1444        .and_then(Value::as_str)
1445        .filter(|value| !value.is_empty() && value.len() <= 64 * 1024 && !value.contains('\0'))
1446        .ok_or_else(|| {
1447            DevelopmentError::InvalidInput(format!("{} requires bounded string {name}", call.name))
1448        })
1449}
1450
1451fn optional_string<'a>(call: &'a ToolCall, name: &str) -> Option<&'a str> {
1452    call.arguments.get(name).and_then(Value::as_str)
1453}
1454
1455fn required_value<'a>(call: &'a ToolCall, name: &str) -> DevelopmentResult<&'a Value> {
1456    call.arguments
1457        .get(name)
1458        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))
1459}
1460
1461fn value_map(
1462    call: &ToolCall,
1463    name: &str,
1464) -> DevelopmentResult<std::collections::BTreeMap<String, Value>> {
1465    match call.arguments.get(name) {
1466        None => Ok(std::collections::BTreeMap::new()),
1467        Some(value) => serde_json::from_value(value.clone()).map_err(DevelopmentError::from),
1468    }
1469}
1470
1471fn boolean(call: &ToolCall, name: &str, default: bool) -> bool {
1472    call.arguments
1473        .get(name)
1474        .and_then(Value::as_bool)
1475        .unwrap_or(default)
1476}
1477
1478fn unsigned(call: &ToolCall, name: &str, default: u64) -> DevelopmentResult<u64> {
1479    let value = call
1480        .arguments
1481        .get(name)
1482        .and_then(Value::as_u64)
1483        .unwrap_or(default);
1484    (value <= i64::MAX as u64).then_some(value).ok_or_else(|| {
1485        DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1486    })
1487}
1488
1489fn integer(call: &ToolCall, name: &str) -> DevelopmentResult<i64> {
1490    call.arguments
1491        .get(name)
1492        .and_then(Value::as_i64)
1493        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))
1494}
1495
1496fn u32_value(call: &ToolCall, name: &str) -> DevelopmentResult<u32> {
1497    u32::try_from(unsigned(call, name, 0)?).map_err(|_| {
1498        DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1499    })
1500}
1501
1502fn u16_value(call: &ToolCall, name: &str) -> DevelopmentResult<u16> {
1503    let value = u16::try_from(unsigned(call, name, 0)?).map_err(|_| {
1504        DevelopmentError::InvalidInput(format!("{}.{} is out of range", call.name, name))
1505    })?;
1506    (value > 0).then_some(value).ok_or_else(|| {
1507        DevelopmentError::InvalidInput(format!("{}.{} must be non-zero", call.name, name))
1508    })
1509}
1510
1511fn position(
1512    call: &ToolCall,
1513    name: &str,
1514) -> DevelopmentResult<crate::development::DiagnosticPosition> {
1515    serde_json::from_value(required_value(call, name)?.clone()).map_err(DevelopmentError::from)
1516}
1517
1518fn value_array_or_empty(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<Value>> {
1519    match call.arguments.get(name) {
1520        None => Ok(Vec::new()),
1521        Some(Value::Array(values)) if values.len() <= 512 => Ok(values.clone()),
1522        Some(_) => Err(DevelopmentError::InvalidInput(format!(
1523            "{}.{} must be an array of at most 512 values",
1524            call.name, name
1525        ))),
1526    }
1527}
1528
1529fn number(call: &ToolCall, name: &str, default: f64) -> DevelopmentResult<f64> {
1530    let value = call
1531        .arguments
1532        .get(name)
1533        .and_then(Value::as_f64)
1534        .unwrap_or(default);
1535    value.is_finite().then_some(value).ok_or_else(|| {
1536        DevelopmentError::InvalidInput(format!("{}.{} must be finite", call.name, name))
1537    })
1538}
1539
1540fn string_array(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<String>> {
1541    let values = call
1542        .arguments
1543        .get(name)
1544        .and_then(Value::as_array)
1545        .filter(|values| !values.is_empty() && values.len() <= 256)
1546        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))?;
1547    values
1548        .iter()
1549        .map(|value| {
1550            value
1551                .as_str()
1552                .filter(|value| !value.is_empty() && value.len() <= 4096 && !value.contains('\0'))
1553                .map(str::to_string)
1554                .ok_or_else(|| DevelopmentError::InvalidInput(format!("invalid {name} item")))
1555        })
1556        .collect()
1557}
1558
1559fn string_array_or_empty(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<String>> {
1560    if call.arguments.get(name).is_none() {
1561        Ok(Vec::new())
1562    } else {
1563        string_array(call, name)
1564    }
1565}
1566
1567fn unsigned_array(call: &ToolCall, name: &str) -> DevelopmentResult<Vec<u64>> {
1568    call.arguments
1569        .get(name)
1570        .and_then(Value::as_array)
1571        .filter(|values| !values.is_empty() && values.len() <= 512)
1572        .ok_or_else(|| DevelopmentError::InvalidInput(format!("{} requires {name}", call.name)))?
1573        .iter()
1574        .map(|value| {
1575            value
1576                .as_u64()
1577                .filter(|value| *value > 0)
1578                .ok_or_else(|| DevelopmentError::InvalidInput(format!("invalid {name} item")))
1579        })
1580        .collect()
1581}
1582
1583fn timeout(call: &ToolCall, maximum_seconds: u64) -> DevelopmentResult<Option<Duration>> {
1584    call.arguments
1585        .get("timeoutSeconds")
1586        .map(|_| unsigned(call, "timeoutSeconds", maximum_seconds))
1587        .transpose()?
1588        .map(|seconds| {
1589            if seconds == 0 || seconds > maximum_seconds {
1590                Err(DevelopmentError::InvalidInput(format!(
1591                    "timeoutSeconds must be 1..={maximum_seconds}"
1592                )))
1593            } else {
1594                Ok(Duration::from_secs(seconds))
1595            }
1596        })
1597        .transpose()
1598}
1599
1600fn parse_kernel_kind(value: &str) -> DevelopmentResult<KernelKind> {
1601    match value {
1602        "python" => Ok(KernelKind::Python),
1603        "javascript" => Ok(KernelKind::JavaScript),
1604        "shell" => Ok(KernelKind::Shell),
1605        "sql" => Ok(KernelKind::Sql),
1606        _ => Err(DevelopmentError::InvalidInput(
1607            "kernel kind must be python, javascript, shell, or sql".into(),
1608        )),
1609    }
1610}
1611
1612fn normalized_actor_id(value: &str) -> String {
1613    let normalized: String = value
1614        .chars()
1615        .filter(|character| character.is_ascii_alphanumeric() || "-_.".contains(*character))
1616        .take(128)
1617        .collect();
1618    if normalized.is_empty() {
1619        "actor".into()
1620    } else {
1621        normalized
1622    }
1623}
1624
1625fn agent_id(
1626    workspace: &mut DevelopmentWorkspace,
1627    value: &str,
1628) -> DevelopmentResult<crate::agents::AgentId> {
1629    workspace
1630        .agents()
1631        .list()?
1632        .into_iter()
1633        .find(|snapshot| snapshot.id.as_str() == value)
1634        .map(|snapshot| snapshot.id)
1635        .ok_or_else(|| DevelopmentError::NotFound(format!("agent {value}")))
1636}
1637
1638fn agent_request(
1639    workspace: &mut DevelopmentWorkspace,
1640    call: &ToolCall,
1641    request: PiSessionRequest,
1642) -> DevelopmentResult<Value> {
1643    let id = agent_id(workspace, required_string(call, "agentId")?)?;
1644    map_service(workspace.agents().request(&id, request))?;
1645    Ok(serde_json::json!({"queued":true}))
1646}
1647
1648fn task_action(
1649    workspace: &mut DevelopmentWorkspace,
1650    call: &ToolCall,
1651    action: impl FnOnce(&mut DevelopmentWorkspace, &TaskId) -> DevelopmentResult<()>,
1652) -> DevelopmentResult<Value> {
1653    let id = TaskId::parse(required_string(call, "taskId")?)?;
1654    action(workspace, &id)?;
1655    Ok(serde_json::json!({"updated":true}))
1656}
1657
1658fn map_service<T: serde::Serialize, E: std::fmt::Display>(
1659    result: Result<T, E>,
1660) -> DevelopmentResult<Value> {
1661    result
1662        .map_err(|error| DevelopmentError::Process(error.to_string()))
1663        .and_then(|value| serde_json::to_value(value).map_err(DevelopmentError::from))
1664}
1665
1666fn map_debug<T: serde::Serialize>(
1667    result: crate::debugger::DebugResult<T>,
1668) -> DevelopmentResult<Value> {
1669    map_service(result)
1670}
1671
1672fn debugger<'a>(
1673    workspace: &'a mut DevelopmentWorkspace,
1674    name: &str,
1675) -> DevelopmentResult<&'a mut crate::debugger::DebuggerSession> {
1676    workspace
1677        .debugger_mut(name)
1678        .map_err(|error| DevelopmentError::Process(error.to_string()))
1679}
1680
1681fn git_value<T: serde::Serialize>(
1682    git: Option<&crate::git::GitService>,
1683    operation: impl FnOnce(&crate::git::GitService) -> crate::git::GitResult<T>,
1684) -> DevelopmentResult<Value> {
1685    map_service(operation(git.ok_or_else(|| {
1686        DevelopmentError::NotFound("Git repository".into())
1687    })?))
1688}
1689
1690fn git_mutation(
1691    git: Option<&crate::git::GitService>,
1692    operation: impl FnOnce(&crate::git::GitService) -> crate::git::GitResult<()>,
1693) -> DevelopmentResult<()> {
1694    operation(git.ok_or_else(|| DevelopmentError::NotFound("Git repository".into()))?)
1695        .map_err(|error| DevelopmentError::Process(error.to_string()))
1696}
1697
1698fn project_observable_result(
1699    workspace: &mut DevelopmentWorkspace,
1700    call: &ToolCall,
1701    actor: &str,
1702    before_revision: u64,
1703    after_revision: u64,
1704    result: &Value,
1705) -> DevelopmentResult<()> {
1706    let tool_node = format!("tool:{}", call.id);
1707    let result_bytes = serde_json::to_vec(result)?.len();
1708    let summary = serde_json::json!({
1709        "tool":call.name,
1710        "callId":call.id,
1711        "beforeRevision":before_revision,
1712        "afterRevision":after_revision,
1713        "resultBytes":result_bytes,
1714    });
1715    let argument = |name: &str| {
1716        call.arguments.get(name).and_then(|value| {
1717            value
1718                .as_str()
1719                .map(str::to_string)
1720                .or_else(|| value.as_u64().map(|value| value.to_string()))
1721                .or_else(|| value.as_i64().map(|value| value.to_string()))
1722        })
1723    };
1724    let resource_name = |preferred: &[&str], fallback: &str| {
1725        preferred
1726            .iter()
1727            .find_map(|name| argument(name))
1728            .unwrap_or_else(|| fallback.to_string())
1729    };
1730    let mut observed = Vec::<(String, DevelopmentNodeKind, String, String)>::new();
1731
1732    if call.name.starts_with("glass.file.") || call.name.starts_with("glass.editor.") {
1733        let path = resource_name(&["path", "from", "to"], &call.id);
1734        let file = format!("file:{}", id_component(&path));
1735        observed.push((
1736            file.clone(),
1737            DevelopmentNodeKind::File,
1738            path,
1739            "referencesFile".into(),
1740        ));
1741        if call.name.starts_with("glass.editor.") {
1742            observed.push((
1743                format!("editorRevision:{}", id_component(&call.id)),
1744                DevelopmentNodeKind::EditorRevision,
1745                format!("editor revision {after_revision}"),
1746                "producedEditorRevision".into(),
1747            ));
1748        }
1749    }
1750    if call.name.starts_with("glass.lsp.") {
1751        let path = resource_name(&["path"], &call.id);
1752        if call.name == "glass.lsp.diagnostics" || call.name == "glass.diagnostics.run" {
1753            observed.push((
1754                format!("diagnostic:{}", id_component(&call.id)),
1755                DevelopmentNodeKind::Diagnostic,
1756                path,
1757                "reportedDiagnostic".into(),
1758            ));
1759        } else if !matches!(
1760            call.name.as_str(),
1761            "glass.lsp.start" | "glass.lsp.stop" | "glass.lsp.list" | "glass.lsp.events"
1762        ) {
1763            observed.push((
1764                format!("symbol:{}", id_component(&call.id)),
1765                DevelopmentNodeKind::Symbol,
1766                path,
1767                "resolvedSymbol".into(),
1768            ));
1769        }
1770    }
1771    if call.name.starts_with("glass.git.") {
1772        let kind = if call.name == "glass.git.commit" {
1773            DevelopmentNodeKind::GitCommit
1774        } else {
1775            DevelopmentNodeKind::GitChange
1776        };
1777        observed.push((
1778            format!("gitChange:{}", id_component(&call.id)),
1779            kind,
1780            call.name.clone(),
1781            "observedGitChange".into(),
1782        ));
1783    }
1784    if call.name.starts_with("glass.process.") {
1785        let name = resource_name(&["name"], &call.id);
1786        observed.push((
1787            format!("process:{}", id_component(&name)),
1788            DevelopmentNodeKind::Process,
1789            name,
1790            "observedProcess".into(),
1791        ));
1792        if let Some(port) = find_scalar(result, &["port", "debugPort", "assignedPort"], 0) {
1793            observed.push((
1794                format!("port:{}", id_component(&port)),
1795                DevelopmentNodeKind::Port,
1796                port,
1797                "observedPort".into(),
1798            ));
1799        }
1800    }
1801    if call.name.starts_with("glass.debug.") {
1802        let session = resource_name(&["session"], &call.id);
1803        observed.push((
1804            format!("debugger:{}", id_component(&session)),
1805            DevelopmentNodeKind::Debugger,
1806            session.clone(),
1807            "observedDebugSession".into(),
1808        ));
1809        if call.name.contains("breakpoint") {
1810            observed.push((
1811                format!("breakpoint:{}", id_component(&call.id)),
1812                DevelopmentNodeKind::Breakpoint,
1813                resource_name(&["path"], &call.id),
1814                "configuredBreakpoint".into(),
1815            ));
1816        }
1817        if let Some(thread) = argument("threadId").or_else(|| find_scalar(result, &["threadId"], 0))
1818        {
1819            observed.push((
1820                format!(
1821                    "thread:{}:{}",
1822                    id_component(&session),
1823                    id_component(&thread)
1824                ),
1825                DevelopmentNodeKind::Thread,
1826                thread,
1827                "observedThread".into(),
1828            ));
1829        }
1830        if let Some(frame) =
1831            argument("frameId").or_else(|| find_scalar(result, &["frameId", "id"], 0))
1832        {
1833            observed.push((
1834                format!(
1835                    "stackFrame:{}:{}",
1836                    id_component(&session),
1837                    id_component(&frame)
1838                ),
1839                DevelopmentNodeKind::StackFrame,
1840                frame,
1841                "observedStackFrame".into(),
1842            ));
1843        }
1844    }
1845    if call.name.starts_with("glass.browser.") {
1846        let target = argument("targetId")
1847            .or_else(|| find_scalar(result, &["targetId", "id"], 0))
1848            .unwrap_or_else(|| "active".into());
1849        observed.push((
1850            format!("browserTarget:{}", id_component(&target)),
1851            DevelopmentNodeKind::BrowserTarget,
1852            target,
1853            "observedBrowserTarget".into(),
1854        ));
1855        if let Some(revision) = find_scalar(result, &["revision", "browserRevision"], 0) {
1856            observed.push((
1857                format!("browserRevision:{}", id_component(&revision)),
1858                DevelopmentNodeKind::BrowserRevision,
1859                revision,
1860                "observedBrowserRevision".into(),
1861            ));
1862        }
1863    }
1864    if call.name.starts_with("glass.semantic.") || call.name.starts_with("glass.web_ir.") {
1865        observed.push((
1866            format!("webIr:{}", id_component(&call.id)),
1867            DevelopmentNodeKind::WebIrEntity,
1868            call.name.clone(),
1869            "observedWebIr".into(),
1870        ));
1871    }
1872    if call.name.starts_with("glass.workflow.") {
1873        let run = resource_name(&["runId", "id", "name"], &call.id);
1874        observed.push((
1875            format!("workflow:{}", id_component(&run)),
1876            DevelopmentNodeKind::Workflow,
1877            run,
1878            "observedWorkflow".into(),
1879        ));
1880    }
1881    if call.name.starts_with("glass.test.") {
1882        let run = resource_name(&["runId", "suiteId"], &call.id);
1883        observed.push((
1884            format!("test:{}", id_component(&run)),
1885            DevelopmentNodeKind::Test,
1886            run,
1887            "observedTest".into(),
1888        ));
1889    }
1890    if call.name.starts_with("glass.eval.") {
1891        let name = resource_name(&["name"], &call.id);
1892        observed.push((
1893            format!("kernel:{}", id_component(&name)),
1894            DevelopmentNodeKind::Kernel,
1895            name,
1896            "observedKernel".into(),
1897        ));
1898    }
1899    if call.name.starts_with("glass.agent.") {
1900        let agent = argument("agentId")
1901            .or_else(|| find_scalar(result, &["agentId", "id"], 0))
1902            .unwrap_or_else(|| call.id.clone());
1903        observed.push((
1904            format!("agent:{}", id_component(&agent)),
1905            DevelopmentNodeKind::Agent,
1906            agent,
1907            "observedAgent".into(),
1908        ));
1909    }
1910    if call.name.starts_with("glass.task.") {
1911        let task = resource_name(&["taskId", "id"], &call.id);
1912        observed.push((
1913            format!("task:{}", id_component(&task)),
1914            DevelopmentNodeKind::Task,
1915            task,
1916            "observedTask".into(),
1917        ));
1918    }
1919    if call.name.starts_with("glass.experiment.") {
1920        let experiment = resource_name(&["id"], &call.id);
1921        observed.push((
1922            format!("experiment:{}", id_component(&experiment)),
1923            DevelopmentNodeKind::Experiment,
1924            experiment,
1925            "observedExperiment".into(),
1926        ));
1927    }
1928
1929    let mut previous: Option<String> = None;
1930    for (id, kind, label, relation) in observed {
1931        workspace.intelligence_mut().upsert_node(DevelopmentNode {
1932            id: id.clone(),
1933            kind,
1934            label,
1935            revision: after_revision,
1936            stale: false,
1937            evidence: summary.clone(),
1938        })?;
1939        workspace.intelligence_mut().link(
1940            previous.as_deref().unwrap_or(&tool_node),
1941            &id,
1942            &relation,
1943            after_revision,
1944            actor,
1945            summary.clone(),
1946        )?;
1947        workspace.intelligence_mut().record(ObservableEventInput {
1948            actor,
1949            subsystem: subsystem_for_tool(&call.name),
1950            kind: "observed",
1951            resource: Some(&id),
1952            workspace_revision: after_revision,
1953            evidence: summary.clone(),
1954            rationale: None,
1955        })?;
1956        previous = Some(id);
1957    }
1958    Ok(())
1959}
1960
1961fn subsystem_for_tool(tool: &str) -> &str {
1962    tool.strip_prefix("glass.")
1963        .and_then(|value| value.split('.').next())
1964        .unwrap_or("project")
1965}
1966
1967fn id_component(value: &str) -> String {
1968    value
1969        .chars()
1970        .map(|character| {
1971            if character.is_control() {
1972                '_'
1973            } else {
1974                character
1975            }
1976        })
1977        .take(240)
1978        .collect()
1979}
1980
1981fn find_scalar(value: &Value, keys: &[&str], depth: usize) -> Option<String> {
1982    if depth > 6 {
1983        return None;
1984    }
1985    match value {
1986        Value::Object(values) => {
1987            for key in keys {
1988                if let Some(value) = values.get(*key) {
1989                    if let Some(value) = value.as_str() {
1990                        return Some(value.to_string());
1991                    }
1992                    if let Some(value) = value.as_u64() {
1993                        return Some(value.to_string());
1994                    }
1995                }
1996            }
1997            values
1998                .values()
1999                .find_map(|value| find_scalar(value, keys, depth + 1))
2000        }
2001        Value::Array(values) => values
2002            .iter()
2003            .find_map(|value| find_scalar(value, keys, depth + 1)),
2004        _ => None,
2005    }
2006}
2007
2008#[cfg(test)]
2009mod tests {
2010    use super::*;
2011    use crate::development::Actor;
2012    use serde_json::json;
2013    use std::sync::atomic::{AtomicU64, Ordering};
2014
2015    static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2016
2017    fn workspace() -> DevelopmentWorkspace {
2018        let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2019        let root = std::env::temp_dir().join(format!(
2020            "glass-tool-router-{}-{sequence}",
2021            std::process::id()
2022        ));
2023        std::fs::create_dir_all(&root).unwrap();
2024        std::fs::write(
2025            root.join("Cargo.toml"),
2026            "[package]\nname='x'\nversion='0.1.0'\n",
2027        )
2028        .unwrap();
2029        let mut workspace = DevelopmentWorkspace::open(root).unwrap();
2030        workspace
2031            .apply_local_trust_decision(crate::LocalTrustDecision::TrustOnce)
2032            .unwrap();
2033        workspace
2034    }
2035
2036    fn context(workspace: &DevelopmentWorkspace, mutate: bool) -> DevelopmentToolContext {
2037        DevelopmentToolContext {
2038            authorization: ToolAuthorization {
2039                actor: Actor::embedded(),
2040                allow_mutation: mutate,
2041                confirmed: mutate,
2042            },
2043            initiator: None,
2044            expected_generation: workspace.generation(),
2045            expected_project_revision: workspace.project().revision(),
2046        }
2047    }
2048
2049    #[test]
2050    fn router_rejects_stale_or_unauthorized_mutations() {
2051        let mut workspace = workspace();
2052        let router = DevelopmentToolRouter::default();
2053        let call = ToolCall {
2054            id: "write-1".into(),
2055            name: "glass.file.write".into(),
2056            arguments: serde_json::json!({"path":"src/lib.rs","content":"pub fn ok() {}\n"}),
2057        };
2058        let read_only = context(&workspace, false);
2059        assert!(router.execute(&mut workspace, &call, &read_only).is_err());
2060        let mut stale = context(&workspace, true);
2061        stale.expected_project_revision = stale.expected_project_revision.saturating_add(1);
2062        assert!(router.execute(&mut workspace, &call, &stale).is_err());
2063        let valid = context(&workspace, true);
2064        workspace.execute_tool(&call, &valid).unwrap();
2065        assert!(workspace.root().join("src/lib.rs").exists());
2066        let replay = workspace.intelligence().replay(0, 16).unwrap();
2067        assert_eq!(
2068            replay
2069                .iter()
2070                .map(|event| event.kind.as_str())
2071                .collect::<Vec<_>>(),
2072            vec!["called", "observed", "completed"]
2073        );
2074        assert!(
2075            workspace
2076                .intelligence()
2077                .path("repository:root", "tool:write-1")
2078                .is_ok()
2079        );
2080    }
2081
2082    #[test]
2083    fn router_uses_resident_kernel_and_test_services() {
2084        let mut workspace = workspace();
2085        let router = DevelopmentToolRouter::default();
2086        let start = ToolCall {
2087            id: "kernel-1".into(),
2088            name: "glass.eval.start".into(),
2089            arguments: serde_json::json!({"name":"analysis","kind":"sql"}),
2090        };
2091        let mutation = context(&workspace, true);
2092        router.execute(&mut workspace, &start, &mutation).unwrap();
2093        let execute = ToolCall {
2094            id: "kernel-2".into(),
2095            name: "glass.eval.execute".into(),
2096            arguments: serde_json::json!({"name":"analysis","code":"SELECT 40 + 2 AS answer"}),
2097        };
2098        let result = router.execute(&mut workspace, &execute, &mutation).unwrap();
2099        assert_eq!(result["value"][0]["answer"], 42);
2100        assert!(
2101            router
2102                .descriptors()
2103                .iter()
2104                .any(|descriptor| descriptor.name == "glass.debug.launch")
2105        );
2106    }
2107
2108    #[test]
2109    fn kernel_bindings_reenter_the_same_router_with_dual_provenance() {
2110        let mut workspace = workspace();
2111        std::fs::write(workspace.root().join("evidence.txt"), "governed\n").unwrap();
2112        let router = DevelopmentToolRouter::default();
2113        let mutation = context(&workspace, true);
2114        router
2115            .execute(
2116                &mut workspace,
2117                &ToolCall {
2118                    id: "kernel-binding-start".into(),
2119                    name: "glass.eval.start".into(),
2120                    arguments: serde_json::json!({
2121                        "name":"analysis",
2122                        "kind":"sql",
2123                        "capabilities":["glass.file.read","glass.file.write"]
2124                    }),
2125                },
2126                &mutation,
2127            )
2128            .unwrap();
2129        let result = router
2130            .execute(
2131                &mut workspace,
2132                &ToolCall {
2133                    id: "kernel-binding-execute".into(),
2134                    name: "glass.eval.execute".into(),
2135                    arguments: serde_json::json!({
2136                        "name":"analysis",
2137                        "code":r#"GLASS CALL {"id":"sql-1","tool":"glass.file.read","arguments":{"path":"evidence.txt"}}"#
2138                    }),
2139                },
2140                &mutation,
2141            )
2142            .unwrap();
2143        assert_eq!(result["value"]["content"], "governed\n");
2144        assert_eq!(result["initiatorId"], "embedded:glass-agent");
2145        assert_eq!(result["executorId"], "kernel:analysis");
2146        let replay = workspace.intelligence().replay(0, 32).unwrap();
2147        let nested = replay
2148            .iter()
2149            .find(|event| event.resource.as_deref() == Some("tool:kernel-analysis-sql-1"))
2150            .unwrap();
2151        assert_eq!(nested.actor, "kernel:analysis");
2152        assert_eq!(nested.evidence["initiator"], "embedded:glass-agent");
2153        assert_eq!(nested.evidence["executor"], "kernel:analysis");
2154
2155        let denied = router.execute(
2156            &mut workspace,
2157            &ToolCall {
2158                id: "kernel-binding-denied".into(),
2159                name: "glass.eval.execute".into(),
2160                arguments: serde_json::json!({
2161                    "name":"analysis",
2162                    "code":r#"GLASS CALL {"id":"sql-2","tool":"glass.file.write","arguments":{"path":"denied.txt","content":"no"}}"#
2163                }),
2164            },
2165            &mutation,
2166        );
2167        assert!(denied.unwrap_err().to_string().contains("mutation"));
2168        assert!(!workspace.root().join("denied.txt").exists());
2169    }
2170
2171    #[test]
2172    fn governed_python_queries_browser_tests_and_graph_before_approved_mutation() {
2173        let mut workspace = workspace();
2174        let router = DevelopmentToolRouter::default();
2175        let mutation = context(&workspace, true);
2176        router
2177            .execute(
2178                &mut workspace,
2179                &ToolCall {
2180                    id: "governed-python-start".into(),
2181                    name: "glass.eval.start".into(),
2182                    arguments: serde_json::json!({
2183                        "name":"analysis",
2184                        "kind":"python",
2185                        "capabilities":[
2186                            "glass.browser.state",
2187                            "glass.test.results",
2188                            "glass.graph.path",
2189                            "glass.file.write"
2190                        ]
2191                    }),
2192                },
2193                &mutation,
2194            )
2195            .unwrap();
2196
2197        for (id, code, expected) in [
2198            (
2199                "governed-python-browser",
2200                "glass.call('glass.browser.state')",
2201                "'connected': False",
2202            ),
2203            (
2204                "governed-python-tests",
2205                "glass.call('glass.test.results')",
2206                "results",
2207            ),
2208            (
2209                "governed-python-graph",
2210                "glass.call('glass.graph.path', {'from': 'repository:root', 'to': 'tool:kernel-analysis-python-1'})",
2211                "repository:root",
2212            ),
2213        ] {
2214            let result = router
2215                .execute(
2216                    &mut workspace,
2217                    &ToolCall {
2218                        id: id.into(),
2219                        name: "glass.eval.execute".into(),
2220                        arguments: serde_json::json!({"name":"analysis","code":code}),
2221                    },
2222                    &mutation,
2223                )
2224                .unwrap();
2225            assert!(
2226                result["value"].as_str().unwrap().contains(expected),
2227                "{id} must return governed {expected} evidence: {result}"
2228            );
2229            assert_eq!(result["initiatorId"], "embedded:glass-agent");
2230            assert_eq!(result["executorId"], "kernel:analysis");
2231        }
2232
2233        let denied = router.execute(
2234            &mut workspace,
2235            &ToolCall {
2236                id: "governed-python-denied".into(),
2237                name: "glass.eval.execute".into(),
2238                arguments: serde_json::json!({
2239                    "name":"analysis",
2240                    "code":"glass.call('glass.file.write', {'path': 'denied.py', 'content': 'no'})"
2241                }),
2242            },
2243            &mutation,
2244        );
2245        assert!(denied.unwrap_err().to_string().contains("mutation"));
2246        assert!(!workspace.root().join("denied.py").exists());
2247
2248        router
2249            .execute(
2250                &mut workspace,
2251                &ToolCall {
2252                    id: "approved-python-start".into(),
2253                    name: "glass.eval.start".into(),
2254                    arguments: serde_json::json!({
2255                        "name":"approved",
2256                        "kind":"python",
2257                        "capabilities":["glass.file.write"],
2258                        "mutationAuthority":true
2259                    }),
2260                },
2261                &mutation,
2262            )
2263            .unwrap();
2264        let approved = router
2265            .execute(
2266                &mut workspace,
2267                &ToolCall {
2268                    id: "approved-python-write".into(),
2269                    name: "glass.eval.execute".into(),
2270                    arguments: serde_json::json!({
2271                        "name":"approved",
2272                        "code":"glass.call('glass.file.write', {'path': 'approved.py', 'content': 'approved\\n'})"
2273                    }),
2274                },
2275                &mutation,
2276            )
2277            .unwrap();
2278        assert_eq!(approved["initiatorId"], "embedded:glass-agent");
2279        assert_eq!(approved["executorId"], "kernel:approved");
2280        assert_eq!(
2281            std::fs::read_to_string(workspace.root().join("approved.py")).unwrap(),
2282            "approved\n"
2283        );
2284
2285        let replay = workspace.intelligence().replay(0, 128).unwrap();
2286        for resource in [
2287            "tool:kernel-analysis-python-1",
2288            "tool:kernel-analysis-python-2",
2289            "tool:kernel-analysis-python-3",
2290            "tool:kernel-approved-python-1",
2291        ] {
2292            let nested = replay
2293                .iter()
2294                .find(|event| event.resource.as_deref() == Some(resource))
2295                .unwrap_or_else(|| panic!("missing provenance for {resource}"));
2296            assert_eq!(nested.evidence["initiator"], "embedded:glass-agent");
2297            assert!(
2298                nested.evidence["executor"]
2299                    .as_str()
2300                    .unwrap()
2301                    .starts_with("kernel:")
2302            );
2303        }
2304    }
2305
2306    #[test]
2307    fn router_exposes_shared_editor_process_browser_and_complete_lsp_tools() {
2308        let mut workspace = workspace();
2309        std::fs::create_dir_all(workspace.root().join("src")).unwrap();
2310        std::fs::write(workspace.root().join("src/lib.rs"), "pub fn old() {}\n").unwrap();
2311        let router = DevelopmentToolRouter::default();
2312        let descriptors = router.descriptors();
2313        for name in [
2314            "glass.editor.open",
2315            "glass.editor.replace",
2316            "glass.editor.save",
2317            "glass.process.restart",
2318            "glass.process.input",
2319            "glass.process.resize",
2320            "glass.process.health",
2321            "glass.process.ports",
2322            "glass.browser.observe",
2323            "glass.browser.snapshot",
2324            "glass.browser.attach",
2325            "glass.browser.reconnect",
2326            "glass.browser.semantic",
2327            "glass.browser.diff",
2328            "glass.browser.navigate",
2329            "glass.browser.act",
2330            "glass.workflow.list",
2331            "glass.workflow.run",
2332            "glass.workflow.pause",
2333            "glass.workflow.resume",
2334            "glass.workflow.cancel",
2335            "glass.workflow.verify",
2336            "glass.workflow.record",
2337            "glass.memory.retrieve",
2338            "glass.memory.explain",
2339            "glass.memory.forget",
2340            "glass.semantic.inspect",
2341            "glass.semantic.diff",
2342            "glass.semantic.links",
2343            "glass.lsp.start",
2344            "glass.lsp.stop",
2345            "glass.lsp.list",
2346            "glass.lsp.events",
2347            "glass.lsp.definition",
2348            "glass.lsp.declaration",
2349            "glass.lsp.implementation",
2350            "glass.lsp.references",
2351            "glass.lsp.document_symbols",
2352            "glass.lsp.workspace_symbols",
2353            "glass.lsp.signature_help",
2354            "glass.lsp.code_actions",
2355            "glass.lsp.formatting",
2356            "glass.lsp.range_formatting",
2357            "glass.lsp.semantic_tokens",
2358            "glass.lsp.rename",
2359            "glass.lsp.raw",
2360            "glass.debug.configuration_done",
2361            "glass.debug.restart",
2362            "glass.debug.breakpoint.remove",
2363            "glass.debug.exception.set",
2364            "glass.debug.threads",
2365            "glass.debug.disconnect",
2366            "glass.debug.terminate",
2367            "glass.agent.model",
2368            "glass.agent.thinking",
2369            "glass.agent.new-session",
2370            "glass.agent.clone-session",
2371            "glass.agent.fork",
2372            "glass.agent.switch-session",
2373            "glass.agent.messages",
2374            "glass.agent.entries",
2375            "glass.agent.stats",
2376            "glass.agent.name",
2377            "glass.task.create",
2378            "glass.task.list",
2379            "glass.task.get",
2380            "glass.task.inspect",
2381            "glass.task.pause",
2382            "glass.task.resume",
2383            "glass.task.cancel",
2384            "glass.task.retry",
2385            "glass.task.reassign",
2386            "glass.task.override-blocked",
2387            "glass.task.evidence",
2388            "glass.task.verify",
2389            "glass.experiment.create",
2390            "glass.experiment.collect",
2391            "glass.experiment.list",
2392            "glass.experiment.compare",
2393            "glass.experiment.select",
2394            "glass.experiment.remove",
2395        ] {
2396            let descriptor = descriptors
2397                .iter()
2398                .find(|descriptor| descriptor.name == name)
2399                .unwrap_or_else(|| panic!("missing {name}"));
2400            assert!(
2401                descriptor.available,
2402                "{name} must execute, not be a placeholder"
2403            );
2404        }
2405
2406        for (id, name, arguments) in [
2407            (
2408                "open",
2409                "glass.editor.open",
2410                serde_json::json!({"path":"src/lib.rs"}),
2411            ),
2412            (
2413                "replace",
2414                "glass.editor.replace",
2415                serde_json::json!({"path":"src/lib.rs","oldText":"old","newText":"resident"}),
2416            ),
2417            (
2418                "save",
2419                "glass.editor.save",
2420                serde_json::json!({"path":"src/lib.rs"}),
2421            ),
2422        ] {
2423            let call = ToolCall {
2424                id: id.into(),
2425                name: name.into(),
2426                arguments,
2427            };
2428            let authorized = context(&workspace, true);
2429            router.execute(&mut workspace, &call, &authorized).unwrap();
2430        }
2431        assert_eq!(
2432            std::fs::read_to_string(workspace.root().join("src/lib.rs")).unwrap(),
2433            "pub fn resident() {}\n"
2434        );
2435    }
2436
2437    #[test]
2438    fn observable_projection_populates_every_issue_35_graph_resource_kind() {
2439        let mut workspace = workspace();
2440        let samples = vec![
2441            ("glass.editor.save", json!({"path":"src/lib.rs"}), json!({})),
2442            ("glass.lsp.hover", json!({"path":"src/lib.rs"}), json!({})),
2443            (
2444                "glass.lsp.diagnostics",
2445                json!({"path":"src/lib.rs"}),
2446                json!([]),
2447            ),
2448            ("glass.git.diff", json!({}), json!({"changed":true})),
2449            (
2450                "glass.process.ports",
2451                json!({"name":"web"}),
2452                json!({"port":8080}),
2453            ),
2454            (
2455                "glass.debug.stack",
2456                json!({"session":"rust","threadId":3}),
2457                json!({"stackFrames":[{"id":9}]}),
2458            ),
2459            (
2460                "glass.browser.state",
2461                json!({}),
2462                json!({"targetId":"page-1","revision":12}),
2463            ),
2464            ("glass.web_ir.inspect", json!({}), json!({"entities":[]})),
2465            (
2466                "glass.workflow.verify",
2467                json!({"runId":"checkout"}),
2468                json!({"passed":false}),
2469            ),
2470            (
2471                "glass.test.results",
2472                json!({"runId":"unit"}),
2473                json!({"passed":true}),
2474            ),
2475            (
2476                "glass.eval.execute",
2477                json!({"name":"analysis"}),
2478                json!({"value":42}),
2479            ),
2480            ("glass.agent.list", json!({}), json!({"agentId":"agent-1"})),
2481            (
2482                "glass.task.get",
2483                json!({"taskId":"task-1"}),
2484                json!({"state":"failed"}),
2485            ),
2486            (
2487                "glass.experiment.collect",
2488                json!({"id":"approach-a"}),
2489                json!({"measured":true}),
2490            ),
2491        ];
2492        for (index, (name, arguments, result)) in samples.into_iter().enumerate() {
2493            let call = ToolCall {
2494                id: format!("projection-{index}"),
2495                name: name.into(),
2496                arguments,
2497            };
2498            let tool_node = format!("tool:{}", call.id);
2499            workspace
2500                .intelligence_mut()
2501                .upsert_node(DevelopmentNode {
2502                    id: tool_node.clone(),
2503                    kind: DevelopmentNodeKind::ToolCall,
2504                    label: call.name.clone(),
2505                    revision: 1,
2506                    stale: false,
2507                    evidence: Value::Null,
2508                })
2509                .unwrap();
2510            workspace
2511                .intelligence_mut()
2512                .link(
2513                    "repository:root",
2514                    &tool_node,
2515                    "receivedToolCall",
2516                    1,
2517                    "test",
2518                    Value::Null,
2519                )
2520                .unwrap();
2521            project_observable_result(&mut workspace, &call, "test", 1, 1, &result).unwrap();
2522        }
2523        for kind in [
2524            DevelopmentNodeKind::Repository,
2525            DevelopmentNodeKind::File,
2526            DevelopmentNodeKind::Symbol,
2527            DevelopmentNodeKind::EditorRevision,
2528            DevelopmentNodeKind::GitChange,
2529            DevelopmentNodeKind::Process,
2530            DevelopmentNodeKind::Port,
2531            DevelopmentNodeKind::Diagnostic,
2532            DevelopmentNodeKind::Debugger,
2533            DevelopmentNodeKind::Thread,
2534            DevelopmentNodeKind::StackFrame,
2535            DevelopmentNodeKind::BrowserTarget,
2536            DevelopmentNodeKind::BrowserRevision,
2537            DevelopmentNodeKind::WebIrEntity,
2538            DevelopmentNodeKind::Workflow,
2539            DevelopmentNodeKind::Test,
2540            DevelopmentNodeKind::Kernel,
2541            DevelopmentNodeKind::Agent,
2542            DevelopmentNodeKind::Task,
2543            DevelopmentNodeKind::Experiment,
2544            DevelopmentNodeKind::ToolCall,
2545        ] {
2546            assert!(
2547                !workspace.intelligence().query_kind(kind).is_empty(),
2548                "missing {kind:?}"
2549            );
2550        }
2551        let router = DevelopmentToolRouter::default();
2552        for (index, (from, to, relation)) in [
2553            ("file:src/lib.rs", "gitChange:projection-3", "changedBy"),
2554            ("gitChange:projection-3", "test:unit", "verifiedBy"),
2555            ("test:unit", "webIr:projection-7", "observedRegression"),
2556        ]
2557        .into_iter()
2558        .enumerate()
2559        {
2560            let context = context(&workspace, true);
2561            router
2562                .execute(
2563                    &mut workspace,
2564                    &ToolCall {
2565                        id: format!("causal-link-{index}"),
2566                        name: "glass.graph.link".into(),
2567                        arguments: json!({
2568                            "from":from,
2569                            "to":to,
2570                            "relation":relation,
2571                            "evidence":{"source":"resident-verification"}
2572                        }),
2573                    },
2574                    &context,
2575                )
2576                .unwrap();
2577        }
2578        let path = workspace
2579            .intelligence()
2580            .path("file:src/lib.rs", "webIr:projection-7")
2581            .unwrap();
2582        assert_eq!(
2583            path.edges
2584                .iter()
2585                .map(|edge| edge.relation.as_str())
2586                .collect::<Vec<_>>(),
2587            vec!["changedBy", "verifiedBy", "observedRegression"]
2588        );
2589        assert!(path.edges.iter().all(|edge| !edge.provenance.is_empty()));
2590        let replay = workspace.intelligence().replay(0, 128).unwrap();
2591        assert!(replay.iter().any(|event| event.subsystem == "task"));
2592        assert!(replay.iter().all(|event| event.rationale.is_none()));
2593    }
2594}