Skip to main content

glass_dev/
customization.rs

1//! Governed project configuration, skills, hooks, commands, and custom tools.
2
3use crate::WorkspaceTrust;
4use crate::development::{DevelopmentError, DevelopmentResult, ToolDescriptor};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::collections::BTreeMap;
8use std::io::Read;
9use std::path::{Path, PathBuf};
10use std::process::{Command, Stdio};
11use std::sync::Mutex;
12use std::thread;
13use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
14
15const MAX_CONFIG_BYTES: u64 = 512 * 1024;
16const MAX_SKILLS: usize = 32;
17const MAX_SKILL_BYTES: u64 = 64 * 1024;
18const MAX_COMMAND_BYTES: usize = 4096;
19const MAX_OUTPUT_BYTES: u64 = 512 * 1024;
20
21#[derive(Debug, Clone, Default, Deserialize, Serialize)]
22#[serde(default, deny_unknown_fields)]
23pub struct GlassConfig {
24    pub project: ProjectConfig,
25    pub commands: BTreeMap<String, String>,
26    pub browser: BrowserConfig,
27    pub agent: AgentConfig,
28    pub lsp: BTreeMap<String, ServerConfig>,
29    pub dap: BTreeMap<String, DapServerConfig>,
30    pub tests: BTreeMap<String, TestConfig>,
31    pub hooks: BTreeMap<String, Vec<HookConfig>>,
32    pub tools: BTreeMap<String, CustomToolConfig>,
33    pub workspace: WorkspaceConfig,
34    pub editor: EditorConfig,
35}
36
37#[derive(Debug, Clone, Default, Deserialize, Serialize)]
38#[serde(default, deny_unknown_fields)]
39pub struct ProjectConfig {
40    pub name: Option<String>,
41}
42
43#[derive(Debug, Clone, Default, Deserialize, Serialize)]
44#[serde(default, deny_unknown_fields)]
45pub struct BrowserConfig {
46    pub url: Option<String>,
47    pub mode: Option<String>,
48}
49
50#[derive(Debug, Clone, Default, Deserialize, Serialize)]
51#[serde(default, deny_unknown_fields)]
52pub struct AgentConfig {
53    pub model: Option<String>,
54    pub reasoning: Option<String>,
55    /// Retained only to reject non-Pi embedded runtimes explicitly.
56    pub harness: Option<String>,
57}
58
59#[derive(Debug, Clone, Default, Deserialize, Serialize)]
60#[serde(default, deny_unknown_fields)]
61pub struct EditorConfig {
62    pub engine: Option<String>,
63    pub fim: FimConfig,
64}
65
66/// Optional fill-in-the-middle provider for editor ghosts.
67#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
68#[serde(default, deny_unknown_fields)]
69pub struct FimConfig {
70    pub endpoint: Option<String>,
71    pub model: Option<String>,
72    pub api_key_env: Option<String>,
73    pub max_tokens: Option<u32>,
74}
75
76#[derive(Debug, Clone, Default, Deserialize, Serialize)]
77#[serde(default, deny_unknown_fields)]
78pub struct WorkspaceConfig {
79    pub persistent: bool,
80}
81
82#[derive(Debug, Clone, Default, Deserialize, Serialize)]
83#[serde(default, deny_unknown_fields)]
84pub struct ServerConfig {
85    pub command: String,
86    pub args: Vec<String>,
87}
88
89#[derive(Debug, Clone, Deserialize, Serialize)]
90#[serde(default, deny_unknown_fields)]
91pub struct DapServerConfig {
92    pub command: String,
93    pub args: Vec<String>,
94    pub tcp_address: Option<String>,
95    pub connect_timeout_ms: u64,
96}
97
98impl Default for DapServerConfig {
99    fn default() -> Self {
100        Self {
101            command: String::new(),
102            args: Vec::new(),
103            tcp_address: None,
104            connect_timeout_ms: 5_000,
105        }
106    }
107}
108
109#[derive(Debug, Clone, Default, Deserialize, Serialize)]
110#[serde(default, deny_unknown_fields)]
111pub struct TestConfig {
112    pub command: String,
113    pub timeout_seconds: Option<u64>,
114}
115
116#[derive(Debug, Clone, Deserialize, Serialize)]
117#[serde(default, deny_unknown_fields)]
118pub struct HookConfig {
119    pub command: String,
120    pub timeout_seconds: u64,
121    pub fail_on_error: bool,
122}
123
124impl Default for HookConfig {
125    fn default() -> Self {
126        Self {
127            command: String::new(),
128            timeout_seconds: 30,
129            fail_on_error: true,
130        }
131    }
132}
133
134#[derive(Debug, Clone, Deserialize, Serialize)]
135#[serde(default, deny_unknown_fields)]
136pub struct CustomToolConfig {
137    pub description: String,
138    pub command: String,
139    pub mutating: bool,
140    pub timeout_seconds: u64,
141    pub input_schema: Value,
142}
143
144impl Default for CustomToolConfig {
145    fn default() -> Self {
146        Self {
147            description: String::new(),
148            command: String::new(),
149            mutating: false,
150            timeout_seconds: 30,
151            input_schema: serde_json::json!({"type":"object"}),
152        }
153    }
154}
155
156#[derive(Debug, Clone, Serialize)]
157#[serde(rename_all = "camelCase")]
158pub struct Skill {
159    pub name: String,
160    pub source: PathBuf,
161    pub instructions: String,
162    pub project_scoped: bool,
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
166#[serde(rename_all = "camelCase")]
167pub enum CustomizationAuthority {
168    GlassBuiltIn,
169    UserGlobal,
170    TrustedProject,
171    UntrustedProject,
172    ExternalClient,
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
176#[serde(rename_all = "camelCase")]
177pub enum CustomizationRisk {
178    Static,
179    AgentContext,
180    Executable,
181}
182
183#[derive(Debug, Clone, Serialize)]
184#[serde(rename_all = "camelCase")]
185pub struct CustomizationInspectionItem {
186    pub kind: String,
187    pub name: String,
188    pub source: PathBuf,
189    pub authority: CustomizationAuthority,
190    pub risk: CustomizationRisk,
191    pub command: Option<String>,
192    pub declared_mutating: Option<bool>,
193    pub trust_required: bool,
194    pub governance: Option<CustomizationGovernance>,
195}
196
197#[derive(Debug, Clone, Serialize)]
198#[serde(rename_all = "camelCase")]
199pub struct CustomizationGovernance {
200    pub event: Option<String>,
201    pub timeout_seconds: Option<u64>,
202    pub failure_policy: Option<String>,
203    pub input_schema: Option<Value>,
204    pub effective_mutating: bool,
205    pub latest_execution: Option<CustomizationExecutionEvidence>,
206}
207
208#[derive(Debug, Clone, Serialize)]
209#[serde(rename_all = "camelCase")]
210pub struct CustomizationExecutionEvidence {
211    pub actor: String,
212    pub authority: CustomizationAuthority,
213    pub started_at_ms: u64,
214    pub duration_ms: u64,
215    pub success: bool,
216    pub ignored_failure: bool,
217    pub result_bytes: Option<usize>,
218    pub error: Option<String>,
219}
220
221#[derive(Debug)]
222pub struct Customization {
223    root: PathBuf,
224    config_path: Option<PathBuf>,
225    config: GlassConfig,
226    skills: BTreeMap<String, Skill>,
227    latest_executions: Mutex<BTreeMap<String, CustomizationExecutionEvidence>>,
228}
229
230impl Customization {
231    pub fn load(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
232        let root = std::fs::canonicalize(root)?;
233        let config_path = [root.join("glass.toml"), root.join(".glass.toml")]
234            .into_iter()
235            .find(|path| path.is_file());
236        let config = match config_path.as_ref() {
237            Some(path) => {
238                if path.metadata()?.len() > MAX_CONFIG_BYTES {
239                    return Err(DevelopmentError::Config(format!(
240                        "{} exceeds the {MAX_CONFIG_BYTES} byte limit",
241                        path.display()
242                    )));
243                }
244                toml::from_str::<GlassConfig>(&std::fs::read_to_string(path)?)
245                    .map_err(|error| DevelopmentError::Config(error.to_string()))?
246            }
247            None => GlassConfig::default(),
248        };
249        validate_config(&config)?;
250        let mut skills = BTreeMap::new();
251        if let Some(config_dir) = dirs::config_dir() {
252            load_skill_dir(&config_dir.join("glass/skills"), false, &mut skills)?;
253        }
254        load_skill_dir(&root.join(".glass/skills"), true, &mut skills)?;
255        Ok(Self {
256            root,
257            config_path,
258            config,
259            skills,
260            latest_executions: Mutex::new(BTreeMap::new()),
261        })
262    }
263
264    pub fn config(&self) -> &GlassConfig {
265        &self.config
266    }
267
268    pub fn config_path(&self) -> Option<&Path> {
269        self.config_path.as_deref()
270    }
271
272    pub fn skills(&self) -> impl Iterator<Item = &Skill> {
273        self.skills.values()
274    }
275
276    pub fn agent_instructions(&self, trust: WorkspaceTrust) -> Option<String> {
277        let active = self
278            .skills
279            .values()
280            .filter(|skill| !skill.project_scoped || trust.permits_project_execution())
281            .collect::<Vec<_>>();
282        if active.is_empty() {
283            return None;
284        }
285        let mut output =
286            String::from("\n\nGlass customization instructions with explicit authority:\n");
287        for skill in active {
288            let authority = if skill.project_scoped {
289                "trusted-project"
290            } else {
291                "user-global"
292            };
293            output.push_str(&format!(
294                "\n<skill name=\"{}\" authority=\"{}\" source=\"{}\">\n{}\n</skill>\n",
295                skill.name,
296                authority,
297                skill.source.display(),
298                skill.instructions
299            ));
300        }
301        Some(output)
302    }
303
304    pub fn inspect(&self, trust: WorkspaceTrust) -> Vec<CustomizationInspectionItem> {
305        let project_authority = if trust.permits_project_execution() {
306            CustomizationAuthority::TrustedProject
307        } else {
308            CustomizationAuthority::UntrustedProject
309        };
310        let source = self
311            .config_path
312            .clone()
313            .unwrap_or_else(|| self.root.join("glass.toml"));
314        let latest = self
315            .latest_executions
316            .lock()
317            .map(|latest| latest.clone())
318            .unwrap_or_default();
319        let governance =
320            |key: &str,
321             event: Option<String>,
322             timeout_seconds: Option<u64>,
323             failure_policy: Option<String>,
324             input_schema: Option<Value>,
325             effective_mutating: bool| CustomizationGovernance {
326                event,
327                timeout_seconds,
328                failure_policy,
329                input_schema,
330                effective_mutating,
331                latest_execution: latest.get(key).cloned(),
332            };
333        let mut items = vec![
334            CustomizationInspectionItem {
335                kind: "skill".into(),
336                name: "glass-runtime-rules".into(),
337                source: PathBuf::from("<glass-built-in>"),
338                authority: CustomizationAuthority::GlassBuiltIn,
339                risk: CustomizationRisk::AgentContext,
340                command: None,
341                declared_mutating: None,
342                trust_required: false,
343                governance: None,
344            },
345            CustomizationInspectionItem {
346                kind: "authorityBoundary".into(),
347                name: "external-client".into(),
348                source: PathBuf::from("<runtime-connection>"),
349                authority: CustomizationAuthority::ExternalClient,
350                risk: CustomizationRisk::Static,
351                command: None,
352                declared_mutating: None,
353                trust_required: false,
354                governance: None,
355            },
356        ];
357        if let Some(name) = self.config.project.name.as_ref() {
358            items.push(CustomizationInspectionItem {
359                kind: "setting".into(),
360                name: "project.name".into(),
361                source: source.clone(),
362                authority: project_authority,
363                risk: CustomizationRisk::Static,
364                command: Some(name.clone()),
365                declared_mutating: None,
366                trust_required: false,
367                governance: None,
368            });
369        }
370        if let Some(url) = self.config.browser.url.as_ref() {
371            items.push(CustomizationInspectionItem {
372                kind: "setting".into(),
373                name: "browser.url".into(),
374                source: source.clone(),
375                authority: project_authority,
376                risk: CustomizationRisk::Static,
377                command: Some(url.clone()),
378                declared_mutating: None,
379                trust_required: false,
380                governance: None,
381            });
382        }
383        for skill in self.skills.values() {
384            items.push(CustomizationInspectionItem {
385                kind: "skill".into(),
386                name: skill.name.clone(),
387                source: skill.source.clone(),
388                authority: if skill.project_scoped {
389                    project_authority
390                } else {
391                    CustomizationAuthority::UserGlobal
392                },
393                risk: CustomizationRisk::AgentContext,
394                command: None,
395                declared_mutating: None,
396                trust_required: skill.project_scoped,
397                governance: None,
398            });
399        }
400        for (name, command) in &self.config.commands {
401            items.push(executable_item(
402                "command",
403                name,
404                command,
405                &source,
406                project_authority,
407                None,
408                governance(
409                    &format!("command:{name}"),
410                    None,
411                    Some(15 * 60),
412                    Some("fail".into()),
413                    Some(serde_json::json!({"type":"object"})),
414                    true,
415                ),
416            ));
417        }
418        for (name, tool) in &self.config.tools {
419            items.push(executable_item(
420                "customTool",
421                name,
422                &tool.command,
423                &source,
424                project_authority,
425                Some(tool.mutating),
426                governance(
427                    &format!("customTool:{name}"),
428                    None,
429                    Some(tool.timeout_seconds),
430                    Some("fail".into()),
431                    Some(tool.input_schema.clone()),
432                    true,
433                ),
434            ));
435        }
436        for (event, hooks) in &self.config.hooks {
437            for (index, hook) in hooks.iter().enumerate() {
438                items.push(executable_item(
439                    "hook",
440                    &format!("{event}[{index}]"),
441                    &hook.command,
442                    &source,
443                    project_authority,
444                    Some(true),
445                    governance(
446                        &format!("hook:{event}[{index}]"),
447                        Some(event.clone()),
448                        Some(hook.timeout_seconds),
449                        Some(
450                            if hook.fail_on_error {
451                                "fail"
452                            } else {
453                                "continue"
454                            }
455                            .into(),
456                        ),
457                        Some(serde_json::json!({"type":"object"})),
458                        true,
459                    ),
460                ));
461            }
462        }
463        for (name, test) in &self.config.tests {
464            items.push(executable_item(
465                "test",
466                name,
467                &test.command,
468                &source,
469                project_authority,
470                Some(true),
471                governance(
472                    &format!("test:{name}"),
473                    None,
474                    test.timeout_seconds,
475                    Some("fail".into()),
476                    None,
477                    true,
478                ),
479            ));
480        }
481        for (name, server) in &self.config.lsp {
482            let command = format!("{} {}", server.command, server.args.join(" "));
483            items.push(executable_item(
484                "lsp",
485                name,
486                command.trim(),
487                &source,
488                project_authority,
489                Some(true),
490                governance(
491                    &format!("lsp:{name}"),
492                    None,
493                    None,
494                    Some("fail".into()),
495                    None,
496                    true,
497                ),
498            ));
499        }
500        for (name, server) in &self.config.dap {
501            let command = format!("{} {}", server.command, server.args.join(" "));
502            items.push(executable_item(
503                "dap",
504                name,
505                command.trim(),
506                &source,
507                project_authority,
508                Some(true),
509                governance(
510                    &format!("dap:{name}"),
511                    None,
512                    None,
513                    Some("fail".into()),
514                    None,
515                    true,
516                ),
517            ));
518        }
519        items
520    }
521
522    pub fn custom_tool(&self, name: &str) -> Option<&CustomToolConfig> {
523        name.strip_prefix("glass.custom.")
524            .and_then(|name| self.config.tools.get(name))
525    }
526
527    pub fn command(&self, name: &str) -> Option<&str> {
528        self.config.commands.get(name).map(String::as_str)
529    }
530
531    pub fn descriptors(&self, trust: WorkspaceTrust) -> Vec<ToolDescriptor> {
532        let available = trust.permits_project_execution();
533        let unavailable_reason = (!available)
534            .then(|| "repository shell commands require explicit workspace trust".to_string());
535        self.config
536            .tools
537            .iter()
538            .map(|(name, tool)| ToolDescriptor {
539                name: format!("glass.custom.{name}"),
540                description: tool.description.clone(),
541                input_schema: tool.input_schema.clone(),
542                // Shell-backed project tools can mutate regardless of their
543                // declaration, so the effective router policy always requires
544                // mutation authority and confirmation.
545                mutating: true,
546                available,
547                unavailable_reason: unavailable_reason.clone(),
548            })
549            .chain(self.config.commands.keys().map(|name| ToolDescriptor {
550                name: format!("glass.command.{name}"),
551                description: format!("Configured Glass project command {name}"),
552                input_schema: serde_json::json!({"type":"object"}),
553                mutating: true,
554                available,
555                unavailable_reason: unavailable_reason.clone(),
556            }))
557            .collect()
558    }
559
560    pub fn execute_tool(
561        &self,
562        name: &str,
563        arguments: &Value,
564        trust: WorkspaceTrust,
565        actor: &str,
566    ) -> DevelopmentResult<Value> {
567        require_project_trust(trust)?;
568        let tool = self
569            .custom_tool(name)
570            .ok_or_else(|| DevelopmentError::NotFound(format!("custom tool {name}")))?;
571        validate_schema(&tool.input_schema, arguments)?;
572        let started_at_ms = now_ms();
573        let started = Instant::now();
574        let result = run_bounded_command(
575            &self.root,
576            &tool.command,
577            Duration::from_secs(tool.timeout_seconds),
578            "GLASS_TOOL_INPUT",
579            arguments,
580        );
581        self.record_execution(
582            &format!("customTool:{}", name.trim_start_matches("glass.custom.")),
583            actor,
584            started_at_ms,
585            started.elapsed(),
586            &result,
587            false,
588        );
589        result
590    }
591
592    pub fn execute_command(
593        &self,
594        name: &str,
595        trust: WorkspaceTrust,
596        actor: &str,
597    ) -> DevelopmentResult<Value> {
598        require_project_trust(trust)?;
599        let command = self
600            .command(name)
601            .ok_or_else(|| DevelopmentError::NotFound(format!("project command {name}")))?;
602        let started_at_ms = now_ms();
603        let started = Instant::now();
604        let result = run_bounded_command(
605            &self.root,
606            command,
607            Duration::from_secs(15 * 60),
608            "GLASS_COMMAND_INPUT",
609            &Value::Null,
610        );
611        self.record_execution(
612            &format!("command:{name}"),
613            actor,
614            started_at_ms,
615            started.elapsed(),
616            &result,
617            false,
618        );
619        result
620    }
621
622    pub fn run_hooks(
623        &self,
624        event: &str,
625        evidence: &Value,
626        trust: WorkspaceTrust,
627        actor: &str,
628    ) -> DevelopmentResult<Vec<Value>> {
629        require_project_trust(trust)?;
630        validate_hook_event(event)?;
631        let mut results = Vec::new();
632        for (index, hook) in self
633            .config
634            .hooks
635            .get(event)
636            .into_iter()
637            .flatten()
638            .enumerate()
639        {
640            let started_at_ms = now_ms();
641            let started = Instant::now();
642            let result = run_bounded_command(
643                &self.root,
644                &hook.command,
645                Duration::from_secs(hook.timeout_seconds),
646                "GLASS_HOOK_EVENT",
647                &serde_json::json!({"event":event,"evidence":evidence}),
648            );
649            self.record_execution(
650                &format!("hook:{event}[{index}]"),
651                actor,
652                started_at_ms,
653                started.elapsed(),
654                &result,
655                result.is_err() && !hook.fail_on_error,
656            );
657            match result {
658                Ok(result) => results.push(result),
659                Err(error) if !hook.fail_on_error => results.push(serde_json::json!({
660                    "ok":false,"ignored":true,"error":error.to_string()
661                })),
662                Err(error) => return Err(error),
663            }
664        }
665        Ok(results)
666    }
667
668    fn record_execution(
669        &self,
670        key: &str,
671        actor: &str,
672        started_at_ms: u64,
673        duration: Duration,
674        result: &DevelopmentResult<Value>,
675        ignored_failure: bool,
676    ) {
677        let (success, result_bytes, error) = match result {
678            Ok(value) => (
679                true,
680                serde_json::to_vec(value).ok().map(|bytes| bytes.len()),
681                None,
682            ),
683            Err(error) => (false, None, Some(error.to_string())),
684        };
685        if let Ok(mut latest) = self.latest_executions.lock() {
686            latest.insert(
687                key.to_string(),
688                CustomizationExecutionEvidence {
689                    actor: actor.to_string(),
690                    authority: CustomizationAuthority::TrustedProject,
691                    started_at_ms,
692                    duration_ms: duration.as_millis() as u64,
693                    success,
694                    ignored_failure,
695                    result_bytes,
696                    error,
697                },
698            );
699        }
700    }
701}
702
703fn now_ms() -> u64 {
704    SystemTime::now()
705        .duration_since(UNIX_EPOCH)
706        .unwrap_or_default()
707        .as_millis() as u64
708}
709
710fn require_project_trust(trust: WorkspaceTrust) -> DevelopmentResult<()> {
711    if trust.permits_project_execution() {
712        Ok(())
713    } else {
714        Err(DevelopmentError::Conflict(
715            "repository-controlled execution is blocked until the workspace is trusted".into(),
716        ))
717    }
718}
719
720fn executable_item(
721    kind: &str,
722    name: &str,
723    command: &str,
724    source: &Path,
725    authority: CustomizationAuthority,
726    declared_mutating: Option<bool>,
727    governance: CustomizationGovernance,
728) -> CustomizationInspectionItem {
729    CustomizationInspectionItem {
730        kind: kind.into(),
731        name: name.into(),
732        source: source.to_path_buf(),
733        authority,
734        risk: CustomizationRisk::Executable,
735        command: Some(command.into()),
736        declared_mutating,
737        trust_required: true,
738        governance: Some(governance),
739    }
740}
741
742fn validate_config(config: &GlassConfig) -> DevelopmentResult<()> {
743    if config
744        .agent
745        .harness
746        .as_deref()
747        .is_some_and(|harness| harness != "pi")
748    {
749        return Err(DevelopmentError::Config(
750            "Pi is the sole embedded Glass Agent runtime; agent.harness must be 'pi' or omitted"
751                .into(),
752        ));
753    }
754    for (name, command) in &config.commands {
755        validate_name(name)?;
756        validate_command(command)?;
757    }
758    for (name, tool) in &config.tools {
759        validate_name(name)?;
760        validate_command(&tool.command)?;
761        if tool.description.is_empty() || tool.description.len() > 1024 {
762            return Err(DevelopmentError::Config(format!(
763                "custom tool {name} requires a bounded description"
764            )));
765        }
766        validate_timeout(tool.timeout_seconds)?;
767        if serde_json::to_vec(&tool.input_schema)?.len() > 64 * 1024 {
768            return Err(DevelopmentError::Config(format!(
769                "custom tool {name} schema exceeds 64 KiB"
770            )));
771        }
772    }
773    for (event, hooks) in &config.hooks {
774        validate_hook_event(event)?;
775        if hooks.len() > 16 {
776            return Err(DevelopmentError::Config(format!(
777                "hook event {event} exceeds 16 commands"
778            )));
779        }
780        for hook in hooks {
781            validate_command(&hook.command)?;
782            validate_timeout(hook.timeout_seconds)?;
783        }
784    }
785    Ok(())
786}
787
788fn validate_name(name: &str) -> DevelopmentResult<()> {
789    if name.is_empty()
790        || name.len() > 64
791        || !name
792            .chars()
793            .all(|character| character.is_ascii_alphanumeric() || "-_".contains(character))
794    {
795        return Err(DevelopmentError::Config(format!(
796            "invalid customization name {name}"
797        )));
798    }
799    Ok(())
800}
801
802fn validate_command(command: &str) -> DevelopmentResult<()> {
803    if command.trim().is_empty() || command.len() > MAX_COMMAND_BYTES || command.contains('\0') {
804        return Err(DevelopmentError::Config(
805            "customization commands must be 1..=4096 bytes without NUL".into(),
806        ));
807    }
808    Ok(())
809}
810
811fn validate_timeout(seconds: u64) -> DevelopmentResult<()> {
812    if !(1..=3600).contains(&seconds) {
813        return Err(DevelopmentError::Config(
814            "customization timeout must be 1..=3600 seconds".into(),
815        ));
816    }
817    Ok(())
818}
819
820fn validate_hook_event(event: &str) -> DevelopmentResult<()> {
821    const EVENTS: &[&str] = &[
822        "workspace.opened",
823        "workspace.closed",
824        "agent.started",
825        "agent.settled",
826        "agent.failed",
827        "tool.before",
828        "tool.after",
829        "file.saved",
830        "process.started",
831        "process.failed",
832        "test.completed",
833        "debugger.stopped",
834        "browser.revision",
835        "workflow.completed",
836        "git.changed",
837        "experiment.completed",
838    ];
839    EVENTS
840        .contains(&event)
841        .then_some(())
842        .ok_or_else(|| DevelopmentError::Config(format!("unsupported hook event {event}")))
843}
844
845fn load_skill_dir(
846    directory: &Path,
847    project_scoped: bool,
848    skills: &mut BTreeMap<String, Skill>,
849) -> DevelopmentResult<()> {
850    if !directory.is_dir() {
851        return Ok(());
852    }
853    let mut entries = std::fs::read_dir(directory)?.collect::<Result<Vec<_>, _>>()?;
854    entries.sort_by_key(|entry| entry.file_name());
855    for entry in entries {
856        let path = entry.path();
857        if path.extension().and_then(|value| value.to_str()) != Some("md") {
858            continue;
859        }
860        if skills.len() >= MAX_SKILLS || path.metadata()?.len() > MAX_SKILL_BYTES {
861            return Err(DevelopmentError::Config(
862                "skills exceed the 32 file or 64 KiB per-file limit".into(),
863            ));
864        }
865        let name = path
866            .file_stem()
867            .and_then(|value| value.to_str())
868            .ok_or_else(|| DevelopmentError::Config("skill name is not UTF-8".into()))?;
869        validate_name(name)?;
870        let instructions = std::fs::read_to_string(&path)?;
871        if instructions.contains('\0') {
872            return Err(DevelopmentError::Config(format!(
873                "skill {name} contains NUL"
874            )));
875        }
876        skills.insert(
877            format!("{}:{name}", if project_scoped { "project" } else { "user" }),
878            Skill {
879                name: name.into(),
880                source: path,
881                instructions,
882                project_scoped,
883            },
884        );
885    }
886    Ok(())
887}
888
889fn validate_schema(schema: &Value, arguments: &Value) -> DevelopmentResult<()> {
890    if schema.get("type").and_then(Value::as_str) != Some("object") || !arguments.is_object() {
891        return Err(DevelopmentError::InvalidInput(
892            "custom tool schema and arguments must be objects".into(),
893        ));
894    }
895    if let Some(required) = schema.get("required").and_then(Value::as_array) {
896        for field in required {
897            let field = field.as_str().ok_or_else(|| {
898                DevelopmentError::Config("custom tool required fields must be strings".into())
899            })?;
900            if arguments.get(field).is_none() {
901                return Err(DevelopmentError::InvalidInput(format!(
902                    "custom tool requires argument {field}"
903                )));
904            }
905        }
906    }
907    if serde_json::to_vec(arguments)?.len() > 256 * 1024 {
908        return Err(DevelopmentError::InvalidInput(
909            "custom tool arguments exceed 256 KiB".into(),
910        ));
911    }
912    Ok(())
913}
914
915fn run_bounded_command(
916    root: &Path,
917    command: &str,
918    timeout: Duration,
919    input_name: &str,
920    input: &Value,
921) -> DevelopmentResult<Value> {
922    validate_command(command)?;
923    if timeout.is_zero() || timeout > Duration::from_secs(3600) {
924        return Err(DevelopmentError::InvalidInput(
925            "command timeout must be between 1 ms and 1 hour".into(),
926        ));
927    }
928    let mut process = if cfg!(windows) {
929        let mut process = Command::new("cmd.exe");
930        process.args(["/D", "/Q", "/C", command]);
931        process
932    } else {
933        let mut process = Command::new("/bin/sh");
934        process.args(["-c", command]);
935        process
936    };
937    #[cfg(unix)]
938    {
939        use std::os::unix::process::CommandExt;
940        // SAFETY: this async-signal-safe call only creates an owned process group.
941        unsafe {
942            process.pre_exec(|| {
943                if libc::setpgid(0, 0) == -1 {
944                    return Err(std::io::Error::last_os_error());
945                }
946                Ok(())
947            });
948        }
949    }
950    let mut child = process
951        .current_dir(root)
952        .env(input_name, serde_json::to_string(input)?)
953        .stdin(Stdio::null())
954        .stdout(Stdio::piped())
955        .stderr(Stdio::piped())
956        .spawn()?;
957    let stdout = child
958        .stdout
959        .take()
960        .ok_or_else(|| DevelopmentError::Process("custom command stdout unavailable".into()))?;
961    let stderr = child
962        .stderr
963        .take()
964        .ok_or_else(|| DevelopmentError::Process("custom command stderr unavailable".into()))?;
965    let stdout = thread::spawn(move || read_bounded(stdout));
966    let stderr = thread::spawn(move || read_bounded(stderr));
967    let started = Instant::now();
968    let status = loop {
969        if let Some(status) = child.try_wait()? {
970            break status;
971        }
972        if started.elapsed() >= timeout {
973            #[cfg(unix)]
974            // SAFETY: the child was placed in a fresh process group above.
975            unsafe {
976                libc::kill(-(child.id() as i32), libc::SIGKILL);
977            }
978            #[cfg(not(unix))]
979            child.kill()?;
980            let _ = child.wait();
981            return Err(DevelopmentError::Process(format!(
982                "custom command exceeded {} seconds",
983                timeout.as_secs()
984            )));
985        }
986        thread::sleep(Duration::from_millis(10));
987    };
988    let (stdout, stdout_truncated) = stdout
989        .join()
990        .map_err(|_| DevelopmentError::Process("custom stdout reader panicked".into()))??;
991    let (stderr, stderr_truncated) = stderr
992        .join()
993        .map_err(|_| DevelopmentError::Process("custom stderr reader panicked".into()))??;
994    if !status.success() {
995        return Err(DevelopmentError::Process(format!(
996            "custom command exited {:?}: {}",
997            status.code(),
998            stderr.trim()
999        )));
1000    }
1001    if let Ok(value) = serde_json::from_str::<Value>(&stdout) {
1002        return Ok(value);
1003    }
1004    Ok(serde_json::json!({
1005        "exitCode":status.code(),
1006        "stdout":stdout,
1007        "stderr":stderr,
1008        "truncated":stdout_truncated || stderr_truncated
1009    }))
1010}
1011
1012fn read_bounded(mut reader: impl Read) -> DevelopmentResult<(String, bool)> {
1013    let mut bytes = Vec::new();
1014    reader
1015        .by_ref()
1016        .take(MAX_OUTPUT_BYTES + 1)
1017        .read_to_end(&mut bytes)?;
1018    let truncated = bytes.len() as u64 > MAX_OUTPUT_BYTES;
1019    bytes.truncate(MAX_OUTPUT_BYTES as usize);
1020    Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated))
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use super::*;
1026
1027    #[test]
1028    fn customization_loads_skills_and_executes_governed_tools_and_hooks() {
1029        let root = std::env::temp_dir().join(format!("glass-customization-{}", std::process::id()));
1030        let echo_input = if cfg!(windows) {
1031            "echo %GLASS_TOOL_INPUT%"
1032        } else {
1033            "printf '%s' \"$GLASS_TOOL_INPUT\""
1034        };
1035        let echo_text = if cfg!(windows) {
1036            "echo command-ok"
1037        } else {
1038            "printf command-ok"
1039        };
1040        let configured_test = if cfg!(windows) {
1041            "echo configured-test"
1042        } else {
1043            "printf configured-test"
1044        };
1045        let hook = if cfg!(windows) {
1046            "echo hook-ok"
1047        } else {
1048            "printf hook-ok"
1049        };
1050        let _ = std::fs::remove_dir_all(&root);
1051        std::fs::create_dir_all(root.join(".glass/skills")).unwrap();
1052        std::fs::write(root.join(".glass/skills/review.md"), "Always run tests.").unwrap();
1053        std::fs::write(
1054            root.join("Cargo.toml"),
1055            "[package]\nname='customization-fixture'\nversion='0.1.0'\n",
1056        )
1057        .unwrap();
1058        std::fs::write(
1059            root.join("glass.toml"),
1060            format!(
1061                r#"
1062[agent]
1063harness = "pi"
1064model = "provider/model"
1065reasoning = "high"
1066[commands]
1067hello = "{echo_text}"
1068[tests.smoke]
1069command = "{configured_test}"
1070timeout_seconds = 30
1071[tools.echo]
1072description = "Echo structured input"
1073command = '''{echo_input}'''
1074input_schema = {{ type = "object", required = ["text"] }}
1075[hooks]
1076"tool.before" = [{{ command = "{hook}" }}]
1077"#,
1078            ),
1079        )
1080        .unwrap();
1081        let customization = Customization::load(&root).unwrap();
1082        assert!(
1083            customization
1084                .agent_instructions(WorkspaceTrust::TrustedOnce)
1085                .unwrap()
1086                .contains("Always run tests")
1087        );
1088        assert_eq!(
1089            customization
1090                .execute_tool(
1091                    "glass.custom.echo",
1092                    &serde_json::json!({"text":"ok"}),
1093                    WorkspaceTrust::TrustedOnce,
1094                    "external:customization-test",
1095                )
1096                .unwrap()["text"],
1097            "ok"
1098        );
1099        assert_eq!(
1100            customization
1101                .run_hooks(
1102                    "tool.before",
1103                    &Value::Null,
1104                    WorkspaceTrust::TrustedOnce,
1105                    "external:customization-test"
1106                )
1107                .unwrap()
1108                .len(),
1109            1
1110        );
1111        assert!(
1112            customization
1113                .execute_command(
1114                    "hello",
1115                    WorkspaceTrust::TrustedOnce,
1116                    "external:customization-test"
1117                )
1118                .unwrap()["stdout"]
1119                .as_str()
1120                .unwrap()
1121                .contains("command-ok")
1122        );
1123        let mut workspace = crate::DevelopmentWorkspace::open(&root).unwrap();
1124        workspace
1125            .apply_local_trust_decision(crate::LocalTrustDecision::TrustOnce)
1126            .unwrap();
1127        assert!(workspace.tests().suites().any(|suite| {
1128            suite.id == "smoke"
1129                && suite.framework == crate::testing::TestFramework::Custom
1130                && suite
1131                    .arguments
1132                    .iter()
1133                    .any(|argument| argument == configured_test)
1134        }));
1135        assert!(
1136            workspace
1137                .tool_descriptors()
1138                .iter()
1139                .any(|descriptor| descriptor.name == "glass.custom.echo"
1140                    && descriptor.available
1141                    && descriptor.mutating)
1142        );
1143        let context = crate::DevelopmentToolContext {
1144            authorization: crate::development::ToolAuthorization {
1145                actor: crate::development::Actor::external("customization-test"),
1146                allow_mutation: true,
1147                confirmed: true,
1148                unrestricted: false,
1149            },
1150            initiator: None,
1151            expected_generation: workspace.generation(),
1152            expected_project_revision: workspace.project().revision(),
1153        };
1154        let result = workspace
1155            .execute_tool(
1156                &crate::development::ToolCall {
1157                    id: "custom-1".into(),
1158                    name: "glass.custom.echo".into(),
1159                    arguments: serde_json::json!({"text":"resident"}),
1160                },
1161                &context,
1162            )
1163            .unwrap();
1164        assert_eq!(result["text"], "resident");
1165        let inspection = workspace.trust_inspection();
1166        let tool = inspection
1167            .iter()
1168            .find(|item| item.kind == "customTool" && item.name == "echo")
1169            .unwrap();
1170        assert_eq!(tool.declared_mutating, Some(false));
1171        let governance = tool.governance.as_ref().unwrap();
1172        assert!(governance.effective_mutating);
1173        assert_eq!(governance.timeout_seconds, Some(30));
1174        assert_eq!(governance.failure_policy.as_deref(), Some("fail"));
1175        assert!(governance.input_schema.is_some());
1176        let latest = governance.latest_execution.as_ref().unwrap();
1177        assert_eq!(latest.actor, "external:customization-test");
1178        assert!(latest.success);
1179        assert!(inspection.iter().any(|item| {
1180            item.kind == "skill"
1181                && item.authority == CustomizationAuthority::GlassBuiltIn
1182                && item.name == "glass-runtime-rules"
1183        }));
1184        assert!(inspection.iter().any(|item| {
1185            item.kind == "authorityBoundary"
1186                && item.authority == CustomizationAuthority::ExternalClient
1187        }));
1188        let hook = inspection
1189            .iter()
1190            .find(|item| item.kind == "hook" && item.name == "tool.before[0]")
1191            .unwrap();
1192        let hook_governance = hook.governance.as_ref().unwrap();
1193        assert_eq!(hook_governance.event.as_deref(), Some("tool.before"));
1194        assert_eq!(hook_governance.failure_policy.as_deref(), Some("fail"));
1195        assert_eq!(
1196            hook_governance.latest_execution.as_ref().unwrap().actor,
1197            "external:customization-test"
1198        );
1199        drop(workspace);
1200        let _ = std::fs::remove_dir_all(root);
1201    }
1202
1203    #[test]
1204    fn customization_rejects_alternate_embedded_harnesses() {
1205        let mut config = GlassConfig::default();
1206        config.agent.harness = Some("omp".into());
1207        assert!(validate_config(&config).is_err());
1208    }
1209}