Skip to main content

glass_dev/
customization.rs

1//! Governed project configuration, skills, hooks, commands, and custom tools.
2
3use glass_browser::development::{DevelopmentError, DevelopmentResult, ToolDescriptor};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use std::collections::BTreeMap;
7use std::io::Read;
8use std::path::{Path, PathBuf};
9use std::process::{Command, Stdio};
10use std::thread;
11use std::time::{Duration, Instant};
12
13const MAX_CONFIG_BYTES: u64 = 512 * 1024;
14const MAX_SKILLS: usize = 32;
15const MAX_SKILL_BYTES: u64 = 64 * 1024;
16const MAX_COMMAND_BYTES: usize = 4096;
17const MAX_OUTPUT_BYTES: u64 = 512 * 1024;
18
19#[derive(Debug, Clone, Default, Deserialize, Serialize)]
20#[serde(default, deny_unknown_fields)]
21pub struct GlassConfig {
22    pub project: ProjectConfig,
23    pub commands: BTreeMap<String, String>,
24    pub browser: BrowserConfig,
25    pub agent: AgentConfig,
26    pub lsp: BTreeMap<String, ServerConfig>,
27    pub dap: BTreeMap<String, ServerConfig>,
28    pub tests: BTreeMap<String, TestConfig>,
29    pub hooks: BTreeMap<String, Vec<HookConfig>>,
30    pub tools: BTreeMap<String, CustomToolConfig>,
31    pub workspace: WorkspaceConfig,
32    pub editor: EditorConfig,
33}
34
35#[derive(Debug, Clone, Default, Deserialize, Serialize)]
36#[serde(default, deny_unknown_fields)]
37pub struct ProjectConfig {
38    pub name: Option<String>,
39}
40
41#[derive(Debug, Clone, Default, Deserialize, Serialize)]
42#[serde(default, deny_unknown_fields)]
43pub struct BrowserConfig {
44    pub url: Option<String>,
45    pub mode: Option<String>,
46}
47
48#[derive(Debug, Clone, Default, Deserialize, Serialize)]
49#[serde(default, deny_unknown_fields)]
50pub struct AgentConfig {
51    pub model: Option<String>,
52    pub reasoning: Option<String>,
53    /// Retained only to reject non-Pi embedded runtimes explicitly.
54    pub harness: Option<String>,
55}
56
57#[derive(Debug, Clone, Default, Deserialize, Serialize)]
58#[serde(default, deny_unknown_fields)]
59pub struct EditorConfig {
60    pub engine: Option<String>,
61}
62
63#[derive(Debug, Clone, Default, Deserialize, Serialize)]
64#[serde(default, deny_unknown_fields)]
65pub struct WorkspaceConfig {
66    pub persistent: bool,
67}
68
69#[derive(Debug, Clone, Default, Deserialize, Serialize)]
70#[serde(default, deny_unknown_fields)]
71pub struct ServerConfig {
72    pub command: String,
73    pub args: Vec<String>,
74}
75
76#[derive(Debug, Clone, Default, Deserialize, Serialize)]
77#[serde(default, deny_unknown_fields)]
78pub struct TestConfig {
79    pub command: String,
80    pub timeout_seconds: Option<u64>,
81}
82
83#[derive(Debug, Clone, Deserialize, Serialize)]
84#[serde(default, deny_unknown_fields)]
85pub struct HookConfig {
86    pub command: String,
87    pub timeout_seconds: u64,
88    pub fail_on_error: bool,
89}
90
91impl Default for HookConfig {
92    fn default() -> Self {
93        Self {
94            command: String::new(),
95            timeout_seconds: 30,
96            fail_on_error: true,
97        }
98    }
99}
100
101#[derive(Debug, Clone, Deserialize, Serialize)]
102#[serde(default, deny_unknown_fields)]
103pub struct CustomToolConfig {
104    pub description: String,
105    pub command: String,
106    pub mutating: bool,
107    pub timeout_seconds: u64,
108    pub input_schema: Value,
109}
110
111impl Default for CustomToolConfig {
112    fn default() -> Self {
113        Self {
114            description: String::new(),
115            command: String::new(),
116            mutating: false,
117            timeout_seconds: 30,
118            input_schema: serde_json::json!({"type":"object"}),
119        }
120    }
121}
122
123#[derive(Debug, Clone, Serialize)]
124#[serde(rename_all = "camelCase")]
125pub struct Skill {
126    pub name: String,
127    pub source: PathBuf,
128    pub instructions: String,
129    pub project_scoped: bool,
130}
131
132#[derive(Debug, Clone)]
133pub struct Customization {
134    root: PathBuf,
135    config_path: Option<PathBuf>,
136    config: GlassConfig,
137    skills: BTreeMap<String, Skill>,
138}
139
140impl Customization {
141    pub fn load(root: impl AsRef<Path>) -> DevelopmentResult<Self> {
142        let root = std::fs::canonicalize(root)?;
143        let config_path = [root.join("glass.toml"), root.join(".glass.toml")]
144            .into_iter()
145            .find(|path| path.is_file());
146        let config = match config_path.as_ref() {
147            Some(path) => {
148                if path.metadata()?.len() > MAX_CONFIG_BYTES {
149                    return Err(DevelopmentError::Config(format!(
150                        "{} exceeds the {MAX_CONFIG_BYTES} byte limit",
151                        path.display()
152                    )));
153                }
154                toml::from_str::<GlassConfig>(&std::fs::read_to_string(path)?)
155                    .map_err(|error| DevelopmentError::Config(error.to_string()))?
156            }
157            None => GlassConfig::default(),
158        };
159        validate_config(&config)?;
160        let mut skills = BTreeMap::new();
161        if let Some(config_dir) = dirs::config_dir() {
162            load_skill_dir(&config_dir.join("glass/skills"), false, &mut skills)?;
163        }
164        load_skill_dir(&root.join(".glass/skills"), true, &mut skills)?;
165        Ok(Self {
166            root,
167            config_path,
168            config,
169            skills,
170        })
171    }
172
173    pub fn config(&self) -> &GlassConfig {
174        &self.config
175    }
176
177    pub fn config_path(&self) -> Option<&Path> {
178        self.config_path.as_deref()
179    }
180
181    pub fn skills(&self) -> impl Iterator<Item = &Skill> {
182        self.skills.values()
183    }
184
185    pub fn agent_instructions(&self) -> Option<String> {
186        if self.skills.is_empty() {
187            return None;
188        }
189        let mut output = String::from("\n\nProject and user skills supplied by Glass authority:\n");
190        for skill in self.skills.values() {
191            output.push_str(&format!(
192                "\n<skill name=\"{}\">\n{}\n</skill>\n",
193                skill.name, skill.instructions
194            ));
195        }
196        Some(output)
197    }
198
199    pub fn custom_tool(&self, name: &str) -> Option<&CustomToolConfig> {
200        name.strip_prefix("glass.custom.")
201            .and_then(|name| self.config.tools.get(name))
202    }
203
204    pub fn command(&self, name: &str) -> Option<&str> {
205        self.config.commands.get(name).map(String::as_str)
206    }
207
208    pub fn descriptors(&self) -> Vec<ToolDescriptor> {
209        self.config
210            .tools
211            .iter()
212            .map(|(name, tool)| ToolDescriptor {
213                name: format!("glass.custom.{name}"),
214                description: tool.description.clone(),
215                input_schema: tool.input_schema.clone(),
216                mutating: tool.mutating,
217                available: true,
218                unavailable_reason: None,
219            })
220            .chain(self.config.commands.keys().map(|name| ToolDescriptor {
221                name: format!("glass.command.{name}"),
222                description: format!("Configured Glass project command {name}"),
223                input_schema: serde_json::json!({"type":"object"}),
224                mutating: true,
225                available: true,
226                unavailable_reason: None,
227            }))
228            .collect()
229    }
230
231    pub fn execute_tool(&self, name: &str, arguments: &Value) -> DevelopmentResult<Value> {
232        let tool = self
233            .custom_tool(name)
234            .ok_or_else(|| DevelopmentError::NotFound(format!("custom tool {name}")))?;
235        validate_schema(&tool.input_schema, arguments)?;
236        run_bounded_command(
237            &self.root,
238            &tool.command,
239            Duration::from_secs(tool.timeout_seconds),
240            "GLASS_TOOL_INPUT",
241            arguments,
242        )
243    }
244
245    pub fn execute_command(&self, name: &str) -> DevelopmentResult<Value> {
246        let command = self
247            .command(name)
248            .ok_or_else(|| DevelopmentError::NotFound(format!("project command {name}")))?;
249        run_bounded_command(
250            &self.root,
251            command,
252            Duration::from_secs(15 * 60),
253            "GLASS_COMMAND_INPUT",
254            &Value::Null,
255        )
256    }
257
258    pub fn run_hooks(&self, event: &str, evidence: &Value) -> DevelopmentResult<Vec<Value>> {
259        validate_hook_event(event)?;
260        let mut results = Vec::new();
261        for hook in self.config.hooks.get(event).into_iter().flatten() {
262            match run_bounded_command(
263                &self.root,
264                &hook.command,
265                Duration::from_secs(hook.timeout_seconds),
266                "GLASS_HOOK_EVENT",
267                &serde_json::json!({"event":event,"evidence":evidence}),
268            ) {
269                Ok(result) => results.push(result),
270                Err(error) if !hook.fail_on_error => results.push(serde_json::json!({
271                    "ok":false,"ignored":true,"error":error.to_string()
272                })),
273                Err(error) => return Err(error),
274            }
275        }
276        Ok(results)
277    }
278}
279
280fn validate_config(config: &GlassConfig) -> DevelopmentResult<()> {
281    if config
282        .agent
283        .harness
284        .as_deref()
285        .is_some_and(|harness| harness != "pi")
286    {
287        return Err(DevelopmentError::Config(
288            "Pi is the sole embedded Glass Agent runtime; agent.harness must be 'pi' or omitted"
289                .into(),
290        ));
291    }
292    for (name, command) in &config.commands {
293        validate_name(name)?;
294        validate_command(command)?;
295    }
296    for (name, tool) in &config.tools {
297        validate_name(name)?;
298        validate_command(&tool.command)?;
299        if tool.description.is_empty() || tool.description.len() > 1024 {
300            return Err(DevelopmentError::Config(format!(
301                "custom tool {name} requires a bounded description"
302            )));
303        }
304        validate_timeout(tool.timeout_seconds)?;
305        if serde_json::to_vec(&tool.input_schema)?.len() > 64 * 1024 {
306            return Err(DevelopmentError::Config(format!(
307                "custom tool {name} schema exceeds 64 KiB"
308            )));
309        }
310    }
311    for (event, hooks) in &config.hooks {
312        validate_hook_event(event)?;
313        if hooks.len() > 16 {
314            return Err(DevelopmentError::Config(format!(
315                "hook event {event} exceeds 16 commands"
316            )));
317        }
318        for hook in hooks {
319            validate_command(&hook.command)?;
320            validate_timeout(hook.timeout_seconds)?;
321        }
322    }
323    Ok(())
324}
325
326fn validate_name(name: &str) -> DevelopmentResult<()> {
327    if name.is_empty()
328        || name.len() > 64
329        || !name
330            .chars()
331            .all(|character| character.is_ascii_alphanumeric() || "-_".contains(character))
332    {
333        return Err(DevelopmentError::Config(format!(
334            "invalid customization name {name}"
335        )));
336    }
337    Ok(())
338}
339
340fn validate_command(command: &str) -> DevelopmentResult<()> {
341    if command.trim().is_empty() || command.len() > MAX_COMMAND_BYTES || command.contains('\0') {
342        return Err(DevelopmentError::Config(
343            "customization commands must be 1..=4096 bytes without NUL".into(),
344        ));
345    }
346    Ok(())
347}
348
349fn validate_timeout(seconds: u64) -> DevelopmentResult<()> {
350    if !(1..=3600).contains(&seconds) {
351        return Err(DevelopmentError::Config(
352            "customization timeout must be 1..=3600 seconds".into(),
353        ));
354    }
355    Ok(())
356}
357
358fn validate_hook_event(event: &str) -> DevelopmentResult<()> {
359    const EVENTS: &[&str] = &[
360        "workspace.opened",
361        "workspace.closed",
362        "agent.started",
363        "agent.settled",
364        "agent.failed",
365        "tool.before",
366        "tool.after",
367        "file.saved",
368        "process.started",
369        "process.failed",
370        "test.completed",
371        "debugger.stopped",
372        "browser.revision",
373        "workflow.completed",
374        "git.changed",
375        "experiment.completed",
376    ];
377    EVENTS
378        .contains(&event)
379        .then_some(())
380        .ok_or_else(|| DevelopmentError::Config(format!("unsupported hook event {event}")))
381}
382
383fn load_skill_dir(
384    directory: &Path,
385    project_scoped: bool,
386    skills: &mut BTreeMap<String, Skill>,
387) -> DevelopmentResult<()> {
388    if !directory.is_dir() {
389        return Ok(());
390    }
391    let mut entries = std::fs::read_dir(directory)?.collect::<Result<Vec<_>, _>>()?;
392    entries.sort_by_key(|entry| entry.file_name());
393    for entry in entries {
394        let path = entry.path();
395        if path.extension().and_then(|value| value.to_str()) != Some("md") {
396            continue;
397        }
398        if skills.len() >= MAX_SKILLS || path.metadata()?.len() > MAX_SKILL_BYTES {
399            return Err(DevelopmentError::Config(
400                "skills exceed the 32 file or 64 KiB per-file limit".into(),
401            ));
402        }
403        let name = path
404            .file_stem()
405            .and_then(|value| value.to_str())
406            .ok_or_else(|| DevelopmentError::Config("skill name is not UTF-8".into()))?;
407        validate_name(name)?;
408        let instructions = std::fs::read_to_string(&path)?;
409        if instructions.contains('\0') {
410            return Err(DevelopmentError::Config(format!(
411                "skill {name} contains NUL"
412            )));
413        }
414        skills.insert(
415            name.into(),
416            Skill {
417                name: name.into(),
418                source: path,
419                instructions,
420                project_scoped,
421            },
422        );
423    }
424    Ok(())
425}
426
427fn validate_schema(schema: &Value, arguments: &Value) -> DevelopmentResult<()> {
428    if schema.get("type").and_then(Value::as_str) != Some("object") || !arguments.is_object() {
429        return Err(DevelopmentError::InvalidInput(
430            "custom tool schema and arguments must be objects".into(),
431        ));
432    }
433    if let Some(required) = schema.get("required").and_then(Value::as_array) {
434        for field in required {
435            let field = field.as_str().ok_or_else(|| {
436                DevelopmentError::Config("custom tool required fields must be strings".into())
437            })?;
438            if arguments.get(field).is_none() {
439                return Err(DevelopmentError::InvalidInput(format!(
440                    "custom tool requires argument {field}"
441                )));
442            }
443        }
444    }
445    if serde_json::to_vec(arguments)?.len() > 256 * 1024 {
446        return Err(DevelopmentError::InvalidInput(
447            "custom tool arguments exceed 256 KiB".into(),
448        ));
449    }
450    Ok(())
451}
452
453fn run_bounded_command(
454    root: &Path,
455    command: &str,
456    timeout: Duration,
457    input_name: &str,
458    input: &Value,
459) -> DevelopmentResult<Value> {
460    validate_command(command)?;
461    if timeout.is_zero() || timeout > Duration::from_secs(3600) {
462        return Err(DevelopmentError::InvalidInput(
463            "command timeout must be between 1 ms and 1 hour".into(),
464        ));
465    }
466    let mut process = if cfg!(windows) {
467        let mut process = Command::new("cmd.exe");
468        process.args(["/D", "/Q", "/C", command]);
469        process
470    } else {
471        let mut process = Command::new("/bin/sh");
472        process.args(["-c", command]);
473        process
474    };
475    #[cfg(unix)]
476    {
477        use std::os::unix::process::CommandExt;
478        // SAFETY: this async-signal-safe call only creates an owned process group.
479        unsafe {
480            process.pre_exec(|| {
481                if libc::setpgid(0, 0) == -1 {
482                    return Err(std::io::Error::last_os_error());
483                }
484                Ok(())
485            });
486        }
487    }
488    let mut child = process
489        .current_dir(root)
490        .env(input_name, serde_json::to_string(input)?)
491        .stdin(Stdio::null())
492        .stdout(Stdio::piped())
493        .stderr(Stdio::piped())
494        .spawn()?;
495    let stdout = child
496        .stdout
497        .take()
498        .ok_or_else(|| DevelopmentError::Process("custom command stdout unavailable".into()))?;
499    let stderr = child
500        .stderr
501        .take()
502        .ok_or_else(|| DevelopmentError::Process("custom command stderr unavailable".into()))?;
503    let stdout = thread::spawn(move || read_bounded(stdout));
504    let stderr = thread::spawn(move || read_bounded(stderr));
505    let started = Instant::now();
506    let status = loop {
507        if let Some(status) = child.try_wait()? {
508            break status;
509        }
510        if started.elapsed() >= timeout {
511            #[cfg(unix)]
512            // SAFETY: the child was placed in a fresh process group above.
513            unsafe {
514                libc::kill(-(child.id() as i32), libc::SIGKILL);
515            }
516            #[cfg(not(unix))]
517            child.kill()?;
518            let _ = child.wait();
519            return Err(DevelopmentError::Process(format!(
520                "custom command exceeded {} seconds",
521                timeout.as_secs()
522            )));
523        }
524        thread::sleep(Duration::from_millis(10));
525    };
526    let (stdout, stdout_truncated) = stdout
527        .join()
528        .map_err(|_| DevelopmentError::Process("custom stdout reader panicked".into()))??;
529    let (stderr, stderr_truncated) = stderr
530        .join()
531        .map_err(|_| DevelopmentError::Process("custom stderr reader panicked".into()))??;
532    if !status.success() {
533        return Err(DevelopmentError::Process(format!(
534            "custom command exited {:?}: {}",
535            status.code(),
536            stderr.trim()
537        )));
538    }
539    if let Ok(value) = serde_json::from_str::<Value>(&stdout) {
540        return Ok(value);
541    }
542    Ok(serde_json::json!({
543        "exitCode":status.code(),
544        "stdout":stdout,
545        "stderr":stderr,
546        "truncated":stdout_truncated || stderr_truncated
547    }))
548}
549
550fn read_bounded(mut reader: impl Read) -> DevelopmentResult<(String, bool)> {
551    let mut bytes = Vec::new();
552    reader
553        .by_ref()
554        .take(MAX_OUTPUT_BYTES + 1)
555        .read_to_end(&mut bytes)?;
556    let truncated = bytes.len() as u64 > MAX_OUTPUT_BYTES;
557    bytes.truncate(MAX_OUTPUT_BYTES as usize);
558    Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated))
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564
565    #[test]
566    fn customization_loads_skills_and_executes_governed_tools_and_hooks() {
567        let root = std::env::temp_dir().join(format!("glass-customization-{}", std::process::id()));
568        let echo_input = if cfg!(windows) {
569            "echo %GLASS_TOOL_INPUT%"
570        } else {
571            "printf '%s' \"$GLASS_TOOL_INPUT\""
572        };
573        let echo_text = if cfg!(windows) {
574            "echo command-ok"
575        } else {
576            "printf command-ok"
577        };
578        let configured_test = if cfg!(windows) {
579            "echo configured-test"
580        } else {
581            "printf configured-test"
582        };
583        let hook = if cfg!(windows) {
584            "echo hook-ok"
585        } else {
586            "printf hook-ok"
587        };
588        let _ = std::fs::remove_dir_all(&root);
589        std::fs::create_dir_all(root.join(".glass/skills")).unwrap();
590        std::fs::write(root.join(".glass/skills/review.md"), "Always run tests.").unwrap();
591        std::fs::write(
592            root.join("Cargo.toml"),
593            "[package]\nname='customization-fixture'\nversion='0.1.0'\n",
594        )
595        .unwrap();
596        std::fs::write(
597            root.join("glass.toml"),
598            format!(
599                r#"
600[agent]
601harness = "pi"
602model = "provider/model"
603reasoning = "high"
604[commands]
605hello = "{echo_text}"
606[tests.smoke]
607command = "{configured_test}"
608timeout_seconds = 30
609[tools.echo]
610description = "Echo structured input"
611command = '''{echo_input}'''
612input_schema = {{ type = "object", required = ["text"] }}
613[hooks]
614"tool.before" = [{{ command = "{hook}" }}]
615"#,
616            ),
617        )
618        .unwrap();
619        let customization = Customization::load(&root).unwrap();
620        assert!(
621            customization
622                .agent_instructions()
623                .unwrap()
624                .contains("Always run tests")
625        );
626        assert_eq!(
627            customization
628                .execute_tool("glass.custom.echo", &serde_json::json!({"text":"ok"}))
629                .unwrap()["text"],
630            "ok"
631        );
632        assert_eq!(
633            customization
634                .run_hooks("tool.before", &Value::Null)
635                .unwrap()
636                .len(),
637            1
638        );
639        assert!(
640            customization.execute_command("hello").unwrap()["stdout"]
641                .as_str()
642                .unwrap()
643                .contains("command-ok")
644        );
645        let mut workspace = crate::DevelopmentWorkspace::open(&root).unwrap();
646        assert!(workspace.tests().suites().any(|suite| {
647            suite.id == "smoke"
648                && suite.framework == crate::testing::TestFramework::Custom
649                && suite
650                    .arguments
651                    .iter()
652                    .any(|argument| argument == configured_test)
653        }));
654        assert!(
655            workspace
656                .tool_descriptors()
657                .iter()
658                .any(|descriptor| descriptor.name == "glass.custom.echo" && descriptor.available)
659        );
660        let context = crate::DevelopmentToolContext {
661            authorization: glass_browser::development::ToolAuthorization {
662                actor: glass_browser::development::Actor::external("customization-test"),
663                allow_mutation: false,
664                confirmed: false,
665            },
666            expected_generation: workspace.generation(),
667            expected_project_revision: workspace.project().revision(),
668        };
669        let result = workspace
670            .execute_tool(
671                &glass_browser::development::ToolCall {
672                    id: "custom-1".into(),
673                    name: "glass.custom.echo".into(),
674                    arguments: serde_json::json!({"text":"resident"}),
675                },
676                &context,
677            )
678            .unwrap();
679        assert_eq!(result["text"], "resident");
680        drop(workspace);
681        let _ = std::fs::remove_dir_all(root);
682    }
683
684    #[test]
685    fn customization_rejects_alternate_embedded_harnesses() {
686        let mut config = GlassConfig::default();
687        config.agent.harness = Some("omp".into());
688        assert!(validate_config(&config).is_err());
689    }
690}