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