← Commit history

Upload chipsmith source (MIT) — Ray can commit on top

John Lauer ·b159f9a693 · ·parent c84b007
6 files changed +363
src/cli/eval.rsadded+67
@@ -0,0 +1,67 @@+use crate::cli::{err, hint, DEFAULT_PORT};+use anyhow::Result;+use clap::Parser;+use std::time::{Duration, Instant};++#[derive(Parser)]+pub struct Args {+    /// JS snippet to run inside the adom-chipsmith webview. Wrap `await` freely;+    /// the UI invokes via AsyncFunction so top-level await works.+    pub code: String,++    /// How long to wait for the UI to return a result.+    #[arg(long, default_value_t = 5)]+    pub timeout_secs: u64,++    #[arg(long)]+    pub quiet: bool,++    #[arg(long, default_value_t = DEFAULT_PORT)]+    pub port: u16,+}++pub fn run(args: Args) -> Result<()> {+    eval_snippet(&args.code, args.timeout_secs, args.port, args.quiet).map(|v| {+        println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());+    })+}++/// Reusable helper for other CLI subcommands that need to drive the UI via JS.+pub fn eval_snippet(code: &str, timeout_secs: u64, port: u16, quiet: bool) -> Result<serde_json::Value> {+    let base = format!("http://127.0.0.1:{}", port);+    let queue: serde_json::Value = match ureq::post(&format!("{base}/eval"))+        .timeout(Duration::from_secs(2))+        .send_json(serde_json::json!({"code": code}))+    {+        Ok(r) => r.into_json()?,+        Err(e) => {+            err(format!("could not reach adom-chipsmith: {e}"));+            hint("start it first with `adom-chipsmith view <file.step>`");+            return Err(anyhow::anyhow!("unreachable"));+        }+    };+    let id = queue+        .get("id")+        .and_then(|v| v.as_str())+        .ok_or_else(|| anyhow::anyhow!("server returned no id: {queue}"))?+        .to_string();+    if !quiet {+        eprintln!("queued {id}");+    }+    let deadline = Instant::now() + Duration::from_secs(timeout_secs);+    loop {+        if Instant::now() >= deadline {+            err(format!("timeout waiting for result of {id}"));+            hint("is the webview open and loaded?");+            return Err(anyhow::anyhow!("timeout"));+        }+        let r: serde_json::Value = ureq::get(&format!("{base}/eval/{id}"))+            .timeout(Duration::from_secs(2))+            .call()?+            .into_json()?;+        if r.get("done").and_then(|v| v.as_bool()).unwrap_or(false) {+            return Ok(r.get("result").cloned().unwrap_or(serde_json::Value::Null));+        }+        std::thread::sleep(Duration::from_millis(150));+    }+}
src/cli/health.rsadded+45
@@ -0,0 +1,45 @@+use crate::cli::{err, hint, ok, DEFAULT_PORT};+use anyhow::Result;+use clap::Parser;+use std::time::Duration;++#[derive(Parser)]+pub struct Args {+    #[arg(long, default_value_t = DEFAULT_PORT)]+    pub port: u16,+    /// Print result as a single JSON line (machine-parseable).+    /// Per gallia/skills/adom-cli-design — every status command supports+    /// `--json` so AI agents can consume it without scraping OK:/ERROR: lines.+    #[arg(long)]+    pub json: bool,+}++pub fn run(args: Args) -> Result<()> {+    let url = format!("http://127.0.0.1:{}/health", args.port);+    match ureq::get(&url).timeout(Duration::from_secs(2)).call() {+        Ok(resp) => {+            let body: serde_json::Value = resp.into_json()?;+            if args.json {+                println!(+                    "{}",+                    serde_json::json!({"ok": true, "port": args.port, "body": body})+                );+            } else {+                ok(format!("healthy on port {} — {}", args.port, body));+            }+            Ok(())+        }+        Err(e) => {+            if args.json {+                println!(+                    "{}",+                    serde_json::json!({"ok": false, "port": args.port, "error": format!("{e}")})+                );+            } else {+                err(format!("not running on port {}: {e}", args.port));+                hint("start it with `adom-chipsmith view <file.step>`");+            }+            Err(anyhow::anyhow!("not running"))+        }+    }+}
src/cli/install.rsadded+66
@@ -0,0 +1,66 @@+use crate::cli::{err, hint, ok};+use anyhow::Result;+use clap::Parser;++#[derive(Parser)]+pub struct Args {+    /// Skip copying the binary; only drop SKILL.md.+    #[arg(long)]+    pub skill_only: bool,+}++pub fn run(args: Args) -> Result<()> {+    let home = std::env::var("HOME").unwrap_or_else(|_| "/home/adom".to_string());++    // 1) Drop SKILL.md so Claude Code agents pick up the chipsmith skill.+    let skill_dir = format!("{home}/.claude/skills/adom-chipsmith");+    if let Err(e) = std::fs::create_dir_all(&skill_dir) {+        err(format!("create {skill_dir}: {e}"));+        return Err(e.into());+    }+    let skill_md = include_str!("../../SKILL.md");+    let skill_path = format!("{skill_dir}/SKILL.md");+    std::fs::write(&skill_path, skill_md)?;+    ok(format!("wrote {skill_path}"));++    if args.skill_only {+        return Ok(());+    }++    // 2) Copy the running binary to ~/.local/bin/adom-chipsmith so it's+    //    on PATH for terminal use without an absolute path. Per the+    //    adom-cli-design skill: every Adom CLI installs into the+    //    user's local bin via this command.+    let bin_dir = format!("{home}/.local/bin");+    if let Err(e) = std::fs::create_dir_all(&bin_dir) {+        err(format!("create {bin_dir}: {e}"));+        return Err(e.into());+    }+    let target = format!("{bin_dir}/adom-chipsmith");+    let current_exe = match std::env::current_exe() {+        Ok(p) => p,+        Err(e) => {+            err(format!("can't locate current exe: {e}"));+            return Err(e.into());+        }+    };+    // Skip overwrite if the running binary IS already the target (avoids+    // ETXTBSY when self-replacing).+    if current_exe != std::path::PathBuf::from(&target) {+        if let Err(e) = std::fs::copy(&current_exe, &target) {+            err(format!("copy {} → {}: {}", current_exe.display(), target, e));+            return Err(e.into());+        }+        ok(format!("copied binary → {target}"));+    } else {+        ok(format!("binary already at {target}"));+    }++    if !std::env::var("PATH").unwrap_or_default().contains(&bin_dir) {+        hint(format!(+            "add {bin_dir} to PATH (e.g. via ~/.bashrc) — currently not on PATH"+        ));+    }++    Ok(())+}
src/cli/isolate.rsadded+25
@@ -0,0 +1,25 @@+use crate::cli::{eval, ok, DEFAULT_PORT};+use anyhow::Result;+use clap::Parser;++#[derive(Parser)]+pub struct Args {+    /// Friendly name of the node to isolate.+    pub name: String,++    #[arg(long, default_value_t = 5)]+    pub timeout_secs: u64,++    #[arg(long, default_value_t = DEFAULT_PORT)]+    pub port: u16,+}++pub fn run(args: Args) -> Result<()> {+    let code = format!(+        "return window.adomStep ? window.adomStep.isolate({}) : {{ error: 'adomStep not loaded' }};",+        serde_json::to_string(&args.name).unwrap()+    );+    let result = eval::eval_snippet(&code, args.timeout_secs, args.port, true)?;+    ok(format!("isolated {}: {result}", args.name));+    Ok(())+}
src/cli/reveal.rsadded+44
@@ -0,0 +1,44 @@+//! `adom-chipsmith reveal <file>` — reveal a file in the VS Code Explorer.+//!+//! Delegates to `adom-vscode reveal <abs-path>`. Used by the UI's+//! reveal-in-explorer buttons (each clickable file path in the source row,+//! sign-off HUD, hierarchy header, error toasts) and by AI sessions that want+//! to surface where an artifact ended up on disk.++use anyhow::Result;+use clap::Args as ClapArgs;+use std::path::PathBuf;+use std::process::Command;++#[derive(ClapArgs)]+pub struct Args {+    /// File or directory to reveal in the VS Code Explorer sidebar.+    pub path: PathBuf,+}++pub fn run(args: Args) -> Result<()> {+    let abs = args.path.canonicalize().unwrap_or(args.path.clone());+    let abs_str = abs.to_string_lossy().to_string();++    let status = Command::new("adom-vscode")+        .arg("reveal")+        .arg(&abs_str)+        .status();++    match status {+        Ok(s) if s.success() => {+            super::ok(format!("revealed {abs_str}"));+            Ok(())+        }+        Ok(s) => {+            super::err(format!("adom-vscode reveal exited with status {s}"));+            super::hint("install adom-vscode if missing: it ships from the wiki via auto-discovery");+            std::process::exit(1);+        }+        Err(e) => {+            super::err(format!("could not invoke adom-vscode: {e}"));+            super::hint("install adom-vscode (it provides the VS Code file-explorer reveal hook)");+            std::process::exit(1);+        }+    }+}
src/cli/view.rsadded+116
@@ -0,0 +1,116 @@+use crate::cli::{err, hint, ok, DEFAULT_PORT};+use crate::server::{self, convert, ServerConfig, ServerState};+use anyhow::{anyhow, Result};+use clap::Parser;+use std::path::PathBuf;++#[derive(Parser)]+pub struct Args {+    /// Path to a .step or .stp file.+    pub file: PathBuf,++    #[arg(long, default_value_t = DEFAULT_PORT)]+    pub port: u16,++    /// Skip opening the Hydrogen webview tab (for headless test runs).+    #[arg(long)]+    pub no_open: bool,++    #[arg(long, default_value = "STEP Viewer")]+    pub tab_name: String,++    #[arg(long, default_value = "mdi:cube-outline")]+    pub display_icon: String,+}++pub fn run(args: Args) -> Result<()> {+    let file = args.file.canonicalize().map_err(|e| {+        anyhow!(+            "{} does not exist: {e}",+            args.file.display()+        )+    })?;++    let ext = file+        .extension()+        .and_then(|s| s.to_str())+        .map(|s| s.to_ascii_lowercase());+    if !matches!(ext.as_deref(), Some("step") | Some("stp")) {+        err(format!(+            "{} is not a .step / .stp file",+            file.display()+        ));+        hint("adom-chipsmith is STEP-only; use the canonical 3D viewer for other formats");+        return Err(anyhow!("not a STEP file"));+    }++    let bytes = std::fs::read(&file).map_err(|e| anyhow!("read {}: {e}", file.display()))?;+    ok(format!(+        "converting {} ({} KB) via service-step2glb...",+        file.display(),+        bytes.len() / 1024+    ));++    let result = match convert::convert_step_bytes(&bytes) {+        Ok(r) => r,+        Err(e) => {+            err(format!("conversion failed: {e}"));+            return Err(e);+        }+    };++    let label = if result.cache_hit {+        "cache HIT"+    } else {+        "cache MISS"+    };+    ok(format!(+        "{label} — GLB at {} ({} KB, {} meshes, {} nodes, {} ms)",+        result.glb_path.display(),+        result.size_bytes / 1024,+        result.meshes,+        result.nodes,+        result.duration_ms+    ));++    let label = file+        .file_name()+        .and_then(|s| s.to_str())+        .unwrap_or("model.step")+        .to_string();++    let config = ServerConfig {+        port: args.port,+        initial_glb_path: Some(result.glb_path.clone()),+        initial_source_label: Some(label),+        initial_source_type: Some("local-file".to_string()),+    };+    let state = ServerState::new(config);++    let shutdown_state = state.clone();+    ctrlc::set_handler(move || {+        eprintln!("\nreceived SIGINT, shutting down adom-chipsmith");+        let _ = &shutdown_state;+        std::process::exit(0);+    })?;++    if !args.no_open {+        // Open in a background thread after the server is up so the+        // webview's first load resolves.+        let port = args.port;+        let tab_name = args.tab_name.clone();+        let icon = args.display_icon.clone();+        std::thread::spawn(move || {+            std::thread::sleep(std::time::Duration::from_millis(400));+            if let Err(e) =+                crate::cli::open::open_webview_tab(port, &tab_name, &icon)+            {+                eprintln!("warn: failed to open webview tab: {e}");+            }+        });+    }++    ok(format!("adom-chipsmith running on port {}", args.port));+    server::run(state)?;+    Ok(())+}