1use crate::types::{parse_tool_args, McpSystemError};
9use serde_json::{json, Value};
10
11pub fn json_to_vibe(v: &serde_json::Value) -> vibe::Value {
13 match v {
14 serde_json::Value::Null => vibe::Value::Null,
15 serde_json::Value::Bool(b) => vibe::Value::Bool(*b),
16 serde_json::Value::Number(n) => {
17 if let Some(i) = n.as_i64() {
18 vibe::Value::I64(i)
19 } else if let Some(u) = n.as_u64() {
20 vibe::Value::U64(u)
21 } else if let Some(f) = n.as_f64() {
22 vibe::Value::F64(f)
23 } else {
24 vibe::Value::F64(0.0)
25 }
26 }
27 serde_json::Value::String(s) => vibe::Value::String(s.clone()),
28 serde_json::Value::Array(arr) => {
29 vibe::Value::List(arr.iter().map(json_to_vibe).collect())
30 }
31 serde_json::Value::Object(map) => {
32 let mut record = std::collections::BTreeMap::new();
33 for (k, val) in map {
34 record.insert(k.clone(), json_to_vibe(val));
35 }
36 vibe::Value::Record(record)
37 }
38 }
39}
40
41pub fn vibe_to_json(v: &vibe::Value) -> serde_json::Value {
43 match v {
44 vibe::Value::Null => serde_json::Value::Null,
45 vibe::Value::Bool(b) => serde_json::json!(b),
46 vibe::Value::I64(i) => serde_json::json!(i),
47 vibe::Value::U64(u) => serde_json::json!(u),
48 vibe::Value::F64(f) => serde_json::json!(f),
49 vibe::Value::String(s)
50 | vibe::Value::Iri(s)
51 | vibe::Value::Blank(s)
52 | vibe::Value::Var(s) => serde_json::json!(s),
53 vibe::Value::Prefixed(p, s) => serde_json::json!(format!("{p}:{s}")),
54 vibe::Value::List(list) => {
55 serde_json::Value::Array(list.iter().map(vibe_to_json).collect())
56 }
57 vibe::Value::Record(map) => {
58 let mut obj = serde_json::Map::with_capacity(map.len());
59 for (k, val) in map {
60 obj.insert(k.clone(), vibe_to_json(val));
61 }
62 serde_json::Value::Object(obj)
63 }
64 vibe::Value::Receipt => serde_json::json!({ "receipt": true }),
65 vibe::Value::Ok(inner) => serde_json::json!({ "ok": vibe_to_json(inner) }),
66 vibe::Value::Err(inner) => serde_json::json!({ "err": vibe_to_json(inner) }),
67 vibe::Value::Triple(s, p, o) => serde_json::json!({
68 "s": vibe_to_json(s),
69 "p": vibe_to_json(p),
70 "o": vibe_to_json(o),
71 }),
72 vibe::Value::Reified { s, p, o, r } => serde_json::json!({
73 "s": vibe_to_json(s),
74 "p": vibe_to_json(p),
75 "o": vibe_to_json(o),
76 "r": vibe_to_json(r),
77 }),
78 vibe::Value::Instant(i) => serde_json::json!({
79 "secs": i.secs,
80 "nanos": i.nanos,
81 }),
82 vibe::Value::Duration(d) => serde_json::json!({
83 "secs": d.secs,
84 "nanos": d.nanos,
85 }),
86 vibe::Value::Quantity(q) => serde_json::json!({
87 "value": q.value,
88 "unit": q.unit,
89 }),
90 vibe::Value::QuinRef(q) => serde_json::json!({
91 "quin_ref": q.content_hash(),
92 }),
93 vibe::Value::Enum(e) => serde_json::json!({
94 "enum": e.enum_name,
95 "variant": e.variant_name,
96 "payload": e.payload.iter().map(vibe_to_json).collect::<Vec<_>>(),
97 }),
98 other => serde_json::json!(format!("{other:?}")),
99 }
100}
101
102pub fn vibe_check(args: &[u8]) -> Result<String, McpSystemError> {
105 let v = parse_tool_args(args)?;
106 let source = v
107 .get("source")
108 .and_then(Value::as_str)
109 .ok_or(McpSystemError::InvalidParameters)?;
110
111 let report = vibe::diagnose(source);
112 Ok(report.to_json())
113}
114
115pub fn vibe_compile(args: &[u8]) -> Result<String, McpSystemError> {
118 let v = parse_tool_args(args)?;
119 let source = v
120 .get("source")
121 .and_then(Value::as_str)
122 .ok_or(McpSystemError::InvalidParameters)?;
123
124 let program = vibe::parse_program(source).map_err(|e| {
125 log::error!("Vibe parse failed: {:?}", e);
126 McpSystemError::InvalidParameters
127 })?;
128
129 vibe::check_program(&program).map_err(|e| {
130 log::error!("Vibe typecheck failed: {:?}", e);
131 McpSystemError::InvalidParameters
132 })?;
133
134 let chunk = vibe::bytecode::compile(&program).map_err(|e| {
135 log::error!("Vibe bytecode compilation failed: {:?}", e);
136 McpSystemError::InvalidParameters
137 })?;
138
139 let encoded = vibe::bytecode::encode_chunk(&chunk);
140 let hex_bytes: String = encoded.iter().map(|b| format!("{b:02x}")).collect();
141
142 let mut instructions = Vec::new();
143 for (idx, op) in chunk.code.iter().enumerate() {
144 instructions.push(format!("{idx:04}: {:?}", op));
145 }
146
147 Ok(json!({
148 "status": "success",
149 "instruction_count": chunk.code.len(),
150 "constants_count": chunk.constants.len(),
151 "functions_count": chunk.functions.len(),
152 "bytecode_hex": hex_bytes,
153 "disassembly": instructions,
154 })
155 .to_string())
156}
157
158pub fn vibe_format(args: &[u8]) -> Result<String, McpSystemError> {
160 let v = parse_tool_args(args)?;
161 let source = v
162 .get("source")
163 .and_then(Value::as_str)
164 .ok_or(McpSystemError::InvalidParameters)?;
165
166 let program = vibe::parse_program(source).map_err(|_| McpSystemError::InvalidParameters)?;
167 let formatted = vibe::project_program(&program, &vibe::ProjectOptions::default());
168
169 Ok(json!({
170 "status": "success",
171 "formatted": formatted
172 })
173 .to_string())
174}
175
176pub fn vibe_invoke(raw_args: &[u8]) -> Result<String, McpSystemError> {
178 let v = parse_tool_args(raw_args)?;
179 let id = v
180 .get("id")
181 .and_then(Value::as_str)
182 .ok_or(McpSystemError::InvalidParameters)?;
183
184 let empty_obj = json!({});
185 let args_val = v.get("args").unwrap_or(&empty_obj);
186 if id.starts_with("hypermedia.") || id == "qualia.species.assemble_corpus" {
187 return Ok(json!({
188 "status": "error", "id": id,
189 "host": "qualia.poet.snapshot",
190 "error": {"code": "wrong_execution_host", "message": "Asset production operations execute in Synth ProductionSession. Use synth_operations to discover them and synth_produce_present with capability.invoke inside source. They are not bound in the generic Poet snapshot."},
191 "production_tool": "synth_produce_present",
192 "handle_lifetime": "one production source evaluation; export encoded resources before the session ends"
193 }).to_string());
194 }
195 let vibe_args = json_to_vibe(args_val);
196
197 let mut snap = qualia_core_db::poet_host::PoetSnapshot::live();
198 let seam = qualia_core_db::poet_host::invoke::ids::seam_for(id);
199
200 match snap.invoke_id(id, vibe_args) {
201 Ok(val) => Ok(json!({
202 "status": "ok",
203 "host": "qualia.poet.snapshot",
204 "id": id,
205 "seam": seam,
206 "result": vibe_to_json(&val),
207 })
208 .to_string()),
209 Err(diag) => Ok(json!({
210 "status": "error",
211 "id": id,
212 "seam": seam,
213 "error": format!("{diag}"),
214 })
215 .to_string()),
216 }
217}
218
219pub fn vibe_eval(raw_args: &[u8]) -> Result<String, McpSystemError> {
221 let v = parse_tool_args(raw_args)?;
222 let source = v
223 .get("source")
224 .and_then(Value::as_str)
225 .ok_or(McpSystemError::InvalidParameters)?;
226
227 let program = vibe::parse_program(source).map_err(|e| {
228 log::error!("Vibe parse failed: {:?}", e);
229 McpSystemError::InvalidParameters
230 })?;
231
232 vibe::check_program(&program).map_err(|e| {
233 log::error!("Vibe typecheck failed: {:?}", e);
234 McpSystemError::InvalidParameters
235 })?;
236
237 let mut snap = qualia_core_db::poet_host::PoetSnapshot::live();
238 let mut env = vibe::Env::default();
239 let mut engine = vibe::Engine::with_program(&mut snap, vibe::Budget::default(), &program);
240 let val = engine.eval_program(&program, &mut env).map_err(|e| {
241 log::error!("Vibe eval failed: {:?}", e);
242 McpSystemError::ExecutionFailed(format!("{e}"))
243 })?;
244
245 let quin_count = snap.visible_count();
246 let mut bindings = serde_json::Map::new();
247 for (k, var_val) in &env.vars {
248 bindings.insert(k.clone(), vibe_to_json(var_val));
249 }
250
251 Ok(json!({
252 "status": "ok",
253 "result": vibe_to_json(&val),
254 "bindings": serde_json::Value::Object(bindings),
255 "quin_count": quin_count,
256 })
257 .to_string())
258}
259
260pub fn vibe_catalog(raw_args: &[u8]) -> Result<String, McpSystemError> {
262 let v = parse_tool_args(raw_args)?;
263 let prefix = v.get("prefix").and_then(Value::as_str);
264 let seam = v.get("seam").and_then(Value::as_str);
265 let limit = v.get("limit").and_then(Value::as_u64).unwrap_or(200) as usize;
266
267 let all_bound = qualia_core_db::poet_host::invoke::ids::ALL_BOUND;
268 let total_bound = all_bound.len();
269
270 let mut matches = Vec::new();
271 for &id in all_bound {
272 let id_seam = qualia_core_db::poet_host::invoke::ids::seam_for(id);
273 if let Some(p) = prefix {
274 if !id.starts_with(p) && !id.contains(p) {
275 continue;
276 }
277 }
278 if let Some(s) = seam {
279 if !id_seam.eq_ignore_ascii_case(s) {
280 continue;
281 }
282 }
283 matches.push(json!({
284 "id": id,
285 "seam": id_seam,
286 }));
287 if matches.len() >= limit {
288 break;
289 }
290 }
291
292 Ok(json!({
293 "status": "ok",
294 "total_bound": total_bound,
295 "host": "qualia.poet.snapshot",
296 "handle_lifetime": "one call",
297 "asset_production": {"host": "synth.production", "catalog_tool": "synth_operations", "execute_tool": "synth_produce_present", "note": "Hypermedia production IDs use a separate AssetHost, not this bound Poet catalog."},
298 "matches": matches,
299 })
300 .to_string())
301}