1pub mod artifacts;
24pub mod canon;
25pub mod catalogue;
26pub mod code;
27pub mod commands;
28pub use crate::declarations;
29pub mod diag;
30pub mod event_journal;
31pub mod event_archive;
32pub mod webhooks;
33pub mod journal;
34pub(crate) mod inputs;
35pub mod keys;
36pub mod ops;
37pub mod output_schema;
38pub mod surface;
39pub mod tools;
40pub mod wire;
41
42use std::sync::Arc;
43
44mod files;
48
49pub struct CadService {
50 pub files: files::Files,
51 pub event_archive: std::sync::OnceLock<event_archive::Archive>,
52 pub webhooks: webhooks::Webhooks,
54 pub ops: ops::Operations,
55 pub artifacts: artifacts::Artifacts,
56 pub code: code::Executions,
57 pub catalogue: catalogue::Catalogue,
58 pub services: Vec<crate::script_sdk::ServiceEntry>,
61 pub server: std::sync::OnceLock<std::sync::Weak<crate::server::ServerState>>,
64 pub retry_keys: std::sync::Mutex<std::collections::HashMap<String, String>>,
68}
69
70pub use crate::script_sdk::{script_callable, ScriptTool};
71
72impl CadService {
73 pub fn new(slot: crate::tools::app::SessionSlot) -> Arc<Self> {
74 let catalogue = catalogue::Catalogue::new();
75 Arc::new_cyclic(|weak| CadService {
76 files: files::Files::new(),
77 event_archive: Default::default(),
78 webhooks: Default::default(),
79 ops: ops::Operations::new(slot, weak.clone()),
80 artifacts: artifacts::Artifacts::new(),
81 code: code::Executions::new(weak.clone()),
82 services: surface::service_entries(&catalogue),
83 catalogue,
84 server: std::sync::OnceLock::new(),
85 retry_keys: Default::default(),
86 })
87 }
88
89 pub fn event(&self, kind: &'static str, id: Option<&str>, state: Option<&str>, code: Option<&str>, sequence: Option<u64>) {
90 let value = diag::event(kind, id, state, code, sequence);
91 self.webhooks.publish(&value);
92 if let Some(archive) = self.event_archive.get() { archive.publish(value); }
93 }
94
95 pub fn archive_resource(&self, uri: &str) -> Result<serde_json::Value, String> {
96 match self.event_archive.get() {
97 Some(archive) => archive.resource(uri),
98 None if uri == "brep://events/archive" => Ok(serde_json::json!({"enabled":false,"records":[],"persistence":{"status":"disabled"}})),
99 None => Err("diagnostic archive is disabled".into()),
100 }
101 }
102
103 pub(crate) fn server_state(&self) -> Option<Arc<crate::server::ServerState>> {
104 self.server.get().and_then(std::sync::Weak::upgrade)
105 }
106
107 pub fn script_tools(&self) -> Vec<ScriptTool> {
110 let Some(state) = self.server_state() else { return vec![] };
111 let set = state.tools.blocking_read();
112 crate::script_sdk::script_tools(&set.specs)
113 }
114
115 pub async fn script_tool(&self, name: &str) -> Option<crate::tools::ToolSpec> {
117 let state = self.server_state()?;
118 let set = state.tools.read().await;
121 set.specs.iter().find(|t| t.name == name && script_callable(t.group, &t.name)).cloned()
122 }
123
124 pub async fn describe(&self, paths: &[String]) -> Result<serde_json::Value, wire::ApiError> {
128 use serde_json::json;
129 if paths.is_empty() || paths.len() > 8 { return Err(wire::ApiError::new("invalid_arguments", "validation", "describe takes 1..8 paths")); }
130 let state = self.server_state();
131 let empty = crate::tools::ToolSet::default();
132 let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
133 let surface = self.surface(guard.as_deref().unwrap_or(&empty), None);
134 let mut methods = Vec::new();
135 for path in paths {
136 let registry = |old: &str| {
137 let (group, tool) = old.split_once('.')?;
138 surface.entries.iter().find(|e| matches!(e.target, crate::script_sdk::Target::Tool(t) if crate::script_sdk::ident(t.group) == group && (t.name == tool || t.name == format!("files_{tool}"))))
139 };
140 let entry = surface.get(path).or_else(|| path.strip_prefix("brep.").and_then(registry))
141 .ok_or_else(|| wire::ApiError::new("method_unknown", "lookup", surface.unknown(path)))?;
142 methods.push(entry.to_json());
143 }
144 let result = json!({"manifest":self.catalogue.identity(),"version":surface.version(),"methods":methods});
145 if result.to_string().len() > 64 << 10 { return Err(wire::ApiError::new("resource_limit", "validation", "describe fewer paths")); }
146 Ok(result)
147 }
148
149 pub fn run_local(&self, source: &str) -> Result<String, String> {
154 let caller = tools::caller_of_transport();
155 let (key, _) = keys::issue(&caller.scope, keys::Purpose::Execution);
156 let req = serde_json::json!({
157 "manifest": self.catalogue.identity(),
158 "source": source,
159 "initialDocuments": [],
160 "requestedCapabilities": [],
161 "idempotencyKey": key,
162 });
163 let status = self.code.submit_as(&caller, &req, true).map_err(|e| e.message)?;
164 Ok(status["executionId"].as_str().unwrap_or_default().to_string())
165 }
166
167 pub fn result_local(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
170 let caller = tools::caller_of_transport();
171 match self.code.result(&caller, &serde_json::json!({ "executionId": id })) {
172 Ok(mut result) => {
173 let log = result["logArtifact"]["artifactId"].as_str().map(str::to_string);
174 if let Some(log) = log {
175 if let Ok((bytes, _)) = self.artifacts.lease(&caller.owner(), &log) {
176 self.artifacts.release(&log);
177 result["logText"] = String::from_utf8_lossy(&bytes).into_owned().into();
178 }
179 }
180 Ok(Some(result))
181 }
182 Err(e) if e.code == "not_ready" => Ok(None),
183 Err(e) => Err(e.message),
184 }
185 }
186
187 pub fn halt_local(&self, id: &str) -> Result<(), String> {
189 let caller = tools::caller_of_transport();
190 self.code.cancel(&caller, &serde_json::json!({ "executionId": id })).map(|_| ()).map_err(|e| e.message)
191 }
192}
193
194#[derive(Clone)]
198pub struct LocalScripts {
199 cad: std::sync::Weak<CadService>,
200 runtime: tokio::runtime::Handle,
201}
202
203impl std::fmt::Debug for LocalScripts {
204 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205 f.write_str("LocalScripts")
206 }
207}
208
209impl LocalScripts {
210 pub fn new(cad: &Arc<CadService>, runtime: tokio::runtime::Handle) -> Self {
211 LocalScripts { cad: Arc::downgrade(cad), runtime }
212 }
213
214 fn cad(&self) -> Result<Arc<CadService>, String> {
215 self.cad.upgrade().ok_or_else(|| "the script runner has stopped".to_string())
216 }
217
218 pub fn ready(&self) -> Result<bool, String> {
221 let state = self.cad()?.server_state().ok_or("the server is stopping")?;
222 Ok(state.tools.try_read().is_ok_and(|set| set.specs.iter().any(|t| t.name == "docs_list")))
223 }
224
225 pub fn run(&self, source: &str) -> Result<String, String> {
226 let _enter = self.runtime.enter();
227 self.cad()?.run_local(source)
228 }
229
230 pub fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
231 self.cad()?.result_local(id)
232 }
233
234 pub fn halt(&self, id: &str) -> Result<(), String> {
235 let _enter = self.runtime.enter();
236 self.cad()?.halt_local(id)
237 }
238}