优化skill
CI / Select checks (push) Has been cancelled
CI / Format and repository checks (push) Has been cancelled
CI / Compile RISC-V (manual) (push) Has been cancelled
Docker / image (push) Has been cancelled
Generated files / Regenerate and commit (push) Has been cancelled
Kernel rig / Select the rig areas (push) Has been cancelled
Lists / Design format changes merge cleanly (push) Has been cancelled
Lists / Lists are sorted one item per line (push) Has been cancelled
Packaging lint / lint (push) Has been cancelled
Pages / build (push) Has been cancelled
CI / Dependency advisories (push) Has been cancelled
CI / Quick compile (push) Has been cancelled
CI / Native Linux Clippy (push) Has been cancelled
CI / Build tests (push) Has been cancelled
CI / Native Linux tests (push) Has been cancelled
CI / GPU path tests (1/4) (push) Has been cancelled
CI / GPU path tests (2/4) (push) Has been cancelled
CI / GPU path tests (3/4) (push) Has been cancelled
CI / GPU path tests (4/4) (push) Has been cancelled
CI / Action matrix (1/16) (push) Has been cancelled
CI / Action matrix (10/16) (push) Has been cancelled
CI / Action matrix (11/16) (push) Has been cancelled
CI / Action matrix (12/16) (push) Has been cancelled
CI / Action matrix (13/16) (push) Has been cancelled
CI / Action matrix (14/16) (push) Has been cancelled
CI / Action matrix (15/16) (push) Has been cancelled
CI / Action matrix (16/16) (push) Has been cancelled
CI / Action matrix (2/16) (push) Has been cancelled
CI / Action matrix (3/16) (push) Has been cancelled
CI / Action matrix (4/16) (push) Has been cancelled
CI / Action matrix (5/16) (push) Has been cancelled
CI / Action matrix (6/16) (push) Has been cancelled
CI / Action matrix (7/16) (push) Has been cancelled
CI / Action matrix (8/16) (push) Has been cancelled
CI / Action matrix (9/16) (push) Has been cancelled
CI / Action matrix determinism (push) Has been cancelled
CI / Property tests (many cases) (push) Has been cancelled
CI / Doc tests (push) Has been cancelled
CI / Reference tests (push) Has been cancelled
CI / Windows D3D12 FXC shaders (push) Has been cancelled
CI / Windows app startup (push) Has been cancelled
CI / ci (push) Has been cancelled
CI / Compile WebAssembly (push) Has been cancelled
CI / Nightly alert (push) Has been cancelled
Kernel rig / Build the CLI (push) Has been cancelled
Kernel rig / Kernel rig (${{ matrix.shard }}) (push) Has been cancelled
Kernel rig / kernel-rig (push) Has been cancelled
Pages / deploy (push) Has been cancelled

This commit is contained in:
2026-11-16 11:32:34 +08:00
parent 2cdf535fd1
commit 678058c940
76 changed files with 3937 additions and 707 deletions
+27 -27
View File
@@ -1,52 +1,52 @@
# SolidCraft: instructions for agents
# makeCAD: instructions for agents
SolidCraft is a clean-room, pure-Rust parametric 3D CAD app (sketch solver, feature timeline, B-rep kernel, an egui UI that agents drive). This file is a router: the hard rules, then the skill to read for your task. Humans: CONTRIBUTING.md.
makeCAD is a clean-room, pure-Rust parametric 3D CAD app (sketch solver, feature timeline, B-rep kernel, an egui UI that agents drive). This file is a router: the hard rules, then the skill to read for your task. Humans: CONTRIBUTING.md.
## Start here
Work: ROADMAP.md, "Where help is wanted most" in CONTRIBUTING.md, issues labelled `help wanted`, `good first issue`, `needs-triage`; architecture in `docs/architecture.md`. Local `plan/` notes are optional.
## Hard rules (what enforces each)
- Independent: never copy another product's code, icons, text or templates; never drive or take data from commercial CAD. `skills/solidcraft-ground-rules/SKILL.md`.
- Independent: never copy another product's code, icons, text or templates; never drive or take data from commercial CAD. `skills/makecad-ground-rules/SKILL.md`.
- No GPL/LGPL/AGPL code, not even reading it (OpenCASCADE, FreeCAD, SolveSpace, CadQuery, LibreCAD, QCAD): `cargo xtask licences --check`.
- Every asset is original or openly licensed with a row in ATTRIBUTION.md; read `assets/AGENTS.md` before icon work: `cargo xtask assets`, `cargo xtask icons`.
- Never crash: no unwrap/expect/panic/unsafe in non-test code, errors are `Result`, input is hostile: clippy `-D warnings`, `hostile_params_never_panic`.
- Model decisions (what an operation does, which bodies it touches, which face or edge a point or name means, depths, nearness) use exact geometry; a mesh is for display, export, previews and mesh bodies (`xtask/mesh-decisions.txt` only shrinks): `cargo xtask mesh-decisions`.
- New kernel cases go to solidcore: `cargo xtask lists`.
- Everything is a command and programmatic calls never open dialogs: `skills/solidcraft-commands/SKILL.md`.
- Everything is a command and programmatic calls never open dialogs: `skills/makecad-commands/SKILL.md`.
- Layering (geom, sketch/kernel/render, doc, io, engine, ui-egui, apps); only `crates/kernel` uses truck: `cargo xtask layers`.
- One outer UI container, one camera path (`navigation::handle`), colours from theme tokens: `cargo xtask ui-containers`.
- Application code is Rust only and builds for wasm: `cargo xtask wasm`, `cargo xtask web-offline-test`.
- The product name is SolidCraft; the old name lives only in `docs/compatibility.md`.
- The product name is makeCAD. Existing crate, CLI, protocol and file-format identifiers remain compatible; new assistant skill identifiers use `makecad-*`.
- Sorted lists (message catalogs, `mod` lines, languages) stay sorted: `cargo xtask lists`. Never edit generated files (`docs/features.md`, `THIRD-PARTY-LICENSES.txt`) in a PR.
- A design-format change is ONE new file in `crates/doc/src/format/pending/`: `scripts/test-format-pending.sh`.
- A command has input and output schemas (will become required; `schema/unconverted.txt` only shrinks): `skills/solidcraft-commands/SKILL.md`.
- A command has input and output schemas (will become required; `schema/unconverted.txt` only shrinks): `skills/makecad-commands/SKILL.md`.
- New UI strings go in `assets/locales/pending/<slug>.json`, ATTRIBUTION rows in `attribution/pending/<slug>.md`: `cargo xtask lists`.
- A changed default keeps the old behaviour behind a preference and fills the PR's `Changes a default:` line: `pr-checks.yml`.
- A regression test goes in the area's existing test file, never a per-bug file (#3226).
- Look at open PRs first, claim with a draft PR (lowest number wins), one topic per PR: `skills/solidcraft-contributing/SKILL.md`.
- A PR's title and first sentence make sense to someone who never saw your chat or the issue: `skills/solidcraft-contributing/SKILL.md`.
- Code, comments, commit messages and docs are in English, always: `skills/solidcraft-contributing/SKILL.md` ("Working as an agent").
- Independent work runs in parallel, dependent work stays sequential: `skills/solidcraft-contributing/SKILL.md` ("Working as an agent").
- Look at open PRs first, claim with a draft PR (lowest number wins), one topic per PR: `skills/makecad-contributing/SKILL.md`.
- A PR's title and first sentence make sense to someone who never saw your chat or the issue: `skills/makecad-contributing/SKILL.md`.
- Code, comments, commit messages and docs are in English, always: `skills/makecad-contributing/SKILL.md` ("Working as an agent").
- Independent work runs in parallel, dependent work stays sequential: `skills/makecad-contributing/SKILL.md` ("Working as an agent").
- Show observable changes with real screenshots or a recording, captured yourself.
- Run `cargo xtask ci` before every commit. `cargo xtask skills` keeps this file and `skills/` honest.
## Working on X: read the skill first
| Working on | Read |
|---|---|
| A PR, a claim, review, CI or evidence | `skills/solidcraft-contributing/SKILL.md` |
| Licences, assets, clean-room, the name | `skills/solidcraft-ground-rules/SKILL.md` |
| Non-test Rust, hostile input, a crash report | `skills/solidcraft-crash-safety/SKILL.md` |
| A command, a crate boundary | `skills/solidcraft-commands/SKILL.md` |
| A dialog, panel, camera, icon, colour | `skills/solidcraft-ui/SKILL.md` |
| Labels, messages, translations | `skills/solidcraft-ui-text/SKILL.md` |
| Saving something new in a design, import, export | `skills/solidcraft-file-formats/SKILL.md` |
| Preferences, a changed default | `skills/solidcraft-preferences/SKILL.md` |
| Writing or running tests | `skills/solidcraft-tests/SKILL.md` |
| Slow work, the window thread, wasm | `skills/solidcraft-performance/SKILL.md` |
| Releases, installers, packages | `skills/solidcraft-packaging/SKILL.md` |
| Running the app, control channel, MCP tools | `skills/solidcraft-agent-tools/SKILL.md` |
| Building a part over MCP | `skills/solidcraft-modeling/SKILL.md` |
| Changing an existing design | `skills/solidcraft-editing/SKILL.md` |
| A bug report, a crash, a wrong result | `skills/solidcraft-reporting/SKILL.md` |
| Checking, porting, designs in git | `skills/solidcraft-checking/SKILL.md` |
| Assemblies, joints, motion | `skills/solidcraft-mechanisms/SKILL.md` |
| A PR, a claim, review, CI or evidence | `skills/makecad-contributing/SKILL.md` |
| Licences, assets, clean-room, the name | `skills/makecad-ground-rules/SKILL.md` |
| Non-test Rust, hostile input, a crash report | `skills/makecad-crash-safety/SKILL.md` |
| A command, a crate boundary | `skills/makecad-commands/SKILL.md` |
| A dialog, panel, camera, icon, colour | `skills/makecad-ui/SKILL.md` |
| Labels, messages, translations | `skills/makecad-ui-text/SKILL.md` |
| Saving something new in a design, import, export | `skills/makecad-file-formats/SKILL.md` |
| Preferences, a changed default | `skills/makecad-preferences/SKILL.md` |
| Writing or running tests | `skills/makecad-tests/SKILL.md` |
| Slow work, the window thread, wasm | `skills/makecad-performance/SKILL.md` |
| Releases, installers, packages | `skills/makecad-packaging/SKILL.md` |
| Running the app, control channel, MCP tools | `skills/makecad-agent-tools/SKILL.md` |
| Building a part over MCP | `skills/makecad-modeling/SKILL.md` |
| Changing an existing design | `skills/makecad-editing/SKILL.md` |
| A bug report, a crash, a wrong result | `skills/makecad-reporting/SKILL.md` |
| Checking, porting, designs in git | `skills/makecad-checking/SKILL.md` |
| Assemblies, joints, motion | `skills/makecad-mechanisms/SKILL.md` |
+1 -1
View File
@@ -37,7 +37,7 @@ wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = [
"Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "Clipboard", "ClipboardItem", "StorageManager",
"Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "Clipboard", "ClipboardItem", "ClipboardEvent", "DataTransfer", "StorageManager",
"FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemGetDirectoryOptions", "FileSystemWritableFileStream",
"WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage", "StorageEvent",
"IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode",
+7 -7
View File
@@ -3,22 +3,22 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>SolidCraft</title>
<title>makeCAD</title>
<meta name="description" content="Open-source parametric CAD built in Rust. Desktop, browser, and MCP for AI agents.">
<meta property="og:type" content="website">
<meta property="og:site_name" content="SolidCraft">
<meta property="og:title" content="SolidCraft: try it in your browser">
<meta property="og:site_name" content="makeCAD">
<meta property="og:title" content="makeCAD: try it in your browser">
<meta property="og:description" content="Open-source parametric CAD built in Rust. Desktop, browser, and MCP for AI agents.">
<meta property="og:url" content="https://solidcraft.ai/">
<meta property="og:image" content="https://docs.solidcraft.io/og.png">
<meta property="og:image:width" content="1280">
<meta property="og:image:height" content="640">
<meta property="og:image:alt" content="SolidCraft: open-source parametric CAD built in Rust">
<meta property="og:image:alt" content="makeCAD: open-source parametric CAD built in Rust">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="SolidCraft: try it in your browser">
<meta name="twitter:title" content="makeCAD: try it in your browser">
<meta name="twitter:description" content="Open-source parametric CAD built in Rust. Desktop, browser, and MCP for AI agents.">
<meta name="twitter:image" content="https://docs.solidcraft.io/og.png">
<meta name="twitter:image:alt" content="SolidCraft: open-source parametric CAD built in Rust">
<meta name="twitter:image:alt" content="makeCAD: open-source parametric CAD built in Rust">
<link data-trunk rel="rust" data-bin="solidcraft-web" data-wasm-opt="z" data-weak-refs />
<link data-trunk rel="copy-file" href="../../assets/fonts/biz-udp-gothic/BIZUDPGothic-Regular.ttf" data-target-path="fonts" />
<link data-trunk rel="copy-file" href="../../assets/fonts/biz-udp-gothic/OFL.txt" data-target-path="fonts" />
@@ -41,7 +41,7 @@
</head>
<body>
<canvas id="solidcraft_canvas"></canvas>
<div id="solidcraft_loading" role="status"><img src="loading-logo.svg" alt=""><span class="sr-only">Loading SolidCraft&hellip;</span></div>
<div id="solidcraft_loading" role="status"><img src="loading-logo.svg" alt=""><span class="sr-only">Loading makeCAD&hellip;</span></div>
<script>
// Offline use and updates (sw.js; written into release builds by `cargo xtask web-offline`).
if ("serviceWorker" in navigator) {
File diff suppressed because it is too large Load Diff
+824
View File
@@ -1,6 +1,830 @@
//! Nonblocking adapter to the original MCP contracts. Cached replies never execute geometry.
use serde_json::Value;
/// The native API worker trims at the beginning of a new user turn, never midway
/// through a tool group. Keep the current turn even when it alone exceeds the cap.
pub fn trim_history_at_turn_start(history: &mut Vec<Value>, target: usize) -> usize {
if history.len() <= target {
return 0;
}
let is_user = |item: &Value| item["type"] == "message" && item["role"] == "user";
let current = history.iter().rposition(is_user).unwrap_or(0);
let cutoff = history.len().saturating_sub(target);
let start =
history.iter().enumerate().take(current + 1).find(|(index, item)| *index >= cutoff && is_user(item)).map_or(current, |(index, _)| index);
history.drain(..start);
start
}
/// Match the native view eviction without altering the transcript or text parts.
pub fn drop_old_history_images(history: &mut [Value], keep: usize) {
let mut seen = 0usize;
for item in history.iter_mut().rev() {
if let Some(content) = item.get_mut("content").and_then(Value::as_array_mut) {
for part in content.iter_mut().rev() {
if part["type"] == "image" {
seen += 1;
if seen > keep {
*part = serde_json::json!({"type":"text","text":solidcraft_ui_egui::agent_chat::api_wire::DROPPED_VIEW_NOTE});
}
}
}
}
}
}
/// Keep completed steps when a later tool is cancelled. Unanswered calls must not
/// be replayed or sent as an incomplete group on the next user message.
pub fn discard_unanswered_calls(history: &mut Vec<Value>) {
let answered: std::collections::BTreeSet<String> =
history.iter().filter(|item| item["type"] == "toolResult").filter_map(|item| item["callCode"].as_str().map(str::to_string)).collect();
history.retain(|item| item["type"] != "toolCall" || item["callCode"].as_str().is_some_and(|code| answered.contains(code)));
}
/// Native's 20,000-byte bound applies only to ordinary prose. Never cut JSON,
/// schemas, knowledge or skills into an apparently complete structured reply.
pub fn bound_plain_tool_text(name: &str, result: &mut Value) {
const LIMIT: usize = 20_000;
if matches!(name, "knowledge_lookup" | "skill_reference") {
return;
}
let Some(content) = result.get_mut("content").and_then(Value::as_array_mut) else { return };
// Preserve multi-part and mixed replies; the existing delivery budget checks
// handle them together and know whether a CAD operation already ran.
if content.len() != 1 {
return;
}
let Some(part) = content.first_mut().filter(|part| part["type"] == "text") else { return };
let Some(text) = part["text"].as_str() else { return };
let trimmed = text.trim_start();
if text.len() <= LIMIT || trimmed.starts_with('{') || trimmed.starts_with('[') || serde_json::from_str::<Value>(text).is_ok() {
return;
}
let mut end = LIMIT;
while !text.is_char_boundary(end) {
end -= 1;
}
part["text"] = Value::String(format!("{}\n…(cut)", &text[..end]));
}
pub fn history_usage(history: &[Value]) -> (usize, usize) {
let mut text_bytes = 0usize;
let mut images = 0usize;
for item in history {
if let Some(content) = item.get("content").and_then(Value::as_array) {
for part in content {
if part["type"] == "text" {
text_bytes = text_bytes.saturating_add(part.get("text").and_then(Value::as_str).map_or(0, str::len));
} else if part["type"] == "image" {
images += 1;
}
}
}
if item["type"] == "toolCall" {
// CadAiProtocol meters the complete call envelope, excluding opaque reasoning.
let mut call = item.clone();
if let Some(call) = call.as_object_mut() {
call.remove("reasoning");
call.remove("reasoningContent");
call.retain(|_, value| !value.is_null());
}
text_bytes = text_bytes.saturating_add(call.to_string().len());
}
}
(text_bytes, images)
}
/// Include fields populated by the host and null record fields metered by Jackson.
/// The wire may omit those nulls, so this deliberately errs on the safe side.
pub fn request_usage(request: &Value) -> (usize, usize, usize, usize) {
let history = request["history"].as_array().map(Vec::as_slice).unwrap_or_default();
let (text, images) = history_usage(history);
let mut context = request["context"].clone();
if let Some(context) = context.as_object_mut() {
for key in ["selection", "knowledgeProtocol", "modelRecovery"] {
context.entry(key).or_insert(Value::Null);
}
context.insert("documentRevision".into(), Value::String("0".repeat(64)));
if !context.get("engineBuild").is_some_and(Value::is_string) {
context.insert("engineBuild".into(), Value::String("0".repeat(24)));
}
}
let context_bytes = context.to_string().len();
let mut wire = request.clone();
wire["context"] = context;
(wire.to_string().len(), text.saturating_add(context_bytes), images, history.len())
}
/// Lossless wire-only compaction. The durable history and transcript stay untouched.
pub fn compact_history_json(history: &mut [Value]) {
for item in history.iter_mut().filter(|item| item["type"] == "toolResult") {
if let Some(content) = item.get_mut("content").and_then(Value::as_array_mut) {
for block in content {
if block["type"] == "text"
&& let Some(text) = block["text"].as_str()
&& let Some(compact) = minify_json(text)
{
block["text"] = Value::String(compact);
}
}
}
}
}
/// Drop only redundant copies of the exact same skill body and request. Equality checks
/// the complete bytes, so a changed body can never be mistaken for the previous version.
pub fn deduplicate_skill_history(history: &mut [Value]) {
let calls: std::collections::BTreeMap<String, String> = history
.iter()
.filter(|item| item["type"] == "toolCall" && item["name"] == "skill_reference")
.filter_map(|item| Some((item["callCode"].as_str()?.to_string(), item["arguments"].to_string())))
.collect();
let mut seen = std::collections::BTreeMap::<(String, String), String>::new();
for item in history.iter_mut().rev() {
if item["type"] != "toolResult" || item["isError"] == true {
continue;
}
let Some(code) = item["callCode"].as_str().map(str::to_string) else { continue };
let Some(arguments) = calls.get(&code) else { continue };
let key = (arguments.clone(), item["content"].to_string());
if let Some(reference) = seen.get(&key) {
let receipt =
format!("Identical skill reference: full unchanged body remains in tool result {reference}. This is not a new instruction.");
let content = item["content"].as_array().map(Vec::as_slice).unwrap_or_default();
if content.iter().all(|block| block["type"] == "text")
&& receipt.len() < content.iter().filter_map(|block| block["text"].as_str()).map(str::len).sum::<usize>()
{
item["content"] = serde_json::json!([{"type":"text","text":receipt}]);
}
} else {
seen.insert(key, code);
}
}
}
fn latest_call_group(history: &[Value]) -> usize {
let Some(mut start) = history.iter().rposition(|item| item["type"] == "toolCall") else { return history.len() };
while start > 0 && history.get(start - 1).is_some_and(|item| item["type"] == "toolCall") {
start -= 1;
}
start
}
/// Evict one already delivered read-only reference, oldest catalogue first. Calls and
/// results remain paired; execution, inspection, errors and the newest call group are kept.
pub fn compact_old_reference(history: &mut [Value]) -> bool {
let latest = latest_call_group(history);
for name in ["list_commands", "describe_command"] {
for call_index in 0..latest {
let Some(call) = history.get(call_index) else { continue };
if call["type"] != "toolCall" || call["name"] != name {
continue;
}
let Some(code) = call["callCode"].as_str().map(str::to_string) else { continue };
let arguments = call["arguments"].clone();
let Some(result_index) = history.iter().position(|item| item["type"] == "toolResult" && item["callCode"] == code) else { continue };
let Some(result) = history.get(result_index) else { continue };
if result["isError"] == true {
continue;
}
let Some(content) = result["content"].as_array() else { continue };
if content.iter().any(|block| block["type"] != "text") {
continue;
}
let mut ids = Vec::new();
let mut already_compact = false;
for block in content {
let parsed = block["text"].as_str().and_then(|text| serde_json::from_str::<Value>(text).ok());
if let Some(parsed) = parsed {
already_compact |= parsed["contextCompacted"] == true;
let rows = parsed["commands"].as_array().or_else(|| parsed.as_array());
if let Some(rows) = rows {
ids.extend(rows.iter().filter_map(|row| row["id"].as_str().map(str::to_string)));
}
}
}
if already_compact {
continue;
}
let receipt = serde_json::json!({
"contextCompacted":true,"readOnlyReference":name,"callCode":code,
"commandIds":ids,"requeryArguments":arguments,
"notice":"Previously delivered read-only reference removed from model context to preserve the original goal and CAD execution results. Requery list_commands or describe_command when exact parameters are needed; never guess parameters or replay geometry based on this receipt. The complete result remains in the conversation record."
}).to_string();
if receipt.len() >= content.iter().filter_map(|block| block["text"].as_str()).map(str::len).sum::<usize>() {
continue;
}
if let Some(result) = history.get_mut(result_index) {
result["content"] = serde_json::json!([{"type":"text","text":receipt}]);
return true;
}
}
}
false
}
pub fn remove_old_reference_pair(history: &mut Vec<Value>) -> bool {
let latest = latest_call_group(history);
for name in ["list_commands", "describe_command"] {
for call_index in 0..latest {
let Some(call) = history.get(call_index) else { continue };
if call["type"] != "toolCall" || call["name"] != name {
continue;
}
let Some(code) = call["callCode"].as_str() else { continue };
let Some(result_index) =
history.iter().position(|item| item["type"] == "toolResult" && item["callCode"] == code && item["isError"] == false)
else {
continue;
};
if result_index <= call_index {
continue;
}
history.remove(result_index);
history.remove(call_index);
return true;
}
}
false
}
/// Free old screenshots without dropping the original goal or any user's reference image.
pub fn reserve_history_image_slot(history: &mut [Value], limit: usize) {
let current = history.iter().rposition(|item| item["type"] == "message" && item["role"] == "user").unwrap_or(0);
let calls: std::collections::BTreeSet<String> = history
.iter()
.take(current)
.filter(|item| item["type"] == "toolCall" && item["name"] == "screenshot")
.filter_map(|item| item["callCode"].as_str().map(str::to_string))
.collect();
let mut count = history_usage(history).1;
for item in history {
if count < limit {
break;
}
if item["type"] != "toolResult" || !item["callCode"].as_str().is_some_and(|code| calls.contains(code)) {
continue;
}
if let Some(content) = item.get_mut("content").and_then(Value::as_array_mut) {
let before = content.len();
content.retain(|block| block["type"] != "image");
let removed = before - content.len();
count = count.saturating_sub(removed);
if removed > 0 {
content.push(serde_json::json!({"type":"text","text":"Earlier-turn screenshot omitted from model context. The original remains in the conversation record. Inspect the current design before relying on its previous appearance."}));
}
}
}
}
use std::{cell::Cell, future::Future};
/// Compact only knowledge results in the wire copy. Original tool events, call IDs,
/// reasoning state and generic skill results remain intact. A new user turn must
/// recheck applicability; it cannot inherit a previous turn's modelling recipe.
pub fn knowledge_wire_history(history: &[Value]) -> Vec<Value> {
let current = history.iter().rposition(|item| item["type"] == "message" && item["role"] == "user").unwrap_or(0);
let calls: std::collections::BTreeSet<&str> = history
.iter()
.filter(|item| item["type"] == "toolCall" && item["name"] == "knowledge_lookup")
.filter_map(|item| item["callCode"].as_str())
.collect();
let mut seen = std::collections::BTreeSet::new();
let mut wire = history.to_vec();
for (index, item) in wire.iter_mut().enumerate() {
if item["type"] != "toolResult" || !item["callCode"].as_str().is_some_and(|code| calls.contains(code)) {
continue;
}
let Some(content) = item.get_mut("content").and_then(Value::as_array_mut) else { continue };
for block in content {
let Some(mut answer) = knowledge_answer(block) else { continue };
if let Some(documents) = answer.get_mut("documents").and_then(Value::as_array_mut) {
for document in documents {
let Some(key) = knowledge_key(document) else { continue };
// A surviving reference cannot suppress a body reloaded after trimming.
let has_text = document["text"].as_str().is_some_and(|text| !text.is_empty());
if (index < current || has_text && !seen.insert(key))
&& let Some(document) = document.as_object_mut()
{
document.remove("text");
}
}
}
if index < current {
answer["status"] = Value::String("expired".into());
answer["reason"] = Value::String(
"Prior-turn knowledge reference only. Query again if this component needs a recipe; current requirements may differ.".into(),
);
}
block["text"] = Value::String(answer.to_string());
}
}
wire
}
/// Deduplicate against the actual effective history, never an ever-loaded cache.
/// If trimming removed the full text, the next lookup delivers it in full again.
pub fn deduplicate_knowledge_result(result: &mut Value, history: &[Value]) {
let wire = knowledge_wire_history(history);
let calls: std::collections::BTreeSet<&str> = wire
.iter()
.filter(|item| item["type"] == "toolCall" && item["name"] == "knowledge_lookup")
.filter_map(|item| item["callCode"].as_str())
.collect();
let mut present = std::collections::BTreeSet::new();
for item in &wire {
if item["type"] != "toolResult" || !item["callCode"].as_str().is_some_and(|code| calls.contains(code)) {
continue;
}
for block in item["content"].as_array().into_iter().flatten() {
if let Some(answer) = knowledge_answer(block) {
for document in answer["documents"].as_array().into_iter().flatten() {
if document["text"].as_str().is_some_and(|text| !text.is_empty())
&& let Some(key) = knowledge_key(document)
{
present.insert(key);
}
}
}
}
}
let Some(content) = result.get_mut("content").and_then(Value::as_array_mut) else { return };
for block in content {
let Some(mut answer) = knowledge_answer(block) else { continue };
if let Some(documents) = answer.get_mut("documents").and_then(Value::as_array_mut) {
for document in documents {
if knowledge_key(document).is_some_and(|key| present.contains(&key))
&& let Some(document) = document.as_object_mut()
{
document.remove("text");
document.insert("reference".into(), Value::String("Full text is already present in this turn's effective context.".into()));
}
}
}
block["text"] = Value::String(answer.to_string());
}
}
fn knowledge_answer(block: &Value) -> Option<Value> {
if block["type"] != "text" {
return None;
}
let answer: Value = serde_json::from_str(block["text"].as_str()?).ok()?;
(answer["documents"].is_array() && answer["status"].is_string()).then_some(answer)
}
fn knowledge_key(document: &Value) -> Option<(String, String, String)> {
Some((document["id"].as_str()?.into(), document["version"].as_str()?.into(), document["sha256"].as_str()?.into()))
}
pub fn sse_boundary(bytes: &[u8]) -> Option<(usize, usize)> {
let mut index = 0;
while index < bytes.len() {
if bytes.get(index..index + 2) == Some(b"\n\n") {
return Some((index, 2));
}
if bytes.get(index..index + 4) == Some(b"\r\n\r\n") {
return Some((index, 4));
}
index += 1;
}
None
}
pub fn sse_event(block: &[u8]) -> Result<Option<(String, Value)>, ModelRequestFailure> {
let text = std::str::from_utf8(block).map_err(|_| ModelRequestFailure::malformed("CAD AI returned invalid UTF-8", "stream_encoding"))?;
let mut event = "message".to_string();
let mut data = Vec::new();
for line in text.split('\n') {
let line = line.strip_suffix('\r').unwrap_or(line);
if line.starts_with(':') {
continue;
}
if let Some(value) = line.strip_prefix("event:") {
event = value.trim_start().to_string();
} else if let Some(value) = line.strip_prefix("data:") {
data.push(value.strip_prefix(' ').unwrap_or(value));
}
}
if data.is_empty() {
return Ok(None);
}
let envelope: Value =
serde_json::from_str(&data.join("\n")).map_err(|_| ModelRequestFailure::malformed("CAD AI returned an invalid SSE event", "event_json"))?;
if !envelope.is_object() {
return Err(ModelRequestFailure::malformed("CAD AI SSE envelope must be an object", "event_shape"));
}
Ok(Some((event, envelope)))
}
/// Missing fields can be regenerated. Conflicting identities must never be retried.
pub fn sse_data<'a>(envelope: &'a Value, request_id: &mut Option<String>, document: &str, turn: &str) -> Result<&'a Value, ModelRequestFailure> {
let malformed = || ModelRequestFailure::malformed("CAD AI SSE envelope has missing or invalid fields", "event_shape");
let id = envelope["requestId"].as_str().filter(|id| !id.is_empty() && id.len() <= 128).ok_or_else(malformed)?;
if request_id.as_deref().is_some_and(|previous| previous != id) {
return Err("CAD AI SSE requestId changed during the response".into());
}
let data = envelope.get("data").filter(|data| data.is_object()).ok_or_else(malformed)?;
// Check explicit mismatches first even if another field is absent.
for (field, expected) in [("documentSessionCode", document), ("turnCode", turn)] {
if data[field].as_str().is_some_and(|actual| actual != expected) {
return Err("CAD AI SSE event belongs to another document or turn".into());
}
}
if data["documentSessionCode"].as_str().is_none() || data["turnCode"].as_str().is_none() || envelope["code"].as_str().is_none_or(str::is_empty) {
return Err(malformed());
}
*request_id = Some(id.to_string());
Ok(data)
}
/// A model request can fail before any CAD tool from that response has run.
#[derive(Debug, PartialEq, Eq)]
pub enum ModelRecoveryStop {
Disabled,
RequestLimit,
TurnLimit,
}
#[derive(Debug, PartialEq, Eq)]
pub struct ModelRequestFailure {
pub message: String,
pub code: Option<String>,
pub request_id: Option<String>,
pub retryable: bool,
pub correction: Option<Value>,
pub recovery_stop: Option<ModelRecoveryStop>,
}
impl ModelRequestFailure {
pub fn response(status: Option<u16>, envelope: &Value, fallback: String) -> Self {
let code = envelope["code"].as_str().filter(|code| !code.is_empty()).map(str::to_string);
let retryable = match code.as_deref() {
Some("CAD_AI_TIMEOUT") => true,
Some("CAD_AI_INVALID_MODEL_TOOL") => true,
// Older servers grouped permanent and transient errors under this code.
// Require the new explicit flag; never infer safety from translated prose.
Some("CAD_AI_PROVIDER_FAILURE") => envelope["data"]["retryable"] == true,
None => envelope.get("code").is_none() && matches!(status, Some(408 | 502 | 503 | 504)),
_ => false,
};
Self {
message: envelope["message"].as_str().filter(|message| !message.is_empty()).unwrap_or(&fallback).to_string(),
request_id: envelope["requestId"].as_str().filter(|id| !id.is_empty() && id.len() <= 128).map(str::to_string),
code,
retryable,
correction: (envelope["code"] == "CAD_AI_INVALID_MODEL_TOOL"
|| retryable && envelope["code"] == "CAD_AI_PROVIDER_FAILURE" && envelope["data"]["correction"].is_object())
.then(|| model_correction(&envelope["data"]["correction"])),
recovery_stop: None,
}
}
pub fn interrupted(message: String) -> Self {
Self { message, code: None, request_id: None, retryable: true, correction: None, recovery_stop: None }
}
pub fn malformed(message: &str, rule: &str) -> Self {
Self {
message: message.to_string(),
code: Some("CAD_AI_PROVIDER_FAILURE".into()),
request_id: None,
retryable: true,
correction: Some(model_correction(&serde_json::json!({"tool":"unknown","rule":rule,"path":"$"}))),
recovery_stop: None,
}
}
pub fn invalid_tool(message: String, tool: &str, rule: &str, path: &str) -> Self {
Self {
message,
code: Some("CAD_AI_INVALID_MODEL_TOOL".into()),
request_id: None,
retryable: true,
correction: Some(model_correction(&serde_json::json!({"tool":tool,"rule":rule,"path":path}))),
recovery_stop: None,
}
}
}
/// Diagnostics are data, never raw model output or argument values.
fn model_correction(value: &Value) -> Value {
let identifier = |key: &str, fallback: &str, max: usize| {
value[key]
.as_str()
.filter(|text| {
!text.is_empty()
&& text.len() <= max
&& text.bytes().next().is_some_and(|byte| byte.is_ascii_alphabetic())
&& text.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
&& (key != "rule" || text.bytes().all(|byte| !byte.is_ascii_uppercase()))
})
.unwrap_or(fallback)
.to_string()
};
let path = value["path"]
.as_str()
.filter(|path| {
if path.len() > 256 || !path.starts_with('$') {
return false;
}
let mut tail = path.get(1..).unwrap_or_default();
while !tail.is_empty() {
if let Some(property) = tail.strip_prefix('.') {
let length = if property.starts_with('*') {
1
} else {
if !property.bytes().next().is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_') {
return false;
}
property.bytes().take_while(|byte| byte.is_ascii_alphanumeric() || *byte == b'_').count()
};
tail = property.get(length..).unwrap_or_default();
} else if let Some(index) = tail.strip_prefix('[') {
let length = index.bytes().take_while(u8::is_ascii_digit).count();
let Some(rest) = index.get(length..).and_then(|rest| rest.strip_prefix(']')) else {
return false;
};
if length == 0 {
return false;
}
tail = rest;
} else {
return false;
}
}
true
})
.unwrap_or("$");
serde_json::json!({"tool":identifier("tool", "unknown", 64),"rule":identifier("rule", "invalid_tool", 64),"path":path})
}
impl From<String> for ModelRequestFailure {
fn from(message: String) -> Self {
Self { message, code: None, request_id: None, retryable: false, correction: None, recovery_stop: None }
}
}
impl From<&str> for ModelRequestFailure {
fn from(message: &str) -> Self {
message.to_string().into()
}
}
/// Retry only the frozen model request, never the enclosing CAD tool loop.
pub struct ModelRecovery<'a> {
enabled: &'a Cell<bool>,
generation: &'a Cell<u64>,
turn: u64,
retries: u8,
}
impl<'a> ModelRecovery<'a> {
pub fn new(enabled: &'a Cell<bool>, generation: &'a Cell<u64>, turn: u64) -> Self {
Self { enabled, generation, turn, retries: 0 }
}
pub async fn request<T, Attempt, AttemptFuture, Wait, WaitFuture, Notice>(
&mut self,
mut attempt: Attempt,
mut wait: Wait,
mut notice: Notice,
) -> Result<Option<T>, ModelRequestFailure>
where
Attempt: FnMut(Option<Value>) -> AttemptFuture,
AttemptFuture: Future<Output = Result<T, ModelRequestFailure>>,
Wait: FnMut(u32) -> WaitFuture,
WaitFuture: Future<Output = ()>,
Notice: FnMut(u8, &ModelRequestFailure),
{
let mut request_retries = 0u8;
let mut correction = None;
loop {
if self.generation.get() != self.turn {
return Ok(None);
}
let result = attempt(correction.clone()).await;
if self.generation.get() != self.turn {
return Ok(None);
}
match result {
Ok(value) => return Ok(Some(value)),
Err(mut error) => {
if !error.retryable {
return Err(error);
}
error.recovery_stop = if !self.enabled.get() {
Some(ModelRecoveryStop::Disabled)
} else if request_retries >= 2 {
Some(ModelRecoveryStop::RequestLimit)
} else if self.retries >= 6 {
Some(ModelRecoveryStop::TurnLimit)
} else {
None
};
if error.recovery_stop.is_some() {
return Err(error);
}
request_retries += 1;
self.retries += 1;
if let Some(diagnostic) = &error.correction {
correction = Some(diagnostic.clone());
}
notice(request_retries, &error);
wait(1000 * u32::from(request_retries)).await;
if self.generation.get() != self.turn {
return Ok(None);
}
if !self.enabled.get() {
error.recovery_stop = Some(ModelRecoveryStop::Disabled);
return Err(error);
}
}
}
}
}
}
/// Hosted discovery keeps every command and its availability, but loads parameter
/// documentation on demand with describe_command. Explicit projections win.
pub fn hosted_tool_arguments(name: &str, arguments: &Value, compact_catalog: bool) -> Value {
let mut effective = arguments.clone();
if !compact_catalog {
return effective;
}
match name {
"list_commands" => {
if let Some(object) = effective.as_object_mut()
&& !object.contains_key("fields")
&& !object.contains_key("compact")
{
object.insert("fields".into(), serde_json::json!(["id", "label", "tab", "panel", "enabled", "disabled_reason", "planned"]));
}
}
"batch" => {
// Only direct read-only catalog steps change. Do not rewrite nested
// batches, engine commands or malformed parameters into valid calls.
if let Some(steps) = effective.get_mut("commands").and_then(Value::as_array_mut) {
for step in steps {
if step.get("command").and_then(Value::as_str) != Some("list_commands") {
continue;
}
if let Some(object) = step.as_object_mut() {
let params = object.entry("params").or_insert_with(|| serde_json::json!({}));
*params = hosted_tool_arguments("list_commands", params, true);
}
}
}
}
_ => {}
}
effective
}
/// Fit platform text without removing any fields from the effective query.
/// Unlike MCP's compact option, this never replaces sketches with summaries.
pub fn prepare_tool_result(name: &str, arguments: &Value, schema: &Value, result: &mut Value, text_limit: Option<u64>) {
let Some(limit) = text_limit.filter(|limit| *limit > 0) else { return };
let can_page = name == "list_commands" && result["isError"] != true && schema["properties"]["offset"]["type"] == "integer";
let Some(content) = result.get_mut("content").and_then(Value::as_array_mut) else { return };
if text_bytes(content) <= limit {
return;
}
for block in content.iter_mut() {
if block.get("type").and_then(Value::as_str) == Some("text")
&& let Some(text) = block.get("text").and_then(Value::as_str)
&& let Some(compact) = minify_json(text)
{
block["text"] = Value::String(compact);
}
}
if can_page && text_bytes(content) > limit {
page_catalog(content, arguments, limit);
}
}
fn text_bytes(content: &[Value]) -> u64 {
content
.iter()
.filter(|block| block.get("type").and_then(Value::as_str) == Some("text"))
.filter_map(|block| block.get("text").and_then(Value::as_str))
.fold(0u64, |total, text| total.saturating_add(text.len() as u64))
}
fn minify_json(text: &str) -> Option<String> {
// Validate before touching a text block: skills and error prose are not JSON.
serde_json::from_str::<Value>(text).ok()?;
let mut compact = String::with_capacity(text.len());
let mut quoted = false;
let mut escaped = false;
for ch in text.chars() {
if quoted {
compact.push(ch);
if escaped {
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if ch == '"' {
quoted = false;
}
} else if ch == '"' {
compact.push(ch);
quoted = true;
} else if !matches!(ch, ' ' | '\t' | '\r' | '\n') {
compact.push(ch);
}
}
Some(compact)
}
struct CatalogPage {
envelope: serde_json::Map<String, Value>,
rows: Vec<Value>,
offset: u64,
}
impl CatalogPage {
fn read(text: &str) -> Option<Self> {
let (mut envelope, rows) = match serde_json::from_str::<Value>(text).ok()? {
Value::Array(rows) => {
let envelope = serde_json::json!({"total":rows.len(),"offset":0,"next_offset":null}).as_object()?.clone();
(envelope, rows)
}
Value::Object(mut envelope) => {
let Value::Array(rows) = envelope.remove("commands")? else { return None };
(envelope, rows)
}
_ => return None,
};
if rows.is_empty() || rows.iter().any(|row| !row.is_object()) || envelope.contains_key("next_arguments") {
return None;
}
let offset = envelope.get("offset")?.as_u64()?;
let total = envelope.get("total")?.as_u64()?;
let end = offset.checked_add(rows.len() as u64)?;
let next = envelope.get("next_offset")?;
if end > total || (end < total && next.as_u64() != Some(end)) || (end == total && !next.is_null()) {
return None;
}
envelope.insert("commands".into(), Value::Array(Vec::new()));
Some(Self { envelope, rows, offset })
}
fn fit(&self, arguments: &Value, budget: u64) -> Option<String> {
let arguments = arguments.as_object()?;
let mut low = 1usize;
let mut high = self.rows.len();
let mut best = None;
while low <= high {
let count = low + (high - low) / 2;
let mut page = self.envelope.clone();
page.insert("commands".into(), Value::Array(self.rows.iter().take(count).cloned().collect()));
if count < self.rows.len() {
page.insert("next_offset".into(), Value::from(self.offset.checked_add(count as u64)?));
}
let next_arguments = match page.get("next_offset")?.as_u64() {
Some(offset) => {
let mut next = arguments.clone();
next.insert("offset".into(), Value::from(offset));
Value::Object(next)
}
None => Value::Null,
};
page.insert("next_arguments".into(), next_arguments);
let text = Value::Object(page).to_string();
if text.len() as u64 <= budget {
best = Some(text);
low = count + 1;
} else {
high = count - 1;
}
}
best
}
}
fn page_catalog(content: &mut [Value], arguments: &Value, limit: u64) {
// Other text blocks and envelope metadata share the same advertised budget.
let mut candidate = None;
for (index, block) in content.iter().enumerate() {
if block.get("type").and_then(Value::as_str) != Some("text") {
continue;
}
let Some(text) = block.get("text").and_then(Value::as_str) else { continue };
let Some(page) = CatalogPage::read(text) else { continue };
if candidate.is_some() {
return;
}
candidate = Some((index, page, text.len() as u64));
}
let Some((index, page, original_bytes)) = candidate else { return };
let other_bytes = text_bytes(content).saturating_sub(original_bytes);
let Some(budget) = limit.checked_sub(other_bytes) else { return };
let Some(text) = page.fit(arguments, budget) else { return };
if let Some(block) = content.get_mut(index) {
block["text"] = Value::String(text);
}
}
pub struct ControlReply {
pub method: String,
pub params: Value,
+946 -1
View File
@@ -1102,6 +1102,7 @@ mod web {
if let Some(delay) = self.wheel_gestures.update(raw, now) {
ctx.request_repaint_after(delay);
}
crate::agent::take_attachment_pastes(&mut self.app, ctx);
crate::agent::take_attachment_drops(&mut self.app, ctx, raw);
if self.launch.persists() {
let theme = solidcraft_ui_egui::prefs::theme_drop_target(&self.app, ctx);
@@ -1396,6 +1397,657 @@ fn main() {
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Value;
#[test]
fn platform_history_counts_complete_tool_envelopes_without_reasoning() {
use crate::agent_tools::history_usage;
use serde_json::json;
let call = json!({"type":"toolCall","callCode":"call_example","name":"describe_command","arguments":{"id":"齿轮"}});
let mut reasoning = call.clone();
reasoning["reasoning"] = json!([{"id":"reasoning","encryptedContent":"excluded"}]);
reasoning["reasoningContent"] = json!("excluded too");
let history = vec![
json!({"type":"message","role":"user","content":[{"type":"text","text":"装配"},{"type":"image","data":"YWJj"}]}),
reasoning,
json!({"type":"toolResult","callCode":"call_example","isError":false,"content":[{"type":"text","text":"{}"}]}),
];
assert_eq!(history_usage(&history), ("装配".len() + call.to_string().len() + 2, 1));
}
#[test]
fn platform_usage_reserves_host_context_and_detects_call_envelope_overflow() {
use crate::agent_tools::{history_usage, request_usage};
use serde_json::json;
let mut history = vec![json!({"type":"message","role":"user","content":[{"type":"text","text":"x".repeat(240671)}]})];
for n in 0..44 {
history.push(json!({"type":"toolCall","callCode":format!("call_{n:032}"),"name":"describe_command","arguments":{"id":"x".repeat(405)}}));
}
let request = json!({"history":history,"context":{"documentRevision":"0".repeat(64),"knowledgeProtocol":"cad-knowledge-v1"}});
let (bytes, text, _, _) = request_usage(&request);
let context = json!({"documentRevision":"0".repeat(64),"knowledgeProtocol":"cad-knowledge-v1","engineBuild":"0".repeat(24),"selection":null,"modelRecovery":null});
assert_eq!(text, history_usage(request["history"].as_array().unwrap()).0 + context.to_string().len());
assert!(bytes > request.to_string().len(), "host context must be reserved before dispatch");
assert!(text > 262144, "the former arguments-only meter admitted this request");
let formerly_counted = 240671 + 44 * json!({"id":"x".repeat(405)}).to_string().len() + context.to_string().len();
assert!(formerly_counted < 262144);
}
#[test]
fn platform_wire_compaction_preserves_goals_execution_results_and_latest_schemas() {
use crate::agent_tools::{compact_history_json, compact_old_reference, remove_old_reference_pair};
use serde_json::json;
let tool = |code: &str, name: &str, args: Value| json!({"type":"toolCall","callCode":code,"name":name,"arguments":args});
let result = |code: &str, text: String| json!({"type":"toolResult","callCode":code,"isError":false,"content":[{"type":"text","text":text}]});
let mut history = vec![
json!({"type":"message","role":"user","content":[{"type":"text","text":"Original complete assembly goal"}]}),
tool("schema", "describe_command", json!({"id":"solid.box"})),
result("schema", json!({"id":"solid.box","input":{"description":"d".repeat(1400)}}).to_string()),
tool("catalog", "list_commands", json!({"filter":"solid","fields":["id","params"]})),
result("catalog", json!({"commands":[{"id":"solid.box","params":"p".repeat(1400)}],"next_offset":null}).to_string()),
tool("edit", "batch", json!({"commands":[]})),
result("edit", " { \"applied\" : [\"Housing\"], \"volume\" : 0.12345678901234567890123 } ".into()),
json!({"type":"message","role":"user","content":[{"type":"text","text":"Continue above"}]}),
tool("latest", "describe_command", json!({"id":"solid.sweep"})),
result("latest", json!({"id":"solid.sweep","input":{"description":"l".repeat(1400)}}).to_string()),
];
let original = history.clone();
compact_history_json(&mut history);
assert_eq!(history[6]["content"][0]["text"], "{\"applied\":[\"Housing\"],\"volume\":0.12345678901234567890123}");
assert!(compact_old_reference(&mut history));
assert!(history[4]["content"][0]["text"].as_str().unwrap().contains("contextCompacted"));
assert_eq!(history[2], original[2], "catalogues are compacted before command schemas");
assert_eq!(history[9], original[9], "the model receives its newest complete schema");
assert_eq!(history[0], original[0]);
assert_eq!(history[7], original[7]);
assert!(compact_old_reference(&mut history));
assert!(!compact_old_reference(&mut history));
assert!(remove_old_reference_pair(&mut history));
assert!(!history.iter().any(|item| item["callCode"] == "catalog"));
assert!(history.iter().any(|item| item["callCode"] == "schema"));
assert!(history.iter().any(|item| item["callCode"] == "edit" && item["type"] == "toolResult"));
assert!(history.iter().any(|item| item["callCode"] == "latest" && item["type"] == "toolResult"));
}
#[test]
fn platform_skill_deduplication_requires_identical_request_and_complete_body() {
use crate::agent_tools::deduplicate_skill_history;
use serde_json::json;
let mut history = Vec::new();
for (code, body) in [("s1", "original skill"), ("s2", "changed skill"), ("s3", "original skill")] {
history
.push(json!({"type":"toolCall","callCode":code,"name":"skill_reference","arguments":{"skill":"makecad-modeling","file":"SKILL.md"}}));
history.push(json!({"type":"toolResult","callCode":code,"isError":false,"content":[{"type":"text","text":body.repeat(30)}]}));
}
let original = history.clone();
deduplicate_skill_history(&mut history);
assert!(history[1]["content"][0]["text"].as_str().unwrap().contains("s3"));
assert_eq!(history[3], original[3]);
assert_eq!(history[5], original[5]);
assert_eq!(original[1]["content"][0]["text"], "original skill".repeat(30));
}
#[test]
fn platform_image_reservation_preserves_original_goal_and_user_reference_images() {
use crate::agent_tools::{history_usage, reserve_history_image_slot};
use serde_json::json;
let mut history = vec![
json!({"type":"message","role":"user","content":[{"type":"text","text":"Complete assembly goal"},{"type":"image","data":"user-image"}]}),
json!({"type":"toolCall","callCode":"old","name":"screenshot","arguments":{}}),
json!({"type":"toolResult","callCode":"old","isError":false,"content":[{"type":"image","data":"old-model"}]}),
json!({"type":"message","role":"user","content":[{"type":"text","text":"Continue"}]}),
];
let original = history.clone();
reserve_history_image_slot(&mut history, 2);
assert_eq!(history_usage(&history).1, 1);
assert_eq!(history[0], original[0]);
assert_eq!(history[1], original[1]);
assert_eq!(history[3], original[3]);
assert!(history[2]["content"][0]["text"].as_str().unwrap().contains("conversation record"));
}
fn knowledge_result(code: &str) -> Value {
serde_json::json!({"type":"toolResult","callCode":code,"content":[{"type":"text","text":serde_json::json!({
"status":"matched","type_id":"involute-spur-gear","documents":[{"id":"gear","version":"2","sha256":"abc","text":"EXACT FORMULA"}]
}).to_string()}]})
}
#[test]
fn browser_knowledge_deduplicates_only_present_body_and_preserves_original_history() {
use crate::agent_tools::{deduplicate_knowledge_result, knowledge_wire_history};
use serde_json::json;
let history = vec![
json!({"type":"message","role":"user","content":[]}),
json!({"type":"toolCall","name":"knowledge_lookup","callCode":"k1"}),
knowledge_result("k1"),
json!({"type":"toolCall","name":"skill_reference","callCode":"s1"}),
json!({"type":"toolResult","callCode":"s1","content":[{"type":"text","text":"ORIGINAL SKILL"}]}),
json!({"type":"toolCall","name":"knowledge_lookup","callCode":"k2"}),
knowledge_result("k2"),
];
let original = history.clone();
let wire = knowledge_wire_history(&history);
assert_eq!(history, original);
assert_eq!(wire[4], history[4]);
assert_eq!(wire.iter().filter(|item| item.to_string().contains("EXACT FORMULA")).count(), 1);
let mut result = json!({"content":knowledge_result("k3")["content"]});
deduplicate_knowledge_result(&mut result, &history);
assert!(!result.to_string().contains("EXACT FORMULA"));
let mut reread = json!({"content":knowledge_result("k3")["content"]});
deduplicate_knowledge_result(&mut reread, &history[..1]);
assert!(reread.to_string().contains("EXACT FORMULA"));
}
#[test]
fn browser_knowledge_reloads_body_when_trimming_leaves_an_earlier_reference() {
use crate::agent_tools::{deduplicate_knowledge_result, knowledge_wire_history};
use serde_json::json;
let complete = vec![
json!({"type":"message","role":"user","content":[]}),
json!({"type":"toolCall","name":"knowledge_lookup","callCode":"k1"}),
knowledge_result("k1"),
];
let mut reference = knowledge_result("k2");
deduplicate_knowledge_result(&mut reference, &complete);
assert!(!reference.to_string().contains("EXACT FORMULA"));
let mut trimmed = vec![
complete[0].clone(),
json!({"type":"toolCall","name":"knowledge_lookup","callCode":"k2","reasoning":[{"encryptedContent":"preserve"}]}),
reference,
json!({"type":"toolCall","name":"skill_reference","callCode":"s1"}),
json!({"type":"toolResult","callCode":"s1","content":[{"type":"text","text":"ORIGINAL SKILL"}]}),
];
let mut reread = knowledge_result("k3");
deduplicate_knowledge_result(&mut reread, &trimmed);
assert!(reread.to_string().contains("EXACT FORMULA"));
trimmed.push(json!({"type":"toolCall","name":"knowledge_lookup","callCode":"k3"}));
trimmed.push(reread);
let original = trimmed.clone();
let wire = knowledge_wire_history(&trimmed);
assert_eq!(trimmed, original);
assert_eq!(wire[1], trimmed[1]);
assert_eq!(wire[4], trimmed[4]);
assert_eq!(wire.iter().filter(|item| item.to_string().contains("EXACT FORMULA")).count(), 1);
let mut duplicate = knowledge_result("k4");
deduplicate_knowledge_result(&mut duplicate, &trimmed);
assert!(!duplicate.to_string().contains("EXACT FORMULA"));
}
#[test]
fn browser_knowledge_expires_at_new_requirement_without_touching_calls_or_reasoning() {
use crate::agent_tools::{deduplicate_knowledge_result, knowledge_wire_history};
use serde_json::json;
let history = vec![
json!({"type":"message","role":"user","content":[]}),
json!({"type":"toolCall","name":"knowledge_lookup","callCode":"k1","reasoning":[{"encryptedContent":"preserve"}]}),
knowledge_result("k1"),
json!({"type":"message","role":"user","content":[{"type":"text","text":"Change to a helical gear"}]}),
];
let wire = knowledge_wire_history(&history);
assert_eq!(wire[1], history[1]);
assert_eq!(wire[3], history[3]);
assert!(wire[2].to_string().contains("expired"));
assert!(!wire[2].to_string().contains("EXACT FORMULA"));
let mut result = json!({"content":knowledge_result("k2")["content"]});
deduplicate_knowledge_result(&mut result, &history);
assert!(result.to_string().contains("EXACT FORMULA"));
}
#[test]
fn native_history_trimming_preserves_complete_turns_and_current_requirements() {
use crate::agent_tools::{discard_unanswered_calls, trim_history_at_turn_start};
use serde_json::json;
let mut history = Vec::new();
for turn in 0..70 {
history.extend([
json!({"type":"message","role":"user","content":[{"type":"text","text":format!("requirement-{turn}")}]}),
json!({"type":"toolCall","name":"measure","callCode":format!("call-{turn}")}),
json!({"type":"toolResult","callCode":format!("call-{turn}"),"content":[]}),
json!({"type":"message","role":"assistant","content":[]}),
]);
}
history.push(json!({"type":"message","role":"user","content":[{"type":"text","text":"current dimensions"}]}));
let full = history.clone();
assert_eq!(trim_history_at_turn_start(&mut history, 240), 44);
assert_eq!(history, full[44..]);
assert!(history.len() <= 240);
assert_eq!(history[0]["role"], "user");
history.extend([
json!({"type":"toolCall","callCode":"applied"}),
json!({"type":"toolCall","callCode":"never-ran"}),
json!({"type":"toolResult","callCode":"applied","content":[]}),
]);
discard_unanswered_calls(&mut history);
assert!(history.iter().any(|item| item["callCode"] == "applied"));
assert!(!history.iter().any(|item| item["callCode"] == "never-ran"));
let single_turn = history[history.iter().rposition(|item| item["role"] == "user").unwrap()..].to_vec();
let mut oversized = single_turn.clone();
assert_eq!(trim_history_at_turn_start(&mut oversized, 1), 0);
assert_eq!(oversized, single_turn);
}
#[test]
fn native_history_images_and_plain_text_bounds_preserve_knowledge_and_json() {
use crate::agent_tools::{bound_plain_tool_text, drop_old_history_images, history_usage};
use serde_json::json;
let mut history = vec![json!({"type":"message","role":"user","content":[
{"type":"text","text":"keep dimensions"},{"type":"image","data":"old"},
{"type":"image","data":"middle"},{"type":"image","data":"new"}
]})];
drop_old_history_images(&mut history, 2);
assert_eq!(history_usage(&history).1, 2);
assert_eq!(history[0]["content"][0]["text"], "keep dimensions");
assert!(history[0]["content"][1]["text"].as_str().unwrap().contains("earlier picture"));
let mut result = json!({"content":[{"type":"text","text":"尺寸".repeat(5000)}]});
bound_plain_tool_text("measure", &mut result);
let text = result["content"][0]["text"].as_str().unwrap();
assert!(text.ends_with("\n…(cut)"));
assert!(text.len() <= 20_000 + "\n…(cut)".len());
for name in ["knowledge_lookup", "skill_reference"] {
let mut protected = json!({"content":[{"type":"text","text":"exact formula".repeat(2500)}]});
let original = protected.clone();
bound_plain_tool_text(name, &mut protected);
assert_eq!(protected, original);
}
for text in [json!({"values":"x".repeat(25000)}).to_string(), format!("{{{}", "x".repeat(25000))] {
let mut structured = json!({"content":[{"type":"text","text":text}]});
let original = structured.clone();
bound_plain_tool_text("inspect_design", &mut structured);
assert_eq!(structured, original);
}
}
fn ready_future<T>(future: impl std::future::Future<Output = T>) -> T {
let mut future = std::pin::pin!(future);
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
match future.as_mut().poll(&mut context) {
std::task::Poll::Ready(value) => value,
std::task::Poll::Pending => panic!("test futures must not use clocks or external I/O"),
}
}
#[test]
fn browser_sse_parser_handles_fragmentation_heartbeats_and_malformed_events() {
use crate::agent_tools::{sse_boundary, sse_event};
let envelope = r#"{"code":"OK","requestId":"r","data":{"text":"中文正文"}}"#;
for separator in ["\n", "\r\n"] {
let bytes = format!(": heartbeat{separator}event: text_delta{separator}data: {envelope}{separator}{separator}").into_bytes();
let mut buffer = Vec::new();
let mut events = Vec::new();
for chunk in bytes.chunks(1) {
buffer.extend(chunk);
while let Some((at, length)) = sse_boundary(&buffer) {
let block: Vec<_> = buffer.drain(..at).collect();
buffer.drain(..length);
if let Some(event) = sse_event(&block).unwrap() {
events.push(event);
}
}
}
assert!(buffer.is_empty());
assert_eq!(events.len(), 1);
assert_eq!(events[0].0, "text_delta");
assert_eq!(events[0].1["data"]["text"], "中文正文");
}
assert_eq!(sse_event(b": heartbeat\r\nid: 1\r\nretry: 1000").unwrap(), None);
assert_eq!(sse_event(b"event: completed\ndata: {\ndata: \"code\":\"OK\"}").unwrap().unwrap().1["code"], "OK");
for invalid in [b"data: {broken}".as_slice(), b"data: \xff", b"data:", b"data: null", b"data: []"] {
let error = sse_event(invalid).unwrap_err();
assert!(error.retryable);
assert_eq!(error.code.as_deref(), Some("CAD_AI_PROVIDER_FAILURE"));
}
assert_eq!(sse_boundary(b"data: {\"unfinished\":"), None);
}
#[test]
fn browser_sse_context_distinguishes_missing_fields_from_conflicting_identities() {
use crate::agent_tools::sse_data;
use serde_json::json;
let valid = json!({"code":"OK","requestId":"request","data":{"documentSessionCode":"doc","turnCode":"turn"}});
for path in ["/requestId", "/data", "/data/documentSessionCode", "/data/turnCode", "/code"] {
let mut envelope = valid.clone();
*envelope.pointer_mut(path).unwrap() = Value::Null;
assert!(sse_data(&envelope, &mut None, "doc", "turn").unwrap_err().retryable, "{path}");
}
for (path, value) in [("/requestId", "another"), ("/data/documentSessionCode", "another"), ("/data/turnCode", "another")] {
let mut envelope = valid.clone();
*envelope.pointer_mut(path).unwrap() = value.into();
assert!(!sse_data(&envelope, &mut Some("request".into()), "doc", "turn").unwrap_err().retryable, "{path}");
}
let mut id = None;
assert_eq!(sse_data(&valid, &mut id, "doc", "turn").unwrap(), &valid["data"]);
assert_eq!(id.as_deref(), Some("request"));
}
#[test]
fn browser_provider_corrections_are_explicit_bounded_and_keep_safety_errors_terminal() {
use crate::agent_tools::{ModelRecovery, ModelRecoveryStop, ModelRequestFailure};
use serde_json::json;
use std::{cell::Cell, future::ready};
let diagnostic = json!({"tool":"unknown","rule":"invalid_response","path":"$"});
let envelope = json!({"code":"CAD_AI_PROVIDER_FAILURE","data":{"retryable":true,"correction":diagnostic}});
let error = ModelRequestFailure::response(None, &envelope, "invalid response".into());
assert_eq!(error.correction, Some(diagnostic.clone()));
let enabled = Cell::new(true);
let generation = Cell::new(1);
let mut recovery = ModelRecovery::new(&enabled, &generation, 1);
let mut corrections = Vec::new();
let error = ready_future(recovery.request(
|correction| {
corrections.push(correction);
ready(Err::<(), _>(ModelRequestFailure::response(None, &envelope, "invalid response".into())))
},
|_| ready(()),
|_, _| {},
))
.unwrap_err();
assert_eq!(corrections, [None, Some(diagnostic.clone()), Some(diagnostic)]);
assert_eq!(error.recovery_stop, Some(ModelRecoveryStop::RequestLimit));
enabled.set(false);
let error = ready_future(recovery.request(
|_| ready(Err::<(), _>(ModelRequestFailure::malformed("invalid JSON", "event_json"))),
|_| ready(()),
|_, _| panic!("disabled recovery must not retry"),
))
.unwrap_err();
assert_eq!(error.recovery_stop, Some(ModelRecoveryStop::Disabled));
for code in ["FORBIDDEN", "STALE_BINDING", "CAD_AI_OUTPUT_LIMIT", "CAD_AI_PROVIDER_HISTORY_MISMATCH"] {
let error = ModelRequestFailure::response(
None,
&json!({"code":code,"data":{"retryable":true,"correction":{"rule":"invalid_response"}}}),
"blocked".into(),
);
assert!(!error.retryable);
assert_eq!(error.correction, None);
}
}
#[test]
fn browser_model_recovery_uses_explicit_codes_and_transient_flags() {
use crate::agent_tools::ModelRequestFailure;
use serde_json::json;
let transient = json!({"code":"CAD_AI_PROVIDER_FAILURE","message":"temporary","requestId":"request-1","data":{"retryable":true}});
let failure = ModelRequestFailure::response(None, &transient, "fallback".into());
assert!(failure.retryable);
assert_eq!(failure.message, "temporary");
assert_eq!(failure.request_id.as_deref(), Some("request-1"));
assert_eq!(failure.code.as_deref(), Some("CAD_AI_PROVIDER_FAILURE"));
for code in [
"CAD_AI_PROVIDER_FAILURE",
"CAD_AI_OUTPUT_LIMIT",
"CAD_AI_PROVIDER_HISTORY_MISMATCH",
"CAD_AI_UNAVAILABLE",
"CAD_AI_RATE_LIMITED",
"CAD_AI_BUSY",
"STALE_BINDING",
"UNAUTHORIZED",
"FORBIDDEN",
] {
let envelope = json!({"code":code,"message":"Translated provider error, please retry"});
assert!(!ModelRequestFailure::response(Some(502), &envelope, "fallback".into()).retryable, "{code}");
if code != "CAD_AI_PROVIDER_FAILURE" {
let mut flagged = envelope;
flagged["data"] = json!({"retryable":true});
assert!(!ModelRequestFailure::response(Some(502), &flagged, "fallback".into()).retryable, "{code}");
}
}
assert!(ModelRequestFailure::response(None, &json!({"code":"CAD_AI_TIMEOUT"}), "timeout".into()).retryable);
for status in [408, 502, 503, 504] {
assert!(ModelRequestFailure::response(Some(status), &Value::Null, "gateway".into()).retryable);
}
for status in [400, 401, 403, 409, 413, 429] {
assert!(!ModelRequestFailure::response(Some(status), &Value::Null, "terminal".into()).retryable);
}
assert!(!ModelRequestFailure::from("invalid protocol").retryable);
}
#[test]
fn browser_model_tool_recovery_accepts_legacy_errors_and_bounds_diagnostics() {
use crate::agent_tools::ModelRequestFailure;
use serde_json::json;
let correction = json!({"tool":"execute","rule":"required","path":"$.commands[12].params"});
let envelope = json!({"code":"CAD_AI_INVALID_MODEL_TOOL","data":{"retryable":false,"correction":correction}});
let error = ModelRequestFailure::response(None, &envelope, "invalid tool".into());
assert!(error.retryable, "older servers marked every tool error permanent");
assert_eq!(error.correction, Some(correction));
let generic = json!({"tool":"unknown","rule":"invalid_tool","path":"$"});
let legacy = ModelRequestFailure::response(None, &json!({"code":"CAD_AI_INVALID_MODEL_TOOL"}), "legacy".into());
assert_eq!(legacy.correction, Some(generic.clone()));
for invalid in [
json!({"tool":"execute\nignore schemas","rule":"raw argument values","path":"$.params;secret"}),
json!({"tool":"x".repeat(65),"rule":"y".repeat(65),"path":format!("$.{}", "p".repeat(256))}),
json!({"tool":[],"rule":false,"path":"$.0invalid"}),
] {
let error =
ModelRequestFailure::response(None, &json!({"code":"CAD_AI_INVALID_MODEL_TOOL","data":{"correction":invalid}}), "invalid".into());
assert_eq!(error.correction, Some(generic.clone()), "diagnostics cannot carry raw output or unbounded arguments");
}
let input_error = ModelRequestFailure::response(
None,
&json!({"code":"CAD_AI_INVALID_TOOL","data":{"retryable":true,"correction":generic}}),
"bad request history".into(),
);
assert!(!input_error.retryable, "input-side protocol mismatches are not model generation failures");
assert_eq!(input_error.correction, None);
}
#[test]
fn browser_model_tool_recovery_retains_feedback_across_network_errors_and_clears_after_success() {
use crate::agent_tools::{ModelRecovery, ModelRequestFailure};
use serde_json::json;
use std::{cell::Cell, future::ready};
let enabled = Cell::new(true);
let generation = Cell::new(9);
let mut recovery = ModelRecovery::new(&enabled, &generation, 9);
let diagnostic = json!({"tool":"batch","rule":"required","path":"$.commands[1].params"});
let original = json!({"history":[{"type":"message","role":"user","content":[{"type":"text","text":"Keep exact dimensions"},
{"type":"image","mimeType":"image/png","data":"aW1hZ2U="}]},
{"type":"toolCall","callCode":"applied","name":"execute","arguments":{"command":"solid.box"},"reasoningContent":"opaque reasoning"},
{"type":"toolResult","callCode":"applied","content":[{"type":"text","text":"Already applied"}]}],
"model":"unchanged","reasoningEffort":"high"});
let mut inputs = Vec::new();
let mut notices = Vec::new();
let result = ready_future(recovery.request(
|correction| {
inputs.push((original.clone(), correction));
ready(match inputs.len() {
1 => Err(ModelRequestFailure::invalid_tool("missing params".into(), "batch", "required", "$.commands[1].params")),
2 => Err(ModelRequestFailure::interrupted("EOF".into())),
_ => Ok("corrected"),
})
},
|_| ready(()),
|_, error| notices.push(error.correction.is_some()),
))
.unwrap();
assert_eq!(result, Some("corrected"));
assert_eq!(inputs, [(original.clone(), None), (original.clone(), Some(diagnostic.clone())), (original, Some(diagnostic))]);
assert_eq!(notices, [true, false]);
assert_eq!(
ready_future(recovery.request(
|correction| {
assert_eq!(correction, None, "a new model step cannot inherit stale corrections");
ready(Ok::<_, ModelRequestFailure>("next"))
},
|_| ready(()),
|_, _| panic!("successful response does not retry"),
))
.unwrap(),
Some("next")
);
}
#[test]
fn browser_model_recovery_keeps_frozen_history_and_applied_geometry() {
use crate::agent_tools::{ModelRecovery, ModelRequestFailure};
use serde_json::json;
use std::{cell::Cell, future::ready};
let enabled = Cell::new(true);
let generation = Cell::new(7);
let mut recovery = ModelRecovery::new(&enabled, &generation, 7);
let mut backend = solidcraft_mcp::Headless::new(Default::default());
let applied = solidcraft_mcp::call_tool(&mut backend, "execute", &json!({"command":"solid.box","params":{"length":2,"width":3,"height":4}}));
assert_ne!(applied["isError"], true);
let request = json!({
"turnCode":"same-turn","model":"same-model","reasoningEffort":"high","history":[
{"type":"message","role":"user","content":[{"type":"text","text":"Keep every dimension: 1.2345678901234567"},{"type":"image","mimeType":"image/png","data":"aW1hZ2U="}]},
{"type":"toolCall","callCode":"already-applied","name":"execute","arguments":{"command":"solid.box"},"reasoning":[{"encryptedContent":"opaque reasoning"}]},
{"type":"toolResult","callCode":"already-applied","content":applied["content"],"isError":false}
]
});
let original = request.to_string();
let mut attempts = Vec::new();
let mut delays = Vec::new();
let mut notices = Vec::new();
let result = ready_future(recovery.request(
|_| {
attempts.push(request.to_string());
ready(if attempts.len() < 3 { Err(ModelRequestFailure::interrupted("EOF".into())) } else { Ok("continue") })
},
|ms| {
delays.push(ms);
ready(())
},
|attempt, _| notices.push(attempt),
))
.unwrap();
assert_eq!(result, Some("continue"));
assert_eq!(attempts, vec![original; 3], "no retry may compact history or change generation settings");
assert_eq!(delays, [1000, 2000]);
assert_eq!(notices, [1, 2]);
let measured = solidcraft_mcp::call_tool(&mut backend, "measure", &json!({}));
let measurement: Value = serde_json::from_str(measured["content"][0]["text"].as_str().unwrap()).unwrap();
assert_eq!(measurement["body_count"], 1, "model recovery must not execute applied CAD operations again");
assert_eq!(measurement["total"]["volume_mm3"], 24.0);
}
#[test]
fn browser_model_recovery_bounds_failures_per_request_and_per_turn() {
use crate::agent_tools::{ModelRecovery, ModelRequestFailure};
use std::{cell::Cell, future::ready};
let enabled = Cell::new(true);
let generation = Cell::new(1);
let mut recovery = ModelRecovery::new(&enabled, &generation, 1);
for _ in 0..3 {
let mut attempts = 0;
let result = ready_future(recovery.request(
|_| {
attempts += 1;
ready(if attempts < 3 { Err(ModelRequestFailure::interrupted("EOF".into())) } else { Ok(()) })
},
|_| ready(()),
|_, _| {},
))
.unwrap();
assert_eq!(result, Some(()));
assert_eq!(attempts, 3, "success resets only the consecutive failure budget");
}
let mut attempts = 0;
assert!(
ready_future(recovery.request(
|_| {
attempts += 1;
ready(Err::<(), _>(ModelRequestFailure::interrupted("EOF".into())))
},
|_| ready(()),
|_, _| panic!("the turn budget is exhausted"),
))
.is_err()
);
assert_eq!(attempts, 1);
let mut fresh = ModelRecovery::new(&enabled, &generation, 1);
let mut attempts = 0;
assert!(
ready_future(fresh.request(
|_| {
attempts += 1;
ready(Err::<(), _>(ModelRequestFailure::interrupted("EOF".into())))
},
|_| ready(()),
|_, _| {},
))
.is_err()
);
assert_eq!(attempts, 3, "persistent failure ends instead of retrying forever");
}
#[test]
fn browser_model_recovery_honors_stop_stale_context_and_disabled_preference() {
use crate::agent_tools::{ModelRecovery, ModelRequestFailure};
use std::{cell::Cell, future::ready};
for disable in [false, true] {
let enabled = Cell::new(true);
let generation = Cell::new(1);
let mut recovery = ModelRecovery::new(&enabled, &generation, 1);
let mut attempts = 0;
let result = ready_future(recovery.request(
|_| {
attempts += 1;
ready(Err::<(), _>(ModelRequestFailure::interrupted("EOF".into())))
},
|_| {
if disable {
enabled.set(false);
} else {
generation.set(2);
}
ready(())
},
|_, _| {},
));
if disable {
assert!(result.is_err());
} else {
assert_eq!(result.unwrap(), None);
}
assert_eq!(attempts, 1, "nothing is requested after Stop, a context change or disabling recovery");
}
let enabled = Cell::new(false);
let generation = Cell::new(1);
let mut recovery = ModelRecovery::new(&enabled, &generation, 1);
let waits = Cell::new(0);
let notices = Cell::new(0);
assert!(
ready_future(recovery.request(
|_| ready(Err::<(), _>(ModelRequestFailure::interrupted("EOF".into()))),
|_| {
waits.set(waits.get() + 1);
ready(())
},
|_, _| notices.set(notices.get() + 1),
))
.is_err()
);
enabled.set(true);
assert!(
ready_future(recovery.request(
|_| ready(Err::<(), _>(ModelRequestFailure::from("invalid schema"))),
|_| {
waits.set(waits.get() + 1);
ready(())
},
|_, _| notices.set(notices.get() + 1),
))
.is_err()
);
assert_eq!(waits.get(), 0, "disabled recovery and permanent failures must not wait");
assert_eq!(notices.get(), 0, "disabled recovery and permanent failures must not notify");
assert_eq!(
ready_future(recovery.request(
|_| {
generation.set(2);
ready(Ok::<_, ModelRequestFailure>("late response"))
},
|_| ready(()),
|_, _| {},
))
.unwrap(),
None,
"a response received after cancellation cannot run tools"
);
}
#[test]
fn link_query_decodes_once_and_embed_disables_persistence() {
@@ -1562,7 +2214,8 @@ mod tests {
replies.push(ControlReply { method, params, result: Ok(result) });
}
let mut planner = Replay { results: &replies, at: 0, next: None };
let answer = solidcraft_mcp::call_tool(&mut planner, "execute", &args);
let mut answer = solidcraft_mcp::call_tool(&mut planner, "execute", &args);
crate::agent_tools::prepare_tool_result("execute", &args, &json!({}), &mut answer, Some(1));
assert!(planner.next.is_none());
assert_ne!(answer["isError"], true);
assert_eq!(sent.len(), 2);
@@ -1597,4 +2250,296 @@ mod tests {
assert!(answer.to_string().contains("rolled_back"));
assert!(planner.next.is_none(), "no fallback can apply the steps a second time");
}
#[test]
fn browser_tool_result_minifies_only_json_whitespace() {
use serde_json::json;
let text = r#" {
"coordinates": [ -0.0, 1.2345678901234567, 1e-12 ],
"name": " hole \\ \"rim\" end ",
"note": "中 文\nnext\tline"
} "#;
let expected = r#"{"coordinates":[-0.0,1.2345678901234567,1e-12],"name":" hole \\ \"rim\" end ","note":"中 文\nnext\tline"}"#;
let prose = "Read the full sketch.\nKeep its coordinate system.";
let mut result = json!({"content":[{"type":"text","text":text},{"type":"text","text":prose}],"isError":false});
crate::agent_tools::prepare_tool_result("inspect_design", &json!({}), &json!({}), &mut result, Some(1));
assert_eq!(result["content"][0]["text"], expected);
assert_eq!(result["content"][1]["text"], prose);
assert_eq!(result["isError"], false);
}
#[test]
fn browser_tool_result_pages_full_command_fields_without_losing_entries() {
use serde_json::{Value, json};
let mut backend = solidcraft_mcp::Headless::default();
let original = solidcraft_mcp::call_tool(&mut backend, "list_commands", &json!({}));
let all: Value = serde_json::from_str(original["content"][0]["text"].as_str().expect("catalog text")).expect("catalog JSON");
let all = all.as_array().expect("full catalog");
let schema = json!({"properties":{"offset":{"type":"integer"}}});
let mut offset = 0;
let mut collected = Vec::new();
for _ in 0..all.len() {
let args = if offset == 0 { json!({}) } else { json!({"offset":offset}) };
let mut result = solidcraft_mcp::call_tool(&mut backend, "list_commands", &args);
crate::agent_tools::prepare_tool_result("list_commands", &args, &schema, &mut result, Some(32768));
let text = result["content"][0]["text"].as_str().expect("page text");
assert!(text.len() <= 32768, "{} bytes", text.len());
let page: Value = serde_json::from_str(text).expect("page JSON");
assert_eq!(page["total"], all.len());
assert_eq!(page["offset"], offset);
let entries = page["commands"].as_array().expect("complete rows");
assert!(!entries.is_empty());
collected.extend(entries.iter().cloned());
let Some(next) = page["next_offset"].as_u64() else { break };
assert!(next > offset);
offset = next;
}
assert_eq!(&collected, all, "all fields and command order survive pagination");
}
#[test]
fn hosted_catalog_index_preserves_all_commands_and_availability_across_pages() {
use crate::agent_tools::{hosted_tool_arguments, prepare_tool_result};
use serde_json::{Value, json};
let mut backend = solidcraft_mcp::Headless::default();
let original = solidcraft_mcp::call_tool(&mut backend, "list_commands", &json!({}));
let full_text = original["content"][0]["text"].as_str().expect("full catalog");
let full: Value = serde_json::from_str(full_text).unwrap();
let all = full.as_array().unwrap();
let expected: Vec<Value> = all
.iter()
.cloned()
.map(|mut row| {
let object = row.as_object_mut().unwrap();
for key in ["params", "icon", "shortcut"] {
object.remove(key);
}
row
})
.collect();
let effective = hosted_tool_arguments("list_commands", &json!({}), true);
let indexed = solidcraft_mcp::call_tool(&mut backend, "list_commands", &effective);
let index: Value = serde_json::from_str(indexed["content"][0]["text"].as_str().unwrap()).unwrap();
assert_eq!(index, json!(expected));
assert!(all.len() >= 600, "exercise the complete real catalog");
assert!(all.iter().any(|row| row["enabled"] == false && row["disabled_reason"].is_string()));
assert!(index.to_string().len() < full.to_string().len() / 3, "reduce repeated documentation without losing commands");
let schema = json!({"properties":{"offset":{"type":"integer"}}});
let mut args = effective;
let mut collected = Vec::new();
let mut delivered_bytes = 0usize;
let mut pages = 0usize;
for _ in 0..=all.len() {
let mut result = solidcraft_mcp::call_tool(&mut backend, "list_commands", &args);
prepare_tool_result("list_commands", &args, &schema, &mut result, Some(32768));
let text = result["content"][0]["text"].as_str().unwrap();
assert!(text.len() <= 32768);
delivered_bytes += text.len();
pages += 1;
let page: Value = serde_json::from_str(text).unwrap();
if let Some(rows) = page.as_array() {
collected.extend(rows.iter().cloned());
break;
}
assert_eq!(page["total"], all.len());
assert_eq!(page["offset"], collected.len());
let rows = page["commands"].as_array().unwrap();
assert!(!rows.is_empty());
collected.extend(rows.iter().cloned());
if page["next_offset"].is_null() {
break;
}
assert_eq!(page["next_arguments"]["fields"], args["fields"]);
assert_eq!(page["next_arguments"]["offset"], collected.len());
args = hosted_tool_arguments("list_commands", &page["next_arguments"], true);
}
assert_eq!(collected, expected, "no missing, duplicated or reordered commands, fields or availability");
eprintln!(
"catalog_measurement={}",
json!({"commands":all.len(),"fullPrettyBytes":full_text.len(),"fullMinifiedBytes":full.to_string().len(),"indexMinifiedBytes":index.to_string().len(),"deliveredIndexBytes":delivered_bytes,"indexPages":pages})
);
}
#[test]
fn hosted_catalog_keeps_explicit_queries_and_opt_out_byte_for_byte() {
use crate::agent_tools::hosted_tool_arguments;
use serde_json::json;
let mut backend = solidcraft_mcp::Headless::default();
for args in [json!({}), json!({"filter":"extrude"}), json!({"fields":["id","params"]}), json!({"compact":false})] {
assert_eq!(hosted_tool_arguments("list_commands", &args, false), args);
}
for args in [
json!({"compact":false}),
json!({"compact":true}),
json!({"fields":["params"],"compact":true,"limit":2,"offset":1}),
json!({"fields":[]}),
json!({"fields":null}),
json!({"compact":null}),
json!({"fields":"invalid"}),
] {
let effective = hosted_tool_arguments("list_commands", &args, true);
assert_eq!(effective, args);
assert_eq!(
solidcraft_mcp::call_tool(&mut backend, "list_commands", &effective),
solidcraft_mcp::call_tool(&mut backend, "list_commands", &args)
);
}
for args in [json!(null), json!([]), json!("invalid")] {
assert_eq!(hosted_tool_arguments("list_commands", &args, true), args);
}
let invalid = json!({"filter":8});
let effective = hosted_tool_arguments("list_commands", &invalid, true);
assert_eq!(
solidcraft_mcp::call_tool(&mut backend, "list_commands", &effective),
solidcraft_mcp::call_tool(&mut backend, "list_commands", &invalid)
);
}
#[test]
fn hosted_catalog_filters_empty_results_and_exact_command_details_remain_available() {
use crate::agent_tools::hosted_tool_arguments;
use serde_json::{Value, json};
let mut backend = solidcraft_mcp::Headless::default();
for args in [
json!({"filter":"extrude"}),
json!({"prefix":"solid.","limit":3,"offset":2}),
json!({"panel":"Sketch","limit":4}),
json!({"filter":"__no_such_command__"}),
json!({"offset":99999}),
] {
let raw = solidcraft_mcp::call_tool(&mut backend, "list_commands", &args);
let effective = hosted_tool_arguments("list_commands", &args, true);
for (key, value) in args.as_object().unwrap() {
assert_eq!(effective[key], *value);
}
let indexed = solidcraft_mcp::call_tool(&mut backend, "list_commands", &effective);
let mut expected: Value = serde_json::from_str(raw["content"][0]["text"].as_str().unwrap()).unwrap();
let rows = if expected.is_array() { expected.as_array_mut().unwrap() } else { expected["commands"].as_array_mut().unwrap() };
for row in rows {
for key in ["params", "icon", "shortcut"] {
row.as_object_mut().unwrap().remove(key);
}
}
assert_eq!(serde_json::from_str::<Value>(indexed["content"][0]["text"].as_str().unwrap()).unwrap(), expected);
}
let args = json!({"id":"solid.extrude"});
let described = solidcraft_mcp::call_tool(&mut backend, "describe_command", &hosted_tool_arguments("describe_command", &args, true));
assert_ne!(described["isError"], true);
assert_eq!(described, solidcraft_mcp::call_tool(&mut backend, "describe_command", &args));
assert!(described["content"][0]["text"].as_str().unwrap().len() > 10000, "full detailed schema, not an index or truncated text");
for name in ["execute", "knowledge_lookup", "skill_reference", "inspect_design"] {
let args = json!({"command":"solid.extrude","document_id":"modeling","params":{"depth":12.5}});
assert_eq!(hosted_tool_arguments(name, &args, true), args);
}
}
#[test]
fn hosted_catalog_batch_only_changes_default_catalog_steps() {
use crate::agent_tools::hosted_tool_arguments;
use serde_json::json;
let args = json!({"commands":[
{"command":"list_commands"},
{"command":"list_commands","params":{"prefix":"solid.","limit":2}},
{"command":"list_commands","params":{"compact":false}},
{"command":"list_commands","params":null},
{"command":"solid.extrude","params":{"depth":12.5}},
{"command":"batch","params":{"commands":[{"command":"list_commands"}]}}
],"rollback":true,"verbose":false});
let mut expected = args.clone();
expected["commands"][0]["params"] = hosted_tool_arguments("list_commands", &json!({}), true);
expected["commands"][1]["params"] = hosted_tool_arguments("list_commands", &args["commands"][1]["params"], true);
assert_eq!(hosted_tool_arguments("batch", &args, true), expected);
assert_eq!(hosted_tool_arguments("batch", &args, false), args);
let mut backend = solidcraft_mcp::Headless::default();
let query = json!({"commands":[{"command":"list_commands","params":{"filter":"extrude"}}]});
let result = solidcraft_mcp::call_tool(&mut backend, "batch", &hosted_tool_arguments("batch", &query, true));
assert_ne!(result["isError"], true);
assert!(!result["content"][0]["text"].as_str().unwrap().contains("\"params\""));
}
#[test]
fn browser_tool_result_pages_preserve_queries_metadata_and_other_blocks_at_exact_budget() {
use serde_json::{Value, json};
let rows: Vec<Value> = (0..6)
.map(|i| json!({"id":format!("sketch.test{i}"),"label":"Sketch","params":"point: [x,y,z]; 文本 ".repeat(10),"enabled":true,"disabled_reason":null}))
.collect();
let args = json!({"filter":"sketch","prefix":"sketch.","panel":"SKETCH","fields":["id","label","params","enabled","disabled_reason"],"limit":6,"offset":7});
let mut next = args.clone();
next["offset"] = json!(9);
let note = json!({"unit":"mm","source":"all fields"});
let original = json!({"commands":rows,"total":20,"offset":7,"next_offset":13,"note":note});
let expected = json!({"commands":rows[..2],"total":20,"offset":7,"next_offset":9,"note":note,"next_arguments":next});
let extra = "Preserve this warning verbatim.";
let image = json!({"type":"image","mimeType":"image/png","data":"AA=="});
let mut result = json!({"isError":false,"structuredContent":{"kept":true},"content":[
{"type":"text","text":serde_json::to_string_pretty(&original).expect("catalog")},
{"type":"text","text":extra},image
]});
let budget = (expected.to_string().len() + extra.len()) as u64;
let schema = json!({"properties":{"offset":{"type":"integer"}}});
crate::agent_tools::prepare_tool_result("list_commands", &args, &schema, &mut result, Some(budget));
let text = result["content"][0]["text"].as_str().expect("page text");
assert_eq!(serde_json::from_str::<Value>(text).expect("page"), expected);
assert_eq!((text.len() + extra.len()) as u64, budget);
assert_eq!(result["content"][1]["text"], extra);
assert_eq!(result["content"][2], image);
assert_eq!(result["structuredContent"], json!({"kept":true}));
assert_eq!(result["isError"], false);
}
#[test]
fn browser_tool_result_never_pages_errors_other_tools_or_unsupported_schemas() {
use serde_json::{Value, json};
let rows = json!([{"id":"test.one","params":"Full parameter documentation. ".repeat(100)},{"id":"test.two","params":"More documentation. ".repeat(100)}]);
let original =
json!({"content":[{"type":"text","text":serde_json::to_string_pretty(&rows).expect("catalog")}],"structuredContent":{"unchanged":true}});
let schema = json!({"properties":{"offset":{"type":"integer"}}});
for (name, schema, error) in [("list_commands", json!({}), false), ("list_commands", schema.clone(), true), ("execute", schema, false)] {
let mut result = original.clone();
result["isError"] = json!(error);
crate::agent_tools::prepare_tool_result(name, &json!({}), &schema, &mut result, Some(512));
let text = result["content"][0]["text"].as_str().expect("text");
assert_eq!(serde_json::from_str::<Value>(text).expect("complete JSON"), rows);
assert!(text.len() > 512, "do not silently discard fields to fit");
assert_eq!(result["isError"], error);
assert_eq!(result["structuredContent"], original["structuredContent"]);
}
for limit in [None, Some(0), Some(u64::MAX)] {
let mut result = original.clone();
crate::agent_tools::prepare_tool_result("list_commands", &json!({}), &json!({}), &mut result, limit);
assert_eq!(result, original, "no positive exceeded budget means no output change");
}
}
#[test]
fn browser_tool_result_retains_a_single_oversized_entry_without_empty_page_loops() {
use serde_json::{Value, json};
let rows = json!([{"id":"test.one","params":"Required documentation. ".repeat(100)}]);
let mut result = json!({"content":[{"type":"text","text":serde_json::to_string_pretty(&rows).expect("catalog")} ]});
crate::agent_tools::prepare_tool_result(
"list_commands",
&json!({}),
&json!({"properties":{"offset":{"type":"integer"}}}),
&mut result,
Some(512),
);
let text = result["content"][0]["text"].as_str().expect("complete entry");
assert_eq!(serde_json::from_str::<Value>(text).expect("catalog"), rows);
assert!(text.len() > 512, "the existing delivery error must handle an entry that cannot fit whole");
}
#[test]
fn browser_tool_result_pages_requested_fields_even_without_command_ids() {
use serde_json::{Value, json};
let row = json!({"params":"Required parameter documentation. ".repeat(20)});
let args = json!({"fields":["params"]});
let expected = json!({"commands":[row],"total":2,"offset":0,"next_offset":1,"next_arguments":{"fields":["params"],"offset":1}});
let rows = json!([row, row]);
let mut result = json!({"content":[{"type":"text","text":serde_json::to_string_pretty(&rows).expect("catalog")}]});
let schema = json!({"properties":{"offset":{"type":"integer"}}});
crate::agent_tools::prepare_tool_result("list_commands", &args, &schema, &mut result, Some(expected.to_string().len() as u64));
let text = result["content"][0]["text"].as_str().expect("page");
assert_eq!(serde_json::from_str::<Value>(text).expect("complete row"), expected);
}
}
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<title>Attach a file</title>
<path d="M41 22L23 40C19 44 13 38 17 34L37 14C45 6 57 18 49 26L26 49C14 61 0 45 12 33L32 13" fill="none" stroke="currentColor" stroke-width="5.6" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 296 B

+1 -1
View File
@@ -4572,7 +4572,7 @@
"ui.agent_chat_mode_ask": "Ask",
"ui.agent_chat_mode_edits": "Edits",
"ui.agent_chat_model_custom": "Use custom: {model}",
"ui.agent_chat_model_no_tools": "{model} can't use SolidCraft's tools, so it can only chat. Pick a model with tool support.",
"ui.agent_chat_model_no_tools": "{model} can't use makeCAD's tools, so it can only chat. Pick a model with tool support.",
"ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}",
"ui.agent_chat_model_search": "Search models…",
"ui.agent_chat_model_tip": "The model the agent uses. Your choice is remembered for this agent.",
@@ -0,0 +1,34 @@
{
"en": {
"vm.agent.compact_catalog": "Load command details on demand",
"vm.agent.compact_catalog_hint": "Keep all commands and availability in the default catalog; read parameter details when needed. Explicit fields or compact options take priority. Turn this off to restore full catalog entries."
},
"zh": {
"vm.agent.compact_catalog": "按需读取命令详情",
"vm.agent.compact_catalog_hint": "默认目录保留全部命令和可用状态,需要时再读取参数详情。显式 fields 或 compact 参数优先。关闭后恢复完整目录条目。"
},
"ja": {
"vm.agent.compact_catalog": "必要に応じてコマンドの詳細を読み込む",
"vm.agent.compact_catalog_hint": "既定の一覧にはすべてのコマンドと使用可否を保持し、パラメーターの詳細は必要時に読み込みます。明示した fields または compact が優先されます。無効にすると完全な一覧に戻ります。"
},
"de": {
"vm.agent.compact_catalog": "Befehlsdetails bei Bedarf laden",
"vm.agent.compact_catalog_hint": "Der Standardkatalog behält alle Befehle und deren Verfügbarkeit. Parameterdetails werden bei Bedarf geladen. Explizite fields- oder compact-Optionen haben Vorrang. Deaktivieren stellt vollständige Einträge wieder her."
},
"ko": {
"vm.agent.compact_catalog": "필요할 때 명령 세부 정보 읽기",
"vm.agent.compact_catalog_hint": "기본 목록에 모든 명령과 사용 가능 상태를 유지하고 매개변수 세부 정보는 필요할 때 읽습니다. 명시한 fields 또는 compact 옵션이 우선합니다. 끄면 전체 목록 항목으로 복원됩니다."
},
"ar": {
"vm.agent.compact_catalog": "تحميل تفاصيل الأوامر عند الحاجة",
"vm.agent.compact_catalog_hint": "يحتفظ الفهرس الافتراضي بجميع الأوامر وحالة توفرها؛ تُقرأ تفاصيل المعاملات عند الحاجة. تكون الأولوية لخيارات fields أو compact الصريحة. عطّل هذا الخيار لاستعادة إدخالات الفهرس الكاملة."
},
"he": {
"vm.agent.compact_catalog": "טעינת פרטי פקודות לפי הצורך",
"vm.agent.compact_catalog_hint": "הקטלוג הרגיל שומר את כל הפקודות ואת זמינותן; פרטי הפרמטרים נטענים לפי הצורך. אפשרויות fields או compact מפורשות מקבלות עדיפות. כיבוי האפשרות מחזיר את הרשומות המלאות."
},
"vi": {
"vm.agent.compact_catalog": "Tải chi tiết lệnh khi cần",
"vm.agent.compact_catalog_hint": "Danh mục mặc định giữ tất cả lệnh và trạng thái khả dụng; chi tiết tham số được đọc khi cần. Tùy chọn fields hoặc compact được chỉ định rõ có ưu tiên cao hơn. Tắt để khôi phục các mục danh mục đầy đủ."
}
}
@@ -0,0 +1,34 @@
{
"en": {
"vm.agent.recovering": "The model connection was interrupted. Recovering the current task (retry {attempt}/2)…",
"vm.agent.correcting_tool": "The model tool call was invalid. Correcting it and continuing the current task (retry {attempt}/2)…"
},
"zh": {
"vm.agent.recovering": "模型连接暂时异常,正在恢复当前任务(重试 {attempt}/2)…",
"vm.agent.correcting_tool": "模型工具调用未通过校验,正在自动纠正并继续当前任务(重试 {attempt}/2)…"
},
"ar": {
"vm.agent.recovering": "حدث خلل مؤقت في اتصال النموذج. جارٍ استرداد المهمة الحالية (المحاولة {attempt}/2)…",
"vm.agent.correcting_tool": "استدعاء أداة النموذج غير صالح. جارٍ تصحيحه ومتابعة المهمة الحالية (المحاولة {attempt}/2)…"
},
"he": {
"vm.agent.recovering": "אירעה תקלה זמנית בחיבור למודל. מתבצע שחזור המשימה הנוכחית (ניסיון חוזר {attempt}/2)…",
"vm.agent.correcting_tool": "קריאת הכלי של המודל אינה תקינה. הקריאה מתוקנת והמשימה נמשכת (ניסיון חוזר {attempt}/2)…"
},
"ja": {
"vm.agent.recovering": "モデルへの接続が一時的に中断しました。現在のタスクを復旧しています(再試行 {attempt}/2)…",
"vm.agent.correcting_tool": "モデルのツール呼び出しが無効です。修正して現在のタスクを続行しています(再試行 {attempt}/2)…"
},
"de": {
"vm.agent.recovering": "Die Modellverbindung wurde unterbrochen. Die aktuelle Aufgabe wird wiederhergestellt (Wiederholung {attempt}/2)…",
"vm.agent.correcting_tool": "Der Werkzeugaufruf des Modells war ungültig. Er wird korrigiert und die Aufgabe fortgesetzt (Wiederholung {attempt}/2)…"
},
"ko": {
"vm.agent.recovering": "모델 연결에 일시적인 문제가 발생했습니다. 현재 작업을 복구하는 중입니다(재시도 {attempt}/2)…",
"vm.agent.correcting_tool": "모델의 도구 호출이 유효하지 않습니다. 수정한 후 현재 작업을 계속하는 중입니다(재시도 {attempt}/2)…"
},
"vi": {
"vm.agent.recovering": "Kết nối với mô hình tạm thời bị gián đoạn. Đang khôi phục tác vụ hiện tại (thử lại {attempt}/2)…",
"vm.agent.correcting_tool": "Lệnh gọi công cụ của mô hình không hợp lệ. Đang sửa và tiếp tục tác vụ hiện tại (thử lại {attempt}/2)…"
}
}
@@ -0,0 +1,50 @@
{
"en": {
"vm.agent.correcting_response": "The model response was invalid. Regenerating the current step (retry {attempt}/2)…",
"vm.agent.recovery_disabled": "Automatic recovery is disabled. Completed changes are kept.",
"vm.agent.recovery_request_limit": "This step still failed after 2 automatic retries. Completed changes are kept; you can continue from the current design.",
"vm.agent.recovery_turn_limit": "This task has used all 6 automatic retries. Completed changes are kept; you can continue from the current design."
},
"zh": {
"vm.agent.correcting_response": "模型响应未通过校验,正在重新生成当前步骤(重试 {attempt}/2)…",
"vm.agent.recovery_disabled": "自动恢复已关闭,已完成的修改已保留。",
"vm.agent.recovery_request_limit": "当前步骤自动重试 2 次后仍失败。已完成的修改已保留,可以从当前设计继续。",
"vm.agent.recovery_turn_limit": "当前任务已用完 6 次自动恢复机会。已完成的修改已保留,可以从当前设计继续。"
},
"ja": {
"vm.agent.correcting_response": "モデルの応答が検証に失敗しました。現在のステップを再生成しています(再試行 {attempt}/2)…",
"vm.agent.recovery_disabled": "自動復旧は無効です。完了した変更は保持されています。",
"vm.agent.recovery_request_limit": "このステップは自動再試行を 2 回行っても失敗しました。完了した変更は保持されており、現在の設計から続行できます。",
"vm.agent.recovery_turn_limit": "このタスクは自動再試行を 6 回使い切りました。完了した変更は保持されており、現在の設計から続行できます。"
},
"de": {
"vm.agent.correcting_response": "Die Modellantwort ist ungültig. Der aktuelle Schritt wird erneut erzeugt (Wiederholung {attempt}/2)…",
"vm.agent.recovery_disabled": "Die automatische Wiederherstellung ist deaktiviert. Abgeschlossene Änderungen bleiben erhalten.",
"vm.agent.recovery_request_limit": "Dieser Schritt ist nach 2 automatischen Wiederholungen weiterhin fehlgeschlagen. Abgeschlossene Änderungen bleiben erhalten; Sie können mit dem aktuellen Entwurf fortfahren.",
"vm.agent.recovery_turn_limit": "Diese Aufgabe hat alle 6 automatischen Wiederholungen verbraucht. Abgeschlossene Änderungen bleiben erhalten; Sie können mit dem aktuellen Entwurf fortfahren."
},
"ko": {
"vm.agent.correcting_response": "모델 응답이 검증에 실패했습니다. 현재 단계를 다시 생성하는 중입니다(재시도 {attempt}/2)…",
"vm.agent.recovery_disabled": "자동 복구가 꺼져 있습니다. 완료된 변경 사항은 유지됩니다.",
"vm.agent.recovery_request_limit": "이 단계는 자동으로 2번 재시도한 후에도 실패했습니다. 완료된 변경 사항은 유지되며 현재 설계에서 계속할 수 있습니다.",
"vm.agent.recovery_turn_limit": "이 작업은 자동 재시도 6회를 모두 사용했습니다. 완료된 변경 사항은 유지되며 현재 설계에서 계속할 수 있습니다."
},
"ar": {
"vm.agent.correcting_response": "لم تجتز استجابة النموذج التحقق. جارٍ إعادة إنشاء الخطوة الحالية (المحاولة {attempt}/2)…",
"vm.agent.recovery_disabled": "الاسترداد التلقائي معطّل. تم الاحتفاظ بالتغييرات المكتملة.",
"vm.agent.recovery_request_limit": "فشلت هذه الخطوة بعد محاولتي إعادة تلقائيتين. تم الاحتفاظ بالتغييرات المكتملة؛ يمكنك المتابعة من التصميم الحالي.",
"vm.agent.recovery_turn_limit": "استهلكت هذه المهمة جميع محاولات الاسترداد التلقائي الست. تم الاحتفاظ بالتغييرات المكتملة؛ يمكنك المتابعة من التصميم الحالي."
},
"he": {
"vm.agent.correcting_response": "תגובת המודל לא עברה אימות. השלב הנוכחי נוצר מחדש (ניסיון חוזר {attempt}/2)…",
"vm.agent.recovery_disabled": "השחזור האוטומטי כבוי. השינויים שהושלמו נשמרו.",
"vm.agent.recovery_request_limit": "השלב נכשל גם לאחר 2 ניסיונות חוזרים אוטומטיים. השינויים שהושלמו נשמרו; אפשר להמשיך מהתכנון הנוכחי.",
"vm.agent.recovery_turn_limit": "המשימה ניצלה את כל 6 ניסיונות השחזור האוטומטי. השינויים שהושלמו נשמרו; אפשר להמשיך מהתכנון הנוכחי."
},
"vi": {
"vm.agent.correcting_response": "Phản hồi của mô hình không hợp lệ. Đang tạo lại bước hiện tại (thử lại {attempt}/2)…",
"vm.agent.recovery_disabled": "Tự động khôi phục đã tắt. Các thay đổi đã hoàn tất được giữ lại.",
"vm.agent.recovery_request_limit": "Bước này vẫn thất bại sau 2 lần tự động thử lại. Các thay đổi đã hoàn tất được giữ lại; bạn có thể tiếp tục từ thiết kế hiện tại.",
"vm.agent.recovery_turn_limit": "Tác vụ này đã dùng hết 6 lần tự động khôi phục. Các thay đổi đã hoàn tất được giữ lại; bạn có thể tiếp tục từ thiết kế hiện tại."
}
}
@@ -0,0 +1,34 @@
{
"en": {
"vm.agent.stream_preview": "Show responses as they arrive",
"vm.agent.stream_preview_hint": "Preview unconfirmed text while the model responds. Failed attempts are cleared before retrying. Turn this off to show only complete responses."
},
"zh": {
"vm.agent.stream_preview": "实时显示模型正文",
"vm.agent.stream_preview_hint": "模型回复时预览尚未确认的正文,失败重试会清除临时文字。关闭后仅显示完整回复。"
},
"ja": {
"vm.agent.stream_preview": "応答をリアルタイムに表示",
"vm.agent.stream_preview_hint": "モデルの応答中に未確定の文章を表示します。失敗した試行の文章は再試行前に消去されます。無効にすると完全な応答だけを表示します。"
},
"de": {
"vm.agent.stream_preview": "Antworten während des Empfangs anzeigen",
"vm.agent.stream_preview_hint": "Zeigt unbestätigten Text während der Modellantwort an. Fehlgeschlagene Versuche werden vor dem nächsten Versuch gelöscht. Deaktivieren, um nur vollständige Antworten anzuzeigen."
},
"ko": {
"vm.agent.stream_preview": "응답을 실시간으로 표시",
"vm.agent.stream_preview_hint": "모델이 응답하는 동안 확인되지 않은 텍스트를 미리 표시합니다. 실패한 시도의 텍스트는 재시도 전에 지워집니다. 끄면 완성된 응답만 표시합니다."
},
"ar": {
"vm.agent.stream_preview": "عرض الاستجابات أثناء وصولها",
"vm.agent.stream_preview_hint": "معاينة النص غير المؤكد أثناء استجابة النموذج. يُحذف نص المحاولات الفاشلة قبل إعادة المحاولة. عطّل هذا الخيار لعرض الاستجابات المكتملة فقط."
},
"he": {
"vm.agent.stream_preview": "הצגת תגובות בזמן קבלתן",
"vm.agent.stream_preview_hint": "תצוגה מקדימה של טקסט שטרם אושר בזמן שהמודל משיב. טקסט של ניסיונות שנכשלו נמחק לפני ניסיון חוזר. כיבוי האפשרות מציג רק תגובות מלאות."
},
"vi": {
"vm.agent.stream_preview": "Hiển thị phản hồi ngay khi nhận được",
"vm.agent.stream_preview_hint": "Xem trước văn bản chưa được xác nhận trong khi mô hình phản hồi. Văn bản của lần thử thất bại sẽ bị xóa trước khi thử lại. Tắt để chỉ hiển thị phản hồi hoàn chỉnh."
}
}
@@ -0,0 +1 @@
| assets/icons/ui/design/svg/flat/paperclip.svg | makeCAD contributors | original attachment icon master (64 grid) | MIT OR Apache-2.0 |
+1
View File
@@ -0,0 +1 @@
| pelican-bicycle.html | makeCAD contributors | Original standalone HTML, SVG pelican and bicycle artwork, coastal scenery, controls and procedural animation; no external assets or dependencies | MIT OR Apache-2.0 |
+13 -1
View File
@@ -332,6 +332,7 @@ pub(crate) struct Followed {
visibility: crate::Visibility,
pending_moves: BTreeMap<u64, solidcraft_doc::Mat>,
revision: u64,
model_revision: u64,
}
/// A new design's id: one for this run, then a number, so no two designs of one run, or of two
@@ -360,12 +361,23 @@ impl Session {
Some(f) => f.revision,
None => {
let revision = NEXT_REVISION.fetch_add(1, Ordering::Relaxed);
let model_revision = self
.followed
.as_ref()
.filter(|f| std::ptr::eq(f.doc.as_ptr(), Arc::as_ptr(&self.doc)) && f.pending_moves == self.pending_moves)
.map_or(revision, |f| f.model_revision);
let (doc, visibility, pending_moves) = (Arc::downgrade(&self.doc), self.visibility.clone(), self.pending_moves.clone());
self.followed = Some(Followed { doc, visibility, pending_moves, revision });
self.followed = Some(Followed { doc, visibility, pending_moves, revision, model_revision });
revision
}
}
}
/// The model content revision, excluding visibility changes that only affect the view.
pub fn model_revision(&mut self) -> u64 {
let revision = self.design_revision();
self.followed.as_ref().map_or(revision, |f| f.model_revision)
}
}
/// `document.revision`: the design's id and [`Session::design_revision`].
+19
View File
@@ -40,6 +40,25 @@ fn rel(a: f64, b: f64) -> f64 {
(a - b).abs() / b.abs().max(1e-12)
}
#[test]
fn model_revision_excludes_visibility_but_keeps_document_and_placement_edits() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Part"}));
let document_revision = s.design_revision();
let model_revision = s.model_revision();
run(&mut s, "browser.visibility", json!({"items":["Part"],"visible":false}));
assert_ne!(s.design_revision(), document_revision, "document.revision must still report view changes");
assert_eq!(s.model_revision(), model_revision);
run(&mut s, "select.clear", json!({}));
s.refresh();
assert_eq!(s.model_revision(), model_revision);
run(&mut s, "solid.box", json!({"length":3,"width":4,"height":5,"body_name":"Next"}));
let edited_revision = s.model_revision();
assert_ne!(edited_revision, model_revision);
s.pending_moves.insert(1, solidcraft_doc::IDENTITY);
assert_ne!(s.model_revision(), edited_revision, "uncaptured placement edits must invalidate tools too");
}
#[test]
fn round_as_tall_as_a_disc_uses_up_its_wall() {
// #190: a disc 13 in radius and 2 high, its top edge rounded by 2.
+6
View File
@@ -0,0 +1,6 @@
#[path = "../../scripts/agent_skills.rs"]
mod agent_skills;
fn main() -> Result<(), Box<dyn std::error::Error>> {
agent_skills::generate()
}
+11 -11
View File
@@ -139,7 +139,7 @@ fn outcome(v: &Value) -> Result<Value, String> {
}
}
/// A running SolidCraft app reached through its loopback control port
/// A running makeCAD app reached through its loopback control port
/// (`solidcraft --control PORT`).
pub struct Remote {
addr: String,
@@ -166,7 +166,7 @@ pub struct Remote {
/// How a tool error starts when no app listens at the bridged address. The agent reads it, and
/// `batch` uses it to tell "never sent" from "sent, reply lost".
pub(crate) const NOT_RUNNING: &str = "no SolidCraft app is listening at";
pub(crate) const NOT_RUNNING: &str = "no makeCAD app is listening at";
impl Remote {
/// Connect to the app at `addr`, with its control token found the usual way
@@ -266,7 +266,7 @@ impl Remote {
)
} else {
format!(
"the SolidCraft app at {addr} did not answer ({e}): it may have quit or crashed during this call, after running it or not. Inspect the design before sending a change again; if the app quit, start it with `solidcraft --control {port}`"
"the makeCAD app at {addr} did not answer ({e}): it may have quit or crashed during this call, after running it or not. Inspect the design before sending a change again; if the app quit, start it with `solidcraft --control {port}`"
)
}
}
@@ -674,11 +674,11 @@ impl Backend for Remote {
}
fn describe(&self) -> String {
if self.conn.is_some() {
format!("connected to the SolidCraft app at {} (the user watches the viewport)", self.addr)
format!("connected to the makeCAD app at {} (the user watches the viewport)", self.addr)
} else {
// Still "connected to the SolidCraft app": the skills tell bridged from headless by it.
// Still "connected to the makeCAD app": the skills tell bridged from headless by it.
format!(
"connected to the SolidCraft app at {} once it runs (the user watches the viewport). It was not running \
"connected to the makeCAD app at {} once it runs (the user watches the viewport). It was not running \
when this server started; until it is (`solidcraft --control {}`), tool calls say so",
self.addr, self.port
)
@@ -865,7 +865,7 @@ impl Backend for Headless {
false
}
fn describe(&self) -> String {
"headless in-process SolidCraft session".into()
"headless in-process makeCAD session".into()
}
fn design_path(&self) -> Option<String> {
self.session.path.clone()
@@ -904,7 +904,7 @@ impl Auto {
return;
}
if let Some(port) = (self.discover)() {
solidcraft_engine::note!("solidcraft mcp: the SolidCraft app is running now; bridged to 127.0.0.1:{port}");
solidcraft_engine::note!("solidcraft mcp: the makeCAD app is running now; bridged to 127.0.0.1:{port}");
let level = self.param_check();
self.remote = Some(Remote::new(&format!("127.0.0.1:{port}"), self.token.as_deref()).with_param_check(level));
self.headless = None;
@@ -930,7 +930,7 @@ impl Backend for Auto {
match (&self.remote, &self.headless) {
(Some(r), _) => r.describe(),
(None, Some(h)) => format!(
"{}, because the SolidCraft app was not running when this server started; if it starts before any design work \
"{}, because the makeCAD app was not running when this server started; if it starts before any design work \
is done here, the next call is bridged to it",
h.describe()
),
@@ -963,8 +963,8 @@ impl Backend for Auto {
}
fn notice(&self) -> Option<String> {
self.headless.as_ref().map(|_| {
"Note: this is a headless session because the SolidCraft app was not found; the user cannot see this work. \
Ask them to start SolidCraft. While this session has no features, the next call connects to the app; once it \
"Note: this is a headless session because the makeCAD app was not found; the user cannot see this work. \
Ask them to start makeCAD. While this session has no features, the next call connects to the app; once it \
has work, it stays here."
.to_owned()
})
+9 -1
View File
@@ -1,4 +1,4 @@
//! SolidCraft MCP server.
//! makeCAD MCP server.
//!
//! JSON-RPC 2.0 over stdio (newline-delimited), implementing the MCP lifecycle, tools and
//! resources. Tools map onto the control-channel methods (`engine.execute`, `document.inspect`,
@@ -20,6 +20,14 @@ pub use options::{COMPACT_ENV, COMPACT_FLAG, Options};
pub use server::{PROTOCOL_VERSION, SUPPORTED_VERSIONS, Server};
pub use tools::{call_tool, call_tool_with, tool_definitions, tool_definitions_with};
/// The generation workflow shared with the desktop assistant and hosted model gateway.
pub const AGENT_WORKFLOW: &str = include_str!("../../../skills/agent-workflow.md");
/// Progressive skill discovery: instructions and metadata, not every reference in every turn.
pub fn agent_instructions() -> String {
format!("{AGENT_WORKFLOW}\n\nAvailable skills (read with skill_reference):\n{}", skill_reference::catalog())
}
use std::path::PathBuf;
use solidcraft_engine::io::vfs::{self, PathScope};
+6 -32
View File
@@ -26,36 +26,10 @@ const RESOURCE_NOT_FOUND: i64 = -32002;
/// Most messages in one JSON-RPC batch.
const MAX_BATCH: usize = 1000;
/// What every MCP client is told at `initialize`: how to plan, build and verify a part. It stays
/// version-neutral (no workaround for a quirk of the current kernel or solver: those belong in
/// `skills/solidcraft-modeling/reference.md`, which `skill_reference` serves per release), and
/// `tests::instructions_name_only_real_tools` checks every tool and command id it names.
const INSTRUCTIONS: &str = "SolidCraft is an independent parametric 3D CAD app, and these tools drive it: when its window is \
open the user watches the model appear, otherwise a headless session builds it. When asked to design or build a part, do it \
with these tools straight away. Units are millimetres and degrees in expressions, Z is up.\n\n\
Start: for anything beyond one primitive, call `skill_reference {\"skill\":\"solidcraft-modeling\"}` first (command shapes, \
ids, plane axes, worked examples and the known traps of this version; `file: \"SKILL.md\"` has the workflow). Then \
`inspect_design {\"measure\":false,\"sketches\":false}` to see what is already there.\n\n\
Plan: work the numbers out first (the parameters, the expected volume and bounding box after each stage, the world point you \
will use for each edge or face pick). Then build in a few `batch` calls (all-or-nothing; the reply names the failing step; \
`save`, `measure` and `set_parameter` can be steps). Use `verbose: false`. Name every feature. `list_commands {\"filter\": word}` \
gives ids and one-line parameter docs (never unfiltered: it also takes prefix, panel, compact: true and limit); `describe_command` gives one command's docs and schemas.\n\n\
Routes: a plate, block, boss, standoff or hole is cheapest as a primitive with expression fields (`solid.box`, `solid.cylinder`, \
`solid.hole`, `solid.fillet`, `solid.shell`, patterns and mirror), no sketch. Sketch when the profile is not a box or a circle. \
Fillet outside edges before shelling, build inside features after the shell, then the holes and cuts through walls. Give a blind \
hole or a hole through one wall of a hollow part its depth.\n\n\
Parametric: a size or position that must follow a parameter is an expression in a feature field (`\"L/2 - 10\"`), a sketch \
dimension to `\"origin\"` or an edge, or a pattern spacing; a plain number never follows a parameter. Every sketch must end at \
dof 0 (`sketch.solve` reports it). A pick (`edges: [[x,y,z]]`, `faces: [[x,y,z]]`) is a number that snaps to the nearest edge \
or face and follows it when parameters change.\n\n\
Verify: `measure {}` after each stage and compare volume and bbox with your numbers; `ok: true` alone proves nothing: a cut \
that leaves the volume unchanged has missed, a join that adds a body did not touch. Positions of holes and bosses come from \
`body_topology` (cylinder origin, axis and radius), not from the volume or the centre of mass of a symmetric part. To check \
that the design follows its parameters, `check_parameters {\"set\": {name: value}}` tries the values and puts the design \
back (volume, errors, cylinder axes), or change them in one `batch` with `coalesce_parameters: true` (one rebuild), `measure`, \
then set them back the same way before saving.\n\n\
Fix, don't rebuild: a wrong number in a feature is changed with `timeline.edit` or `parameters.change` on its input \
(`parameters.list {\"filter\":\"feature\"}` names them); `edit.checkpoint` and `edit.restore_checkpoint` go back exactly.\n\n\
/// Transport-specific capabilities stay separate from the shared generation workflow.
const MCP_NOTE: &str = "These tools drive makeCAD: with its window open the user watches the model appear; otherwise a headless session builds it. \
Use only advertised tools. File operations follow this server's allowed paths and the client's approval policy. \
`save`, `measure` and `set_parameter` may be batch steps when available. \
A call whose error starts `still running:` was not cancelled: don't send it again; `pending` waits for its result.";
pub struct Server {
@@ -238,8 +212,8 @@ impl Server {
Ok(json!({
"protocolVersion": version,
"capabilities": {"tools": {"listChanged": false}, "resources": {"listChanged": false}},
"serverInfo": {"name": "solidcraft", "title": "SolidCraft", "version": env!("CARGO_PKG_VERSION")},
"instructions": format!("{INSTRUCTIONS} Backend: {}.", self.backend.describe()),
"serverInfo": {"name": "solidcraft", "title": "makeCAD", "version": env!("CARGO_PKG_VERSION")},
"instructions": format!("{}\n\n{MCP_NOTE} Backend: {}.", crate::agent_instructions(), self.backend.describe()),
}))
}
"ping" => Ok(json!({})),
+23 -27
View File
@@ -1,46 +1,37 @@
//! Read-only access to the skill documents shipped with SolidCraft.
//! Read-only access to every skill document shipped with makeCAD.
use serde_json::{Map, Value};
struct Skill {
name: &'static str,
description: &'static str,
files: &'static [(&'static str, &'static str)],
}
// Exact names only: these are embedded documents, never filesystem paths to open.
const SKILLS: &[Skill] = &[
Skill {
name: "solidcraft-checking",
files: &[
("SKILL.md", include_str!("../../../skills/solidcraft-checking/SKILL.md")),
("reference/porting.md", include_str!("../../../skills/solidcraft-checking/reference/porting.md")),
],
},
Skill { name: "solidcraft-editing", files: &[("SKILL.md", include_str!("../../../skills/solidcraft-editing/SKILL.md"))] },
Skill {
name: "solidcraft-mechanisms",
files: &[
("SKILL.md", include_str!("../../../skills/solidcraft-mechanisms/SKILL.md")),
("reference.md", include_str!("../../../skills/solidcraft-mechanisms/reference.md")),
],
},
Skill {
name: "solidcraft-modeling",
files: &[
("SKILL.md", include_str!("../../../skills/solidcraft-modeling/SKILL.md")),
("reference.md", include_str!("../../../skills/solidcraft-modeling/reference.md")),
],
},
];
// Generated at build time from skills/. Exact names only: no runtime paths are opened.
include!(concat!(env!("OUT_DIR"), "/skills.rs"));
pub(crate) fn catalog() -> String {
SKILLS
.iter()
.map(|skill| {
format!("- {}: {} Files: {}", skill.name, skill.description, skill.files.iter().map(|(file, _)| *file).collect::<Vec<_>>().join(", "))
})
.collect::<Vec<_>>()
.join("\n")
}
pub(crate) fn read(args: &Map<String, Value>) -> Result<Value, String> {
let name = args.get("skill").and_then(Value::as_str).ok_or("`skill` is required and must be a string")?;
// Existing MCP clients can finish a conversation after a product rename.
let canonical = name.strip_prefix("solidcraft-").map(|suffix| format!("makecad-{suffix}"));
let name = canonical.as_deref().unwrap_or(name);
let skill = SKILLS
.iter()
.find(|s| s.name == name)
.ok_or_else(|| format!("Unknown skill. Available skills: {}", SKILLS.iter().map(|s| s.name).collect::<Vec<_>>().join(", ")))?;
let file = match args.get("file") {
None | Some(Value::Null) => "reference.md",
None | Some(Value::Null) => "SKILL.md",
Some(Value::String(file)) => file,
Some(_) => return Err("`file` must be a string".into()),
};
@@ -48,3 +39,8 @@ pub(crate) fn read(args: &Map<String, Value>) -> Result<Value, String> {
format!("Unknown file for {}. Available files: {}", skill.name, skill.files.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", "))
})
}
#[cfg(test)]
pub(crate) fn documents() -> Vec<(&'static str, &'static str, &'static str)> {
SKILLS.iter().flat_map(|skill| skill.files.iter().map(move |(file, text)| (skill.name, *file, *text))).collect()
}
+44 -37
View File
@@ -481,21 +481,19 @@ fn handshake_and_tools_list() {
#[test]
fn skill_reference_returns_bundled_text_without_backend_calls() {
let mut b = Recorder { calls: Vec::new(), batch: Err("unused".into()) };
let docs = [
("solidcraft-modeling", "reference.md", include_str!("../../../skills/solidcraft-modeling/reference.md")),
("solidcraft-mechanisms", "reference.md", include_str!("../../../skills/solidcraft-mechanisms/reference.md")),
("solidcraft-checking", "reference/porting.md", include_str!("../../../skills/solidcraft-checking/reference/porting.md")),
("solidcraft-modeling", "SKILL.md", include_str!("../../../skills/solidcraft-modeling/SKILL.md")),
("solidcraft-mechanisms", "SKILL.md", include_str!("../../../skills/solidcraft-mechanisms/SKILL.md")),
("solidcraft-checking", "SKILL.md", include_str!("../../../skills/solidcraft-checking/SKILL.md")),
("solidcraft-editing", "SKILL.md", include_str!("../../../skills/solidcraft-editing/SKILL.md")),
];
let docs = crate::skill_reference::documents();
let names: std::collections::BTreeSet<_> = docs.iter().map(|(skill, _, _)| *skill).collect();
assert_eq!(names.len(), 17);
for required in ["makecad-modeling", "makecad-editing", "makecad-checking", "makecad-mechanisms", "makecad-reporting", "makecad-packaging"] {
assert!(names.contains(required), "{names:?}");
}
for (skill, file, expected) in docs {
let args = json!({"skill": skill, "file": file});
let r = crate::call_tool(&mut b, "skill_reference", &args);
assert_ne!(r["isError"], true, "{r}");
assert_eq!(r["content"][0]["text"], expected);
if file == "reference.md" {
assert!(!expected.contains(concat!("Solid", "Craft")), "legacy display name in {skill}/{file}");
if file == "SKILL.md" {
assert_eq!(crate::call_tool(&mut b, "skill_reference", &json!({"skill": skill})), r);
}
}
@@ -505,26 +503,28 @@ fn skill_reference_returns_bundled_text_without_backend_calls() {
#[test]
fn skill_reference_refuses_unknown_names_and_paths_with_available_choices() {
let mut s = server();
let skills = ["solidcraft-checking", "solidcraft-editing", "solidcraft-mechanisms", "solidcraft-modeling"];
for skill in ["unknown", "../solidcraft-modeling", "/tmp/solidcraft-modeling"] {
let skills: Vec<_> = crate::skill_reference::documents().into_iter().map(|(skill, _, _)| skill).collect();
for skill in ["unknown", "../makecad-modeling", "/tmp/makecad-modeling"] {
let r = raw_tool(&mut s, "skill_reference", json!({"skill": skill}));
assert_eq!(r["result"]["isError"], true, "{r}");
let text = r["result"]["content"][0]["text"].as_str().unwrap();
for available in skills {
for available in &skills {
assert!(text.contains(available), "{text}");
}
}
for file in ["missing.md", "../reference.md", "/etc/passwd", "reference/../reference.md"] {
let r = raw_tool(&mut s, "skill_reference", json!({"skill": "solidcraft-modeling", "file": file}));
let r = raw_tool(&mut s, "skill_reference", json!({"skill": "makecad-modeling", "file": file}));
assert_eq!(r["result"]["isError"], true, "{r}");
let text = r["result"]["content"][0]["text"].as_str().unwrap();
assert!(text.contains("Available files: SKILL.md, reference.md"), "{text}");
}
for (skill, files) in [("solidcraft-checking", "SKILL.md, reference/porting.md"), ("solidcraft-editing", "SKILL.md")] {
for skill in ["makecad-checking", "makecad-editing", "makecad-contributing"] {
let r = raw_tool(&mut s, "skill_reference", json!({"skill": skill}));
assert_eq!(r["result"]["isError"], true, "{r}");
assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains(files), "{r}");
assert_ne!(r["result"]["isError"], true, "{r}");
}
let old = raw_tool(&mut s, "skill_reference", json!({"skill":"solidcraft-modeling", "file":"reference.md"}));
let current = raw_tool(&mut s, "skill_reference", json!({"skill":"makecad-modeling", "file":"reference.md"}));
assert_eq!(old["result"], current["result"]);
}
#[test]
@@ -536,7 +536,14 @@ fn skill_reference_is_advertised_as_read_only() {
assert_eq!(t["annotations"]["destructiveHint"], false);
assert_eq!(t["annotations"]["openWorldHint"], false);
assert_eq!(t["inputSchema"]["required"], json!(["skill"]));
assert_eq!(t["inputSchema"]["properties"]["file"]["default"], "reference.md");
let init = call(&mut s, 2, "initialize", json!({"protocolVersion": PROTOCOL_VERSION, "capabilities": {}}));
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(crate::AGENT_WORKFLOW));
for (skill, _, _) in crate::skill_reference::documents() {
assert!(instructions.contains(skill), "missing catalog entry {skill}");
}
assert_eq!(t["inputSchema"]["properties"]["file"]["default"], "SKILL.md");
}
/// A URDF goes through `export` with its own options (#719).
@@ -2535,11 +2542,11 @@ fn compact_execute_uses_one_backend_call_and_keeps_removed_bodies() {
assert_eq!(v, json!({"feature": 7, "name": "Combine1", "created_bodies": [], "changed_bodies": ["Base"], "removed_bodies": ["Tool"]}));
}
/// The worked example in `skills/solidcraft-modeling/reference.md` is what agents copy, so it has
/// The worked example in `skills/makecad-modeling/reference.md` is what agents copy, so it has
/// to keep building with the volume the file documents, and follow a parameter change.
#[test]
fn skill_reference_example_builds_as_documented() {
let doc = include_str!("../../../skills/solidcraft-modeling/reference.md");
let doc = include_str!("../../../skills/makecad-modeling/reference.md");
let start = doc.find("{\"commands\":[").expect("the reference has a worked example");
let end = start + doc[start..].find("```").expect("the example's code block ends");
let example: Value = serde_json::from_str(&doc[start..end]).expect("the example is JSON");
@@ -2703,12 +2710,12 @@ fn sketch_plane_axes_match_the_skill_reference() {
}
}
/// The worked example in `skills/solidcraft-mechanisms/reference.md` is what agents copy: the
/// The worked example in `skills/makecad-mechanisms/reference.md` is what agents copy: the
/// actuator has to follow the hinge with the stroke the file computes, the mirrored panel its link,
/// and the drive has to stop where the rod reaches its limit.
#[test]
fn mechanisms_skill_example_moves_as_documented() {
let doc = include_str!("../../../skills/solidcraft-mechanisms/reference.md");
let doc = include_str!("../../../skills/makecad-mechanisms/reference.md");
let start = doc.find("{\"commands\":[").expect("the reference has a worked example");
let end = start + doc[start..].find("```").expect("the example's code block ends");
let example: Value = serde_json::from_str(&doc[start..end]).expect("the example is JSON");
@@ -2760,15 +2767,15 @@ fn mechanisms_skill_example_moves_as_documented() {
#[test]
fn skills_name_only_real_tools_and_commands() {
let docs = [
include_str!("../../../skills/solidcraft-modeling/SKILL.md"),
include_str!("../../../skills/solidcraft-modeling/reference.md"),
include_str!("../../../skills/solidcraft-editing/SKILL.md"),
include_str!("../../../skills/solidcraft-checking/SKILL.md"),
include_str!("../../../skills/solidcraft-checking/reference/porting.md"),
include_str!("../../../skills/solidcraft-mechanisms/SKILL.md"),
include_str!("../../../skills/solidcraft-mechanisms/reference.md"),
include_str!("../../../skills/solidcraft-reporting/SKILL.md"),
include_str!("../../../skills/solidcraft-reporting/reference/report-template.md"),
include_str!("../../../skills/makecad-modeling/SKILL.md"),
include_str!("../../../skills/makecad-modeling/reference.md"),
include_str!("../../../skills/makecad-editing/SKILL.md"),
include_str!("../../../skills/makecad-checking/SKILL.md"),
include_str!("../../../skills/makecad-checking/reference/porting.md"),
include_str!("../../../skills/makecad-mechanisms/SKILL.md"),
include_str!("../../../skills/makecad-mechanisms/reference.md"),
include_str!("../../../skills/makecad-reporting/SKILL.md"),
include_str!("../../../skills/makecad-reporting/reference/report-template.md"),
];
let mut s = server();
let tools: Vec<String> = tool_definitions().iter().filter_map(|t| t["name"].as_str()).map(str::to_owned).collect();
@@ -2967,7 +2974,7 @@ fn batch_falls_back_while_the_agent_cursor_is_shown() {
#[test]
fn batch_does_not_resend_after_a_transport_error() {
let (b, body, is_error) =
recorded_batch(Err("SolidCraft at 127.0.0.1:1: timed out".into()), json!({"commands": [{"command": "a.one"}, {"command": "a.two"}]}));
recorded_batch(Err("makeCAD at 127.0.0.1:1: timed out".into()), json!({"commands": [{"command": "a.one"}, {"command": "a.two"}]}));
assert_eq!(methods(&b), ["engine.batch"]);
assert!(is_error);
assert!(body.as_str().is_some_and(|t| t.contains("may have run") && t.contains("timed out")), "{body}");
@@ -3044,8 +3051,8 @@ fn a_bridge_made_before_the_app_runs_connects_once_it_does() {
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let addr = format!("127.0.0.1:{port}");
let mut remote = crate::Remote::new(&addr, Some("0123456789abcdef0123456789abcdef"));
// Still "connected to the SolidCraft app", which the skills read as bridged.
assert!(remote.describe().starts_with("connected to the SolidCraft app") && remote.describe().contains("not running"), "{}", remote.describe());
// Still "connected to the makeCAD app", which the skills read as bridged.
assert!(remote.describe().starts_with("connected to the makeCAD app") && remote.describe().contains("not running"), "{}", remote.describe());
let e = remote.call("engine.execute", json!({"command": "inspect.measure"})).unwrap_err();
assert!(e.starts_with(crate::backend::NOT_RUNNING) && e.contains(&format!("solidcraft --control {port}")), "{e}");
let batch = crate::call_tool(&mut remote, "batch", &json!({"commands": [{"command": "solid.box"}]}));
@@ -3707,7 +3714,7 @@ fn auto_session_bridges_to_a_late_app_only_while_empty() {
let text = |r: &Value| r["result"]["content"].as_array().unwrap().iter().filter_map(|c| c["text"].as_str()).collect::<Vec<_>>().join("\n");
let r = raw_tool(&mut s, "list_commands", json!({}));
assert!(text(&r).contains("headless session because the SolidCraft app was not found"), "{r}");
assert!(text(&r).contains("headless session because the makeCAD app was not found"), "{r}");
let init = call(&mut s, 1, "initialize", json!({}));
assert!(init["result"]["instructions"].as_str().unwrap().contains("was not running when this server started"));
@@ -3716,7 +3723,7 @@ fn auto_session_bridges_to_a_late_app_only_while_empty() {
let r = raw_tool(&mut s, "inspect_design", json!({}));
assert!(!text(&r).contains("headless session because"), "{r}");
assert!(s.backend().has_ui());
assert!(s.backend().describe().contains("connected to the SolidCraft app"));
assert!(s.backend().describe().contains("connected to the makeCAD app"));
// The headless session's `--param-check` level goes on checking the bridged calls.
let mut headless = Headless::default();
headless.session.param_check = solidcraft_engine::schema::ParamCheck::Strict;
@@ -3739,7 +3746,7 @@ fn auto_session_bridges_to_a_late_app_only_while_empty() {
assert_ne!(r["result"]["isError"], json!(true), "{r}");
port.set(Some(1));
let r = raw_tool(&mut s, "inspect_design", json!({}));
assert!(text(&r).contains("headless session because the SolidCraft app was not found"), "{r}");
assert!(text(&r).contains("headless session because the makeCAD app was not found"), "{r}");
assert!(!s.backend().has_ui());
}
+9 -7
View File
@@ -373,7 +373,7 @@ pub fn tool_definitions_with(opts: Options) -> Vec<Value> {
tool(
"crash_reports",
"Crash reports",
"SolidCraft's crash reports on this computer (the app's when connected to it). Without `id`: the list, newest \
"makeCAD's crash reports on this computer (the app's when connected to it). Without `id`: the list, newest \
first (id, kind, time, message, command, count, version, path, replayable). With `id`: the whole report: \
message, location, backtrace, app version and commit, system, the command that crashed and the recent ones, \
and design_path / replay_path when it can be replayed: `solidcraft-cli crashes replay <id>`, or \
@@ -441,7 +441,7 @@ pub fn tool_definitions_with(opts: Options) -> Vec<Value> {
"Save the design",
"Save the design to `path` or its current file (a design opened as .solidcraft keeps that name). New designs are .sc files. The default is a design container; a .json path selects plain JSON. Set format to container or json to override the path. \
By default the path must lie in one of the agent's folders: the folder of a design opened or saved in this session (not its hidden files), \
SolidCraft's recovery folder, or a folder this server was started with `--allow-path DIR`. For a folder outside them, ask the user \
makeCAD's recovery folder, or a folder this server was started with `--allow-path DIR`. For a folder outside them, ask the user \
to add `--allow-path` and that folder to this server's arguments in their MCP client configuration.",
obj(
json!({"path": string("Path to save to, e.g. part.sc (default: the current file)"), "format": {"type": "string", "enum": ["container", "json"], "description": "Design encoding (default: JSON for .json, container otherwise)"}}),
@@ -452,13 +452,15 @@ pub fn tool_definitions_with(opts: Options) -> Vec<Value> {
tool(
"skill_reference",
"Skill reference",
"Read a document of SolidCraft's bundled agent skills (solidcraft-modeling, solidcraft-mechanisms, \
solidcraft-editing, solidcraft-checking) from the copy built into SolidCraft. `file` defaults to reference.md; \
each skill also has SKILL.md. Unknown skills or files are refused with the available ones.",
&format!(
"Read a bundled makeCAD skill document. Defaults to SKILL.md. All skill resources are read-only text; scripts are not executed. \
Exact skill/file pairs only; unknown names return available choices.\n{}",
crate::skill_reference::catalog()
),
obj(
json!({
"skill": string("Skill name, such as solidcraft-modeling"),
"file": {"type": "string", "description": "Document of that skill", "default": "reference.md"},
"skill": string("Skill name, such as makecad-modeling"),
"file": {"type": "string", "description": "Document of that skill", "default": "SKILL.md"},
}),
&["skill"],
),
+7
View File
@@ -2,6 +2,9 @@
//! "unknown" when git is missing (a source tarball). Also one test per UI scenario file
//! (`tests/scenarios/*.json`), so adding a scenario needs no Rust edit.
#[path = "../../scripts/agent_skills.rs"]
mod agent_skills;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -39,6 +42,10 @@ fn main() {
eprintln!("themes: {e}");
std::process::exit(1);
}
if let Err(error) = agent_skills::generate() {
eprintln!("agent skills: {error}");
std::process::exit(1);
}
scenario_tests();
if let Err(e) = merged_locales() {
eprintln!("locales: {e}");
+30 -26
View File
@@ -3,8 +3,8 @@
//! reads messages; the process lives in `process.rs` and the state in `mod.rs`, so everything
//! here is plain data and tested without an agent.
//!
//! What SolidCraft says it can do (`clientCapabilities`): no file system and no terminal (the agent
//! reaches the design through SolidCraft's MCP server instead), and terminal login, so an agent
//! What makeCAD says it can do (`clientCapabilities`): no file system and no terminal (the agent
//! reaches the design through makeCAD's MCP server instead), and terminal login, so an agent
//! that needs one describes a command for the user to run rather than asking for a key.
use serde::Serialize;
@@ -151,7 +151,7 @@ pub fn initialize_params(version: &str) -> Value {
"auth": {"terminal": true},
"_meta": {"terminal-auth": true},
},
"clientInfo": {"name": "solidcraft", "title": "SolidCraft", "version": version},
"clientInfo": {"name": "solidcraft", "title": "makeCAD", "version": version},
})
}
@@ -161,7 +161,7 @@ pub fn initialize_params(version: &str) -> Value {
pub const BRIDGE_NAME: &str = "solidcraft-app";
/// Whether a permission question is about a tool of the chat's own MCP server, whose calls
/// SolidCraft's gate checks. The agent writes both values and ACP has nothing better to go on, so
/// makeCAD's gate checks. The agent writes both values and ACP has nothing better to go on, so
/// the test is strict: the whole title is the tool's name as the Claude adapter forms it
/// (`mcp__solidcraft-app__batch`), one word with no room for a command line, a path or other free
/// text, and the kind is `other` (the kind an MCP tool has) or not given. Any other title goes
@@ -224,16 +224,14 @@ pub fn wsl_path(path: &std::path::Path) -> std::path::PathBuf {
}
}
include!(concat!(env!("OUT_DIR"), "/skill_catalog.rs"));
/// What every session is told about where it is. An agent with no route for it in
/// [`session_new_params`] doesn't get it.
pub const SYSTEM_NOTE: &str = "You are running inside SolidCraft, a parametric 3D CAD application, as the user's assistant. \
The open design is reachable through the `solidcraft-app` MCP server: use its tools (list_commands, batch, execute, inspect_design, \
measure, screenshot, set_parameter, undo, skill_reference) to read and change the design the user is looking at, and verify with \
measure or inspect_design. Before building anything beyond one primitive, read `skill_reference` for `solidcraft-modeling` (its \
SKILL.md has the workflow, its reference.md the command shapes and this version's traps), work the numbers out first, and after \
each stage compare `measure` with them. Prefer one `batch` over many small calls. Saving, opening or exporting files waits for the user's approval in \
the chat, and each message allows a limited number of changes. Don't use shell or file tools: work through the SolidCraft tools. \
Keep answers short.";
pub const SYSTEM_NOTE: &str = "You are running inside makeCAD, a parametric 3D CAD application, as the user's assistant. \
The open design is reachable through the `solidcraft-app` MCP server. Use its advertised CAD tools to read and change the open design. \
Saving, opening or exporting files waits for the user's approval in the chat, and each message allows a limited number of changes. \
Don't use shell or file tools. Keep answers short.";
/// The most of the user's custom instructions (#8220) a session gets, in characters: the
/// Preferences field takes no more, and a longer text from an edited settings file is cut here.
@@ -244,14 +242,18 @@ pub const INSTRUCTIONS_LIMIT: usize = 4000;
pub fn system_note(instructions: &str) -> String {
let text: String = instructions.trim().chars().take(INSTRUCTIONS_LIMIT).collect();
let text = text.trim_end();
let note = format!(
"{SYSTEM_NOTE}\n\n{}\n\nAvailable skills (read with skill_reference):\n{AGENT_SKILL_CATALOG}",
include_str!("../../../../skills/agent-workflow.md")
);
if text.is_empty() {
return SYSTEM_NOTE.to_string();
return note;
}
format!("{SYSTEM_NOTE}\n\nThe user's custom instructions, set in SolidCraft's preferences:\n{text}")
format!("{note}\n\nThe user's custom instructions, set in makeCAD's preferences:\n{text}")
}
/// The Claude Code adapter's own tools that reach the computer rather than the design: turned off
/// for the session (`_meta.claudeCode.options.disallowedTools`), so it works through SolidCraft's.
/// for the session (`_meta.claudeCode.options.disallowedTools`), so it works through makeCAD's.
pub const CLAUDE_DISALLOWED_TOOLS: &[&str] =
&["Bash", "BashOutput", "KillShell", "Read", "Write", "Edit", "MultiEdit", "NotebookEdit", "Glob", "Grep", "WebFetch", "WebSearch", "Task"];
@@ -265,7 +267,7 @@ pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, ini
"systemPrompt": {"append": note},
// Hosts may opt a session out of "bypass permissions" (the Claude adapter reads it):
// every tool call the agent asks about reaches the panel.
// Its own shell and file tools are off: the agent works through SolidCraft's tools.
// Its own shell and file tools are off: the agent works through makeCAD's tools.
"claudeCode": {"options": {"allowDangerouslySkipPermissions": false, "disallowedTools": CLAUDE_DISALLOWED_TOOLS}},
});
if takes_antigravity_note(init)
@@ -420,7 +422,7 @@ pub fn auth_methods(init: &Value) -> Vec<AuthMethod> {
.map(|v| v.iter().take(16).filter_map(|x| x.get("name").and_then(Value::as_str).map(str::to_string)).collect())
.unwrap_or_default(),
},
// A key the agent would take from the client: SolidCraft never handles
// A key the agent would take from the client: makeCAD never handles
// keys, so this becomes "set it in your environment" instead.
_ if m.get("_meta").and_then(|x| x.get("api-key")).is_some() => {
let provider = m
@@ -736,7 +738,7 @@ mod tests {
assert_ne!(BRIDGE_NAME, "solidcraft");
assert!(SYSTEM_NOTE.contains(&format!("`{BRIDGE_NAME}` MCP server")), "{SYSTEM_NOTE}");
assert!(!SYSTEM_NOTE.contains("`solidcraft` MCP server"));
// The panel still recognises the bridge's tools as SolidCraft's (agents name them after
// The panel still recognises the bridge's tools as makeCAD's (agents name them after
// their server, e.g. `mcp__solidcraft-app__batch`).
assert!(BRIDGE_NAME.contains("solidcraft"));
assert!(is_bridge_tool(&format!("mcp__{BRIDGE_NAME}__batch"), Some("other")));
@@ -752,11 +754,11 @@ mod tests {
for title in [
"",
"solidcraft",
"SolidCraft",
"makeCAD",
"run solidcraft-cli; ls",
"solidcraft-cli --version",
"Edit ~/.local/share/solidcraft/agent-chat/work/notes.txt",
// A user's own MCP server (docs/mcp.md), which SolidCraft's gate doesn't see.
// A user's own MCP server (docs/mcp.md), which makeCAD's gate doesn't see.
"mcp__solidcraft__batch",
"mcp__solidcraft-live__batch",
"mcp__other__solidcraft-app",
@@ -835,8 +837,10 @@ mod tests {
/// ones leave the note as it is.
#[test]
fn custom_instructions_follow_the_note_trimmed_and_capped() {
assert_eq!(system_note(""), SYSTEM_NOTE);
assert_eq!(system_note(" \n\t "), SYSTEM_NOTE);
assert!(system_note("").starts_with(SYSTEM_NOTE));
assert!(system_note("").contains(include_str!("../../../../skills/agent-workflow.md")));
assert!(system_note("").contains("makecad-packaging"));
assert_eq!(system_note(" \n\t "), system_note(""));
let note = system_note("\n Use M3 screws.\nPrint flat side down. \n");
assert!(note.starts_with(SYSTEM_NOTE), "{note}");
assert!(note.ends_with("preferences:\nUse M3 screws.\nPrint flat side down."), "{note}");
@@ -856,17 +860,17 @@ mod tests {
assert!(!runs_in_wsl(&[]));
let wsl = |p: &str| wsl_path(std::path::Path::new(p)).to_string_lossy().into_owned();
assert_eq!(wsl(r"C:\Users\u\AppData\Local\SolidCraft\agent-chat\work"), "/mnt/c/Users/u/AppData/Local/SolidCraft/agent-chat/work");
assert_eq!(wsl(r"\\?\D:\Program Files\SolidCraft\solidcraft-cli.exe"), "/mnt/d/Program Files/SolidCraft/solidcraft-cli.exe");
assert_eq!(wsl(r"C:\Users\u\AppData\Local\makeCAD\agent-chat\work"), "/mnt/c/Users/u/AppData/Local/makeCAD/agent-chat/work");
assert_eq!(wsl(r"\\?\D:\Program Files\makeCAD\solidcraft-cli.exe"), "/mnt/d/Program Files/makeCAD/solidcraft-cli.exe");
assert_eq!(wsl("E:/designs"), "/mnt/e/designs");
assert_eq!(wsl("C:"), "/mnt/c/");
assert_eq!(wsl("/home/u/designs"), "/home/u/designs");
assert_eq!(wsl(r"\\server\share\x"), r"\\server\share\x");
let b = McpBridge { cli: r"C:\Program Files\SolidCraft\solidcraft-cli.exe".into(), port: 41234 };
let b = McpBridge { cli: r"C:\Program Files\makeCAD\solidcraft-cli.exe".into(), port: 41234 };
let p = session_new_params(&wsl_path(std::path::Path::new(r"C:\Users\u\work")), Some(&b.in_wsl()), &json!({}), SYSTEM_NOTE);
assert_eq!(p["cwd"], "/mnt/c/Users/u/work");
assert_eq!(p["mcpServers"][0]["command"], "/mnt/c/Program Files/SolidCraft/solidcraft-cli.exe");
assert_eq!(p["mcpServers"][0]["command"], "/mnt/c/Program Files/makeCAD/solidcraft-cli.exe");
assert_eq!(p["mcpServers"][0]["args"], json!(["mcp", "--connect", "127.0.0.1:41234"]));
}
+1 -1
View File
@@ -211,7 +211,7 @@ impl AcpBackend {
}
Incoming::ModeChanged(_) | Incoming::ModelChanged(_) | Incoming::ConfigOptions { .. } => {}
Incoming::Unsupported { rpc, method } => {
self.proc.send(&acp::reply_error(rpc, acp::METHOD_NOT_FOUND, &format!("SolidCraft does not serve `{method}`")));
self.proc.send(&acp::reply_error(rpc, acp::METHOD_NOT_FOUND, &format!("makeCAD does not serve `{method}`")));
}
Incoming::Ignored => {}
}
+1 -1
View File
@@ -61,7 +61,7 @@ impl Kind {
Kind::Anthropic => "anthropic",
}
}
/// Whether the agent is an endpoint SolidCraft talks to itself (either protocol).
/// Whether the agent is an endpoint makeCAD talks to itself (either protocol).
pub fn is_api(self) -> bool {
matches!(self, Kind::Api | Kind::Anthropic)
}
+9 -9
View File
@@ -1,6 +1,6 @@
//! The API backend (desktop only): a model behind an endpoint SolidCraft talks to itself, either
//! The API backend (desktop only): a model behind an endpoint makeCAD talks to itself, either
//! OpenAI-compatible (Ollama, LM Studio, OpenAI, any URL the user gives) or Anthropic-compatible
//! (the Anthropic Messages API, or an endpoint that speaks it). SolidCraft runs the tool loop
//! (the Anthropic Messages API, or an endpoint that speaks it). makeCAD runs the tool loop
//! itself, with the same tools the ACP agents get: it starts the same MCP server (`solidcraft-cli
//! mcp --connect` to the chat's own endpoint) and is its client, so every tool call passes the
//! same gate, limits and folder checks. The key, when there is one, comes from the system keychain
@@ -33,7 +33,7 @@ const MAX_HISTORY: usize = 240;
/// otherwise each attached view makes every later request bigger, until the endpoint refuses it.
const MAX_HISTORY_IMAGES: usize = 2;
/// How long one tool call may take (it may wait for the user's Allow, declined after four
/// minutes). It does not depend on the endpoint's request timeout: a tool call is SolidCraft's own
/// minutes). It does not depend on the endpoint's request timeout: a tool call is makeCAD's own
/// work and the user's answer, never a wait for the model, so a longer request timeout does not
/// need a longer tool timeout.
const TOOL_TIMEOUT: Duration = Duration::from_secs(330);
@@ -859,7 +859,7 @@ impl Worker {
/// One MCP request to the server; its `result`.
fn mcp_call(&mut self, method: &str, params: Value) -> Result<Value, String> {
let Some(m) = self.mcp.as_ref() else { return Err("no SolidCraft tools in this session".into()) };
let Some(m) = self.mcp.as_ref() else { return Err("no makeCAD tools in this session".into()) };
self.next += 1;
let id = self.next;
m.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
@@ -882,9 +882,9 @@ impl Worker {
}
return Ok(v.get("result").cloned().unwrap_or(Value::Null));
}
Ok(FromAgent::Exited(_)) => return Err("the SolidCraft tools stopped".into()),
Ok(FromAgent::Exited(_)) => return Err("the makeCAD tools stopped".into()),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) if std::time::Instant::now() < deadline => {}
Err(_) => return Err("the SolidCraft tools did not answer".into()),
Err(_) => return Err("the makeCAD tools did not answer".into()),
}
}
}
@@ -1580,7 +1580,7 @@ mod tests {
}
/// A scripted endpoint: one answer with a tool call, then a plain answer. The loop runs the
/// tool (here without SolidCraft tools: an unknown tool fails) and reports the turn's end.
/// tool (here without makeCAD tools: an unknown tool fails) and reports the turn's end.
#[test]
fn the_tool_loop_runs_calls_and_ends_the_turn() {
let answers = std::sync::Mutex::new(vec![
@@ -1738,7 +1738,7 @@ mod tests {
assert_eq!(sent[0]["messages"][0]["content"], super::super::acp::system_note("Use M3 screws."));
let roles: Vec<&str> = sent[1]["messages"].as_array().unwrap().iter().map(|m| m["role"].as_str().unwrap_or("")).collect();
assert_eq!(roles, ["system", "user"]);
assert_eq!(sent[1]["messages"][0]["content"], super::super::acp::SYSTEM_NOTE);
assert_eq!(sent[1]["messages"][0]["content"], super::super::acp::system_note(""));
assert_eq!(sent[1]["messages"][1]["content"], "two");
b.shutdown(true);
}
@@ -2679,7 +2679,7 @@ mod tests {
}
/// A scripted Anthropic endpoint: one answer with a tool call, then a plain answer. The loop
/// runs the tool (here without SolidCraft tools: an unknown tool fails) and reports the end.
/// runs the tool (here without makeCAD tools: an unknown tool fails) and reports the end.
#[test]
fn the_anthropic_tool_loop_runs_calls_and_ends_the_turn() {
let answers = std::sync::Mutex::new(vec![
+12 -2
View File
@@ -51,7 +51,7 @@ pub enum PromptPart {
pub enum Event {
/// Whether the agent takes documents (PDFs) in a message; sent before [`Event::Ready`].
Documents(bool),
/// Whether SolidCraft tools were offered by the backend.
/// Whether makeCAD tools were offered by the backend.
ToolsAvailable(bool),
/// Ready for a message. `agent`: its name and version; `images`: it takes pictures.
Ready {
@@ -63,6 +63,8 @@ pub enum Event {
thought: bool,
text: String,
},
/// Hosted SSE preview. `None` clears unconfirmed text; never enters history.
TextPreview(Option<String>),
/// A new tool call, or news about one (`input`: its arguments, when the agent says).
Tool {
id: String,
@@ -112,6 +114,8 @@ pub enum Event {
TurnEnded {
reason: String,
},
/// Informational progress that does not end a turn or enter model history.
Notice(String),
/// Something failed; the backend is still running unless [`Event::Exited`] follows.
Error(String),
/// It ended; its last error output.
@@ -122,7 +126,7 @@ pub enum Event {
/// What a backend gets to start.
pub struct StartContext {
/// Its working folder: an empty folder of SolidCraft's own, not the user's files.
/// Its working folder: an empty folder of makeCAD's own, not the user's files.
pub cwd: std::path::PathBuf,
/// The MCP server that reaches this window (`solidcraft-cli mcp --connect` to the chat's own
/// endpoint), for backends that start MCP servers; `None` when it could not be set up.
@@ -157,6 +161,12 @@ pub trait ChatBackend {
fn set_mode(&mut self, _mode: &str) {}
/// An endpoint's new request timeout, in seconds, from the next request on.
fn set_request_timeout(&mut self, _secs: u64) {}
/// Recover transient hosted model failures without ending the current turn.
fn set_model_recovery(&mut self, _enabled: bool) {}
/// Show unconfirmed hosted SSE text; off preserves completed-only display.
fn set_stream_preview(&mut self, _enabled: bool) {}
/// Use a hosted discovery index, loading command parameters on demand.
fn set_compact_catalog(&mut self, _enabled: bool) {}
/// An endpoint's new reasoning effort (empty: send nothing), from the next request on.
fn set_reasoning_effort(&mut self, _effort: &str) {}
fn set_config_option(&mut self, _id: &str, _value: &str) {}
+1 -1
View File
@@ -90,7 +90,7 @@ impl Context {
return String::new();
}
let mut out = format!(
"[Selected in SolidCraft when this message was sent: {} item(s). The names, indices and points are the ones the tools take.]",
"[Selected in makeCAD when this message was sent: {} item(s). The names, indices and points are the ones the tools take.]",
self.total()
);
for kind in Kind::ALL {
+4 -4
View File
@@ -8,7 +8,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
/// An agent SolidCraft knows how to start in ACP mode.
/// An agent makeCAD knows how to start in ACP mode.
pub struct Known {
pub id: &'static str,
pub name: &'static str,
@@ -220,7 +220,7 @@ fn home() -> Option<PathBuf> {
}
/// PATH, then the usual places npm, Homebrew, nvm, Volta, bun, pipx and Grok put commands, and on
/// Windows Node's own install folders: a launcher can start SolidCraft with a PATH that lacks
/// Windows Node's own install folders: a launcher can start makeCAD with a PATH that lacks
/// them, and an npm agent's `.cmd` shim then can't find `node` (#9297).
pub fn search_dirs() -> Vec<PathBuf> {
search_dirs_in(&|name| std::env::var_os(name), cfg!(windows))
@@ -911,7 +911,7 @@ mod tests {
let _ = std::fs::remove_dir_all(root);
}
/// A launcher can start SolidCraft with a PATH that lacks Node (#9297). On Windows, Node's
/// A launcher can start makeCAD with a PATH that lacks Node (#9297). On Windows, Node's
/// install folders are searched after it, so `node` is found, and an agent started with these
/// folders as its PATH (`command_for`) finds it too.
#[test]
@@ -931,7 +931,7 @@ mod tests {
}
};
let dirs = search_dirs_in(&env, true);
assert_eq!(dirs.first(), Some(&system), "the PATH SolidCraft was given comes first");
assert_eq!(dirs.first(), Some(&system), "the PATH makeCAD was given comes first");
for node in [program_files.join("nodejs"), x86.join("nodejs"), nvm.clone()] {
assert!(dirs.contains(&node), "{} in {dirs:?}", node.display());
}
+41 -22
View File
@@ -1,9 +1,9 @@
//! Agent chat: a side panel that talks to a coding agent the user already has (Claude Code,
//! Codex, Antigravity, OpenCode, …) over the Agent Client Protocol, and gives that agent
//! SolidCraft's MCP server, bridged to this window, as its way to read and change the open design
//! makeCAD's MCP server, bridged to this window, as its way to read and change the open design
//! (docs/agent-chat.md, docs/design/in-app-agent-chat.md).
//!
//! Desktop only: the agent is a child process. Off unless turned on in Preferences. SolidCraft
//! Desktop only: the agent is a child process. Off unless turned on in Preferences. makeCAD
//! never handles the agent's credentials: an agent that needs a login says so, and the panel
//! shows the agent's own login command for the user to run.
//!
@@ -240,7 +240,7 @@ pub enum Item {
options: Vec<PermissionOption>,
answer: Option<String>,
},
/// A request of the agent's that SolidCraft holds for the user (files, replacing the design,
/// A request of the agent's that makeCAD holds for the user (files, replacing the design,
/// or any change while the mode is "ask"); `tool`: what "Always allow" remembers.
Approval {
id: u64,
@@ -345,6 +345,8 @@ pub struct AgentChat {
/// creating/opening a design may carry the conversation, but a person's tab switch may not.
pub(crate) following_document: bool,
pub items: Vec<Item>,
/// One hosted model attempt's unconfirmed text, separate from the transcript.
preview: Option<String>,
pub input: String,
/// The viewer, open on one message's pictures.
gallery: Option<Gallery>,
@@ -579,6 +581,9 @@ impl AgentChat {
fn files(&self) -> usize {
self.attachments.len() + self.loading.len()
}
fn files_loading(&self) -> bool {
!self.loading.is_empty() || self.browser_attachment.is_some()
}
/// Read a file for the next message on a worker thread, in the window's language.
#[cfg(not(target_arch = "wasm32"))]
fn load(
@@ -644,6 +649,7 @@ impl AgentChat {
}
fn stop_backend(&mut self, wait: bool) {
self.preview = None;
self.steering = false;
// The next agent starts without this one's memory of the design.
self.seen = None;
@@ -719,6 +725,9 @@ impl AgentChat {
self.mode = m;
}
}
Event::TextPreview(text) => {
self.preview = text;
}
Event::Text { thought, text } => {
if !thought
&& !text.trim().is_empty()
@@ -847,6 +856,7 @@ impl AgentChat {
}
Event::AuthStatus(s) => self.auth_status = Some(s),
Event::TurnEnded { reason } => {
self.preview = None;
if self.state() == State::Busy {
self.state = Some(State::Ready);
}
@@ -863,7 +873,9 @@ impl AgentChat {
}
return Some(Outcome::TurnEnd);
}
Event::Notice(message) => self.notice(message, false),
Event::Error(e) => {
self.preview = None;
self.notice(e, true);
match self.state() {
State::Starting | State::Failed => self.state = Some(State::Failed),
@@ -987,7 +999,7 @@ pub(crate) fn find_cli() -> Option<std::path::PathBuf> {
.or_else(|| discover::find_in("solidcraft-cli", &discover::search_dirs()))
}
/// The agent's working folder: an empty folder of SolidCraft's own, so an agent's own file tools
/// The agent's working folder: an empty folder of makeCAD's own, so an agent's own file tools
/// (where it has them) see nothing of the user's.
#[cfg(not(target_arch = "wasm32"))]
fn working_dir() -> std::path::PathBuf {
@@ -1186,7 +1198,7 @@ pub(crate) fn with_tool_request<T>(
let previous = std::mem::replace(&mut app.agent_chat.following_document, own);
let result = run(app);
if own && app.platform.enabled {
app.agent_chat.expected_revision = Some(app.session.design_revision());
app.agent_chat.expected_revision = Some(app.session.model_revision());
app.agent_chat.expected_doc = Some(app.session.doc.clone());
}
app.agent_chat.following_document = previous;
@@ -1381,7 +1393,7 @@ pub fn remove_picked(app: &mut SolveApp, at: usize) {
/// is working, else once it is ready (starting it if needed).
pub fn send(app: &mut SolveApp, ctx: &egui::Context, text: String) {
// A message waits for its files: the words go back in the box until they are read.
if !app.agent_chat.loading.is_empty() {
if app.agent_chat.files_loading() {
if app.agent_chat.input.trim().is_empty() {
app.agent_chat.input = text;
}
@@ -1517,6 +1529,7 @@ pub fn new_chat(app: &mut SolveApp) {
let chat = &mut app.agent_chat;
chat.confirm_new = false;
chat.items.clear();
chat.preview = None;
chat.turn_warning = None;
chat.gallery = None;
chat.picked.clear();
@@ -1606,7 +1619,7 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option<usi
// The undo step is named after the message, or its first file when it has no words.
let first_line = text.lines().find(|l| !l.trim().is_empty()).or_else(|| files.first().map(|f| f.name.as_str())).unwrap_or("");
let label: String = first_line.chars().take(48).collect();
app.agent_chat.expected_revision = Some(app.session.design_revision());
app.agent_chat.expected_revision = Some(app.session.model_revision());
app.agent_chat.expected_doc = Some(app.session.doc.clone());
app.agent_chat.turn_warning = None;
app.agent_chat.turn = Some(Turn {
@@ -1762,11 +1775,12 @@ pub fn cancel(app: &mut SolveApp) {
}
/// A human command ends the AI undo group before it changes the document. Read-only commands
/// and selection/camera navigation may continue; trusted assistant dispatch bypasses this hook.
/// and selection/camera/visibility navigation may continue; trusted assistant dispatch bypasses this hook.
pub(crate) fn before_command(app: &mut SolveApp, id: &str) {
if app.platform.enabled
&& !app.agent_chat.following_document
&& app.agent_chat.turn.is_some()
&& id != "browser.visibility"
&& (matches!(id, "edit.undo" | "edit.redo") || solidcraft_engine::command_specs().iter().any(|spec| spec.id == id && spec.undoable))
{
cancel(app);
@@ -1850,7 +1864,7 @@ pub fn answer_permission(app: &mut SolveApp, index: usize, option: Option<&str>)
}
/// The agent asks before running something of its own. The chat's own MCP tools are checked by
/// SolidCraft's gate, so they're allowed here (no double question, see [`acp::is_bridge_tool`]);
/// makeCAD's gate, so they're allowed here (no double question, see [`acp::is_bridge_tool`]);
/// otherwise the mode or an earlier "always allow" may answer, and the chat says so; otherwise the
/// user is asked.
fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str>, options: Vec<PermissionOption>) {
@@ -1886,7 +1900,7 @@ fn approve_with(app: &mut SolveApp, id: u64, allow: bool, why: &str) {
|| (!app.platform.is_locked()
&& app.platform.agent_context.is_some()
&& app.platform_snapshot_available()
&& app.agent_chat.expected_revision == Some(app.session.design_revision())));
&& app.agent_chat.expected_revision == Some(app.session.model_revision())));
let chat = &mut app.agent_chat;
let Some(i) = chat.held.iter().position(|h| h.id == id) else { return };
@@ -2028,11 +2042,7 @@ fn pump_tools(app: &mut SolveApp) {
}
let undo_left = undo_len.saturating_sub(turn.start_undo);
// The permission mode (the agent's own, else the global one) and "always allow" answers.
let mode = if app.platform.enabled && app.preferences.ai_permissions == agents::Mode::All {
agents::Mode::Edits
} else {
agents::mode_for(&app.preferences, &app.agent_chat.running_id)
};
let mode = if app.platform.enabled { agents::Mode::All } else { agents::mode_for(&app.preferences, &app.agent_chat.running_id) };
let tool = gate::tool_key(&req.method, &req.params);
let always = !app.platform.enabled && agents::always_allowed(&app.preferences, &app.agent_chat.running_id, &tool);
let verdict = match gate::request(&req.method, &req.params, undo_left) {
@@ -2124,9 +2134,14 @@ pub(crate) fn take_loaded(app: &mut SolveApp, ctx: &egui::Context) {
}
pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
// Selection, camera commands and refreshes also bump Session::revision. Only a change to
// the design invalidates a platform turn; otherwise a tool failure can stop its own recovery.
let revision = app.session.design_revision();
if let Some(backend) = app.agent_chat.backend.as_mut() {
backend.set_model_recovery(app.preferences.agent_model_recovery);
backend.set_stream_preview(app.preferences.agent_stream_preview);
backend.set_compact_catalog(app.preferences.agent_compact_catalog);
}
// Selection, visibility, camera commands and refreshes do not change model content.
// Only a model edit invalidates a platform turn, including edits outside this UI.
let revision = app.session.model_revision();
if app.platform.enabled && app.agent_chat.turn.is_some() && (app.platform.is_locked() || app.agent_chat.expected_revision != Some(revision)) {
if app.agent_chat.expected_revision != Some(revision) {
changed_outside_turn(app);
@@ -2170,7 +2185,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {
}
// AI features turned off: nothing keeps running, nothing is looked for.
if !shown(app) {
// Turned back on later, AI features don't connect as if SolidCraft were starting.
// Turned back on later, AI features don't connect as if makeCAD were starting.
app.agent_chat.connect_at_start = false;
crate::documents::disconnect_background_chats(app, false);
if app.agent_chat.backend.is_some() || app.agent_chat.open {
@@ -2789,7 +2804,7 @@ pub fn status(app: &SolveApp) -> Value {
"connectAtStart": app.preferences.agent_connect_at_start,
"openAtStart": app.preferences.agent_chat_open_at_start,
"lastAgent": app.preferences.agent_last,
"permissions": app.preferences.ai_permissions.id(),
"permissions": if app.platform.enabled { agents::Mode::All.id() } else { app.preferences.ai_permissions.id() },
"agents": agents::entries(app).iter().map(|e| json!({"id": e.id, "name": e.name, "kind": e.kind.id(), "found": e.found, "version": e.version, "login": e.login, "problem": e.problem, "request_timeout_s": e.kind.is_api().then_some(e.request_timeout_s)})).collect::<Vec<_>>(),
"currentAgent": agents::current(app).map(|e| e.id),
"models": c.models.iter().map(|m| json!({"id": m.id, "name": m.name, "description": m.description})).collect::<Vec<_>>(),
@@ -2826,6 +2841,7 @@ pub fn status(app: &SolveApp) -> Value {
});
// Added apart: `json!` has reached the compiler's recursion limit above.
if let Some(state) = state.as_object_mut() {
state.insert("textPreview".into(), json!(c.preview));
state.insert("modelsNote".into(), json!(c.models_note));
state.insert("customModels".into(), json!(custom_models_accepted(app)));
state.insert("instructions".into(), json!(app.preferences.agent_instructions));
@@ -2852,7 +2868,7 @@ pub(crate) fn platform_tool_valid(app: &mut SolveApp) -> bool {
if !app.platform.enabled {
return true;
}
if app.agent_chat.expected_revision != Some(app.session.design_revision()) {
if app.agent_chat.expected_revision != Some(app.session.model_revision()) {
changed_outside_turn(app);
return false;
}
@@ -2886,7 +2902,10 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) {
let platform =
backend::PlatformAgentContext { document_session_code, cad_project_code: app.platform.agent_project_code.clone(), capabilities };
match connect(platform, tx.clone(), ctx.clone()) {
Ok(backend) => {
Ok(mut backend) => {
backend.set_model_recovery(app.preferences.agent_model_recovery);
backend.set_stream_preview(app.preferences.agent_stream_preview);
backend.set_compact_catalog(app.preferences.agent_compact_catalog);
let chat = &mut app.agent_chat;
chat.backend = Some(backend);
chat.tools_tx = Some(tx);
+68 -42
View File
@@ -1006,39 +1006,43 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
Layout::left_to_right(Align::Center),
|ui| {
ui.set_min_height(Tokens::get().control_height + Tokens::get().space_2);
add_menu(app, ui);
let agent =
if state.running() { Some(app.agent_chat.running_id.clone()) } else { agents::current(app).map(|entry| entry.id) };
let mode = agent.as_deref().map_or(app.preferences.ai_permissions, |id| agents::mode_for(&app.preferences, id));
let permissions = ui
.allocate_ui(vec2(Tokens::get().space_24 * 4.0, Tokens::get().control_height), |ui| {
ui_kit::dropdown_menu(
ui,
"sc_agent_permissions",
tr(match mode {
agents::Mode::Ask => "ui.agent_chat_mode_ask",
agents::Mode::Edits => "ui.agent_chat_mode_edits",
agents::Mode::All => "ui.agent_chat_mode_all",
}),
|ui| {
for choice in agents::Mode::ALL {
if ui_kit::list_picker(ui, choice.id(), choice.label(), mode == choice).clicked() {
if let Some(id) = &agent {
app.preferences.agent_permissions.insert(id.clone(), choice);
} else {
app.preferences.ai_permissions = choice;
if app.platform.enabled {
attachment_button(app, ui);
} else {
add_menu(app, ui);
let agent =
if state.running() { Some(app.agent_chat.running_id.clone()) } else { agents::current(app).map(|entry| entry.id) };
let mode = agent.as_deref().map_or(app.preferences.ai_permissions, |id| agents::mode_for(&app.preferences, id));
let permissions = ui
.allocate_ui(vec2(Tokens::get().space_24 * 4.0, Tokens::get().control_height), |ui| {
ui_kit::dropdown_menu(
ui,
"sc_agent_permissions",
tr(match mode {
agents::Mode::Ask => "ui.agent_chat_mode_ask",
agents::Mode::Edits => "ui.agent_chat_mode_edits",
agents::Mode::All => "ui.agent_chat_mode_all",
}),
|ui| {
for choice in agents::Mode::ALL {
if ui_kit::list_picker(ui, choice.id(), choice.label(), mode == choice).clicked() {
if let Some(id) = &agent {
app.preferences.agent_permissions.insert(id.clone(), choice);
} else {
app.preferences.ai_permissions = choice;
}
}
}
}
},
)
})
.inner;
let permissions = permissions.backing_on_hover_text(mode.label());
crate::scenario::publish_rect("agent_chat:permissions", permissions.rect);
crate::scenario::publish_handle("agent_chat:permissions", permissions.rect.center());
},
)
})
.inner;
let permissions = permissions.backing_on_hover_text(mode.label());
crate::scenario::publish_rect("agent_chat:permissions", permissions.rect);
crate::scenario::publish_handle("agent_chat:permissions", permissions.rect.center());
}
// A message waits for files still being read.
let reading = !app.agent_chat.loading.is_empty();
let reading = app.agent_chat.files_loading();
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let action = ui_kit::assistant_send(
ui,
@@ -1049,10 +1053,12 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
if busy {
crate::scenario::publish_handle("agent_chat:stopturn", action.rect.center());
stop_clicked = action.clicked();
let queued = ui_kit::button(ui, tr("ui.agent_chat_queue"), ui_kit::Button::Enabled(!reading));
crate::scenario::publish_rect("agent_chat:send", queued.rect);
crate::scenario::publish_handle("agent_chat:send", queued.rect.center());
send_clicked = queued.clicked();
if !app.platform.enabled {
let queued = ui_kit::button(ui, tr("ui.agent_chat_queue"), ui_kit::Button::Enabled(!reading));
crate::scenario::publish_rect("agent_chat:send", queued.rect);
crate::scenario::publish_handle("agent_chat:send", queued.rect.center());
send_clicked = queued.clicked();
}
} else {
crate::scenario::publish_rect("agent_chat:send", action.rect);
crate::scenario::publish_handle("agent_chat:send", action.rect.center());
@@ -1066,12 +1072,14 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
Layout::left_to_right(Align::Center).with_main_wrap(true),
|ui| {
ui.set_min_height(Tokens::get().control_height);
let upload =
ui_kit::button(ui, tr("ui.agent_chat_upload_attachment"), ui_kit::Button::Enabled(attachment_picker_enabled(app)))
.backing_on_hover_text(tr("ui.agent_chat_upload_attachment_tip"));
crate::scenario::publish_target("agent_chat:upload_attachment", upload.rect);
if upload.clicked() {
choose_attachment_file(app, ui.ctx());
if !app.platform.enabled {
let upload =
ui_kit::button(ui, tr("ui.agent_chat_upload_attachment"), ui_kit::Button::Enabled(attachment_picker_enabled(app)))
.backing_on_hover_text(tr("ui.agent_chat_upload_attachment_tip"));
crate::scenario::publish_target("agent_chat:upload_attachment", upload.rect);
if upload.clicked() {
choose_attachment_file(app, ui.ctx());
}
}
// A picture of the view goes with the message to agents that take pictures.
let images = app.agent_chat.images || !state.running();
@@ -1135,7 +1143,7 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
cancel(app);
}
// A message waits for files still being read, and files alone make a message.
let reading = !app.agent_chat.loading.is_empty();
let reading = app.agent_chat.files_loading();
let something = !app.agent_chat.input.trim().is_empty() || !app.agent_chat.attachments.is_empty();
if reading {
// Enter waits with the button.
@@ -1960,6 +1968,9 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
}
if let Some(text) = app.agent_chat.preview.as_deref().filter(|text| !text.is_empty()) {
ui_kit::assistant_prose(ui, |ui| super::markdown_view::show(ui, app.agent_chat.items.len(), text));
}
let (mut send_now_clicked, mut send_queue_clicked) = (false, false);
let mut remove: Option<usize> = None;
let mut edit_done: Option<(usize, Option<String>)> = None;
@@ -2259,7 +2270,7 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap<u64, egui::Tex
clicked
}
/// Both attachment entry points share the same quota and picker.
/// All attachment entry points share the same quota and picker.
fn attachment_picker_enabled(app: &SolveApp) -> bool {
let available = app.agent_chat.browser_attachment.is_none() && app.agent_chat.files() < attach::MAX_FILES;
#[cfg(target_arch = "wasm32")]
@@ -2267,6 +2278,21 @@ fn attachment_picker_enabled(app: &SolveApp) -> bool {
available
}
/// The hosted composer has one attachment action; clipboard pictures arrive through paste.
fn attachment_button(app: &mut SolveApp, ui: &mut egui::Ui) {
let response = ui
.add_enabled_ui(attachment_picker_enabled(app), |ui| {
let size = Tokens::get().control_height + Tokens::get().space_2;
let (rect, _) = ui.allocate_exact_size(vec2(size, size), Sense::hover());
ui_kit::quiet_icon_button_at(ui, rect, "paperclip", tr("ui.agent_chat_upload_attachment"))
})
.inner;
crate::scenario::publish_target("agent_chat:attachment", response.rect);
if response.clicked() {
choose_attachment_file(app, ui.ctx());
}
}
#[cfg(not(target_arch = "wasm32"))]
fn choose_attachment_file(app: &mut SolveApp, _ctx: &egui::Context) {
app.pick_file(tr("ui.agent_chat_attachable"), &attach::extensions(), |app, path| {
+7 -1
View File
@@ -500,6 +500,12 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
let model = app.platform.agent_capabilities.as_ref().and_then(|caps| caps["model"].as_str()).unwrap_or("VibeMake CAD Agent");
ui_kit::settings_section(ui, "platform_agent", tr("ui.agent_chat_pick"), |ui| {
ui_kit::text(ui, &trf("vm.agent.platform_mode", &[("model", model)]), ui_kit::Text::Inline);
let response = ui_kit::checkbox(ui, tr("vm.agent.stream_preview"), &mut app.preferences.agent_stream_preview)
.backing_on_hover_text(tr("vm.agent.stream_preview_hint"));
crate::scenario::publish_target("prefs:agent_stream_preview", response.rect);
let response = ui_kit::checkbox(ui, tr("vm.agent.compact_catalog"), &mut app.preferences.agent_compact_catalog)
.backing_on_hover_text(tr("vm.agent.compact_catalog_hint"));
crate::scenario::publish_target("prefs:agent_compact_catalog", response.rect);
});
return;
}
@@ -1986,7 +1992,7 @@ mod card_tests {
fn model_warning_only_for_explicitly_missing_tools() {
assert_eq!(
capability_warning("local:4b", Some(false)).as_deref(),
Some("local:4b can't use SolidCraft's tools, so it can only chat. Pick a model with tool support.")
Some("local:4b can't use makeCAD's tools, so it can only chat. Pick a model with tool support.")
);
assert_eq!(capability_warning("local:4b", Some(true)), None);
assert_eq!(capability_warning("local:4b", None), None);
+4 -4
View File
@@ -28,7 +28,7 @@ pub struct Units<'a> {
pub decimals: u8,
}
/// The call in words, or `None` when it is not one of SolidCraft's tools or says too little.
/// The call in words, or `None` when it is not one of makeCAD's tools or says too little.
/// `title`: the call's title as the agent gave it; `input`: its arguments; `output`: what it
/// returned (text); `done`: it completed (a finished save reads "Saved …", one still running
/// or failed "Save …").
@@ -39,8 +39,8 @@ pub fn summary(title: &str, input: Option<&Value>, output: Option<&str>, done: b
Some(clip(&text, MAX_SUMMARY))
}
/// SolidCraft's tool a title names: `mcp__<server>__<tool>` (an agent names MCP tools after their
/// server, which for SolidCraft's has `solidcraft` in it), or the in-app client's own `measure`,
/// makeCAD's tool a title names: `mcp__<server>__<tool>` (an agent names MCP tools after their
/// server, which for makeCAD's has `solidcraft` in it), or the in-app client's own `measure`,
/// `execute: solid.box`, `batch: …`.
pub fn tool_name(title: &str) -> Option<&str> {
let head = title.trim();
@@ -282,7 +282,7 @@ fn file_name(path: &str) -> Option<String> {
Some(word(path.rsplit(['/', '\\']).find(|p| !p.is_empty()).unwrap_or(path)))
}
/// A path in a temporary folder (`/tmp`, `%TEMP%`, macOS `/var/folders`) or one of SolidCraft's
/// A path in a temporary folder (`/tmp`, `%TEMP%`, macOS `/var/folders`) or one of makeCAD's
/// own scratch folders.
fn is_temp(path: &str) -> bool {
let p = path.replace('\\', "/").to_ascii_lowercase();
+163 -7
View File
@@ -45,6 +45,30 @@ fn browser_drop_results_preserve_all_files_and_respect_the_attachment_limit() {
assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES);
}
#[test]
fn a_pending_browser_attachment_keeps_the_prompt_until_its_files_are_ready() {
let mut app = SolveApp::new(Default::default(), Default::default());
let ctx = crate::fonts::test_context();
let (tx, rx) = channel();
receive_browser_attachments(&mut app, 1, rx);
send(&mut app, &ctx, "Use this reference".into());
assert_eq!(app.agent_chat.input, "Use this reference");
assert!(app.agent_chat.files_loading());
assert!(!app.agent_chat.items.iter().any(|item| matches!(item, Item::User { .. })));
tx.send(Ok(attach::Attachment {
id: 0,
name: "reference.txt".into(),
content: attach::Content::Text(Arc::new("reference".into())),
thumb: None,
}))
.unwrap();
drop(tx);
poll(&mut app, &ctx);
assert!(!app.agent_chat.files_loading());
assert_eq!(app.agent_chat.attachments.len(), 1);
assert_eq!(app.agent_chat.input, "Use this reference");
}
#[test]
fn clearing_a_chat_discards_its_pending_browser_file_receiver() {
let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
@@ -125,7 +149,7 @@ fn transcript_paste_does_not_insert_a_previously_copied_body() {
assert_eq!(h.app.session.undo.len(), undo);
// A deliberate click outside the panel returns ownership to CAD.
transcript_click(&mut h, egui::pos2(700.0, 500.0));
h.frame_with(vec![egui::Event::Paste("SolidCraft bodies".into())]);
h.frame_with(vec![egui::Event::Paste("makeCAD bodies".into())]);
assert_eq!(h.app.session.model.state().bodies.len(), 2, "{layout:?}: CAD paste still works after returning to the model");
}
}
@@ -171,7 +195,7 @@ fn transcript_shortcut_ownership_ends_when_the_panel_is_hidden() {
"minimized" => h.app.preferences.agent_chat_minimized = true,
_ => h.app.preferences.ai_features = false,
}
h.frame_with(vec![egui::Event::Paste("SolidCraft bodies".into())]);
h.frame_with(vec![egui::Event::Paste("makeCAD bodies".into())]);
assert_eq!(h.app.session.model.state().bodies.len(), 2, "{hidden}: the invisible panel must not retain CAD keys");
}
}
@@ -330,6 +354,45 @@ fn streamed_text_joins_and_tool_updates_change_their_call() {
assert!(matches!(&c.items[1], Item::Tool { title, status: Some(ToolStatus::Completed), output: Some(o), .. } if title == "batch" && o == "ok"));
}
#[test]
fn model_recovery_notices_keep_the_task_busy_and_the_preference_can_restore_immediate_failure() {
let mut c = chat();
c.state = Some(State::Busy);
assert!(c.on_event(Event::Notice("Recovering the current task".into())).is_none());
assert_eq!(c.state(), State::Busy);
assert_eq!(c.ended, None);
assert!(matches!(c.items.last(), Some(Item::Notice { error: false, .. })));
assert!(crate::prefs::Prefs::default().agent_model_recovery);
let restored: crate::prefs::Prefs = serde_json::from_value(json!({"agent_model_recovery":false})).unwrap();
assert!(!restored.agent_model_recovery);
}
#[test]
fn hosted_text_preview_never_commits_a_partial_attempt_or_changes_desktop_text() {
let mut c = chat();
c.state = Some(State::Busy);
c.on_event(Event::Text { thought: false, text: "Confirmed earlier step".into() });
c.on_event(Event::TextPreview(Some("Partial Chinese 正文".into())));
assert_eq!(c.preview.as_deref(), Some("Partial Chinese 正文"));
assert_eq!(c.items.len(), 1);
c.on_event(Event::TextPreview(None));
c.on_event(Event::Notice("Recovering".into()));
c.on_event(Event::TextPreview(Some("New attempt".into())));
assert_eq!(c.preview.as_deref(), Some("New attempt"));
c.on_event(Event::TextPreview(None));
c.on_event(Event::Text { thought: false, text: "Final response".into() });
assert!(c.preview.is_none());
assert!(matches!(&c.items[0], Item::Agent { text, .. } if text == "Confirmed earlier step"));
assert!(matches!(c.items.last(), Some(Item::Agent { text, .. }) if text == "Final response"));
c.on_event(Event::TextPreview(Some("Not yet validated".into())));
c.on_event(Event::TurnEnded { reason: "cancelled".into() });
assert!(c.preview.is_none());
assert_eq!(c.items.iter().filter(|item| matches!(item, Item::Agent { .. })).count(), 2);
assert!(crate::prefs::Prefs::default().agent_stream_preview);
let restored: crate::prefs::Prefs = serde_json::from_value(json!({"agent_stream_preview":false})).unwrap();
assert!(!restored.agent_stream_preview);
}
#[test]
fn a_sign_in_request_keeps_the_question_for_after_the_login() {
let mut c = chat();
@@ -343,6 +406,15 @@ fn a_sign_in_request_keeps_the_question_for_after_the_login() {
assert_eq!(files.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["motor.step"], "its files go again too");
}
#[test]
fn hosted_command_catalog_preference_defaults_on_and_can_restore_full_entries() {
assert!(crate::prefs::Prefs::default().agent_compact_catalog);
let restored: crate::prefs::Prefs = serde_json::from_value(json!({"agent_compact_catalog":false})).unwrap();
assert!(!restored.agent_compact_catalog);
let saved = serde_json::to_value(&restored).unwrap();
assert_eq!(saved["agent_compact_catalog"], false);
}
#[test]
fn a_plan_update_replaces_the_turns_plan() {
let mut c = chat();
@@ -694,7 +766,7 @@ fn permission_modes_decide_what_asks() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The agent's own questions: SolidCraft's tools are allowed (its gate checks them), an earlier
/// The agent's own questions: makeCAD's tools are allowed (its gate checks them), an earlier
/// "Always allow" answers by itself, and both leave a note; anything else is asked.
#[test]
fn the_agents_own_questions_are_answered_by_the_mode_or_asked() {
@@ -718,7 +790,7 @@ fn the_agents_own_questions_are_answered_by_the_mode_or_asked() {
assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "remembered");
}
/// A title that only mentions SolidCraft is no tool of SolidCraft's: in every mode but Allow
/// A title that only mentions makeCAD is no tool of makeCAD's: in every mode but Allow
/// everything the user is asked, and the mode still answers when it says to.
#[test]
fn a_title_that_mentions_solidcraft_goes_through_the_users_mode() {
@@ -3611,7 +3683,7 @@ fn an_attached_selection_goes_as_text_for_the_agent_and_as_chips_in_the_conversa
app.agent_chat.attach_selection = true;
send(&mut app, &ctx, "round this".into());
let prompt = script.calls().pop().expect("a prompt");
assert!(prompt.starts_with("prompt: round this\n\n[Selected in SolidCraft"), "{prompt}");
assert!(prompt.starts_with("prompt: round this\n\n[Selected in makeCAD"), "{prompt}");
for want in ["Elements:", "- Flat face ", "planar", "area ", "- Edge ", "length ", "name ", "Features:", "feature id", "Bodies:", "- Body1"] {
assert!(prompt.contains(want), "{want:?} missing from {prompt}");
}
@@ -4145,7 +4217,7 @@ fn the_picks_go_with_the_next_message_once() {
app.agent_chat.attach_selection = true;
send(&mut app, &ctx, "look at these".into());
let prompt = script.calls().pop().expect("a prompt");
assert!(prompt.starts_with("prompt: look at these\n\n[Selected in SolidCraft"), "{prompt}");
assert!(prompt.starts_with("prompt: look at these\n\n[Selected in makeCAD"), "{prompt}");
assert!(prompt.contains("3 item(s)"), "two picked and one more selected: {prompt}");
assert_eq!(prompt.matches("- Body1").count(), 1, "{prompt}");
let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") };
@@ -4507,7 +4579,7 @@ fn tool_cards_show_file_names_never_paths() {
assert_eq!(summary::plain_title("Read /tmp/claude-1000/scratch/out.txt"), "Read");
assert_eq!(summary::plain_title("ui.render: /var/folders/xy/T/shot.png"), "ui.render");
assert_eq!(summary::plain_title("Run mcp__x__y with a/b and /"), "Run mcp__x__y with a/b and /");
// SolidCraft's own file tools: the name alone; a temp file has none.
// makeCAD's own file tools: the name alone; a temp file has none.
assert_eq!(
said("export", json!({"path": "/home/me/cad/part.step"}), None).as_deref().map(|s| s.ends_with("part.step") && !s.contains('/')),
Some(true)
@@ -4823,6 +4895,56 @@ fn a_picture_only_prompt_and_a_thought_have_no_copy_message_action() {
assert!(h.widget("Copy message").is_none(), "nothing to click");
}
#[test]
fn platform_assistant_runs_allowed_tools_without_saved_permission_prompts() {
for saved in agents::Mode::ALL {
let (mut app, tx) = app_in_a_turn();
app.platform.enabled = true;
app.platform.agent_context = Some("test-binding".into());
app.preferences.ai_permissions = saved;
app.preferences.agent_permissions.insert(app.agent_chat.running_id.clone(), agents::Mode::Ask);
let response = ask(&tx, "engine.execute", boxed(0.0));
frame(&mut app);
assert_eq!(response.try_recv().unwrap()["ok"], true);
assert!(app.agent_chat.held.is_empty());
assert_eq!(app.session.model.state().bodies.len(), 1);
let forbidden = ask(&tx, "engine.execute", json!({"command":"file.open","params":{"path":"/tmp/other.sc"}}));
frame(&mut app);
let refused = forbidden.try_recv().unwrap();
assert_eq!(refused["ok"], false);
assert!(refused.to_string().contains("HOST_CAPABILITY_UNAVAILABLE"));
assert_eq!(app.preferences.ai_permissions, saved, "native preferences remain intact");
}
}
#[test]
fn platform_composer_has_one_attachment_action_and_no_permission_or_queue_button() {
for width in [821, 1440] {
for busy in [false, true] {
let mut h = narrow_chat();
h.app.home.open = false;
h.app.platform.enabled = true;
h.app.platform.agent_context = Some("test-binding".into());
h.app.agent_chat.state = Some(if busy { State::Busy } else { State::Ready });
h.call("ui.resize", json!({"width":width,"height":720}));
h.frames(4);
let panel = crate::scenario::rect_of("agent_chat:panel").expect("assistant panel");
let attachment = crate::scenario::handle_at("agent_chat:attachment").expect("single attachment action");
assert!(panel.contains(attachment));
for removed in ["add", "upload_attachment", "paste_picture", "permissions"] {
assert!(crate::scenario::handle_at(&format!("agent_chat:{removed}")).is_none(), "no {removed} button");
}
assert_eq!(status(&h.app)["permissions"], "all");
if busy {
assert!(crate::scenario::handle_at("agent_chat:stopturn").is_some());
assert!(crate::scenario::handle_at("agent_chat:send").is_none(), "no queue button while busy");
} else {
assert!(crate::scenario::handle_at("agent_chat:send").is_some());
}
}
}
}
#[test]
fn platform_turn_ignores_a_saved_local_assistant_change_limit() {
let (mut app, tx) = app_in_a_turn();
@@ -4955,6 +5077,40 @@ fn platform_refresh_and_selection_do_not_stop_error_recovery() {
assert!(platform_tool_valid(&mut app));
}
#[test]
fn platform_visibility_changes_keep_the_turn_and_the_latest_view() {
let mut app = SolveApp::new(Default::default(), Default::default());
app.run("solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Part"})).unwrap();
app.platform.enabled = true;
app.platform.agent_context = Some("test-binding".into());
start_turn(&mut app, "Continue the design".into(), false, None, Vec::new());
let active = app.agent_chat.turn.as_ref().unwrap().active.clone();
for visible in [false, true, false] {
app.run("browser.visibility", json!({"items":["Part"],"visible":visible})).unwrap();
poll(&mut app, &egui::Context::default());
assert!(active.load(std::sync::atomic::Ordering::Relaxed), "viewing must not cancel generation");
assert!(platform_tool_valid(&mut app));
}
with_tool_request(&mut app, Some(&active), |app| app.run("solid.box", json!({"length":3,"width":4,"height":5,"body_name":"Next"}))).unwrap();
assert!(app.session.visibility.hidden_bodies.iter().any(|name| name == "Part"));
assert_eq!(app.session.model.state().bodies.len(), 2);
assert!(active.load(std::sync::atomic::Ordering::Relaxed));
}
#[test]
fn platform_direct_visibility_changes_do_not_invalidate_a_queued_tool() {
let mut app = SolveApp::new(Default::default(), Default::default());
app.run("solid.box", json!({"length":2,"width":3,"height":4,"body_name":"Part"})).unwrap();
app.platform.enabled = true;
app.platform.agent_context = Some("test-binding".into());
start_turn(&mut app, "Continue the design".into(), false, None, Vec::new());
let active = app.agent_chat.turn.as_ref().unwrap().active.clone();
app.session.execute("browser.visibility", &json!({"items":["Part"],"visible":false})).unwrap();
poll(&mut app, &egui::Context::default());
assert!(active.load(std::sync::atomic::Ordering::Relaxed));
assert!(platform_tool_valid(&mut app));
}
#[test]
fn platform_failed_batch_can_be_corrected_after_rollback() {
let mut app = SolveApp::new(Default::default(), Default::default());
+6
View File
@@ -1570,6 +1570,12 @@ preference_settings! {
agent_chat_window: Option<[f32; 4]> = None, PAGE_ASSISTANT;
/// Changes the agent may make for one message; 0 is no limit.
agent_chat_turn_limit: u32 = crate::agent_chat::gate::DEFAULT_TURN_LIMIT, PAGE_ASSISTANT;
/// Retry transient hosted model failures. Off preserves immediate turn termination.
agent_model_recovery: bool = true, PAGE_ASSISTANT;
/// Preview hosted SSE text before validation. Off keeps completed-only display.
agent_stream_preview: bool = true, PAGE_ASSISTANT;
/// Hosted command discovery omits parameter docs; off restores full entries.
agent_compact_catalog: bool = true, PAGE_ASSISTANT;
/// Custom instructions (#8220): text the agent chat adds to its system note when a session
/// starts (`agent_chat::acp::system_note`). No page reset discards this user-authored text.
agent_instructions: String = String::new();
+4 -9
View File
@@ -307,16 +307,11 @@ completely (from the notification area) and start it again to load the servers.
### Agent skills
[`skills/`](https://github.com/bherbruck/solidcraft/tree/main/skills) holds five [Agent Skills](https://agentskills.io) for agents that model through this server:
- `solidcraft-modeling` covers building a new part.
- `solidcraft-editing` covers changing an existing design.
- `solidcraft-checking` adds checks for errors SolidCraft does not report, regression tests and porting, next to the other two.
- `solidcraft-mechanisms` covers assemblies: joints placed by world coordinates, motion links, closed loops such as actuators, contact sets and motion studies, checked against analytic values.
- `solidcraft-reporting` turns a problem the user hit into a bug report: it reproduces it in a fresh design, shrinks it to a minimal command script, checks the numbers with `measure` and a screenshot, and searches existing issues first.
`skills/` contains 17 makeCAD skills in the Agent Skills format. The model selects skills by task from the metadata catalog sent at MCP initialize and in the desktop assistant's system note. New parts use `makecad-modeling`, existing designs use `makecad-editing`, parametric validation uses `makecad-checking`, assemblies use `makecad-mechanisms`, and failures use `makecad-reporting`. The remaining skills cover repository development, commands, UI, formats, tests, safety, performance and packaging.
They cover the workflow, the command shapes, how to verify with `measure`, and the known traps. With them an agent builds a part in a few `batch` calls and reads far less output. To install them for Claude Code, copy the folders into `~/.claude/skills/`; [skills/README.md](https://github.com/bherbruck/solidcraft/blob/main/skills/README.md) has the details.
`skill_reference {"skill":"makecad-modeling"}` returns SKILL.md by default. Read `reference.md` explicitly for modeling and mechanisms; other exact file names are listed in the catalog. All skill text resources are embedded at build time. Unknown skill/file pairs and traversal paths are refused; no runtime filesystem is opened and scripts are returned as text, never executed. Lowercase legacy skill ids are accepted as compatibility aliases by MCP but never advertised.
The `skill_reference` tool returns these documents from the copies built into SolidCraft, so an agent without file access can follow them: `{"skill": "solidcraft-modeling"}` returns its `reference.md`, the default file. Mechanisms also has `reference.md`, checking has `reference/porting.md`, and every skill has `SKILL.md` (editing uses modeling's reference). It never reads a path from disk, and an unknown skill or file is refused with the available choices. SolidCraft's own chat turns the agent's file tools off, so this is how its agent reads the skills there. The instructions the server sends at `initialize` point agents at `skill_reference` first, then say how to plan the numbers, build in a few `batch` calls and verify each stage with `measure`; the same pointer is in the system note SolidCraft's own chat gives its agent.
`skills/agent-workflow.md` is the shared process for MCP, desktop and the hosted browser assistant: inspect, resolve ambiguity, calculate expected geometry, build stages, measure, test parameter ranges, repair and report. `scripts/sync-cad-ai-skills.mjs <community-root>` packages the same workflow and files for Java; `--check` verifies parity before deployment. Rebuild Java and WASM after changes. Host-specific capabilities and approval rules still apply; reading repository skills cannot grant the browser shell or file access.
## Tools
@@ -357,7 +352,7 @@ builds it.
| `undo`, `redo` | — | Undo / redo one change. |
| `pending` | — | Bridged: the result of a request that was still running when its call returned (an error starting `still running:`), waiting up to 60 s for it; `done: false` while it runs (call again), `pending: null` when nothing runs. See [Long-running requests](#long-running-requests). |
| `crash_reports` | `id?`, `limit?` | The crash reports on this computer, newest first; with `id`, the whole report (backtrace, command, recent commands, `design_path`/`replay_path`). See [crash-reports.md](crash-reports.md). |
| `skill_reference` | `skill`, `file?` (default `reference.md`) | Read a bundled skill document. Skills: `solidcraft-modeling`, `solidcraft-mechanisms`, `solidcraft-editing`, `solidcraft-checking`. |
| `skill_reference` | `skill`, `file?` (default `SKILL.md`) | Read an exact bundled document from any of the 17 skills advertised in the catalog. |
| `running` | - | What the app is running or has queued, for every client (`control.running`, see [control-protocol.md](control-protocol.md#limits)): each request's connection and id, method, command id or a batch's step count, `running_s` and `queued`, never its parameters. Answers at once while the app is busy: ask it when a call timed out before sending a change again. Headless: always `{"running": []}`. |
| `new_design` | `name?` | Start an empty design. |
| `open` | `path` | Open a `.sc` design (or a `.solidcraft` one from an earlier release), a STEP file (`.step`/`.stp`) as a new design holding its bodies (an Import base feature), or a 3MF/STL file as mesh bodies. |
+128
View File
@@ -92,3 +92,131 @@ npm run test:cad:assistant
最新一轮前端还原、最终构建、46 项 CAD 浏览器回归(含 26 项助手专项)及截图,参见 [前端还原验收记录](assistant-frontend-parity-2026-11-03.md)。此前的 38 项浏览器回归、完整 CI 的失败及未验收边界保留在 [上一轮 Web 助手验收记录](web-assistant-validation.md)。
下一阶段服务接口和原版事件映射,参见 [后端接入交接](assistant-backend-handoff.md)。该文档描述待实现服务,不代表当前已接入后端。
## Hosted tool result delivery
Hosted discovery defaults to an index of all matching commands: `id`, `label`, `tab`,
`panel`, `enabled`, `disabled_reason` and `planned` wherever present. Only parameter
documentation, icons and shortcuts are omitted. `describe_command` still provides the
complete parameter documentation and schema before execution. Filters and command order
are unchanged. Explicit `fields` or `compact` always take precedence; `compact:false`
requests full entries for one call. Direct `list_commands` steps inside `batch` use the
same default, without changing modification steps. Use a standalone catalog call for
byte-bounded paging. Native MCP, CLI and direct browser API assistants keep their defaults.
The account-scoped **Load command details on demand** preference defaults to true.
`ui.prefs {"agent_compact_catalog": false}` restores full entries for subsequent calls.
Existing history is unchanged. This reduces catalog bytes, not a guaranteed percentage
of an entire task's input tokens; precise schemas remain available when requested.
The hosted assistant honours the backend's positive toolResultTextBytes limit without
changing a CAD command or removing requested result fields. When a JSON text result is
too large, it first removes only whitespace outside strings. Number tokens, strings,
coordinates, object identifiers, errors and sketch contents remain unchanged. This does
not enable MCP's compact mode, which also changes sketch inspection defaults.
If a successful list_commands result still exceeds the limit and the advertised tool
schema supports offset, the browser returns complete command entries as a byte-bounded
page. Every requested field remains in each entry. total, offset and next_offset identify
the remaining matches; next_arguments preserves the original query conditions for the
next call. The assistant may describe and use a command already found without loading
unrelated pages, but must read the remaining pages before claiming exhaustive results
or that a command is absent. Result formatting never reruns the tool or modifies the design.
Other tools are not silently summarised. A command entry that cannot fit whole, an
unsupported paging schema or another result that remains too large retains the explicit
delivery error and the existing prohibition on replaying modifications. Missing or zero
limits do not introduce a frontend quota. Normal MCP and CLI output remains unchanged.
## Hosted model response recovery
The hosted assistant retries only model generation when a temporary provider failure,
network interruption, timeout or invalid model tool response occurs. Each model request gets at most two retries,
after one and two seconds; the whole task has a maximum of six retries. The task stays
busy during recovery. Stop, account/project changes and manual design edits cancel
recovery through the existing turn generation and document checks.
Every retry preserves the complete request, history, reasoning state, pictures and
model settings. Tool validation failures add only a bounded `context.modelRecovery`
diagnostic (`tool`, `rule`, `path`), so the model can correct the failed response.
No tool from that response has run. The diagnostic is kept across network retries
and cleared at the next successful model step. It contains no raw arguments or
rejected response text. When it cannot fit the advertised request limits, the
original request is retried without deleting any existing information.
Recovery never compacts semantic data or restarts the CAD tool loop.
Previously completed tool calls and their results remain in history. Failed attempts
are not committed to history or the transcript. Text deltas update a separate preview
for the current attempt immediately; tool announcements are published only after the
complete response passes validation. Each retry clears the previous preview, and
completed.output supplies the one confirmed answer. Stop and terminal failure also
clear unconfirmed text. The account-scoped agent_stream_preview preference defaults
to true; ui.prefs {"agent_stream_preview": false} restores completed-only display.
Desktop Event::Text handling is unchanged. The existing working indicator remains
visible while the response is being validated.
The backend adds `data.retryable` to SSE error events without changing error codes.
`CAD_AI_TIMEOUT`, `CAD_AI_INVALID_MODEL_TOOL` and explicitly transient
`CAD_AI_PROVIDER_FAILURE` errors can recover. Invalid model tool arguments, malformed
argument JSON, unknown tools and duplicate/reused call IDs are rejected before
execution and regenerated with safe schema feedback. Local output validation errors
also enter this path; document/turn/request identity checks remain terminal.
Older generic provider failures without the flag remain terminal because they also
cover authentication, output limits and refusals. Authentication, denied access,
gateway rate/concurrency limits, invalid input history, incompatible protocol, output limits and stale
contexts are not retried. Deploy the host frontend, engine and backend changes together.
Upstream HTTP 408, 429 and 5xx responses carry an explicit transient flag; gateway
CAD_AI_RATE_LIMITED and CAD_AI_BUSY remain terminal.
The host preserves the document revision for the same request object; the backend
provides explicit failure classification. General transport retries remain in the browser. Only the native Chat Completions
HTTP-400 compatibility path can resend once with reasoning_effort=none when the
provider names that parameter and no explicit effort is configured. Responses and
explicit settings never take this path; the original request deadline still applies.
The account-scoped `agent_model_recovery` preference defaults to `true`. Setting it
to `false` restores immediate termination on a failed request; it can be set through
`ui.prefs {"agent_model_recovery": false}`. Turning it off during backoff prevents
another attempt. No automatic recovery saves or rolls back the design.
## Hosted history budgets
The browser meters text using the gateway contract: message and tool-result text,
the complete tool-call envelope without opaque reasoning, and the host context.
The estimate includes the host's engine identifier, revision hash and nullable
record fields. The backend remains authoritative; its limits are not increased.
Before each model request, only a wire copy of history is compacted. Valid JSON
tool-result text loses whitespace outside strings. Exact duplicate Skill requests
and unchanged bodies keep one full copy. If the request still exceeds a text or
request-byte limit, already delivered command catalogues are replaced first by
requery receipts, then older command schemas. The latest tool-call group stays
complete. A receipt records the original query and requires a fresh description
before relying on omitted parameters; it never implies that geometry ran again.
At the start of each new user turn, the effective history is trimmed to a target of
240 items, or a lower positive backend historyItems limit. Whole oldest user turns
are removed, never part of a tool group. The current user turn and the visible
transcript are retained even when that turn alone is larger than the target. Only
the latest two images remain, subject to a lower backend image limit; earlier
images become the native explanatory text. If the per-request history-item limit
is reached during a turn, only old successful catalogue/schema call and result
pairs may be removed. Screenshots from an earlier user turn may be
omitted from the wire to make room for a new screenshot; user reference images
remain. Within the retained turns, the original user goal, all user messages, CAD execution
and inspection results, and the complete visible transcript are retained. If these conservative
steps cannot satisfy a backend limit, the task stops explicitly rather than
discarding the original goal or replaying CAD modifications.
## Native text bounds and retained extensions
Ordinary single-block prose tool results are bounded at 20,000 UTF-8 bytes with the
native truncation marker. Knowledge, Skills, structured JSON and mixed content keep
the existing complete-result protection and paging rules. Each completed tool result
is saved before the next tool runs. A later cancellation keeps completed pairs and
drops unanswered calls, without replaying operations or rolling the design back.
The knowledge_lookup extension, cad-knowledge-v1, catalogue, Markdown bodies and
permissions remain unchanged. Knowledge deduplication uses the effective history
actually sent to the model. When trimming removes a body, the model can read it
again. No summary service, persistence, web search or additional agent framework is
introduced. Oversized single turns still stop with an explicit resource-limit error.
+433
View File
@@ -0,0 +1,433 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f8f6ef">
<meta name="description" content="An original SVG animation of a very relaxed pelican riding a bicycle along the coast.">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='9' fill='%23f8f6ef'/%3E%3Ccircle cx='16' cy='16' r='8' fill='%23bb4f32'/%3E%3C/svg%3E">
<title>The coastal ride — A little motion</title>
<style>
:root {
color-scheme: light;
--paper: #f8f6ef;
--ink: #293e3c;
--muted: #63706a;
--line: #dcded3;
--orange: #bb4f32;
--sky: #e3eee7;
--sea: #a4c4bb;
--sea-light: #bfd5ca;
--sand: #eee4ca;
--road: #e4d7b8;
--sun: #e9b66d;
--bike: #cf674c;
--white: #fcfaf0;
--feather: #d4ddd3;
--bill: #edb45b;
--pouch: #e9a17b;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-width: 280px;
background: var(--paper);
color: var(--ink);
font-family: "Avenir Next", Avenir, "Segoe UI", sans-serif;
-webkit-font-smoothing: antialiased;
}
button { font: inherit; color: inherit; touch-action: manipulation; }
button:focus-visible { outline: 3px solid var(--orange); outline-offset: 5px; }
.page { width: min(1192px, calc(100% - 96px)); margin: 0 auto; }
.masthead {
display: flex; justify-content: space-between; align-items: center;
padding: 30px 0 24px; border-bottom: 1px solid var(--line); gap: 24px;
}
.wordmark { display: flex; align-items: center; gap: 11px; font-size: 16px; font-weight: 650; letter-spacing: -.5px; }
.brand-mark { width: 24px; height: 24px; color: var(--orange); }
.edition { font-size: 11px; letter-spacing: 1.9px; text-transform: uppercase; color: var(--muted); }
.intro { text-align: center; padding: 42px 0 31px; }
.eyebrow { margin: 0 0 13px; font-size: 10px; letter-spacing: 2.7px; font-weight: 600; color: var(--muted); }
h1 { margin: 0; font: 400 clamp(35px, 4.1vw, 57px)/1.14 Georgia, "Times New Roman", serif; letter-spacing: -2px; text-wrap: balance; }
h1 em { font-weight: 400; color: var(--orange); }
.subtitle { margin: 14px 0 0; font-size: 14px; color: var(--muted); letter-spacing: .1px; }
.scene {
position: relative; overflow: hidden; margin: 0;
border: 1px solid #ced9cc; border-radius: 18px; background: var(--sky);
}
.scene > svg { display: block; width: 100%; aspect-ratio: 2 / 1; }
.scene-label {
position: absolute; z-index: 1; top: 25px; left: 29px;
display: flex; align-items: center; gap: 9px;
font-size: 10px; letter-spacing: 1.8px; font-weight: 600;
}
.scene-label span { width: 5px; height: 5px; background: var(--ink); border-radius: 50%; }
.weather { left: auto; right: 29px; color: #50675d; font-weight: 400; letter-spacing: 1px; }
.scene-note { position: absolute; right: 28px; bottom: 22px; font: italic 15px Georgia, serif; color: #57604d; }
.console {
display: flex; align-items: center; justify-content: space-between;
padding: 21px 0; gap: 20px; border-bottom: 1px solid var(--line);
}
.caption { display: flex; gap: 16px; align-items: center; }
.number { font: 400 29px Georgia, serif; color: #7c8a7f; }
.caption-title { font-size: 13px; font-weight: 600; }
.status { margin-top: 5px; font-size: 11px; color: var(--muted); }
.status::before { content: ""; display: inline-block; width: 5px; height: 5px; margin-right: 7px; border-radius: 50%; background: #578067; vertical-align: 1px; }
[data-paused="true"] .status::before { background: #ad794c; }
.controls { display: flex; align-items: center; gap: 24px; }
.play-button {
display: flex; align-items: center; justify-content: center; gap: 9px;
min-width: 131px; min-height: 44px; padding: 10px 18px;
background: var(--ink); color: var(--paper); border: 1px solid var(--ink);
border-radius: 99px; font-size: 12px; font-weight: 500; cursor: pointer;
transition: background .18s, transform .18s;
}
.play-button:hover { background: #415b53; }
.play-button:active { transform: scale(.97); }
.play-button svg { width: 14px; height: 14px; }
.play-icon { display: none; }
[data-paused="true"] .play-icon { display: block; }
[data-paused="true"] .pause-icon { display: none; }
.speed-control { display: flex; gap: 3px; align-items: center; }
.speed-label { font-size: 10px; text-transform: uppercase; letter-spacing: 1.4px; color: var(--muted); margin-right: 10px; }
.speed-control button {
min-width: 44px; min-height: 44px; padding: 8px; cursor: pointer;
border-radius: 50%; border: 1px solid transparent; background: transparent;
font-size: 11px; transition: background .18s, border-color .18s;
}
.speed-control button:hover { background: #e9ecdf; }
.speed-control button[aria-pressed="true"] { border-color: #bec9b9; background: #e9ecdf; font-weight: 600; }
footer { display: flex; justify-content: space-between; gap: 20px; padding: 19px 0 26px; font-size: 10px; color: var(--muted); letter-spacing: .35px; }
kbd { font: inherit; border: 1px solid #d4d8cd; border-radius: 4px; padding: 2px 5px; margin-right: 5px; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
.outline { stroke: var(--ink); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.fine { fill: none; stroke: var(--ink); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
@media (min-width: 1600px) { .intro { padding-top: 54px; padding-bottom: 39px; } }
@media (max-width: 760px) {
.page { width: calc(100% - 40px); }
.masthead { padding: 23px 0 20px; }
.edition { font-size: 9px; letter-spacing: 1px; }
.intro { padding: 33px 0 25px; }
h1 { font-size: 41px; letter-spacing: -1.8px; }
.console { flex-wrap: wrap; gap: 18px; }
.controls { gap: 12px; }
.speed-label { display: none; }
}
@media (max-width: 540px) {
.page { width: calc(100% - 32px); }
.wordmark { font-size: 14px; gap: 8px; }
.edition { font-size: 8px; max-width: 95px; text-align: right; line-height: 1.6; }
.eyebrow { font-size: 8px; letter-spacing: 1.65px; }
h1 { font-size: 38px; }
.subtitle { font-size: 12px; }
.scene { border-radius: 13px; }
.scene > svg { aspect-ratio: 1.1; }
.scene-label { top: 18px; left: 18px; font-size: 8px; letter-spacing: 1.3px; }
.weather { display: none; }
.scene-note { bottom: 17px; right: 18px; font-size: 13px; }
.console { padding: 18px 0; }
.caption { gap: 12px; }
.controls { width: 100%; justify-content: space-between; }
.play-button { min-width: 137px; }
.speed-control { gap: 8px; }
footer { font-size: 9px; line-height: 1.6; }
.keyboard-hint { display: none; }
}
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; } }
</style>
</head>
<body>
<main class="page" id="ride" data-paused="false">
<header class="masthead">
<div class="wordmark">
<svg class="brand-mark" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4" fill="currentColor"/><g stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M12 1v3m0 16v3M1 12h3m16 0h3M4.2 4.2l2.1 2.1m11.4 11.4 2.1 2.1M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></g></svg>
a little motion
</div>
<div class="edition">Small scenes. Simple joys.</div>
</header>
<section class="intro" aria-labelledby="page-title">
<p class="eyebrow">A PELICAN, TWO WHEELS &amp; A SEA BREEZE</p>
<h1 id="page-title">Taking the <em>scenic</em> route.</h1>
<p class="subtitle">Nowhere to be. A lovely way to get there.</p>
</section>
<figure class="scene" aria-label="The coastal ride animation">
<div class="scene-label" aria-hidden="true"><span></span> THE COASTAL LOOP</div>
<div class="scene-label weather" aria-hidden="true">24°C &nbsp; / &nbsp; SEA BREEZE</div>
<svg id="landscape" viewBox="0 0 1200 600" role="img" aria-labelledby="scene-title scene-description">
<title id="scene-title">A pelican on a bicycle</title>
<desc id="scene-description">A white pelican with a long golden bill, a green cap and a rust-red scarf pedals a coral bicycle along a sunny coastal path. Its webbed feet follow the pedals, the wheels turn, and clouds, waves and coastal grasses drift past.</desc>
<defs>
<g id="cloud" fill="var(--white)"><path d="M0 21C0 12 9 6 18 9 22-8 46-7 52 9 65 1 81 9 79 21Z"/></g>
<g id="grass" fill="none" stroke-linecap="round" stroke-width="2.3"><path d="M0 0Q-3-21-17-30M0 0Q-1-35 8-44M0 0Q8-24 21-29"/><path d="M-17-30l-5-3m30-11 1-5m12 20 5-2"/></g>
<g id="gull" fill="none" stroke="#6b8579" stroke-width="2.3" stroke-linecap="round"><path d="M-17 3Q-7-7 0 2 7-7 17 3"/></g>
<g id="coast-strip">
<path d="M0 335Q110 307 220 331T460 335 700 325 940 330 1200 335V400H0Z" fill="#bdd0b9"/>
<path d="M0 354Q160 325 310 351T620 346 910 350 1200 354V409H0Z" fill="#d5ddc3"/>
<path d="M88 338v-32m-12 6 12-12 12 12" fill="none" stroke="#9bb69d" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<g id="wave-strip" fill="none" stroke="#e1e9da" stroke-width="2" stroke-linecap="round">
<path d="M35 311h79m43 0h17m130 12h91m-8-24h45m136 16h114m80-13h51m76 22h91m143-15h90m53 13h42"/>
</g>
<g id="road-strip" fill="none" stroke="#f7eed6" stroke-width="3" stroke-linecap="round">
<path d="M20 477h39m96 0h42m105 0h34m104 0h42m105 0h34m105 0h42m105 0h34m105 0h42m105 0h34m105 0h42"/>
</g>
<g id="verge-strip">
<use href="#grass" transform="translate(142 536) scale(1.1)" stroke="#819978"/>
<use href="#grass" transform="translate(947 527) scale(.8)" stroke="#819978"/>
<use href="#grass" transform="translate(1127 563) scale(1.2)" stroke="#9ba87b"/>
<path d="M322 536h18m-9 5h26m389-11h14m23 4h9" stroke="#c8bd98" stroke-width="2" stroke-linecap="round"/>
<ellipse cx="386" cy="514" rx="6" ry="3" fill="#c2b899"/><ellipse cx="861" cy="555" rx="9" ry="4" fill="#c2b899"/>
<g transform="translate(112 535)"><path d="M0 0v-16m0 3-8-6m8 2 7-7" fill="none" stroke="#819978" stroke-width="2"/><circle cx="-9" cy="-20" r="3" fill="#ca7953"/><circle cx="8" cy="-25" r="3" fill="#ca7953"/></g>
</g>
<g id="wheel-spokes" fill="none" stroke="#8c9a8b" stroke-width="1.6">
<path d="M0-85V85M-85 0H85M-60.1-60.1 60.1 60.1M-60.1 60.1 60.1-60.1M-32.5-78.5 32.5 78.5M-78.5-32.5 78.5 32.5M-78.5 32.5 78.5-32.5M-32.5 78.5 32.5-78.5"/>
<circle r="86" stroke="#899789" stroke-width="2"/>
<path d="M-5-83h10" stroke="var(--white)" stroke-width="5" stroke-linecap="round"/>
</g>
</defs>
<path fill="var(--sky)" d="M0 0h1200v600H0Z"/>
<circle cx="946" cy="145" r="49" fill="var(--sun)"/>
<circle cx="946" cy="145" r="62" fill="none" stroke="#d7dbc0" stroke-width="1"/>
<g id="clouds" opacity=".85"><use href="#cloud" x="174" y="137"/><use href="#cloud" transform="translate(687 81) scale(.7)"/><use href="#cloud" transform="translate(1103 195) scale(.6)"/><use href="#cloud" x="1374" y="137"/><use href="#cloud" transform="translate(1887 81) scale(.7)"/><use href="#cloud" transform="translate(2303 195) scale(.6)"/></g>
<g id="gulls"><use href="#gull" transform="translate(866 215) scale(.65)"/><use href="#gull" transform="translate(1020 232) scale(.45)"/><use href="#gull" transform="translate(301 227) scale(.55)"/></g>
<path d="M0 294Q260 290 600 294T1200 294V385H0Z" fill="var(--sea)"/>
<path d="M0 291Q260 287 600 291T1200 291" fill="none" stroke="#8faf9f" stroke-width="1.5"/>
<g id="waves"><use href="#wave-strip"/><use href="#wave-strip" x="1200"/></g>
<g id="coast"><use href="#coast-strip"/><use href="#coast-strip" x="1200"/></g>
<path d="M0 379Q330 363 600 378T1200 379V600H0Z" fill="var(--sand)"/>
<path d="M0 424Q300 415 600 424T1200 424V495Q900 486 600 495T0 495Z" fill="var(--road)"/>
<path d="M0 414Q300 405 600 414T1200 414" fill="none" stroke="#f9f2dd" stroke-width="3"/>
<g id="road"><use href="#road-strip"/><use href="#road-strip" x="1200"/></g>
<ellipse id="ground-shadow" cx="588" cy="527" rx="217" ry="11" fill="#56634b" opacity=".11"/>
<g id="cyclist">
<!-- The wheel centers, crank and feet share one coordinate system. -->
<g transform="translate(430 430)">
<circle r="95" fill="#faf4df" fill-opacity=".4" stroke="var(--ink)" stroke-width="8"/>
<circle r="89" fill="none" stroke="#f9f1dc" stroke-width="4"/>
<g id="rear-wheel"><use href="#wheel-spokes"/></g>
<circle r="6" fill="var(--ink)"/>
</g>
<g transform="translate(760 430)">
<circle r="95" fill="#faf4df" fill-opacity=".4" stroke="var(--ink)" stroke-width="8"/>
<circle r="89" fill="none" stroke="#f9f1dc" stroke-width="4"/>
<g id="front-wheel"><use href="#wheel-spokes"/></g>
<circle r="6" fill="var(--ink)"/>
</g>
<g id="back-leg" class="outline" stroke-width="3">
<path id="back-leg-shape" d="M533 264 507 363 555 410" fill="none" stroke="#bd8749" stroke-width="10"/>
<g id="back-foot" transform="translate(555 410)"><path d="M-15-5 3-8 25 2 9 7-15 4Z" fill="#c78b4a" stroke-width="2.5"/><path d="M4-5 13 3m-7-2 3 6" fill="none" stroke="#925f3b" stroke-width="1.5"/></g>
</g>
<g id="back-pedal"><path d="M539 427h24" stroke="#53645a" stroke-width="6" stroke-linecap="round"/></g>
<!-- Coral step-through bicycle, drawn with original vector paths. -->
<path d="M335 414A97 97 0 0 1 509 371M681 374A97 97 0 0 1 853 409" fill="none" stroke="#7e9483" stroke-width="5" stroke-linecap="round"/>
<path d="M430 430 527 315 580 425 430 430M527 315 705 321 580 425M705 321 760 430" fill="none" stroke="var(--ink)" stroke-width="12" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M430 430 527 315 580 425 430 430M527 315 705 321 580 425M705 321 760 430" fill="none" stroke="var(--bike)" stroke-width="7" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M527 315 512 277M705 321 694 279Q691 266 707 260L729 255" fill="none" stroke="var(--ink)" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="m716 259 19-5" fill="none" stroke="#9d6849" stroke-width="9" stroke-linecap="round"/>
<path d="M488 276Q513 270 539 275L539 282Q515 290 491 284Z" fill="#895e47" class="outline" stroke-width="2.5"/>
<path d="M704 271Q741 274 735 333" fill="none" stroke="#526a5c" stroke-width="1.5"/>
<circle cx="713" cy="262" r="6" fill="var(--bill)" stroke="var(--ink)" stroke-width="2"/>
<path d="M430 418h150a12 12 0 0 1 0 24H430a12 12 0 0 1 0-24Z" fill="var(--paper)" stroke="#82917e" stroke-width="2"/>
<path id="chain" d="M430 423h150a7 7 0 0 1 0 14H430a7 7 0 0 1 0-14Z" fill="none" stroke="#8f9c86" stroke-width="1.5" stroke-dasharray="2 5"/>
<circle cx="580" cy="425" r="23" fill="#718374" stroke="var(--ink)" stroke-width="2.5"/>
<circle cx="580" cy="425" r="16" fill="#cbd1b8" stroke="#344d42" stroke-width="1.5"/>
<g id="crank" transform="rotate(0 580 425)"><path d="M551 425h58" stroke="var(--ink)" stroke-width="5" stroke-linecap="round"/><circle cx="580" cy="425" r="5" fill="var(--paper)" stroke="var(--ink)" stroke-width="2"/></g>
<g id="front-leg" class="outline">
<path id="front-leg-shape" d="M533 264 501 363 609 425" fill="none" stroke="#e6a54e" stroke-width="11"/>
<path id="leg-highlight" d="M533 264 501 363 609 425" fill="none" stroke="#f3c374" stroke-width="4"/>
<g id="front-foot" transform="translate(609 425)"><path d="M-16-6 3-9 27 2 10 8-16 4Z" fill="var(--bill)" stroke-width="2.5"/><path d="M3-6 14 3M4-1 10 7" fill="none" stroke="#b17b38" stroke-width="1.5"/></g>
</g>
<path id="front-pedal" d="M597 432h25" stroke="var(--ink)" stroke-width="6" stroke-linecap="round"/>
<g id="pelican">
<path d="M443 239Q407 221 387 226L406 244 391 247Q415 269 448 263Z" fill="var(--feather)" class="outline"/>
<path d="M555 239C580 217 568 181 583 151C573 137 573 117 584 101C599 80 632 81 648 100C666 118 656 140 636 145C624 148 612 141 607 134C604 153 623 187 614 214C606 242 581 259 558 265Z" fill="var(--white)" class="outline"/>
<path d="M584 152Q584 187 594 201T580 239" fill="none" stroke="var(--feather)" stroke-width="12" stroke-linecap="round"/>
<path d="M412 245C428 229 436 197 465 184C497 167 533 179 552 200C580 223 579 259 550 275C509 296 450 280 427 267Z" fill="var(--white)" class="outline"/>
<path d="M420 252Q466 285 515 271Q540 263 551 248C538 279 484 295 443 270Z" fill="var(--feather)"/>
<path d="M444 230Q479 205 521 226Q540 238 543 254Q503 276 463 257Z" fill="#e9ece0" class="outline" stroke-width="2.5"/>
<path d="M460 237Q488 225 514 241M464 248Q486 240 507 250" class="fine" stroke="#a1b0a0" stroke-width="2"/>
<path d="M535 220C562 221 584 242 612 254L688 267Q700 265 703 273Q700 282 687 281L612 275C582 272 557 258 541 246Z" fill="var(--white)" class="outline" stroke-width="2.5"/>
<path d="m683 270 7 7m-15-7 7 8" class="fine" stroke-width="1.5"/>
<!-- The long bill and hanging throat pouch define the pelican silhouette. -->
<path d="M641 119 805 126Q785 144 758 151C711 181 664 165 641 131Z" fill="var(--pouch)" class="outline" stroke-width="2.5"/>
<path d="M644 105Q718 110 808 125L814 132Q727 136 644 127Z" fill="var(--bill)" class="outline" stroke-width="2.5"/>
<path d="M653 118 795 128" fill="none" stroke="#fff0bb" stroke-width="3" stroke-linecap="round"/>
<path d="M652 138Q684 161 727 154" fill="none" stroke="#c98261" stroke-width="2" stroke-linecap="round"/>
<circle cx="632" cy="109" r="8" fill="#e4c986"/>
<circle cx="633" cy="109" r="4" fill="var(--ink)"/>
<circle cx="634" cy="107.5" r="1.2" fill="var(--white)"/>
<path d="M624 96q8-4 14 0" class="fine" stroke-width="2"/>
<path d="M584 101Q584 78 608 77Q630 77 640 95L649 100Q611 94 584 101Z" fill="#789888" class="outline" stroke-width="2.5"/>
<path d="M589 96Q621 89 656 98Q653 105 636 103" fill="#9bb39b" class="outline" stroke-width="2.5"/>
<path d="M609 80q-6 7-5 14" fill="none" stroke="#527765" stroke-width="2"/>
<circle cx="608" cy="77" r="3.5" fill="var(--ink)"/>
<path id="scarf-tail" d="M590 168C562 169 550 145 519 154L528 167 514 173C545 166 559 190 588 181Z" fill="var(--bike)" stroke="var(--ink)" stroke-width="2.5" stroke-linejoin="round"/>
<path d="M581 157Q594 166 610 158L614 170Q596 181 582 171Z" fill="var(--bike)" class="outline" stroke-width="2.5"/>
<path d="M585 165q9 6 18 2" fill="none" stroke="#e8906a" stroke-width="2"/>
<path d="M584 166q-12-7-10 4t12 6" fill="var(--bike)" class="outline" stroke-width="2"/>
</g>
</g>
<g id="verge"><use href="#verge-strip"/><use href="#verge-strip" x="1200"/></g>
<g opacity=".35" fill="none" stroke="#fff9e7" stroke-width="1.5" stroke-linecap="round"><path d="M51 553h40m-18 8h17m956-67h25m-12 7h30"/></g>
</svg>
<div class="scene-note" aria-hidden="true">a good day to take it slow.</div>
<figcaption class="sr-only">An original, looping SVG coastal cycling scene. Use the controls below to pause the ride or change its speed.</figcaption>
</figure>
<section class="console" aria-label="Animation controls">
<div class="caption"><span class="number" aria-hidden="true">01</span><div><div class="caption-title">The coastal ride</div><div class="status" id="status" role="status" aria-live="polite">Just cruising along</div></div></div>
<div class="controls">
<button class="play-button" id="play-toggle" type="button" aria-controls="landscape" aria-keyshortcuts="Space">
<svg class="pause-icon" viewBox="0 0 16 16" aria-hidden="true"><path d="M5 3v10M11 3v10" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>
<svg class="play-icon" viewBox="0 0 16 16" aria-hidden="true"><path d="m5 2 9 6-9 6Z" fill="currentColor"/></svg>
<span id="play-label">Pause ride</span>
</button>
<div class="speed-control" role="group" aria-label="Animation speed">
<span class="speed-label" aria-hidden="true">Pace</span>
<button type="button" data-speed="0.5" aria-pressed="false" aria-label="Half speed">0.5×</button>
<button type="button" data-speed="1" aria-pressed="true" aria-label="Normal speed">1×</button>
<button type="button" data-speed="1.5" aria-pressed="false" aria-label="One and a half speed">1.5×</button>
</div>
</div>
</section>
<footer><span>Made of vectors &amp; a little imagination.</span><span class="keyboard-hint"><kbd>space</kbd> to pause &amp; wander</span><span>Enjoy the little things.</span></footer>
<noscript><p>This scene is drawn entirely in SVG. Enable JavaScript to start the bicycle animation and use the controls.</p></noscript>
</main>
<script>
(() => {
'use strict';
const byId = (id) => document.getElementById(id);
const parts = Object.fromEntries([
'ride', 'landscape', 'clouds', 'gulls', 'waves', 'coast', 'road', 'verge',
'cyclist', 'pelican', 'rear-wheel', 'front-wheel', 'crank', 'chain',
'front-leg-shape', 'back-leg-shape', 'leg-highlight', 'front-foot',
'back-foot', 'front-pedal', 'back-pedal',
'scarf-tail', 'ground-shadow', 'play-toggle', 'play-label', 'status'
].map((id) => [id, byId(id)]));
const speedButtons = [...document.querySelectorAll('[data-speed]')];
const motionPreference = window.matchMedia('(prefers-reduced-motion: reduce)');
const smallScreen = window.matchMedia('(max-width: 540px)');
let playing = !motionPreference.matches;
let speed = 1;
let elapsed = 0;
let previousTime = null;
let frameId = null;
const set = (id, name, value) => parts[id].setAttribute(name, value);
const move = (id, x, y = 0) => set(id, 'transform', `translate(${x.toFixed(3)} ${y.toFixed(3)})`);
const scroll = (id, distance) => move(id, -(distance % 1200));
// Solve the two leg segments so each webbed foot stays on its pedal.
function legPath(hip, foot) {
const upper = 112;
const lower = 110;
const dx = foot.x - hip.x;
const dy = foot.y - hip.y;
const distance = Math.max(.001, Math.hypot(dx, dy));
const cosine = (upper * upper + distance * distance - lower * lower) / (2 * upper * distance);
const angle = Math.atan2(dy, dx) + Math.acos(Math.max(-1, Math.min(1, cosine)));
const knee = { x: hip.x + Math.cos(angle) * upper, y: hip.y + Math.sin(angle) * upper };
return `M${hip.x} ${hip.y}L${knee.x.toFixed(3)} ${knee.y.toFixed(3)}L${foot.x.toFixed(3)} ${foot.y.toFixed(3)}`;
}
function render(t) {
const phase = t * 2.5;
const degrees = phase * 180 / Math.PI;
const bob = Math.sin(phase * 2) * 1.1;
const birdBob = Math.sin(phase * 2 - .5) * 1.7;
move('cyclist', 0, bob);
move('pelican', 0, birdBob);
set('rear-wheel', 'transform', `rotate(${t * 200})`);
set('front-wheel', 'transform', `rotate(${t * 200})`);
set('crank', 'transform', `rotate(${degrees} 580 425)`);
set('chain', 'stroke-dashoffset', (-t * 24).toFixed(3));
const front = { x: 580 + Math.cos(phase) * 29, y: 425 + Math.sin(phase) * 29 };
const back = { x: 580 - Math.cos(phase) * 29, y: 425 - Math.sin(phase) * 29 };
const hip = { x: 533, y: 264 + birdBob };
const frontPath = legPath(hip, front);
set('front-leg-shape', 'd', frontPath);
set('leg-highlight', 'd', frontPath);
set('back-leg-shape', 'd', legPath(hip, back));
move('front-foot', front.x, front.y - 5);
move('back-foot', back.x, back.y - 5);
set('front-pedal', 'd', `M${front.x - 12} ${front.y + 2}h25`);
// The rear arm is already part of the rotating crank; only its platform translates.
set('back-pedal', 'transform', `translate(${back.x - 551} ${back.y - 425})`);
set('ground-shadow', 'rx', (217 - bob * .8).toFixed(3));
const flutter = Math.sin(t * 5.5) * 5;
set('scarf-tail', 'd', `M590 168C562 ${169 + flutter} 550 ${145 - flutter} 519 ${154 + flutter}L528 ${167 + flutter} 514 ${173 + flutter}C545 ${166 + flutter} 559 ${190 - flutter} 588 181Z`);
scroll('clouds', t * 9);
scroll('waves', t * 34);
scroll('coast', t * 53);
scroll('road', t * (200 * Math.PI / 180 * 95));
scroll('verge', t * (200 * Math.PI / 180 * 95));
move('gulls', Math.sin(t * .55) * 9, Math.sin(t * 1.2) * 3);
}
function updateControls() {
parts.ride.dataset.paused = String(!playing);
parts['play-label'].textContent = playing ? 'Pause ride' : 'Resume ride';
parts.status.textContent = playing ? 'Just cruising along' : 'Taking in the view';
}
function tick(timestamp) {
frameId = null;
if (!playing || document.hidden) { previousTime = null; return; }
if (previousTime !== null) elapsed += Math.min((timestamp - previousTime) / 1000, .08) * speed;
previousTime = timestamp;
render(elapsed);
frameId = window.requestAnimationFrame(tick);
}
function schedule() {
if (playing && !document.hidden && frameId === null) frameId = window.requestAnimationFrame(tick);
}
function setPlaying(value) {
playing = value;
previousTime = null;
if (frameId !== null) window.cancelAnimationFrame(frameId);
frameId = null;
updateControls();
schedule();
}
parts['play-toggle'].addEventListener('click', () => setPlaying(!playing));
speedButtons.forEach((button) => button.addEventListener('click', () => {
speed = Number(button.dataset.speed);
speedButtons.forEach((item) => item.setAttribute('aria-pressed', String(item === button)));
}));
document.addEventListener('keydown', (event) => {
if (event.code === 'Space' && !event.repeat && !event.altKey && !event.ctrlKey && !event.metaKey &&
(event.target === document.body || event.target === document.documentElement)) {
event.preventDefault();
setPlaying(!playing);
}
});
document.addEventListener('visibilitychange', () => {
previousTime = null;
if (document.hidden && frameId !== null) { window.cancelAnimationFrame(frameId); frameId = null; }
schedule();
});
motionPreference.addEventListener('change', (event) => { if (event.matches) setPlaying(false); });
function updateViewBox() { set('landscape', 'viewBox', smallScreen.matches ? '280 0 660 600' : '0 0 1200 600'); }
smallScreen.addEventListener('change', updateViewBox);
updateViewBox();
render(0);
updateControls();
schedule();
})();
</script>
</body>
</html>
+64
View File
@@ -0,0 +1,64 @@
//! Embed the complete, sorted skill library without runtime filesystem access.
use std::{
env,
error::Error,
fs,
path::{Path, PathBuf},
};
fn files(directory: &Path) -> Result<Vec<PathBuf>, Box<dyn Error>> {
let mut result = Vec::new();
for entry in fs::read_dir(directory)? {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_symlink() {
return Err(format!("Skill resources may not be symlinks: {}", entry.path().display()).into());
}
if kind.is_dir() {
result.extend(files(&entry.path())?);
} else if kind.is_file() {
result.push(entry.path());
}
}
result.sort();
Ok(result)
}
pub fn generate() -> Result<(), Box<dyn Error>> {
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?).join("../../skills").canonicalize()?;
println!("cargo:rerun-if-changed={}", root.display());
let mut folders = fs::read_dir(&root)?.collect::<Result<Vec<_>, _>>()?;
folders.sort_by_key(|entry| entry.file_name());
let mut output = String::from("const SKILLS: &[Skill] = &[\n");
let mut catalog = Vec::new();
for entry in folders {
let folder = entry.path();
if !entry.file_type()?.is_dir() || !folder.join("SKILL.md").is_file() {
continue;
}
let name = entry.file_name().to_string_lossy().into_owned();
let text = fs::read_to_string(folder.join("SKILL.md"))?;
let description = text
.lines()
.find_map(|line| line.strip_prefix("description: "))
.ok_or_else(|| format!("Missing skill description: {name}"))?
.trim_matches('"');
output.push_str(&format!("Skill {{ name: {name:?}, description: {description:?}, files: &[\n"));
let paths = files(&folder)?;
let mut names = Vec::new();
for path in paths {
let relative = path.strip_prefix(&folder)?.to_string_lossy().replace('\\', "/");
names.push(relative.clone());
// Include only text resources. A new non-text asset must get an explicit transport.
fs::read_to_string(&path)?;
output.push_str(&format!("({relative:?}, include_str!({path:?})),\n"));
}
output.push_str("] },\n");
catalog.push(format!("- {name}: {description} Files: {}", names.join(", ")));
}
output.push_str("];\n");
let out = PathBuf::from(env::var("OUT_DIR")?);
fs::write(out.join("skills.rs"), output)?;
fs::write(out.join("skill_catalog.rs"), format!("const AGENT_SKILL_CATALOG: &str = {:?};\n", catalog.join("\n")))?;
Ok(())
}
+1 -1
View File
@@ -43,7 +43,7 @@ EMBEDDED = {
}
# Folders that only some packages read: the UI embeds the catalogs and xtask checks them; the MCP
# server's tests read the agent skills.
EMBEDDED_PREFIXES = {"assets/locales/": ("solidcraft-ui-egui", "xtask"), "skills/": ("solidcraft-mcp",)}
EMBEDDED_PREFIXES = {"assets/locales/": ("solidcraft-ui-egui", "xtask"), "skills/": ("solidcraft-mcp", "solidcraft-ui-egui", "xtask")}
# Test data and the package directories whose tests (or xtask) read it. Any other folder under
# tests/ selects the full workspace.
TEST_DATA = {
+1 -1
View File
@@ -127,7 +127,7 @@ class RealWorkspace(unittest.TestCase):
def test_embedded_root_files_select_their_crate(self):
for path, pkg in [("ATTRIBUTION.md", "solidcraft-ui-egui"), ("LICENSE-MIT", "solidcraft-engine"),
("NOTICE", "solidcraft-engine"), ("THIRD-PARTY-LICENSES.txt", "solidcraft-engine"),
("skills/solidcraft-modeling/SKILL.md", "solidcraft-mcp")]:
("skills/makecad-modeling/SKILL.md", "solidcraft-mcp")]:
full, pk = affected.select(self.meta, [path])
self.assertFalse(full, path)
self.assertIn(pkg, pk, path)
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env node
// One source for native MCP, desktop, WASM and the packaged Java model gateway.
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync, lstatSync, writeFileSync, mkdirSync } from 'node:fs';
import { resolve, dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const args = process.argv.slice(2);
if (args.some((arg) => arg.startsWith('--') && arg !== '--check')) throw new Error('Unknown option. Usage: node scripts/sync-cad-ai-skills.mjs [--check] <community-root>');
const check = args.includes('--check');
const paths = args.filter((arg) => arg !== '--check');
if (paths.length !== 1) throw new Error('Usage: node scripts/sync-cad-ai-skills.mjs [--check] <community-root>');
const communityRoot = resolve(paths[0]);
if (!readFileSync(join(communityRoot, 'pom.xml'), 'utf8').includes('<artifactId>vibemake</artifactId>')) throw new Error('Target must be the community Maven project root');
const skillsRoot = join(root, 'skills');
const walk = (folder, prefix = '') => readdirSync(folder).sort().flatMap((name) => {
const path = join(folder, name), relative = prefix + name, stat = lstatSync(path);
if (stat.isSymbolicLink()) throw new Error(`Skill resource is a symlink: ${relative}`);
return stat.isDirectory() ? walk(path, relative + '/') : [[relative, readFileSync(path, 'utf8')]];
});
const skills = readdirSync(skillsRoot).sort().filter((name) => lstatSync(join(skillsRoot, name)).isDirectory()).map((name) => {
const files = Object.fromEntries(walk(join(skillsRoot, name)));
const entry = files['SKILL.md'];
if (!entry) throw new Error(`Missing SKILL.md: ${name}`);
const declared = entry.match(/^name:\s*(.+)$/m)?.[1];
const description = entry.match(/^description:\s*(.+)$/m)?.[1].replace(/^"|"$/g, '');
if (declared !== name || !description || !/^makecad-[a-z-]+$/.test(name)) throw new Error(`Invalid skill metadata: ${name}`);
if (Object.values(files).some((text) => text.includes('Solid' + 'Craft'))) throw new Error(`Legacy display name in ${name}`);
return { name, description, files };
});
const source = { formatVersion: 1, workflow: readFileSync(join(skillsRoot, 'agent-workflow.md'), 'utf8'), skills };
const revision = createHash('sha256').update(JSON.stringify(source)).digest('hex');
const bundle = JSON.stringify({ ...source, revision }, null, 2) + '\n';
const target = resolve(communityRoot, 'vibemake-service/src/main/resources/cad/ai/skills.json');
if (check) {
if (readFileSync(target, 'utf8') !== bundle) throw new Error('Packaged skills differ from the MCP/desktop source. Run the sync command before building.');
} else {
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, bundle);
}
console.log(`${check ? 'Verified' : 'Synchronized'} ${skills.length} skills, revision ${revision}`);
+43 -32
View File
@@ -1,32 +1,32 @@
# Agent skills
Skills for contributing to SolidCraft and modelling through its [MCP server](../docs/mcp.md). Each folder is
Skills for contributing to makeCAD and modelling through its [MCP server](../docs/mcp.md). Each folder is
one skill in the [Agent Skills](https://agentskills.io) format: a `SKILL.md` with a name and a
description that tell the agent when to load it, and an optional supporting reference file.
The modelling documents are built into SolidCraft: its MCP server's `skill_reference` tool returns them, so an
agent without file access (such as the one in SolidCraft's own chat) can still read a skill's reference.
The contributor skills (everything except modeling, editing, checking and mechanisms) are for repository work and are not embedded in that tool. `AGENTS.md` routes to them; `cargo xtask skills` fails when its table and this folder disagree or a file, `cargo xtask` command or skill they name is gone.
The modelling documents are built into makeCAD: its MCP server's `skill_reference` tool returns them, so an
agent without file access (such as the one in makeCAD's own chat) can still read a skill's reference.
All 17 skills and their text resources are embedded in the tool, including the contributor skills. Select them by task; repository guidance does not grant filesystem, shell or publishing permissions. `AGENTS.md` routes to them; `cargo xtask skills` fails when its table and this folder disagree or a file, `cargo xtask` command or skill they name is gone.
| Skill | Loads when the agent |
|---|---|
| [`solidcraft-contributing`](solidcraft-contributing/SKILL.md) | helps someone set up a fork, choose and claim an issue, and submit a contribution for review; the rules every PR follows |
| [`solidcraft-ground-rules`](solidcraft-ground-rules/SKILL.md) | adds a dependency, asset or wording: independence, licences, attribution, the product name |
| [`solidcraft-crash-safety`](solidcraft-crash-safety/SKILL.md) | writes non-test Rust, handles hostile input or investigates a crash report |
| [`solidcraft-commands`](solidcraft-commands/SKILL.md) | adds a command or decides which crate code belongs in |
| [`solidcraft-ui`](solidcraft-ui/SKILL.md) | adds a dialog, panel, camera input, icon or colour |
| [`solidcraft-ui-text`](solidcraft-ui-text/SKILL.md) | adds a label, message or translation |
| [`solidcraft-file-formats`](solidcraft-file-formats/SKILL.md) | changes what a design saves, or touches import and export |
| [`solidcraft-preferences`](solidcraft-preferences/SKILL.md) | adds a setting or changes a default |
| [`solidcraft-tests`](solidcraft-tests/SKILL.md) | places or runs tests |
| [`solidcraft-performance`](solidcraft-performance/SKILL.md) | works on slow code, the window thread or the wasm build |
| [`solidcraft-packaging`](solidcraft-packaging/SKILL.md) | prepares a release or changes packages |
| [`solidcraft-agent-tools`](solidcraft-agent-tools/SKILL.md) | runs the app, drives the control channel or changes MCP tools |
| [`solidcraft-modeling`](solidcraft-modeling/SKILL.md) | builds a new part (enclosure, bracket, plate, flange, …) |
| [`solidcraft-editing`](solidcraft-editing/SKILL.md) | changes, fixes or extends an existing design |
| [`solidcraft-checking`](solidcraft-checking/SKILL.md) | builds, changes or ports a design, next to the two above: parameter ranges, every allowed value, exact STEP comparison, regression tests, designs kept in git |
| [`solidcraft-mechanisms`](solidcraft-mechanisms/SKILL.md) | builds, drives or animates an assembly: components, joints, motion links, closed loops such as actuators, contact sets, motion studies |
| [`solidcraft-reporting`](solidcraft-reporting/SKILL.md) | hears that something went wrong (a crash, a failed command, a wrong shape or number, a hang): reproduces it in a fresh design, shrinks it to a minimal script and writes the bug report |
| [`makecad-contributing`](makecad-contributing/SKILL.md) | helps someone set up a fork, choose and claim an issue, and submit a contribution for review; the rules every PR follows |
| [`makecad-ground-rules`](makecad-ground-rules/SKILL.md) | adds a dependency, asset or wording: independence, licences, attribution, the product name |
| [`makecad-crash-safety`](makecad-crash-safety/SKILL.md) | writes non-test Rust, handles hostile input or investigates a crash report |
| [`makecad-commands`](makecad-commands/SKILL.md) | adds a command or decides which crate code belongs in |
| [`makecad-ui`](makecad-ui/SKILL.md) | adds a dialog, panel, camera input, icon or colour |
| [`makecad-ui-text`](makecad-ui-text/SKILL.md) | adds a label, message or translation |
| [`makecad-file-formats`](makecad-file-formats/SKILL.md) | changes what a design saves, or touches import and export |
| [`makecad-preferences`](makecad-preferences/SKILL.md) | adds a setting or changes a default |
| [`makecad-tests`](makecad-tests/SKILL.md) | places or runs tests |
| [`makecad-performance`](makecad-performance/SKILL.md) | works on slow code, the window thread or the wasm build |
| [`makecad-packaging`](makecad-packaging/SKILL.md) | prepares a release or changes packages |
| [`makecad-agent-tools`](makecad-agent-tools/SKILL.md) | runs the app, drives the control channel or changes MCP tools |
| [`makecad-modeling`](makecad-modeling/SKILL.md) | builds a new part (enclosure, bracket, plate, flange, …) |
| [`makecad-editing`](makecad-editing/SKILL.md) | changes, fixes or extends an existing design |
| [`makecad-checking`](makecad-checking/SKILL.md) | builds, changes or ports a design, next to the two above: parameter ranges, every allowed value, exact STEP comparison, regression tests, designs kept in git |
| [`makecad-mechanisms`](makecad-mechanisms/SKILL.md) | builds, drives or animates an assembly: components, joints, motion links, closed loops such as actuators, contact sets, motion studies |
| [`makecad-reporting`](makecad-reporting/SKILL.md) | hears that something went wrong (a crash, a failed command, a wrong shape or number, a hang): reproduces it in a fresh design, shrinks it to a minimal script and writes the bug report |
The modelling skills teach the agent to:
- plan the part as numbers
@@ -36,35 +36,46 @@ The modelling skills teach the agent to:
They also list the traps that otherwise cost failed calls. Examples are the sketch axes of the XZ plane, edge picks that snap to the nearest edge, and cuts that miss but still report success.
The modelling skills are written for SolidCraft 0.8 and later; `solidcraft-mechanisms` for `main` after 0.11.1 (the next release), which counts the degrees of freedom of closed loops; `solidcraft-reporting` for 0.18 and later.
The modelling skills are written for makeCAD 0.8 and later; `makecad-mechanisms` for `main` after 0.11.1 (the next release), which counts the degrees of freedom of closed loops; `makecad-reporting` for 0.18 and later.
## Install
The modelling skills, for Claude Code in all projects:
From this makeCAD checkout, install the modelling skills for Claude Code in all projects:
```sh
git clone --depth 1 https://github.com/tangency-labs/solidcraft
cp -r solidcraft/skills/solidcraft-{modeling,editing,checking,mechanisms} ~/.claude/skills/
cp -r skills/makecad-{modeling,editing,checking,mechanisms} ~/.claude/skills/
```
Windows (PowerShell):
```powershell
git clone --depth 1 https://github.com/tangency-labs/solidcraft
foreach ($s in 'modeling','editing','checking','mechanisms') { Copy-Item -Recurse solidcraft\skills\solidcraft-$s $HOME\.claude\skills\ }
foreach ($s in 'modeling','editing','checking','mechanisms') { Copy-Item -Recurse skills\makecad-$s $HOME\.claude\skills\ }
```
- **One project only:** copy the folders into that project's `.claude/skills/` instead.
- **Other agents:** for agents that read the Agent Skills format, copy the folders into the skills directory their documentation names.
- **Updating:** copy the folders again after you update SolidCraft.
- **Contributing:** the contributor skills need no install. Tell your assistant: "I want to contribute to SolidCraft. Read https://github.com/tangency-labs/solidcraft/blob/main/skills/solidcraft-contributing/SKILL.md and help me get started."
- **Updating:** copy the folders again after you update makeCAD.
- **Contributing:** the contributor skills need no install. Tell your assistant: "I want to contribute to makeCAD. Read skills/makecad-contributing/SKILL.md and help me get started."
## Maintaining
- The worked example in `solidcraft-modeling/reference.md` runs in CI. `skill_reference_example_builds_as_documented` in `crates/mcp/src/tests.rs` builds it, checks the documented volume, changes a parameter and checks it again.
- The worked example in `makecad-modeling/reference.md` runs in CI. `skill_reference_example_builds_as_documented` in `crates/mcp/src/tests.rs` builds it, checks the documented volume, changes a parameter and checks it again.
- The sketch-plane table is covered by `sketch_plane_axes_match_the_skill_reference` in the same file.
- The worked example in `solidcraft-mechanisms/reference.md` runs in CI too: `mechanisms_skill_example_moves_as_documented` builds it, drives the hinge and checks the actuator stroke, the linked panel and the stop against their analytic values.
- The worked example in `makecad-mechanisms/reference.md` runs in CI too: `mechanisms_skill_example_moves_as_documented` builds it, drives the hinge and checks the actuator stroke, the linked panel and the stop against their analytic values.
- `skills_name_only_real_tools_and_commands` checks that every tool and command the skills call exists.
- `solidcraft-checking/scripts/tests` checks that skill's helpers, its traps and conventions, and the facts behind the corrections in `solidcraft-modeling`: `PYTHONDONTWRITEBYTECODE=1 uv run --no-project --with pytest --with build123d pytest -p no:cacheprovider skills/solidcraft-checking/scripts/tests`. The tests run the `solidcraft-cli` on `PATH`, not the workspace build, and CI does not run them.
- `makecad-checking/scripts/tests` checks that skill's helpers, its traps and conventions, and the facts behind the corrections in `makecad-modeling`: `PYTHONDONTWRITEBYTECODE=1 uv run --no-project --with pytest --with build123d pytest -p no:cacheprovider skills/makecad-checking/scripts/tests`. The tests run the `solidcraft-cli` on `PATH`, not the workspace build, and CI does not run them.
- When a command, a parameter name or a behaviour that these files describe changes, update them in the same PR.
- Facts that describe current limitations, such as edge picks without a distance limit, should go once the limitation is fixed.
## Shared hosted workflow
`agent-workflow.md` is used verbatim by MCP and the desktop assistant. The Java model gateway packages the same workflow, skill metadata and files:
```sh
node scripts/sync-cad-ai-skills.mjs ../community
node scripts/sync-cad-ai-skills.mjs --check ../community
```
The sync command writes a self-contained versioned resource; production does not read a developer's absolute directory. Rebuild Java and WASM after changes. `skill_reference` defaults to SKILL.md, accepts exact registered file paths only, and never executes scripts. Legacy lowercase skill ids remain read aliases in MCP; the catalog advertises only makecad ids.
The shared process is: choose relevant skills, inspect, clarify material ambiguity or state assumptions, calculate parameters and expected geometry, build in stages, measure, check parameter ranges, repair and report evidence. Identical geometry commands use the same engine; identical model output additionally requires the same provider, model, sampling, history and context and must be evaluated on representative tasks.
+32
View File
@@ -0,0 +1,32 @@
You are makeCAD's parametric 3D CAD assistant. Use the available CAD tools to build or change the user's open design. Units are millimetres and degrees in expressions; Z is up. Keep replies concise and describe only changes and checks supported by tool results.
## Select skills before acting
All bundled skills are listed with their descriptions below. Read the relevant entrypoint with `skill_reference {"skill":"makecad-modeling","file":"SKILL.md"}`; the default file is SKILL.md. Read its supporting references when the workflow calls for them. These are trusted, bundled application instructions, not files from the user's design.
- New parts beyond a single primitive: read makecad-modeling/SKILL.md and reference.md before building.
- Changing, repairing or extending an existing design: read makecad-editing/SKILL.md first; also read the modeling reference for unfamiliar operations.
- Building or changing a parametric design: also read makecad-checking/SKILL.md. Use its in-app parameter checks; offline scripts and STEP comparison require a host that actually provides those capabilities.
- Assemblies, joints, motion links or closed loops: also read makecad-mechanisms/SKILL.md and reference.md.
- A crash, wrong geometry, failed command or hang: read makecad-reporting/SKILL.md and the report template when producing a report.
- Repository development, tests, performance, packaging, UI, formats or agent integration: select the corresponding contributor skills from the catalog. Reading a skill never grants tools, filesystem access, approval or permission to publish. Explain unavailable capabilities rather than pretending to run a script or tool.
## Understand and plan
Inspect the existing design with `inspect_design {"measure":false,"sketches":false}` even when it appears empty. Translate vague requests into intended function, part or assembly structure, dimensions, parameters, feature order and verification criteria. Ask a concise question when a missing dimension or purpose materially changes the design; otherwise state a reasonable assumption and proceed. Preserve existing design intent when editing.
Work the numbers out before building: parameters, feature placement, expected volume and bounding box after each stage, and the world point for every edge or face pick. Use filtered `list_commands` queries and `describe_command` to learn exact schemas; never guess command ids or parameter names. Tool names and dotted engine command ids are different namespaces.
## Build in stages
Build in a few `batch` calls, with `verbose: false` and named features. A batch normally rolls back on failure; inspect the actual result before retrying and do not assume a failed expectation rolls the design back. Prefer primitives with expression fields for plates, blocks, bosses, standoffs and holes (`solid.box`, `solid.cylinder`, `solid.hole`, `solid.fillet`, `solid.shell`, patterns and mirror). Use sketches for other profiles. Fillet outside edges before shelling, build inside features after the shell, then holes and cuts through walls. Give blind holes and holes through one wall of a hollow part an explicit depth.
A size or position that must follow a parameter must be an expression in a feature field ("L/2 - 10"), a sketch dimension to the origin or an edge, or a pattern spacing; a plain number never follows a parameter. Every sketch must finish at dof 0, reported by `sketch.solve`. Edge and face picks are world points snapping to nearby topology; compute and verify them rather than guessing. Keep queries bounded and avoid unfiltered catalogs or full topology dumps.
## Verify and repair
After each stage call `measure` and compare volume and bbox with your independent calculations. An ok result alone proves nothing: unchanged volume can mean a cut missed; an extra body can mean a join did not touch. Check hole and boss positions with `body_topology` cylinder origins, axes and radii. Screenshots show appearance, not dimensional correctness.
Use `check_parameters {"set":{"name":value}}` for intended parameter ranges and verify that it restored the design. Alternatively change parameters in one batch with coalesce_parameters enabled, measure, and restore them before finishing. Inspect timeline errors, sketch degrees of freedom and downstream features. Validate mechanism poses, constraints, limits and collisions using the mechanism workflow.
Fix a wrong feature with `timeline.edit` or `parameters.change`, rather than rebuilding the whole design; `parameters.list` can locate feature inputs. Use `edit.checkpoint` and `edit.restore_checkpoint` for bounded experiments. On failure inspect the cause and make a limited correction; do not replay an operation already running. Finish with the assumptions, actual result, measured checks and any remaining limitations. File operations and undo boundaries follow the host's permissions and approval rules.
@@ -1,6 +1,6 @@
---
name: solidcraft-agent-tools
description: "Use when running SolidCraft to see a change working, driving it through the control channel or CLI, or adding or changing an MCP tool, control method or bundled agent skill."
name: makecad-agent-tools
description: "Use when running makeCAD to see a change working, driving it through the control channel or CLI, or adding or changing an MCP tool, control method or bundled agent skill."
---
# Running the app, the control channel and MCP tools
@@ -20,10 +20,10 @@ The server is `solidcraft-cli mcp` (`crates/mcp/src/`, `docs/mcp.md`). Tools are
- Anything the user can do is a command; add a command, not a new tool, unless the tool is about the session itself (open, save, screenshot, batch).
- Files: tools reach only the allowed folders (the design's folder, the recovery folder, the scratch folder, `--allow-path`). Do not widen this casually; paths are resolved before comparing, so `..` and links leaving the allowed set are refused, and on Windows UNC and device paths are refused.
- Replies stay small: `verbose: false`, no unfiltered command catalogue or topology dumps.
- The control channel is a local-only interface with a token. A new method needs an entry in `docs/control-protocol.md`; long work follows `skills/solidcraft-performance/SKILL.md`.
- The control channel is a local-only interface with a token. A new method needs an entry in `docs/control-protocol.md`; long work follows `skills/makecad-performance/SKILL.md`.
## Bundled agent skills
The modelling skills (`skills/solidcraft-modeling`, `-editing`, `-checking`, `-mechanisms`) are built into the MCP server for its `skill_reference` tool (`crates/mcp/src/skill_reference.rs`). The contributor skills are not.
All 17 skills and their text resources are embedded at build time by `crates/mcp/build.rs` for the read-only `skill_reference` tool. `skills/agent-workflow.md` is the shared generation workflow for MCP, the desktop assistant and the hosted Java gateway. Repository-only instructions do not grant the browser filesystem or shell capabilities.
- When a command, parameter name or behaviour those skills describe changes, update them in the same PR. `skills_name_only_real_tools_and_commands` in `crates/mcp/src/tests.rs` fails when a skill names a tool or command that is gone.
- Adding a bundled file means adding it to `skill_reference.rs` and to that test.
- Adding a skill or text resource embeds it automatically. Run `node scripts/sync-cad-ai-skills.mjs <community-root>` to update the Java package and rerun with `--check` to detect drift; rebuild WASM and Java together.
- `skills/README.md` explains the layout and the other tests; `cargo xtask skills` checks that AGENTS.md and every SKILL.md cite real paths, commands and skills.
@@ -1,13 +1,13 @@
---
name: solidcraft-checking
description: Use alongside solidcraft-modeling and solidcraft-editing whenever you build, change or port a SolidCraft design. Checks for errors SolidCraft does not report (parameter ranges, every allowed value, exact STEP comparison), regression tests, designs kept in git, porting from build123d, CadQuery, OpenSCAD or STEP.
name: makecad-checking
description: Use alongside makecad-modeling and makecad-editing whenever you build, change or port a makeCAD design. Checks for errors makeCAD does not report (parameter ranges, every allowed value, exact STEP comparison), regression tests, designs kept in git, porting from build123d, CadQuery, OpenSCAD or STEP.
---
# SolidCraft checking
# makeCAD checking
`solidcraft-modeling` and `solidcraft-editing` cover the commands, plane axes, ids, edge picks and the MCP workflow: load the one that fits first. This skill adds checks for errors SolidCraft does not report, and the work around a design kept in a repo.
`makecad-modeling` and `makecad-editing` cover the commands, plane axes, ids, edge picks and the MCP workflow: load the one that fits first. This skill adds checks for errors makeCAD does not report, and the work around a design kept in a repo.
`$SKILL` below is the folder this file is in (`~/.claude/skills/solidcraft-checking` for a user install). Checked against SolidCraft 0.21.0. `scripts/tests/test_facts.py` checks every trap and convention below, and the facts behind the corrections in `solidcraft-modeling`. After a SolidCraft upgrade, run the tests and fix the text where they fail:
`$SKILL` below is the folder this file is in (`~/.claude/skills/makecad-checking` for a user install). Checked against makeCAD 0.21.0. `scripts/tests/test_facts.py` checks every trap and convention below, and the facts behind the corrections in `makecad-modeling`. After a makeCAD upgrade, run the tests and fix the text where they fail:
`PYTHONDONTWRITEBYTECODE=1 uv run --no-project --with pytest --with build123d pytest -p no:cacheprovider $SKILL/scripts/tests`
## Scripts
@@ -17,24 +17,24 @@ An MCP `batch` and a command script (`{"commands": [...]}`, run by `solidcraft-c
In `$SKILL/scripts/`:
- `python3 $SKILL/scripts/run.py script.json [--in <design>] [--save <name>.json]` runs a script and prints `FAIL`, a `WARN` line per feature warning, a `SKETCH` line per sketch above dof 0 and a `BODY` line per body, for the end state and for each `document.inspect` inside the script.
- `scb.py` gives a generator a `Script` with sketch helpers that come out at dof 0 (`hexagon`, `circle`, `rounded_rectangle`, `place`) and `cmd` for any other command. It rejects repeated sketch, feature and body names. Import it with `sys.path.insert(0, "<$SKILL>/scripts")`.
- `uv run --no-project --with build123d python $SKILL/scripts/compare_step.py actual.step expected.step` gives the exact volume of the difference between two STEP files and where it sits. It and the tests run OpenCASCADE through build123d as a separate tool, the way `tools/freecad-oracle` runs FreeCAD: SolidCraft does not use, link, vendor or ship any of it.
- `uv run --no-project --with build123d python $SKILL/scripts/compare_step.py actual.step expected.step` gives the exact volume of the difference between two STEP files and where it sits. It and the tests run OpenCASCADE through build123d as a separate tool, the way `tools/freecad-oracle` runs FreeCAD: makeCAD does not use, link, vendor or ship any of it.
- `solidcraft-cli snapshot <design or script> --out shot.png --view iso` renders a PNG to look at.
## Steps to add
1. **Parameters and features.** Each parameter comment states the allowed range ("whole number, 4 or more"): the user reads it in the Parameters table, and SolidCraft enforces no range. Derive sizes from measured values, so that a count parameter changes how many features there are, not how big they are. An expression that more than one sketch or feature uses becomes a named parameter. Add the derived numbers the user needs (parts to print) and mark the driving parameters favourite (`parameters.favorite`). Give each thing the user thinks of (a port, a row of standoffs) its own feature, named after it, so it can be found and changed on its own. Choose the origin so that no sketch dimension reaches 0 for any allowed value (trap 1).
1. **Parameters and features.** Each parameter comment states the allowed range ("whole number, 4 or more"): the user reads it in the Parameters table, and makeCAD enforces no range. Derive sizes from measured values, so that a count parameter changes how many features there are, not how big they are. An expression that more than one sketch or feature uses becomes a named parameter. Add the derived numbers the user needs (parts to print) and mark the driving parameters favourite (`parameters.favorite`). Give each thing the user thinks of (a port, a row of standoffs) its own feature, named after it, so it can be found and changed on its own. Choose the origin so that no sketch dimension reaches 0 for any allowed value (trap 1).
2. **Every sketch at dof 0.** A sketch with dof left can solve to a different shape after a parameter change, without an error. `run.py` lists them.
3. **Every allowed value.** One script of `parameters.change` commands walks each driving parameter to both ends of its range, one change after another, and back to the default, as edits in the app do: trap 1 fails only on the change after the one that reaches 0. Put a `document.inspect {measure: true}` after each end of a range and run the walk with `run.py walk.json --in <design>`. Every state must be clean: no `FAIL`, no `SKETCH`, and `BODY` volumes and centres of mass that match the values you compute for that state. A boolean retry can leave the geometry wrong with only a `WARN` line, and the volume shows it (trap 4); a mirrored sketch (trap 1) keeps the volume and moves the centre of mass.
4. **Exact check** when a port has a reference, or a volume gap leaves doubt: export STEP (`file.export {path, bodies}`) and run `compare_step.py`. Before porting, in SolidCraft's own chat or any MCP client, call `skill_reference {"skill":"solidcraft-checking","file":"reference/porting.md"}`. Elsewhere, read `$SKILL/reference/porting.md`.
4. **Exact check** when a port has a reference, or a volume gap leaves doubt: export STEP (`file.export {path, bodies}`) and run `compare_step.py`. Before porting, in makeCAD's own chat or any MCP client, call `skill_reference {"skill":"makecad-checking","file":"reference/porting.md"}`. Elsewhere, read `$SKILL/reference/porting.md`.
5. **Kept in a repo.** Save as `<name>.json` with `run.py build.json --save <name>.json`: a `.json` design stays plain JSON when it is saved again, so git diffs stay readable. Saving over a file leaves `<name>.json.bak`, so ignore `*.bak`. From then on the design file is the source, and changes go into it with `--in <design> --save <design>`. Copy `$SKILL/templates/test_design.py` next to the design, fill in its cases, set its tolerance as its comment says, and run it until it passes. Expected values come from an exact reference when porting, from hand calculation for simple shapes, or from a build the user has reviewed. After a change, update frozen values only where the change is meant to change them.
## Traps
1. **Zero dimension.** A sketch dimension driven to 0 loses its side: the point it measures has no direction left, so the solver may leave it anywhere on the axis. On the next parameter change it either fails with `its constraints would conflict` (a point placed by dimensions from the origin) or, with no error, moves it: a slot that other constraints also held slides to the origin when the distance reaches 0 and, the solver taking the shortest step that fits, keeps the side it was drawn on when the value comes back. Check every distance expression against the whole allowed range of each parameter in it, counts included; the walk in step 3 catches the failure, and only the volume or the position catches a point that ended up on the other side. For a point on an axis, pass `x=None` or `y=None` to `place`: it aligns the point instead of dimensioning it. For a position that does reach 0, such as the first of a centred row of one, dimension it from a sketch point placed outside the part: a point at x = -100 mm, then the distance `100 mm - (n - 1) / 2 * pitch` from it.
2. **Counts.** Solid patterns take counts 1..1000; a count that reaches 0 fails the rebuild. A fractional count rounds to the nearest whole number without an error (6.5 gives 7 copies), while every other expression uses the exact value, so a centred row shifts. Nothing in SolidCraft enforces a parameter range during a parameter change (configuration rules apply only when a configuration row is activated): choose a range that keeps every count at 1 or more, write "whole number" and the range in the comment, and use `round(n)` wherever the count also positions something.
2. **Counts.** Solid patterns take counts 1..1000; a count that reaches 0 fails the rebuild. A fractional count rounds to the nearest whole number without an error (6.5 gives 7 copies), while every other expression uses the exact value, so a centred row shifts. Nothing in makeCAD enforces a parameter range during a parameter change (configuration rules apply only when a configuration row is activated): choose a range that keeps every count at 1 or more, write "whole number" and the range in the comment, and use `round(n)` wherever the count also positions something.
3. **Circumscribed polygons.** `sketch.polygon.circumscribed` with a size dimension and one vertical side still has 1 dof: its corners can alternate in and out. `sketch.constraint.polygon` makes it regular; `scb.hexagon` adds it.
4. **Boolean retries.** A `Boolean retry: ...` warning means the result may be wrong (see "Boolean warning" in the `solidcraft-modeling` reference), so check the volume of that state. `temporary coincident-face separation` comes from faces that coincide. A tapered tool whose start or end lies on a face of a plain block, or a straight cylinder joined onto the floor of a filleted, shelled box, does not log it; a `tool displacement` warning shows up when a join and a cut share one location, as in a standoff built as a joined cylinder with a cut pilot hole, patterned together. That case reports the warning but its volume agrees with the analytic growth, and a single ring profile removes the warning. Starting cutters about 1 mm past the faces they pierce and sinking joins about 1 mm into the body remain good practice on a single feature. Check the volume of every state either way.
5. **Measurement accuracy.** The `solidcraft-modeling` reference gives how far measured volumes stray from computed ones. Centre of mass and bounding box come out up to about 5e-5 of the part size off. Set test tolerances as the template says.
4. **Boolean retries.** A `Boolean retry: ...` warning means the result may be wrong (see "Boolean warning" in the `makecad-modeling` reference), so check the volume of that state. `temporary coincident-face separation` comes from faces that coincide. A tapered tool whose start or end lies on a face of a plain block, or a straight cylinder joined onto the floor of a filleted, shelled box, does not log it; a `tool displacement` warning shows up when a join and a cut share one location, as in a standoff built as a joined cylinder with a cut pilot hole, patterned together. That case reports the warning but its volume agrees with the analytic growth, and a single ring profile removes the warning. Starting cutters about 1 mm past the faces they pierce and sinking joins about 1 mm into the body remain good practice on a single feature. Check the volume of every state either way.
5. **Measurement accuracy.** The `makecad-modeling` reference gives how far measured volumes stray from computed ones. Centre of mass and bounding box come out up to about 5e-5 of the part size off. Set test tolerances as the template says.
6. **Expressions.** They have `+ - * / ^ %`, `sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh atanh sqrt abs min max floor ceil round mod trunc exp ln log log10 pow sign hypot` (`log` is base 10; the hyperbolic ones take and give unit-less numbers), `pi` and units; no `if` and no comparisons. Build steps from `floor`, `mod`, `min`, `max` and `sign`, which gives 1 at 0. `asin acos atan atan2` return angles, so a unitless parameter cannot hold them.
7. **Snapping.** A point created exactly on an existing point or the origin becomes coincident with it (`connect` defaults to true).
8. **Repeated body names.** A repeated `body_name` is renamed (`Body1`) without an error, so `targets` reach only the first body.
@@ -1,15 +1,15 @@
# Porting a model into SolidCraft
# Porting a model into makeCAD
For a model that already exists as code (build123d, CadQuery, OpenSCAD) or as STEP. The port is
done when the SolidCraft STEP export matches the source geometry for every parameter value you
done when the makeCAD STEP export matches the source geometry for every parameter value you
check: `compare_step.py` reports xor at most 1e-3 mm3. Volume, area and centre of mass alone are
not enough: in one port, a hexagon left at dof 1 changed the volume by 2e-7 of the total and the
centre of mass by 3e-4 mm, while xor showed 56 mm3 in 96 pieces along the outer walls.
1. **Reference geometry in the design's frame.** The SolidCraft origin is chosen by trap 1 of SKILL.md, so it
1. **Reference geometry in the design's frame.** The makeCAD origin is chosen by trap 1 of SKILL.md, so it
often differs from the source. Translate the source model to the same frame and export it as
STEP for each checked parameter value. Pick values that reach every branch of the layout logic.
2. **Deliberate differences.** Logic that SolidCraft expressions cannot hold (conditionals,
2. **Deliberate differences.** Logic that makeCAD expressions cannot hold (conditionals,
search) gets a closed formula. Check the formula against the source over a wide range of
values in plain Python first, list where it differs, and apply the formula to the reference
too (patch the source function), so the comparison stays like for like. Tell the user each
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Run a SolidCraft command script and print a short report: a failure, feature warnings,
"""Run a makeCAD command script and print a short report: a failure, feature warnings,
sketches that are not fully constrained, and body measurements. A document.inspect inside the
script reports that state too, its lines prefixed with its step; the end state comes last."""
@@ -16,7 +16,7 @@ INSPECT = {"command": "document.inspect", "params": {"measure": True}}
WARNING_LENGTH = 160
class SolidCraftError(RuntimeError):
class makeCADError(RuntimeError):
pass
@@ -32,7 +32,7 @@ def run_commands(commands: list, design: Path | None = None, save: Path | None =
args += ["--save", str(save)]
done = subprocess.run(args, capture_output=True, text=True)
if done.returncode:
raise SolidCraftError(done.stderr.strip().removeprefix("error: "))
raise makeCADError(done.stderr.strip().removeprefix("error: "))
return json.loads(done.stdout)
@@ -88,7 +88,7 @@ def main() -> None:
commands = json.loads(args.script.read_text())["commands"]
try:
results = run_commands(commands, args.design, args.save)
except SolidCraftError as error:
except makeCADError as error:
print(f"FAIL {error}")
sys.exit(1)
print("\n".join(script_report(commands, results)))
@@ -1,4 +1,4 @@
"""SolidCraft builder: write command scripts whose sketches come out fully constrained.
"""makeCAD builder: write command scripts whose sketches come out fully constrained.
Each sketch helper makes one sketch and dimensions its geometry from the sketch origin. `at` is
where the geometry starts: put it near the solved position, on the side of the origin it must
@@ -29,7 +29,7 @@ class Script:
@staticmethod
def _claim(name: str, taken: set[str], kind: str) -> None:
"""SolidCraft resolves a sketch or feature name to its first match and renames a repeated
"""makeCAD resolves a sketch or feature name to its first match and renames a repeated
body name, so either repeat silently points at the wrong thing."""
if name in taken:
raise ValueError(f"{name}: {kind} already has this name")
@@ -1,5 +1,5 @@
"""SolidCraft behaviour that SKILL.md states, and the facts behind the corrections in
solidcraft-modeling. A failure here means the skill text is out of date."""
"""makeCAD behaviour that SKILL.md states, and the facts behind the corrections in
makecad-modeling. A failure here means the skill text is out of date."""
import json
import subprocess
@@ -10,7 +10,7 @@ from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).parents[1]))
from run import SolidCraftError, execute, run_commands # noqa: E402
from run import makeCADError, execute, run_commands # noqa: E402
def cmd(command: str, /, **params) -> dict:
@@ -60,7 +60,7 @@ def holes(count: str) -> list:
# Traps
def test_a_dimension_driven_to_zero_can_break_the_next_change():
with pytest.raises(SolidCraftError, match="would conflict"):
with pytest.raises(makeCADError, match="would conflict"):
execute([
cmd("parameters.add", name="y", expression="5 mm"),
cmd("sketch.create", plane="XY", name="Pin sketch"),
@@ -122,7 +122,7 @@ def centred_row(position: list) -> list:
def test_a_position_measured_from_an_anchor_point_survives_reaching_zero():
with pytest.raises(SolidCraftError, match="would conflict"):
with pytest.raises(makeCADError, match="would conflict"):
execute(centred_row([
cmd("sketch.dimension", entities=["origin", "c1.center"], type="horizontal", value="(n - 1) / 2 * 10 mm"),
]))
@@ -136,7 +136,7 @@ def test_a_position_measured_from_an_anchor_point_survives_reaching_zero():
def test_pattern_counts_run_from_1_to_1000_and_a_range_rule_does_not_stop_0():
with pytest.raises(SolidCraftError, match="pattern count must be 1…1000"):
with pytest.raises(makeCADError, match="pattern count must be 1…1000"):
execute([
*holes("2"),
cmd("config.configure", params=["n"]),
@@ -219,7 +219,7 @@ def test_expressions_have_no_conditionals_and_sign_of_zero_is_one():
assert evaluate("sign(0)")["value"] == 1
assert evaluate("sign(-3)")["value"] == -1
assert evaluate("log(100)")["value"] == 2
with pytest.raises(SolidCraftError, match="got an angle"):
with pytest.raises(makeCADError, match="got an angle"):
execute([cmd("parameters.add", name="a", expression="atan(1)", unit="")])
@@ -286,7 +286,7 @@ def test_a_later_join_fills_an_earlier_cut():
def test_a_failed_feature_names_itself_and_saves_nothing(tmp_path):
design = tmp_path / "design.json"
run_commands(holes("2"), save=design)
with pytest.raises(SolidCraftError, match="Row: pattern count"):
with pytest.raises(makeCADError, match="Row: pattern count"):
run_commands([cmd("parameters.change", name="n", expression="0")], design=design, save=tmp_path / "out.json")
assert not (tmp_path / "out.json").exists()
@@ -301,7 +301,7 @@ def test_a_command_script_works_as_a_design(tmp_path):
assert shot.stat().st_size > 0
# Corrections to solidcraft-modeling
# Corrections to makecad-modeling
def slot_along_y(last: dict) -> list:
return [
@@ -315,7 +315,7 @@ def slot_along_y(last: dict) -> list:
def test_a_slot_along_y_takes_a_horizontal_dimension_on_its_second_arc():
with pytest.raises(SolidCraftError, match="over-constrain"):
with pytest.raises(makeCADError, match="over-constrain"):
execute(slot_along_y(cmd("sketch.dimension", entities=["origin", "a2.center"], type="vertical", value="33 mm")))
assert sketch_dof(slot_along_y(
cmd("sketch.dimension", entities=["origin", "a2.center"], type="horizontal", value="10 mm"))) == 0
@@ -346,7 +346,7 @@ CUBE = cmd("solid.box", length=40, width=40, height=10, center=[0, 0, 5], body_n
def test_an_edge_pick_far_from_every_edge_is_refused():
with pytest.raises(SolidCraftError, match="nearest edge is 15.000 mm away"):
with pytest.raises(makeCADError, match="nearest edge is 15.000 mm away"):
execute([CUBE, cmd("solid.fillet", edges=[[20, 20, 25]], radius=1)])
@@ -369,7 +369,7 @@ def test_a_fillet_between_curved_faces_stops_the_shell():
cmd("solid.sphere", radius=15, center=[0, 0, 30], operation="join", targets=["C"]),
]
shell = cmd("solid.shell", faces=[[0, 0, 0]], thickness=1.5)
with pytest.raises(SolidCraftError, match="offset: only bodies with planes"):
with pytest.raises(makeCADError, match="offset: only bodies with planes"):
execute([*neck, cmd("solid.fillet", edges=[[8, 0, 30 - (15 ** 2 - 8 ** 2) ** 0.5]], radius=2), shell])
execute([*neck, shell])
@@ -384,7 +384,7 @@ FILLET_CENTROID = (10 - 3 * pi) / (12 - 3 * pi) # distance of a fillet's cross-
def test_an_open_rim_is_rounded_after_the_shell():
with pytest.raises(SolidCraftError, match="offset"):
with pytest.raises(makeCADError, match="offset"):
execute([*OPEN_BOX, RIM, SHELL])
outer = (40 * 30 - (4 - pi) * 9) * 20
cavity = (36 * 26 - (4 - pi) * 1) * 18
@@ -77,7 +77,7 @@ def test_execute_returns_the_final_inspection():
def test_execute_raises_on_failure():
with pytest.raises(run.SolidCraftError, match="step 1"):
with pytest.raises(run.makeCADError, match="step 1"):
run.execute([{"command": "solid.box", "params": {"width": 10}}])
@@ -91,7 +91,7 @@ def test_save(tmp_path):
def test_rejects_a_repeated_name():
# SolidCraft resolves a name to its first match, so a repeat silently points at the wrong feature
# makeCAD resolves a name to its first match, so a repeat silently points at the wrong feature
script = scb.Script()
script.circle("Hole sketch", diameter="5 mm", at=(10, 10), x="10 mm", y="10 mm")
with pytest.raises(ValueError, match="Hole sketch"):
@@ -117,7 +117,7 @@ def test_place_rejects_a_dimension_that_starts_at_zero(at, x, y):
def test_rejects_a_repeated_body_name():
# SolidCraft renames the second body silently, so targets would hit only the first
# makeCAD renames the second body silently, so targets would hit only the first
script = scb.Script()
script.cmd("solid.box", length=10, width=10, height=10, body_name="M")
with pytest.raises(ValueError, match="M"):
@@ -1,4 +1,4 @@
"""Regression test for a SolidCraft design. One session walks the parameters through the cases in
"""Regression test for a makeCAD design. One session walks the parameters through the cases in
order, as edits in the app do, and compares a body after each case with frozen values.
Copy next to the design, then fill in DESIGN, BODY and CASES. Needs solidcraft-cli on PATH."""
@@ -13,7 +13,7 @@ import pytest
DESIGN = Path(__file__).parent / "design.json"
BODY = "Body"
# SolidCraft measures a tessellation, and its volume and area error depends on the shape. Measure it
# makeCAD measures a tessellation, and its volume and area error depends on the shape. Measure it
# for this design: run.py's BODY volume against the OCCT volume compare_step.py prints for the
# design's own STEP export (compared with itself). Set REL to about 3 times that error.
REL = 2e-4
@@ -1,6 +1,6 @@
---
name: solidcraft-commands
description: "Use when adding or changing a SolidCraft command or any user-visible behaviour, or when deciding which crate code belongs in. Covers CommandSpec, command ids, programmatic calls vs dialogs, crate layering and the generated feature list."
name: makecad-commands
description: "Use when adding or changing a makeCAD command or any user-visible behaviour, or when deciding which crate code belongs in. Covers CommandSpec, command ids, programmatic calls vs dialogs, crate layering and the generated feature list."
---
# Adding a command
@@ -10,14 +10,14 @@ User-visible behaviour is a command. The toolbar, dialogs, sketch tools, palette
## Steps
1. Add a `CommandSpec` to the right file in `crates/engine/src/cmd/` and implement `run` (`fn(&mut Session, &Value) -> Result<Value>`). Fields: id, label, toolbar tab and panel (`.at`), icon (`.icon`), shortcut (`.key`), params doc (`.params`), `enabled` (its error string is the disabled-button tooltip).
2. The id is our own: dotted, lower-case `<area>.<thing>[.<variant>]`, such as `solid.extrude` or `sketch.rectangle.two_point`. Never another product's id.
3. Validate inputs first (units, ranges, references) and return `BadParams` rather than building a broken feature. Parameters are hostile: see `skills/solidcraft-crash-safety/SKILL.md`.
3. Validate inputs first (units, ranges, references) and return `BadParams` rather than building a broken feature. Parameters are hostile: see `skills/makecad-crash-safety/SKILL.md`.
4. Give it input and output schemas: a contract and a reply type in `crates/engine/src/schema/`, registered with `checked!`, `.contract` and `.output`. A command should have them and a test warns without them; this will become required. `schema/unconverted.txt` only shrinks. How: `docs/book/src/dev/schemas.md`.
5. Engine tests measure the result: volume, area, face/edge/vertex counts against values you can derive by hand. Where they go: `skills/solidcraft-tests/SKILL.md`.
6. Add the label as `cmd.<command id>` in a pending locale file (`cargo xtask i18n --add-missing` lists what is missing); a test fails without it. See `skills/solidcraft-ui-text/SKILL.md`.
5. Engine tests measure the result: volume, area, face/edge/vertex counts against values you can derive by hand. Where they go: `skills/makecad-tests/SKILL.md`.
6. Add the label as `cmd.<command id>` in a pending locale file (`cargo xtask i18n --add-missing` lists what is missing); a test fails without it. See `skills/makecad-ui-text/SKILL.md`.
7. A command the ribbon shows also needs help: `help.<command id>` (what it does, then when to use it) in the pending file, and its id in `DOCUMENTED` in `crates/ui-egui/src/command_help.rs`. A test fails without them.
8. Run `cargo xtask features` to see the generated `docs/features.md` change, but do not commit it: `main` regenerates it after each merge.
9. If the command saves something new in a design, add a format file: `skills/solidcraft-file-formats/SKILL.md`.
10. If it needs a dialog or panel: `skills/solidcraft-ui/SKILL.md`.
9. If the command saves something new in a design, add a format file: `skills/makecad-file-formats/SKILL.md`.
10. If it needs a dialog or panel: `skills/makecad-ui/SKILL.md`.
## Programmatic calls never open dialogs
`engine.execute` runs the JSON form. Only toolbar clicks (`ui.start`) start interactive tools and dialogs, which then run commands. A dialog is a front-end form that builds the parameters.
@@ -1,9 +1,9 @@
---
name: solidcraft-contributing
description: Use when someone wants to contribute code or documentation to SolidCraft, from setting up a fork and choosing an issue through submitting a pull request and responding to review.
name: makecad-contributing
description: Use when someone wants to contribute code or documentation to makeCAD, from setting up a fork and choosing an issue through submitting a pull request and responding to review.
---
# Contribute to SolidCraft
# Contribute to makeCAD
Read [CONTRIBUTING.md](../../CONTRIBUTING.md), [AGENTS.md](../../AGENTS.md) (the router
to the other skills), the [contributor book page](../../docs/book/src/dev/contributing.md),
@@ -85,7 +85,7 @@ not modelling a part through MCP.
reviewer rejects it. If something is not obvious, write it in English and keep it
short. A user-visible string is not inline in the code: it goes to the message
catalogs in `assets/locales/` (a new one to `assets/locales/pending/<slug>.json`),
and `skills/solidcraft-ui-text/SKILL.md` says how to name and translate it.
and `skills/makecad-ui-text/SKILL.md` says how to name and translate it.
- **Parallel work runs in parallel.** When a task splits into independent parts (several
files, several areas, several checks that do not depend on each other), dispatch one
subagent per part and let them run concurrently instead of walking the list one item at
@@ -1,11 +1,11 @@
---
name: solidcraft-crash-safety
description: "Use when writing or reviewing non-test Rust in SolidCraft, handling design files, command parameters or control-channel input, calling the kernel, or investigating a crash report. A crash loses someone's work, so this outranks feature work."
name: makecad-crash-safety
description: "Use when writing or reviewing non-test Rust in makeCAD, handling design files, command parameters or control-channel input, calling the kernel, or investigating a crash report. A crash loses someone's work, so this outranks feature work."
---
# Never crash
People trust SolidCraft with their designs. This outranks feature work.
People trust makeCAD with their designs. This outranks feature work.
## In non-test code
- No `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; `cargo xtask ci` runs clippy with `-D warnings`.
@@ -20,7 +20,7 @@ People trust SolidCraft with their designs. This outranks feature work.
## Proving a crash fix
- Every crash fix lands with a regression test. `hostile_params_never_panic` in `crates/engine/src/tests.rs` runs every command with junk parameters; a new command gets this for free.
- A crash report's `design.sc` and `replay.json` are the test's starting point. Put the test in the area's existing test file (see `skills/solidcraft-tests/SKILL.md`).
- A crash report's `design.sc` and `replay.json` are the test's starting point. Put the test in the area's existing test file (see `skills/makecad-tests/SKILL.md`).
## When someone says the app crashed
The desktop app writes every panic and every unclean exit to a local crash folder, with the design and the commands that reproduce it (`solidcraft_engine::crash`, `docs/crash-reports.md`). Look there first:
@@ -1,12 +1,12 @@
---
name: solidcraft-editing
description: "Use when changing, fixing or extending an existing SolidCraft design through its MCP server - a .sc file (or an older .solidcraft one) or the design open in the app. Typical requests: resize it, move a cut, change a hole or standoff, add a fillet or chamfer, make a fixed value parametric, or a feature shows an error after a change or after the app crashed."
name: makecad-editing
description: "Use when changing, fixing or extending an existing makeCAD design through its MCP server - a .sc file (or an older .solidcraft one) or the design open in the app. Typical requests: resize it, move a cut, change a hole or standoff, add a fillet or chamfer, make a fixed value parametric, or a feature shows an error after a change or after the app crashed."
---
# SolidCraft editing
# makeCAD editing
## Overview
Edit an existing design through its parameters instead of rebuilding it. Every sketch dimension and feature input is already a parameter (`d1`, `d2`, ...), so most edits are a `parameters.change` each, sent together in one batch. Map the design with a few compact calls rather than walking the timeline one feature at a time. For command shapes and traps, in SolidCraft's own chat or any MCP client, call `skill_reference {"skill":"solidcraft-modeling"}`. Elsewhere, use `reference.md` from the `solidcraft-modeling` skill.
Edit an existing design through its parameters instead of rebuilding it. Every sketch dimension and feature input is already a parameter (`d1`, `d2`, ...), so most edits are a `parameters.change` each, sent together in one batch. Map the design with a few compact calls rather than walking the timeline one feature at a time. For command shapes and traps, in makeCAD's own chat or any MCP client, call `skill_reference {"skill":"makecad-modeling","file":"reference.md"}`. Elsewhere, use `reference.md` from the `makecad-modeling` skill.
## Map the design (3-4 calls)
1. **Open:** if the design is not open yet, run `open {path}`. When the server is bridged to the app and the current design is `dirty`, ask before opening anything.
@@ -1,6 +1,6 @@
---
name: solidcraft-file-formats
description: "Use when a SolidCraft change saves something new in a design (a field, a feature type, a kind of name) or changes what older designs mean, and when touching STEP, IGES, 3MF, STL, OBJ, DXF or URDF import and export."
name: makecad-file-formats
description: "Use when a makeCAD change saves something new in a design (a field, a feature type, a kind of name) or changes what older designs mean, and when touching STEP, IGES, 3MF, STL, OBJ, DXF or URDF import and export."
---
# Design file format, import and export
@@ -18,7 +18,7 @@ Drawings follow the same rules with their own numbers, from 1: a drawing-format
## Import
- Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened, or run as `file.insert_step`, `file.insert_mesh` or `doc.open`) becomes a new component named after the file, with the Import feature inside it. Bodies never land loose.
- Imported files are untrusted: sizes, entity counts and nesting are capped, and every kernel call is guarded (`skills/solidcraft-crash-safety/SKILL.md`). What cannot be read becomes a warning on the feature.
- Imported files are untrusted: sizes, entity counts and nesting are capped, and every kernel call is guarded (`skills/makecad-crash-safety/SKILL.md`). What cannot be read becomes a warning on the feature.
- STEP is read by our own reader in `crates/kernel/src/step_in`, written from the public standards, with no third-party STEP code. The reader and what it supports: `docs/step-import.md`.
- Imported assemblies are rigid by default; Unlock Contents releases them.
- Kernel work (booleans, STEP/IGES import and export, tessellation) is paused except crashes and data loss: CONTRIBUTING.md, "Kernel work is paused".
@@ -26,4 +26,4 @@ Drawings follow the same rules with their own numbers, from 1: a drawing-format
## Export
- STEP, 3MF, STL, OBJ and URDF go through `file.export` and `file.save_mesh`; the MCP `export` tool calls them. URDF: `docs/urdf.md`. 3MF face tags: `docs/formats/3mf-face-tags.md`.
- Mesh and design readers and writers live in `crates/io/src/`. Write files through `crates/io/src/safe_write.rs`.
- Reference tests for exports never take their expected values from SolidCraft's own output (`skills/solidcraft-tests/SKILL.md`).
- Reference tests for exports never take their expected values from makeCAD's own output (`skills/makecad-tests/SKILL.md`).
@@ -1,6 +1,6 @@
---
name: solidcraft-ground-rules
description: "Use before adding any dependency, icon, image, font, test reference data or product wording to SolidCraft, or when unsure whether something may be copied, read or named. Covers independence from other CAD products, GPL code, asset attribution and the product name."
name: makecad-ground-rules
description: "Use before adding any dependency, icon, image, font, test reference data or product wording to makeCAD, or when unsure whether something may be copied, read or named. Covers independence from other CAD products, GPL code, asset attribution and the product name."
---
# Independence, licences, assets and the name
@@ -21,14 +21,14 @@ The rules that cannot be broken in a PR. `AGENTS.md` lists them in one line each
- Code adapted from other permissive projects (MIT OR Apache-2.0) is noted in ATTRIBUTION.md. Projects published by [storytold](https://github.com/storytold) can serve as references for implementation conventions.
## Assets: the most serious rule
- SolidCraft contains no iconography, images, fonts or artwork from commercial CAD products, ever. Screenshots of commercial CAD software are never committed.
- makeCAD contains no iconography, images, fonts or artwork from commercial CAD products, ever. Screenshots of commercial CAD software are never committed.
- Every file asset is original or openly licensed and has a row in ATTRIBUTION.md. `cargo xtask assets` enforces it.
- Command icons are the original SVG masters in `assets/icons/ui/design/svg/`, compiled through `crates/ui-egui/src/icon_svg.rs`.
- Before any icon, icon assignment or media edit, read `assets/AGENTS.md`, `assets/icons/ui/AGENTS.md` and `assets/icons/ui/STYLE_GUIDE.md`. Use the canonical bases and named finished references there; never invent a parallel icon style. `cargo xtask icons` validates them.
## The name
- SolidCraft everywhere: crates `solidcraft-*`, binaries `solidcraft` and `solidcraft-cli`, `.sc` designs (`.solidcraft` still opens), the `solidcraft/N` format tag, `SOLIDCRAFT_*` environment variables, settings and recovery folders, the MCP server name, docs, CI and packaging.
- The old name survives only in the compatibility shims listed in `docs/compatibility.md`. Do not add new uses of it.
- Public docs, web and Flatpak deployments use project Pages `/solidcraft/`. Do not add permanent old-name Pages aliases.
- Product-facing prose, assistant replies and skill names use makeCAD (`makecad-*`). Do not introduce the previous display name.
- Existing crate and binary names (`solidcraft-*`, `solidcraft`, `solidcraft-cli`), `.sc`/`.solidcraft` designs, the `solidcraft/N` format tag, `SOLIDCRAFT_*` environment variables, settings paths and MCP bridge ids remain technical compatibility identifiers. Do not rename them as a wording change or break existing designs and integrations.
- Upstream repository URLs and licence attribution remain accurate. Deployment paths follow the host configuration.
- Labels, parameter docs, messages and docs use the terms in the glossary (`docs/book/src/reference/glossary.md`): one term for each idea. A change that adds a new idea adds its term there.
- Units are millimetres and radians internally; Z is up.
@@ -1,17 +1,17 @@
---
name: solidcraft-mechanisms
description: Use when building, driving or animating an assembly or mechanism in SolidCraft through its MCP server - components, grounding, joints and joint origins, rigid groups, motion links, closed loops such as an actuator on a hinged panel or a linkage, contact sets, motion studies, degrees of freedom - or when a drive moves nothing, stops early or a part jumps when it is joined. To model the parts themselves, use solidcraft-modeling.
name: makecad-mechanisms
description: Use when building, driving or animating an assembly or mechanism in makeCAD through its MCP server - components, grounding, joints and joint origins, rigid groups, motion links, closed loops such as an actuator on a hinged panel or a linkage, contact sets, motion studies, degrees of freedom - or when a drive moves nothing, stops early or a part jumps when it is joined. To model the parts themselves, use makecad-modeling.
---
# SolidCraft mechanisms
# makeCAD mechanisms
## Overview
An assembly is components placed by joints. Work the mechanism out as world points and axes first: every pin, slide and hinge, which part each one joins, and the value you expect at each pose. Then give every joint origin by those coordinates, and check each step against a number you computed yourself. A drive that reports success can still have moved nothing. Command shapes, a worked example, the traps and reply sizes are in `reference.md` next to this file. To build the parts themselves, use `solidcraft-modeling`.
An assembly is components placed by joints. Work the mechanism out as world points and axes first: every pin, slide and hinge, which part each one joins, and the value you expect at each pose. Then give every joint origin by those coordinates, and check each step against a number you computed yourself. A drive that reports success can still have moved nothing. Command shapes, a worked example, the traps and reply sizes are in `reference.md` next to this file. To build the parts themselves, use `makecad-modeling`.
Written against SolidCraft `main` after 0.11.1, which counts the degrees of freedom of closed loops, carries motion links through chains made in any order, and answers drives in degrees with `moved` (and a `reason` when nothing could move).
Written against makeCAD `main` after 0.11.1, which counts the degrees of freedom of closed loops, carries motion links through chains made in any order, and answers drives in degrees with `moved` (and a `reason` when nothing could move).
## Before the first call
1. In SolidCraft's own chat or any MCP client, call `skill_reference {"skill":"solidcraft-mechanisms"}`. Elsewhere, read `reference.md`.
1. In makeCAD's own chat or any MCP client, call `skill_reference {"skill":"makecad-mechanisms","file":"reference.md"}`. Elsewhere, read `reference.md`.
2. **Open:** if the design is not open yet, run `open {path}`. When the server is bridged to the app and the current design is `dirty`, ask before opening anything.
3. **Map it:** run `inspect_design {"measure":false,"sketches":false}`, then `execute joint.list`. `joint.list` shows `fixed` (the grounded occurrences, always with the root, 0), `dof` per occurrence, `conflicts`, the joints, links and named origins, at about 0.5 KB per joint. `execute motion.list` lists the motion studies.
4. **Existing design:** take `edit.checkpoint` in its own call before you move bodies into components. `edit.restore_checkpoint {checkpoint}` goes back exactly, once: restoring uses the checkpoint up, so take a new one to go back again.
@@ -1,4 +1,4 @@
# SolidCraft mechanism reference for agents
# makeCAD mechanism reference for agents
These are the shapes of the commands an assembly needs, so an agent rarely has to call `list_commands`. All of them run through the `execute` tool or a `batch`. The worked example below runs in CI (`mechanisms_skill_example_moves_as_documented` in `crates/mcp/src/tests.rs`).
@@ -1,17 +1,17 @@
---
name: solidcraft-modeling
description: Use when building a new part, enclosure, bracket, plate, flange or any other 3D solid in SolidCraft through its MCP server (tools such as batch, execute, measure, screenshot), or when a SolidCraft session is using many tool calls or tokens.
name: makecad-modeling
description: Use when building a new part, enclosure, bracket, plate, flange or any other 3D solid in makeCAD through its MCP server (tools such as batch, execute, measure, screenshot), or when a makeCAD session is using many tool calls or tokens.
---
# SolidCraft modeling
# makeCAD modeling
## Overview
Work the part out as numbers first. Then build it in a few large `batch` calls, and check each stage with `measure` against values you computed yourself. A clean build takes 3-4 build batches, about 10-13 calls with the checks. Command shapes, plane axes, ids, reply sizes and known traps are in `reference.md` next to this file, so you do not need to explore the command catalog.
## Before the first call
1. In SolidCraft's own chat or any MCP client, call `skill_reference {"skill":"solidcraft-modeling"}`. Elsewhere, read `reference.md`.
1. In makeCAD's own chat or any MCP client, call `skill_reference {"skill":"makecad-modeling","file":"reference.md"}`. Elsewhere, read `reference.md`.
2. Run `inspect_design {"measure":false,"sketches":false}`, even when you think the session is empty.
- The SolidCraft server's instructions end with `Backend: connected to the SolidCraft app` when it drives the user's open app, and with `Backend: headless` otherwise.
- The makeCAD server's instructions end with `Backend: connected to the makeCAD app` when it drives the user's open app, and with `Backend: headless` otherwise.
- If the design has timeline features, ask before calling `new_design` or `open`, because both discard unsaved work. You can also build into the open design.
3. Write a plan:
- the parameters
@@ -1,4 +1,4 @@
# SolidCraft command reference for agents
# makeCAD command reference for agents
These are the shapes of the commands a part build needs, so an agent rarely has to call `list_commands`. The worked example at the end runs in CI (`skill_reference_example_builds_as_documented` in `crates/mcp/src/tests.rs`).
@@ -1,6 +1,6 @@
---
name: solidcraft-packaging
description: "Use when preparing or shipping a SolidCraft release, changing installers or packages (AppImage, MSI, dmg, Flatpak, Snap, WinGet, Nix, FreeBSD, web), release asset names, signing or the Pages deployment."
name: makecad-packaging
description: "Use when preparing or shipping a makeCAD release, changing installers or packages (AppImage, MSI, dmg, Flatpak, Snap, WinGet, Nix, FreeBSD, web), release asset names, signing or the Pages deployment."
---
# Packaging and releases
@@ -10,7 +10,7 @@ Development pushes are not application releases. Pushing to `main` or pushing a
## Preparing
1. Choose one version for the whole batch from the actual changes (patch, minor, major, `-rc.N`). Do not infer it from commit prefixes. Moving to `1.0` is the owner's decision.
2. Update `[workspace.package] version` in `Cargo.toml`, then `cargo update --workspace --offline`; only our own crates' `version =` lines in `Cargo.lock` change.
3. Fold the pending design-format changes with `scripts/fold-format-pending.sh` (`skills/solidcraft-file-formats/SKILL.md`).
3. Fold the pending design-format changes with `scripts/fold-format-pending.sh` (`skills/makecad-file-formats/SKILL.md`).
4. Run `cargo xtask ci` and the packaging checks in `.github/workflows/packaging-lint.yml`. Land the version commit on `main` through the normal review flow; never use `[skip ci]`.
## Building and publishing
@@ -1,6 +1,6 @@
---
name: solidcraft-performance
description: "Use when a SolidCraft change is slow, blocks the window, runs long work, or must build for the browser. Covers keeping the window thread free, measuring a speed-up, the wasm build and what may be JavaScript or Python."
name: makecad-performance
description: "Use when a makeCAD change is slow, blocks the window, runs long work, or must build for the browser. Covers keeping the window thread free, measuring a speed-up, the wasm build and what may be JavaScript or Python."
---
# Performance, threads and wasm
@@ -16,7 +16,7 @@ description: "Use when a SolidCraft change is slow, blocks the window, runs long
- Report medians with the range, the machine, and the cases. The pattern to follow is `docs/perf.md`: what was slow, why, the result, and proof that nothing changed (same bodies, volumes, areas and triangle counts).
- A speed-up never skips work on a mesh's box: decide with the exact bounds (`Body::exact_bounds`, grown by the record's tolerance as `apart` in `crates/kernel/src/ops.rs` does). A mesh is for display, export, previews and mesh bodies.
- Do not rewrite kernel code for speed: the kernel is being replaced, and kernel work is paused. Report a slow case with its file under the `kernel-perf` label (CONTRIBUTING.md, "Where help is wanted most").
- Pull requests run only the tests for what they touch; geometry-heavy tests run in the merge queue. Use `cargo xtask test` with the `ci` profile locally (`skills/solidcraft-tests/SKILL.md`).
- Pull requests run only the tests for what they touch; geometry-heavy tests run in the merge queue. Use `cargo xtask test` with the `ci` profile locally (`skills/makecad-tests/SKILL.md`).
## The browser build
- Everything below the apps must build for `wasm32-unknown-unknown`: `cargo xtask wasm` checks every library crate and the web app, and is part of `cargo xtask ci`. Do not add a dependency that cannot.
@@ -1,11 +1,11 @@
---
name: solidcraft-preferences
description: "Use when a SolidCraft change alters a default behaviour, an existing shortcut or the look users already have, or adds a setting in Preferences. Covers keeping the old behaviour behind a preference and the PR's 'Changes a default' line."
name: makecad-preferences
description: "Use when a makeCAD change alters a default behaviour, an existing shortcut or the look users already have, or adds a setting in Preferences. Covers keeping the old behaviour behind a preference and the PR's 'Changes a default' line."
---
# Preferences and defaults
People rely on how SolidCraft behaves today. A change that makes users see or do something different out of the box is a change of a default.
People rely on how makeCAD behaves today. A change that makes users see or do something different out of the box is a change of a default.
## The rule
- Keep the old behaviour reachable. Add a preference whose old value gives the old behaviour, and test that it still does.
@@ -16,10 +16,10 @@ People rely on how SolidCraft behaves today. A change that makes users see or do
## Adding a preference
Settings live in the `preference_settings!` table in `crates/ui-egui/src/prefs.rs`: the field, its default, the page whose reset restores it, an optional accepted range for the control channel, and the form control. Add one row there.
- A new setting that changes nothing by default needs no `yes` on the line; one that changes what users see by default does.
- Give it a label and help text through the catalogs (`skills/solidcraft-ui-text/SKILL.md`).
- Give it a label and help text through the catalogs (`skills/makecad-ui-text/SKILL.md`).
- A reset on its page restores the default; fields left out of every page keep their values when defaults are restored.
- Control channel: `ui.prefs {...}` reads and sets preferences by name (`docs/control-protocol.md`).
- Test it in a UI scenario or a `*_tests.rs` file next to the setting (`skills/solidcraft-tests/SKILL.md`).
- Test it in a UI scenario or a `*_tests.rs` file next to the setting (`skills/makecad-tests/SKILL.md`).
## What counts as a default
Anything a user sees or does differently on first launch after the update: a changed shortcut, camera or navigation behaviour, unit, naming, theme or autosave behaviour, or a tool that appears unasked. A fix that makes the app do what it already claimed is not a default change; say so on the line.
@@ -1,13 +1,13 @@
---
name: solidcraft-reporting
description: Use when a SolidCraft user says something went wrong - the app crashed or closed, a command failed or gave the wrong shape, a number is off, a design no longer rebuilds, something hangs - and wants it reported or fixed upstream. Turns the problem into a minimal, reproducible bug report with exact steps, a command script, expected and actual results and a screenshot.
name: makecad-reporting
description: Use when a makeCAD user says something went wrong - the app crashed or closed, a command failed or gave the wrong shape, a number is off, a design no longer rebuilds, something hangs - and wants it reported or fixed upstream. Turns the problem into a minimal, reproducible bug report with exact steps, a command script, expected and actual results and a screenshot.
---
# SolidCraft reporting
# makeCAD reporting
A report the maintainers can act on reproduces in a fresh design, in as few steps as possible, with the exact message and numbers. Build that here, so nobody has to rebuild the problem from a description. Use `reference.md` from `solidcraft-modeling` for command shapes, and `reference/report-template.md` (next to this file) for the report.
A report the maintainers can act on reproduces in a fresh design, in as few steps as possible, with the exact message and numbers. Build that here, so nobody has to rebuild the problem from a description. Use `reference.md` from `makecad-modeling` for command shapes, and `reference/report-template.md` (next to this file) for the report.
Written against SolidCraft 0.18.2. Report what you observed, never a guessed cause: "the fillet fails with `…`", not "the kernel can't handle tangent edges".
Written against makeCAD 0.18.2. Report what you observed, never a guessed cause: "the fillet fails with `…`", not "the kernel can't handle tangent edges".
## 1. Gather (ask only for what you cannot find)
- **Version and OS.** Help → About in the app, `solidcraft --version` or `solidcraft-cli --version`; the MCP server reports its version in `initialize` (`serverInfo.version`). Note whether the user built from source.
@@ -41,7 +41,7 @@ Shrink while the same failure, with the same message, still happens. Re-run afte
## 5. Privacy
- Never attach, upload or quote the user's design, a crash report's `design.sc`, or file contents without asking. The minimal synthetic script is the default attachment.
- GitHub does not accept `.sc` attachments. A design the user agrees to share goes up as a `.zip`: a `.sc` file is a ZIP already, so copy or rename it to `name.sc.zip`, or zip it. SolidCraft opens either kind of `.zip`.
- GitHub does not accept `.sc` attachments. A design the user agrees to share goes up as a `.zip`: a `.sc` file is a ZIP already, so copy or rename it to `name.sc.zip`, or zip it. makeCAD opens either kind of `.zip`.
- Strip home folders, user names, part and project names and file paths from messages and logs (`/home/alice/clients/acme/bracket.sc` → `bracket.sc`).
- Check screenshots for other windows, file names and anything personal.
@@ -3,7 +3,7 @@
Fill in every section and delete the hints in angle brackets. Keep it short: the script and the numbers say most of it.
````markdown
**Reproduced on:** SolidCraft <version> (<release, or built from source at commit …>), <OS and version>, <GPU, for a display problem>
**Reproduced on:** makeCAD <version> (<release, or built from source at commit …>), <OS and version>, <GPU, for a display problem>
<or: **Only in my design:** <what was tried: its history as a script rebuilds fine / fails the same way>>
### Steps
@@ -40,7 +40,7 @@ Minimal script (`solidcraft-cli run repro.json`):
The shape filled in, for a command that fails with an error. (This one is expected behaviour; a real report would be one where Actual differs from Expected.)
````markdown
**Reproduced on:** SolidCraft 0.18.2 (release), Linux x86_64
**Reproduced on:** makeCAD 0.18.2 (release), Linux x86_64
### Steps
1. Box, 20 × 20 × 10 mm, corner at the origin.
@@ -1,6 +1,6 @@
---
name: solidcraft-tests
description: "Use when writing, placing or running tests in SolidCraft: a regression test for a bug, an engine test for a command, a UI scenario, a reference (oracle) test, goldens, or when CI fails a test you did not touch."
name: makecad-tests
description: "Use when writing, placing or running tests in makeCAD: a regression test for a bug, an engine test for a command, a UI scenario, a reference (oracle) test, goldens, or when CI fails a test you did not touch."
---
# Where tests go and how to run them
@@ -11,8 +11,8 @@ The long form is `docs/book/src/dev/testing.md`.
- A regression test goes into its area's existing test file (booleans, blends, shell, STEP, naming, ...), never a new file named after the bug (#3226).
- Engine tests sit next to the code or in `*_tests.rs` files, measured against a value you can derive.
- UI scenarios are JSON in `crates/ui-egui/tests/scenarios/*.json`. Put `{"pending": "why"}` in a scenario that records a bug before it is fixed, and remove it in the fixing PR.
- Reference tests are `tests/oracle/<case>/recipe.json` with an `expected.json` beside it, run by `cargo xtask oracle`, expected values in closed form (`tools/oracle-analytic/`) or from FreeCAD as a separate program (`tools/freecad-oracle/`). A known failure names its issue (`"known_failure": "#123"`). Never change an expected value to match SolidCraft's output, and never take one from a commercial CAD product.
- Crash fixes: a regression test from the report's `design.sc` and `replay.json` (`skills/solidcraft-crash-safety/SKILL.md`).
- Reference tests are `tests/oracle/<case>/recipe.json` with an `expected.json` beside it, run by `cargo xtask oracle`, expected values in closed form (`tools/oracle-analytic/`) or from FreeCAD as a separate program (`tools/freecad-oracle/`). A known failure names its issue (`"known_failure": "#123"`). Never change an expected value to match makeCAD's output, and never take one from a commercial CAD product.
- Crash fixes: a regression test from the report's `design.sc` and `replay.json` (`skills/makecad-crash-safety/SKILL.md`).
## Unit test or rig case
- Unit tests assert the code's logic: which edges a chain picks, name resolution, history labels, refusal wording, hostile input, parsing and saving (`a_corner_round_wider_than_its_faces_overflows_and_takes_the_corners_other_edges`: per-edge radii, which no command takes).
@@ -1,11 +1,11 @@
---
name: solidcraft-ui-text
description: "Use when adding or changing any user-visible text in SolidCraft: a label, tooltip, message, command label or a new language. Covers the message catalogs in assets/locales, sorted lists, which locales a new key needs, UK English and terminology."
name: makecad-ui-text
description: "Use when adding or changing any user-visible text in makeCAD: a label, tooltip, message, command label or a new language. Covers the message catalogs in assets/locales, sorted lists, which locales a new key needs, UK English and terminology."
---
# UI text and translations
SolidCraft embeds its translations and works offline. The long form is `docs/localization.md`.
makeCAD embeds its translations and works offline. The long form is `docs/localization.md`.
## Adding a message
1. Add the id and English text in a new pending file (next section); `assets/locales/en.json` itself is only edited to change an existing message. Ids are stable: keep them when you change wording.
@@ -1,11 +1,11 @@
---
name: solidcraft-ui
description: "Use when adding or changing a SolidCraft dialog, panel, menu, overlay, canvas, camera input, slider, icon or colour in crates/ui-egui. Covers the single UI container, the UI kit, navigation::handle, theme tokens, command icons and UI scenarios."
name: makecad-ui
description: "Use when adding or changing a makeCAD dialog, panel, menu, overlay, canvas, camera input, slider, icon or colour in crates/ui-egui. Covers the single UI container, the UI kit, navigation::handle, theme tokens, command icons and UI scenarios."
---
# Dialogs and UI
The UI is thin: it reads engine state and acts through `app.run(id, params)` or `app.start(id)`. A dialog is a form that builds the parameters of a command (`skills/solidcraft-commands/SKILL.md`). The full control list is `docs/ui-kit.md`.
The UI is thin: it reads engine state and acts through `app.run(id, params)` or `app.start(id)`. A dialog is a form that builds the parameters of a command (`skills/makecad-commands/SKILL.md`). The full control list is `docs/ui-kit.md`.
## One outer container
- All panels, floating sheets, menus, overlays and platform UI windows use `ui_kit::Container`, directly or through `Panel`, `Window`, `Confirm` and `Menu`. Declare the semantic `Surface`; workspace panels use its shared layout policy and chrome.
@@ -22,10 +22,10 @@ The UI is thin: it reads engine state and acts through `app.run(id, params)` or
Every page or canvas with a camera (viewport, Render preview, a flat pattern or drawing page) calls `navigation::handle` (`crates/ui-egui/src/navigation.rs`) with its `NavCaps` (orbit off for flat 2D pages). Never hand-roll camera input from drags, the wheel or pinch; `hand_rolled_camera_input_is_rejected` fails if a page does.
## Icons
Command icons are original SVG masters compiled through `crates/ui-egui/src/icon_svg.rs`. Read `assets/AGENTS.md`, `assets/icons/ui/AGENTS.md` and `assets/icons/ui/STYLE_GUIDE.md` first, add the ATTRIBUTION.md row, and run `cargo xtask icons` and `cargo xtask assets`. See `skills/solidcraft-ground-rules/SKILL.md`.
Command icons are original SVG masters compiled through `crates/ui-egui/src/icon_svg.rs`. Read `assets/AGENTS.md`, `assets/icons/ui/AGENTS.md` and `assets/icons/ui/STYLE_GUIDE.md` first, add the ATTRIBUTION.md row, and run `cargo xtask icons` and `cargo xtask assets`. See `skills/makecad-ground-rules/SKILL.md`.
## Text
Every label, tooltip and message goes through the catalogs: `skills/solidcraft-ui-text/SKILL.md`. A new behaviour that is on by default: `skills/solidcraft-preferences/SKILL.md`.
Every label, tooltip and message goes through the catalogs: `skills/makecad-ui-text/SKILL.md`. A new behaviour that is on by default: `skills/makecad-preferences/SKILL.md`.
## Look at the result
Run the app, drive it and read the screenshot: `skills/solidcraft-agent-tools/SKILL.md`. A UI scenario (`crates/ui-egui/tests/scenarios/*.json`) covers the clicks; see `skills/solidcraft-tests/SKILL.md`. Work that takes long must not block the window: `skills/solidcraft-performance/SKILL.md`.
Run the app, drive it and read the screenshot: `skills/makecad-agent-tools/SKILL.md`. A UI scenario (`crates/ui-egui/tests/scenarios/*.json`) covers the clicks; see `skills/makecad-tests/SKILL.md`. Work that takes long must not block the window: `skills/makecad-performance/SKILL.md`.
+47 -49
View File
@@ -18,7 +18,7 @@ pub const ROUTER_MAX_CHARS: usize = 5000;
pub const SKILL_MAX_CHARS: usize = 3600;
/// Skills written before the size cap (the modelling skills carry their command shapes).
const LONG_SKILLS: &[&str] =
&["solidcraft-checking", "solidcraft-contributing", "solidcraft-editing", "solidcraft-mechanisms", "solidcraft-modeling", "solidcraft-reporting"];
&["makecad-checking", "makecad-contributing", "makecad-editing", "makecad-mechanisms", "makecad-modeling", "makecad-reporting"];
const SKIPPED_ROOTS: &[&str] = &["plan", "target", "target-wasm"];
/// A file that is checked: its path from the repository root and its text.
@@ -300,7 +300,7 @@ mod tests {
check(docs, &Repo { exists: &exists, roots: &roots, commands: &commands })
}
const SKILL: &str = "---\nname: solidcraft-a\ndescription: Use when a.\n---\n# A\n";
const SKILL: &str = "---\nname: makecad-a\ndescription: Use when a.\n---\n# A\n";
fn router(table: &str) -> Doc {
doc("AGENTS.md", &format!("# Router\n\n| Working on | Read |\n|---|---|\n{table}\n"))
@@ -313,80 +313,79 @@ mod tests {
#[test]
fn a_consistent_router_passes() {
let docs = [router("| a | `skills/solidcraft-a/SKILL.md` |"), doc("skills/solidcraft-a/SKILL.md", SKILL)];
assert_eq!(problems(&docs, &["skills/solidcraft-a/SKILL.md"]), Vec::<String>::new());
let docs = [router("| a | `skills/makecad-a/SKILL.md` |"), doc("skills/makecad-a/SKILL.md", SKILL)];
assert_eq!(problems(&docs, &["skills/makecad-a/SKILL.md"]), Vec::<String>::new());
}
#[test]
fn a_missing_path_is_reported_and_placeholders_are_not() {
let text = "See `docs/gone.md`, `docs/here.md`, `crates/doc/src/format/v<N>/`, `crates/*/x.rs`, `plan/STATUS.md`, `~/.claude/skills/x`, `src/lib.rs`, `lib.rs`.";
let docs = [router("| a | `skills/solidcraft-a/SKILL.md` |"), doc("skills/solidcraft-a/SKILL.md", &format!("{SKILL}{text}"))];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md", "docs/here.md"]);
assert_eq!(p, ["skills/solidcraft-a/SKILL.md: `docs/gone.md` does not exist"]);
let docs = [router("| a | `skills/makecad-a/SKILL.md` |"), doc("skills/makecad-a/SKILL.md", &format!("{SKILL}{text}"))];
let p = problems(&docs, &["skills/makecad-a/SKILL.md", "docs/here.md"]);
assert_eq!(p, ["skills/makecad-a/SKILL.md: `docs/gone.md` does not exist"]);
}
#[test]
fn links_resolve_from_the_file_and_fences_are_skipped() {
let text = "[ok](../../docs/here.md#top) [bad](../../docs/no.md) [web](https://x.io/docs/no.md)\n```\n`docs/in-fence.md`\n```\n";
let docs = [router("| a | `skills/solidcraft-a/SKILL.md` |"), doc("skills/solidcraft-a/SKILL.md", &format!("{SKILL}{text}"))];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md", "docs/here.md"]);
assert_eq!(p, ["skills/solidcraft-a/SKILL.md: `../../docs/no.md` does not exist"]);
let docs = [router("| a | `skills/makecad-a/SKILL.md` |"), doc("skills/makecad-a/SKILL.md", &format!("{SKILL}{text}"))];
let p = problems(&docs, &["skills/makecad-a/SKILL.md", "docs/here.md"]);
assert_eq!(p, ["skills/makecad-a/SKILL.md: `../../docs/no.md` does not exist"]);
}
#[test]
fn a_skills_own_relative_path_resolves_from_its_folder() {
let docs = [
router("| a | `skills/solidcraft-a/SKILL.md` |"),
doc("skills/solidcraft-a/SKILL.md", &format!("{SKILL}`docs/scripts/x.py` `docs/other/y.py`")),
router("| a | `skills/makecad-a/SKILL.md` |"),
doc("skills/makecad-a/SKILL.md", &format!("{SKILL}`docs/scripts/x.py` `docs/other/y.py`")),
];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md", "skills/solidcraft-a/docs/scripts/x.py"]);
assert_eq!(p, ["skills/solidcraft-a/SKILL.md: `docs/other/y.py` does not exist"]);
let p = problems(&docs, &["skills/makecad-a/SKILL.md", "skills/makecad-a/docs/scripts/x.py"]);
assert_eq!(p, ["skills/makecad-a/SKILL.md: `docs/other/y.py` does not exist"]);
}
#[test]
fn a_line_number_suffix_is_ignored() {
let docs = [router("| a | `skills/solidcraft-a/SKILL.md` |"), doc("skills/solidcraft-a/SKILL.md", &format!("{SKILL}`docs/here.md:12-30`"))];
assert!(problems(&docs, &["skills/solidcraft-a/SKILL.md", "docs/here.md"]).is_empty());
let docs = [router("| a | `skills/makecad-a/SKILL.md` |"), doc("skills/makecad-a/SKILL.md", &format!("{SKILL}`docs/here.md:12-30`"))];
assert!(problems(&docs, &["skills/makecad-a/SKILL.md", "docs/here.md"]).is_empty());
}
#[test]
fn an_unknown_xtask_command_is_reported() {
let docs = [
router("| a | `skills/solidcraft-a/SKILL.md` |"),
doc("skills/solidcraft-a/SKILL.md", &format!("{SKILL}Run `cargo xtask lists --fix` then `cargo xtask nope`.")),
router("| a | `skills/makecad-a/SKILL.md` |"),
doc("skills/makecad-a/SKILL.md", &format!("{SKILL}Run `cargo xtask lists --fix` then `cargo xtask nope`.")),
];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md"]);
assert_eq!(p, ["skills/solidcraft-a/SKILL.md: `cargo xtask nope` is not an xtask command"]);
let p = problems(&docs, &["skills/makecad-a/SKILL.md"]);
assert_eq!(p, ["skills/makecad-a/SKILL.md: `cargo xtask nope` is not an xtask command"]);
}
#[test]
fn a_skill_that_does_not_exist_is_reported() {
let docs =
[router("| a | `skills/solidcraft-a/SKILL.md` |\n| b | `skills/solidcraft-b/SKILL.md` |"), doc("skills/solidcraft-a/SKILL.md", SKILL)];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md"]);
assert!(p.contains(&"AGENTS.md: `skills/solidcraft-b` does not exist".to_string()), "{p:?}");
assert!(p.contains(&"AGENTS.md: the router table lists skills/solidcraft-b/SKILL.md, which has no SKILL.md".to_string()), "{p:?}");
let docs = [router("| a | `skills/makecad-a/SKILL.md` |\n| b | `skills/makecad-b/SKILL.md` |"), doc("skills/makecad-a/SKILL.md", SKILL)];
let p = problems(&docs, &["skills/makecad-a/SKILL.md"]);
assert!(p.contains(&"AGENTS.md: `skills/makecad-b` does not exist".to_string()), "{p:?}");
assert!(p.contains(&"AGENTS.md: the router table lists skills/makecad-b/SKILL.md, which has no SKILL.md".to_string()), "{p:?}");
}
#[test]
fn a_skill_missing_from_the_table_is_reported() {
let docs = [
router("| a | `skills/solidcraft-a/SKILL.md` |"),
doc("skills/solidcraft-a/SKILL.md", SKILL),
doc("skills/solidcraft-c/SKILL.md", &SKILL.replace("-a", "-c")),
router("| a | `skills/makecad-a/SKILL.md` |"),
doc("skills/makecad-a/SKILL.md", SKILL),
doc("skills/makecad-c/SKILL.md", &SKILL.replace("-a", "-c")),
];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md", "skills/solidcraft-c/SKILL.md"]);
assert_eq!(p, ["AGENTS.md: the router table does not list skills/solidcraft-c/SKILL.md"]);
let p = problems(&docs, &["skills/makecad-a/SKILL.md", "skills/makecad-c/SKILL.md"]);
assert_eq!(p, ["AGENTS.md: the router table does not list skills/makecad-c/SKILL.md"]);
}
#[test]
fn prose_mentions_of_skills_outside_the_table_do_not_route() {
let docs = [doc("AGENTS.md", "Install into `~/.claude/skills/` or see skills/solidcraft-a.\n"), doc("skills/solidcraft-a/SKILL.md", SKILL)];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md"]);
let docs = [doc("AGENTS.md", "Install into `~/.claude/skills/` or see skills/makecad-a.\n"), doc("skills/makecad-a/SKILL.md", SKILL)];
let p = problems(&docs, &["skills/makecad-a/SKILL.md"]);
assert_eq!(
p,
[
"AGENTS.md: the router table does not list skills/solidcraft-a/SKILL.md",
"AGENTS.md: the router table does not list skills/makecad-a/SKILL.md",
"AGENTS.md: no router table (rows naming `skills/<name>/SKILL.md`)"
]
);
@@ -394,20 +393,19 @@ mod tests {
#[test]
fn front_matter_must_match_the_folder() {
let docs =
[router("| a | `skills/solidcraft-a/SKILL.md` |"), doc("skills/solidcraft-a/SKILL.md", "---\nname: other\ndescription: \"\"\n---\n")];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md"]);
let docs = [router("| a | `skills/makecad-a/SKILL.md` |"), doc("skills/makecad-a/SKILL.md", "---\nname: other\ndescription: \"\"\n---\n")];
let p = problems(&docs, &["skills/makecad-a/SKILL.md"]);
assert_eq!(
p,
[
"skills/solidcraft-a/SKILL.md: front matter name `other` is not the folder name `solidcraft-a`",
"skills/solidcraft-a/SKILL.md: front matter has no description"
"skills/makecad-a/SKILL.md: front matter name `other` is not the folder name `makecad-a`",
"skills/makecad-a/SKILL.md: front matter has no description"
]
);
assert_eq!(front_matter("no front matter"), None);
assert_eq!(
front_matter("---\r\nname: solidcraft-a\r\ndescription: Windows checkout\r\n---\r\n"),
Some(("solidcraft-a".into(), "Windows checkout".into()))
front_matter("---\r\nname: makecad-a\r\ndescription: Windows checkout\r\n---\r\n"),
Some(("makecad-a".into(), "Windows checkout".into()))
);
}
@@ -415,14 +413,14 @@ mod tests {
fn sizes_are_capped_except_for_the_older_skills() {
let long = "x".repeat(SKILL_MAX_CHARS);
let docs = [
doc("AGENTS.md", &format!("| `skills/solidcraft-a/SKILL.md` |{}", "y".repeat(ROUTER_MAX_CHARS))),
doc("skills/solidcraft-a/SKILL.md", &format!("{SKILL}{long}")),
doc("skills/solidcraft-modeling/SKILL.md", &format!("{}{long}", SKILL.replace("-a", "-modeling"))),
doc("AGENTS.md", &format!("| `skills/makecad-a/SKILL.md` |{}", "y".repeat(ROUTER_MAX_CHARS))),
doc("skills/makecad-a/SKILL.md", &format!("{SKILL}{long}")),
doc("skills/makecad-modeling/SKILL.md", &format!("{}{long}", SKILL.replace("-a", "-modeling"))),
];
let p = problems(&docs, &["skills/solidcraft-a/SKILL.md", "skills/solidcraft-modeling/SKILL.md"]);
let p = problems(&docs, &["skills/makecad-a/SKILL.md", "skills/makecad-modeling/SKILL.md"]);
assert!(p.iter().any(|m| m.starts_with("AGENTS.md is ")), "{p:?}");
assert!(p.iter().any(|m| m.starts_with("skills/solidcraft-a/SKILL.md: ") && m.contains("split it")), "{p:?}");
assert!(!p.iter().any(|m| m.contains("solidcraft-modeling/SKILL.md: ") && m.contains("split it")), "{p:?}");
assert!(p.iter().any(|m| m.starts_with("skills/makecad-a/SKILL.md: ") && m.contains("split it")), "{p:?}");
assert!(!p.iter().any(|m| m.contains("makecad-modeling/SKILL.md: ") && m.contains("split it")), "{p:?}");
}
/// A SKILL.md filled to the size cap, read from a CRLF checkout: its front matter is found
@@ -431,12 +429,12 @@ mod tests {
fn a_crlf_checkout_is_checked_as_git_stores_it() {
let root = std::env::temp_dir().join(format!("xtask-skills-crlf-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("skills/solidcraft-a")).unwrap();
std::fs::create_dir_all(root.join("skills/makecad-a")).unwrap();
let lines = "x\n".repeat((SKILL_MAX_CHARS - SKILL.len()) / 2);
let skill = format!("{SKILL}{lines}{}", "x".repeat(SKILL_MAX_CHARS - SKILL.len() - lines.len()));
let crlf = |t: &str| t.replace('\n', "\r\n");
std::fs::write(root.join("AGENTS.md"), crlf("# Router\n\n| a | `skills/solidcraft-a/SKILL.md` |\n")).unwrap();
std::fs::write(root.join("skills/solidcraft-a/SKILL.md"), crlf(&skill)).unwrap();
std::fs::write(root.join("AGENTS.md"), crlf("# Router\n\n| a | `skills/makecad-a/SKILL.md` |\n")).unwrap();
std::fs::write(root.join("skills/makecad-a/SKILL.md"), crlf(&skill)).unwrap();
let result = run(&root);
let _ = std::fs::remove_dir_all(&root);
assert_eq!(result, Ok(()));