@coloopx/colocad 0.1.0-alpha.3 → 0.1.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/NOTICE.md +2 -0
  2. package/README.md +130 -4
  3. package/README.zh-CN.md +111 -4
  4. package/bin/colocad.mjs +28 -4
  5. package/docs/README.md +28 -0
  6. package/docs/README.zh-CN.md +85 -0
  7. package/docs/agent-modeling-handbook.md +68 -0
  8. package/docs/agent-modeling-handbook.zh-CN.md +222 -0
  9. package/docs/agent-modeling-research.md +22 -0
  10. package/docs/api.md +95 -0
  11. package/docs/best-practices.md +45 -0
  12. package/docs/concepts.md +37 -0
  13. package/docs/getting-started.md +53 -0
  14. package/docs/integrations/claude-code.md +52 -0
  15. package/docs/integrations/codex.md +55 -0
  16. package/docs/integrations/overview.md +53 -0
  17. package/docs/integrations/pi.md +73 -0
  18. package/docs/integrations/verification.md +30 -0
  19. package/docs/modeling-history.md +60 -0
  20. package/docs/modeling-workflow.zh-CN.md +77 -0
  21. package/docs/troubleshooting.md +25 -0
  22. package/docs/validation.md +23 -0
  23. package/examples/hiwin-kk60/README.md +55 -0
  24. package/examples/hiwin-kk60/model.mjs +94 -0
  25. package/examples/hiwin-kk60/run.mjs +14 -0
  26. package/examples/hiwin-kk60/sources.json +88 -0
  27. package/examples/integrations/README.md +47 -0
  28. package/examples/integrations/compact-tools.mjs +27 -0
  29. package/examples/integrations/guided-workflow.mjs +31 -0
  30. package/kernel/native/darwin-arm64/agent-cad +1 -1
  31. package/kernel/native/darwin-arm64/manifest.json +1 -2
  32. package/kernel/native/linux-arm64/agent-cad +1 -1
  33. package/kernel/native/linux-arm64/manifest.json +1 -2
  34. package/kernel/native/linux-x64/agent-cad +2 -2
  35. package/kernel/native/linux-x64/manifest.json +2 -3
  36. package/kernel/release.json +4 -4
  37. package/package.json +40 -4
  38. package/skills/colocad/SKILL.md +18 -8
  39. package/skills/colocad/assets/product-brief.example.json +20 -0
  40. package/skills/colocad/references/history.md +19 -0
  41. package/skills/colocad/references/materials.md +37 -0
  42. package/skills/colocad/references/modeling-loop.md +33 -0
  43. package/skills/colocad/references/prompt-patterns.md +70 -0
  44. package/skills/colocad/references/tool-contracts.md +33 -0
  45. package/skills/colocad/references/tuning.md +30 -0
  46. package/src/render.mjs +72 -0
  47. package/src/session.d.mts +34 -0
  48. package/src/session.mjs +140 -0
  49. package/src/view-server.mjs +50 -0
  50. package/viewer/THREE-LICENSE +21 -0
  51. package/viewer/dist/index.js +4236 -0
  52. package/viewer/dist/standalone.js +4236 -0
  53. package/viewer/index.d.ts +18 -0
@@ -0,0 +1,53 @@
1
+ # Integrate with an existing harness
2
+
3
+ Keep the agent, harness, SDK and native CAD process in the **same sandbox**. Install colocad in the sandbox image or project dependency layer. Bind it to the harness's existing tool execution and artifact storage.
4
+
5
+ ```mermaid
6
+ flowchart LR
7
+ subgraph Sandbox[One sandbox]
8
+ A[Agent + existing harness] --> B[Skill + shell tools]
9
+ A --> C[Typed CAD tools]
10
+ B --> D[Local SDK]
11
+ C --> D
12
+ D --> E[Rust child process]
13
+ E --> F[Revision files]
14
+ F --> A
15
+ end
16
+ ```
17
+
18
+ | Harness | Recommended first route | Optional route |
19
+ | --- | --- | --- |
20
+ | Codex | Project skill + existing shell/image tools | Host-provided tool bridge |
21
+ | Claude Code | Project skill + existing Bash/Read tools | Host-provided MCP adapter |
22
+ | Pi coding agent | Project skill or explicit `--skill` | Local extension registering CAD tools |
23
+ | Pi agent core / custom TypeScript harness | `createCadTools` through a thin adapter | Existing shell tool + loaded skill instructions |
24
+
25
+ An MCP transport is optional integration code, not a shipped colocad server. A skill supplies workflow guidance; it does not grant filesystem access, install Node, or register typed tools by itself.
26
+
27
+ ## Session lifecycle
28
+
29
+ 1. Allocate a session output root from trusted harness state. Load the pinned package and skill once; record package and native versions.
30
+ 2. Parse the task into dimensions, datum, constraints and explicit assumptions. Pick a kernel model or a feature tree deliberately.
31
+ 3. Preflight the source, then build a geometry revision. Return failures with their feature ID so the agent can correct the relevant feature.
32
+ 4. Inspect the result: geometry counts/bounds/volume, requested views and any internal regions. Persist the accepted source and receipt before moving to the next edit.
33
+ 5. Return artifact references through the harness's existing attachment system. Upload or copy the source, STEP, receipt and useful previews before the sandbox is destroyed.
34
+
35
+ With typed tools, allocate one `CadClient` for each sequential modeling session. Do not share its mutable revision/cache state across unrelated concurrent sessions. Schedule independent jobs with separate clients and output roots, and cap concurrency according to actual sandbox memory. The Pi sample deliberately serializes modeling calls.
36
+
37
+ With shell tools, use argument arrays in a process API rather than interpolating model text into shell commands. Store JSON in a file. Agent-controlled dimensions belong in model input; executable paths, output roots and credentials belong to harness configuration. Keep normal harness permissions in force.
38
+
39
+ ## Results and failures
40
+
41
+ A useful tool result includes the artifact directory, counts/bounds/volume, validation summary and timings. Keep detailed feature diagnostics in the full receipt and attach a PNG for visual inspection. A path in text is not itself an image input to a remote vision model. The [Pi adapter](../../examples/integrations/pi-tools.mjs) shows text/image content and full `details` together.
42
+
43
+ `cad_validate` success is only preflight. A nonzero child exit, a failed receipt or an explicit degraded feature must remain visible. Do not turn a failed build into a success containing an empty output path. Do not retry the same invalid geometry indefinitely; change the failing feature or report the unresolved constraint.
44
+
45
+ The `on_fail` record policy is an explicit degraded-model choice, not a general recovery default. Its object includes `kind: "record"`, a reason, omitted details and affected requirements. Check recorded degradations before accepting a revision; the Pi adapter includes these in model-visible text. Preserve the original exact model when using a simplified display/envelope representation.
46
+
47
+ ## Resource and storage policy
48
+
49
+ Start with the default 30-second call budget and one active native operation. Increase the budget for a measured workload; do not infer a universal 512 MiB allowance from one benchmark. Account for agent runtime, Node, native descendants, previews and file cache in a real sandbox measurement.
50
+
51
+ For multiple camera angles, use the same client or `observeArtifact`. For repeated parts, reuse a part definition and place occurrences. Keep cache/source revisions while referenced; artifact cleanup is a host policy and must not delete a live observation's source STEP.
52
+
53
+ Use [Pi](pi.md), [Claude Code](claude-code.md) or [Codex](codex.md) for concrete setup. [Best practices](../best-practices.md) covers modeling and performance choices.
@@ -0,0 +1,73 @@
1
+ # Pi agent core and Pi coding agent
2
+
3
+ The adapter is tested with `@earendil-works/pi-agent-core@1.5.0` and `@earendil-works/pi-coding-agent@1.5.0`. Pi APIs have changed across releases: pin the versions in your harness and run the adapter tests before upgrading. Older harnesses can use the skill/CLI route without replacing their agent core.
4
+
5
+ ## Pi agent core: register local tools
6
+
7
+ Clone the example project and install its lockfile:
8
+
9
+ ```sh
10
+ git clone https://github.com/Coloopx/colocad.git
11
+ cd colocad/examples/integrations
12
+ npm ci --ignore-scripts
13
+ npm test
14
+ ```
15
+
16
+ [pi-tools.mjs](../../examples/integrations/pi-tools.mjs) adapts colocad's JSON Schemas and receipts to Pi `AgentTool`s. [pi-core.mjs](../../examples/integrations/pi-core.mjs) constructs an agent with these tools. Your harness supplies its existing model, stream function and authentication:
17
+
18
+ ```js
19
+ import { createCadAgent } from './pi-core.mjs';
20
+
21
+ // model, streamFn and getApiKey come from your existing harness configuration.
22
+ const agent = await createCadAgent({
23
+ model, streamFn, getApiKey,
24
+ outputRoot: '/workspace/cad-output/session-001',
25
+ });
26
+ await agent.prompt('Build an 80 × 50 × 6 mm mounting plate with four Ø6 holes. '
27
+ + 'Use a centered 2 × 2 grid at 50 × 30 mm pitch. Export STEP and inspect a preview.');
28
+ ```
29
+
30
+ This is a host wiring fragment, not a standalone provider login script. Pi core 1.5 requires a `streamFn`. For an existing agent, merge the returned tools into its tools array while idle, retaining your existing tools and context policies:
31
+
32
+ ```js
33
+ import { createPiCadTools } from './pi-tools.mjs';
34
+ const cadTools = await createPiCadTools({ outputRoot: '/workspace/cad-output/session-001' });
35
+ agent.state.tools = [...agent.state.tools, ...cadTools]; // register once; names must be unique
36
+ ```
37
+
38
+ The adapter preserves schema `$defs`, serializes CAD operations, throws on failed receipts, and attaches preview PNG content. It does not add a database or copy artifacts outside the sandbox. The harness still owns accepted model state, attachments, token budget and session persistence.
39
+
40
+ ## Pi coding agent: use the extension
41
+
42
+ From the example project after `npm ci`:
43
+
44
+ ```sh
45
+ ./node_modules/.bin/pi --extension ./pi-extension.mjs
46
+ ```
47
+
48
+ The extension registers five `cad_*` tools. Output defaults to `./cad-output`; set `COLOCAD_OUTPUT_DIR` in the shell launching Pi to choose a trusted absolute destination. Start it from the intended project directory and restart/rebind when changing projects. Use Pi's existing model/auth configuration.
49
+
50
+ For the modeling workflow as well, load the bundled skill:
51
+
52
+ ```sh
53
+ ./node_modules/.bin/pi --extension ./pi-extension.mjs \
54
+ --skill ./node_modules/@coloopx/colocad/skills/colocad
55
+ ```
56
+
57
+ Use `/skill:colocad` with the part description. The skill may use the shell helper for its starting assets; the extension adds direct typed tools. You can use either route independently.
58
+
59
+ ## Skill-only integration
60
+
61
+ In a project where colocad and Pi are already installed:
62
+
63
+ ```sh
64
+ mkdir -p .agents/skills
65
+ test ! -e .agents/skills/colocad && \
66
+ cp -R node_modules/@coloopx/colocad/skills/colocad .agents/skills/colocad
67
+ ```
68
+
69
+ Start Pi in that project and invoke `/skill:colocad`. Keep the complete folder: its instructions reference scripts, assets and supporting guides. Review the project skill under Pi's normal project trust flow. No global install or permissions bypass is required.
70
+
71
+ The example tests execute the actual Pi core loop with deterministic model responses, the actual extension loader, and the published Rust binary. They do not call a live model provider. See [verification scope](verification.md).
72
+
73
+ References checked 2026-11-07: [Pi core](https://github.com/earendil-works/pi/tree/main/packages/agent), [extensions](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md), [skills](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/skills.md). The installed 1.5.0 declarations and CLI help were also checked.
@@ -0,0 +1,30 @@
1
+ # Integration verification
2
+
3
+ Verified on **2026-11-07**, Node.js **22.23.3**, **macOS arm64**, using the public npm package **@coloopx/colocad@0.1.0-alpha.3** and its bundled Rust binary. Pi core, Pi AI and Pi coding agent are pinned to **1.5.0** in the example lockfile.
4
+
5
+ | Check | Result | What it establishes |
6
+ | --- | --- | --- |
7
+ | SDK validate → preview → camera change → parameter edit | Pass | Real geometry, cached observation, expected removed volume and persisted source |
8
+ | Pi adapter schemas, preview image, failure mapping and cancellation before dispatch | Pass | Complete `$defs`, valid PNG content, error results and no dispatch after pre-cancellation |
9
+ | Explicit degraded feature | Pass | The omitted fillet and native error remain in model-visible tool text |
10
+ | Pi core tool loop with a failed edit then corrected build | Pass | Actual agent loop propagates failure and resumes to a successful STEP export |
11
+ | Pi coding agent extension loader and skill discovery | Pass | Five executable CAD tools register; the complete skill is discoverable |
12
+ | Existing root Node regression suite | 5 passed | Feature compiler, edits, output collision handling and native-output refusal |
13
+ | Documented CLI and copied skill commands | Pass | Feature-tree planning/build/edit and kernel-model helpers execute from a consuming project |
14
+ | Independent OCCT STEP readback | 4 passed | Two manifold revisions and two copied-skill plates are valid single solids with checked material regions |
15
+
16
+ [Machine-readable results, volumes, probes and STEP hashes](../evidence/harness-integrations.json).
17
+
18
+ Reproduce the integration tests from the repository root:
19
+
20
+ ```sh
21
+ npm ci --prefix examples/integrations --ignore-scripts
22
+ npm test --prefix examples/integrations
23
+ node examples/integrations/sdk.mjs ./out/sdk-example
24
+ ```
25
+
26
+ The five integration tests run native CAD operations and actual Pi library code. The model response stream is deliberately scripted: no provider API key, inference request or autonomous model decision is involved. Thus the result verifies execution contracts and recovery, not unseen-drawing success rate or a model's ability to choose the correct CAD features.
27
+
28
+ Codex skill paths/invocation and Claude Code skill paths/invocation were checked against their official documentation. The bundled helper was run from both `.agents/skills/colocad` and `.claude/skills/colocad`. No Claude Code live session was run, and this test run did not evaluate a live Codex model reconstructing a drawing. The Pi live-provider schema negotiation remains dependent on the provider you configure.
29
+
30
+ This verification adds no new performance claims. Cross-platform npm release checks are recorded separately in [release-alpha.3.json](../evidence/release-alpha.3.json); the new adapter regression itself was run on macOS arm64. Native SOLIDWORKS acceptance remains subject to the [existing limitations](../validation.md).
@@ -0,0 +1,60 @@
1
+ # Modeling history: CLI first
2
+
3
+ Added in alpha.4. In a source checkout, use `node bin/colocad.mjs` in place of `colocad` below. The package entry points are `/session` for the recorder and `/viewer` for the browser component.
4
+
5
+ ```sh
6
+ # Build a real milestone and preserve its source, receipt and native preview.
7
+ colocad record model.json ./history --label "Bore the hub"
8
+
9
+ # Repeat record with the next model revision, using the same history directory.
10
+ # Launch the local viewer and open the default browser.
11
+ colocad view ./history
12
+
13
+ # Headless sandbox: print the URL; use the existing harness's port forwarding.
14
+ colocad view ./history --no-open --port 8787
15
+
16
+ # Start a display cutaway and also write a standalone offline file.
17
+ colocad view ./history --cutaway --export ./review.html
18
+
19
+ # Export only: no browser and no listening process.
20
+ colocad replay ./history ./review.html
21
+ ```
22
+
23
+ `view` binds only to `127.0.0.1`; port 0 (the default) chooses an available port. It prints one JSON ready event with the actual URL. Ctrl+C shuts it down. No native GUI or separately provisioned CAD service is required. It serves a snapshot of the recorded session; rerun the command after adding milestones. `--export` writes the same HTML that the viewer serves. Only the HTML root is served, not an arbitrary directory of files.
24
+
25
+ A session records each actual build/inspection attempt, including failures and interrupted calls. Native artifacts use paths relative to the session. The recorder owns the last successful source so `edit` starts from an accepted model. Archive the whole session directory to preserve all intermediate STEP files. The standalone HTML embeds models, receipts, meshes and previews, plus the final successful geometry STEP.
26
+
27
+ The viewer supports stage selection, review playback, orbit/zoom, four camera presets, display clipping/explosion, part selection/visibility and input/receipt inspection. These display controls do not change exact CAD. Playback is a presentation cadence; measured call durations are shown separately. With no WebGL, native PNG previews provide a fallback.
28
+
29
+ ## Export an animation from the CLI
30
+
31
+ ```sh
32
+ # Optional media dependencies; not needed for CAD builds or the HTML viewer.
33
+ npm install -D playwright
34
+ npx playwright install chromium
35
+ # Install FFmpeg using your host package manager.
36
+ colocad render ./history ./modeling.mp4 --width 1280 --height 800 --fps 15
37
+ colocad render ./history ./modeling.gif --width 960 --height 600 --fps 10 --seconds-per-step 0.75
38
+ ```
39
+
40
+ The renderer reads the saved native meshes and starts Chromium and FFmpeg locally. It displays four synchronized cameras, measured call durations and the construction journal. The final segment explodes and reassembles the saved geometry for inspection. It writes the movie, a `.json` manifest (hashes, timings, frames, source revisions) and a `.poster.png`. Existing movies are not overwritten. Encoding does not invoke the CAD kernel. Video duration is edited review pacing and is **not** a performance benchmark. Rendering uses more memory than a geometry-only sandbox; run it where Chromium and FFmpeg are available.
41
+
42
+ [Real catalog product: HIWIN KK60](../examples/hiwin-kk60/README.md) includes the generation and independent STEP verification commands.
43
+
44
+ ## SDK integration
45
+
46
+ ```js
47
+ import { ModelingSession, exportSessionHtml, createSessionTools } from '@coloopx/colocad/session';
48
+ const session = await ModelingSession.create('./history', { title: 'Product reconstruction' });
49
+ const result = await session.build(model, { label: 'Main housing', kind: 'geometry' });
50
+ if (!result.ok) throw new Error(JSON.stringify(result.error));
51
+ await session.edit({ boreDiameter: 8 }, { label: 'Correct bore diameter' });
52
+ await exportSessionHtml(session.root, './review.html');
53
+ const tools = await createSessionTools(session);
54
+ ```
55
+
56
+ Use existing parameters when editing. `createSessionTools` changes `cad_edit` to `{ parameters }`: it uses the recorded accepted source, rather than accepting another model argument. Other modeling calls use their existing arguments. The Pi examples accept `cadSession` or `COLOCAD_SESSION_DIR` to opt into history. See [recorded-pi.mjs](../examples/integrations/recorded-pi.mjs).
57
+
58
+ For embedding into a host UI, `readSessionBundle(directory)` returns the viewer data. Import `@coloopx/colocad/viewer` in the browser, add `<colocad-viewer>`, and assign that data to its `session` property. This is optional host integration; the CLI remains the end-user entry point.
59
+
60
+ [Actual modeling workflow and proposed improvements](modeling-workflow.zh-CN.md) · [Specification and test mapping](../specs/0001-modeling-history.md)
@@ -0,0 +1,77 @@
1
+ # 实际建模操作、数据流与完整产品的验收
2
+
3
+ [完整方案:材料、工具、skill/提示词、调优](agent-modeling-handbook.zh-CN.md)在本次操作记录基础上给出可复用方法。
4
+
5
+ 本说明区分已执行的操作与下一阶段拟采用的方法。熟悉某类机械的原理,有助于拆解设计;具体型号的尺寸、公差和内部结构仍需资料与测量支持。
6
+
7
+ ## 当前实际执行了什么
8
+
9
+ 本次实际完成的是 [HIWIN KK60 完整执行器复建](../examples/hiwin-kk60/README.md),配置为 300 mm 导轨、5 mm 导程、单滑块、无选配电机与罩壳。此前的涡扇仍只是合成几何测试件。
10
+
11
+ | 阶段 | 实际输入与操作 | 实际输出 |
12
+ | --- | --- | --- |
13
+ | 查资料与读图 | 厂家目录 PDF;提取尺寸文字,渲染第 25 页,再放大检查剖视图 | 指定型号/配置,尺寸来源、坐标基准与假设清单 |
14
+ | 纠正读图 | 放大 SECTION A-A,把误读的 15 mm 丝杠中心高纠正为 23 mm | 更新共轴零件与接口尺寸 |
15
+ | 编写几何程序 | 助手依据图纸、数值和接口编写 `model.mjs` | 52 个特征及 81 个命名实例的生成器;运行时开放行程参数 |
16
+ | 实际执行 | 生成明确的 kernel JSON,调用 `ModelingSession.build` | 16 个阶段的源文件、回执、精确 STEP、预览网格 |
17
+ | 处理失败 | 总装触发内部 STEP 的 10 万实体限制 | 修复内部序列化预算、增加 Rust 回归;保留原失败会话 |
18
+ | 独立检查 | 用 OCCT 读回 STEP,检查实体、体积、孔/槽材料点与行程端点 | 可复现的验证脚本与 JSON 结果 |
19
+ | 人类查看与交付 | `colocad view / replay / render` | 本地查看器、单文件 HTML、四视图 MP4/GIF、整机 STEP |
20
+
21
+ **图像转参数化指令是本次助手读图与编程产生的中间结果,不是要求用户预先提供的输入,也不是 colocad 内置的自动图像转换能力。** 我先读取文字/图像并形成尺寸判断,再编写程序,colocad 执行明确指令。当前没有经过盲测的“任意图纸一键工业级复建”结论。
22
+
23
+ 资料不足的内部结构仍标为假设:螺旋槽是有几何实体的近似,螺母回珠通道未还原,不能将验证通过解释为制造精度认证。动画也没有隐藏这些范围说明。
24
+
25
+ ## 更适合真实产品任务的输入
26
+
27
+ 先确定唯一的产品目标:厂家、型号、变型、行程或尺寸配置、版本。目标交付是该配置的完整产品,零件图和 BOM 是输入资料。优先取得总装尺寸、剖面、零件图、接口图和实物照片;若有参考 CAD,可单独留给验收使用。
28
+
29
+ 输入不必全是图片。矢量 PDF 的尺寸文字、厂家参数表、图纸图像、剖视图和必要的局部裁图各有作用。图像提供视图对应和空间结构;准确数值优先取尺寸标注/表格;清晰度不足或互相矛盾的标注不能靠视觉印象补成精确值。照片通常用于核对形态,不作为未经标定的尺寸来源。
30
+
31
+ ## 从本次操作整理的工作方法:尚非盲测通过的通用能力
32
+
33
+ 1. **固定完整产品的规格。** 建立单位、坐标系、投影法、型号配置和验收范围,先确定总装包络、主要轴线、运动方向与安装接口。
34
+ 2. **建立可追溯的尺寸记录。** 每个关键参数记录原文件、页码、标注区域、数值和单位。分清图纸给定、由关系推导、暂时假设、尚未知四种状态。关键未知项应体现在完成度中。
35
+ 3. **先规划总装约束。** 建立零件定义、实例、父子关系、基准与配合接口。不要先随意画一批零件,再靠移动拼成看起来相似的产品。
36
+ 4. **生成小步的建模程序。** 助手按工程含义选择旋转、拉伸、切除、扫掠、放样、阵列等操作,使用稳定 ID、命名尺寸和关系式。先实现安装与运动接口,再处理次要外观细节。重复件复用定义。
37
+ 5. **执行并读取反馈。** 每个有意义的里程碑由 CLI/SDK 实际构建,保存输入和回执。失败后根据 feature ID 和几何反馈修改,保留失败记录。不能用略去关键结构来换取成功状态。
38
+ 6. **定向检查,再接受版本。** 内核有效性、图纸尺寸、装配关系分别验证。生成与原图一致的投影视角/剖面检查轮廓和孔位;独立回读 STEP 检查实体、体积及内部区域。调整参数后复查受影响的接口和整机包络。
39
+
40
+ 建议中间数据与内核输入分开保存:
41
+
42
+ ```text
43
+ product.json 型号、配置、单位、坐标与整机验收要求
44
+ sources/ 原始资料、页码与局部裁图
45
+ measurements.json 尺寸、来源、推导关系与未知项
46
+ interfaces.json 零件间接口、装配基准和运动关系
47
+ model.mjs 必要时使用的可编辑参数生成程序
48
+ model.json 给 colocad 的明确几何指令
49
+ history/ 每次实际执行的输入、回执、STEP 和预览
50
+ ```
51
+
52
+ 其中前四项是建议的任务数据约定,当前不是 colocad 内核 schema 的新增字段,也还没有自动提取器。不能把这些任意字段塞入 kernel model。
53
+
54
+ ## 给助手的有效任务约束
55
+
56
+ 比“照图做一个工业级模型”更明确的提示应包含:
57
+
58
+ ```text
59
+ 目标:还原指定厂家、型号、配置的完整产品。
60
+ 依据:列出图纸/手册文件及其版本,指定优先来源。
61
+ 单位与基准:确认投影法、总装坐标、主要轴线。
62
+ 精度目标:列出应核对的尺寸、公差、配合和行程。
63
+ 未知项:不得默默替换为确定尺寸;单独记录假设与影响。
64
+ 执行:先列整体布局和接口,再分阶段建模;保留失败与修改。
65
+ 验收:给出整机、关键接口、内部结构的测量与对应视图。
66
+ 交付:可编辑源、整机 STEP、建模会话、CLI 导出的离线回放。
67
+ ```
68
+
69
+ 不要只靠一个很长的提示。每轮仅给当前子系统所需的清晰视图、相关尺寸和接口约束,并保留共享整机基准。让校验返回具体数值与误差,而非只有“看着不对”。这套方法是否提高成功率,应通过实际任务记录证明。
70
+
71
+ ## 如何判断效果真的提升
72
+
73
+ 在相同型号、资料、模型版本和预算下,比较尺寸识别正确率、关键特征遗漏、独立几何检查、装配接口误差、未知项数量与人工修改次数。推理时间/费用、CAD 执行、预览分别计量。执行器更快,不直接等于读图更准;实体数更多也不等于完整产品更准确。
74
+
75
+ 对于滚珠丝杠执行器,完整产品验收应覆盖所选配置的轨道/壳体、滑台、丝杠螺母、支承与连接,以及实际公开资料能确定的内部结构;还包括轴线关系、安装孔位、行程端点和旋转—平移关系。仅有外形 CAD 时,不能据此声称滚道、滚珠回流和制造公差均已还原。
76
+
77
+ [CLI 查看与导出](modeling-history.md) · [本次真实产品实例](../examples/hiwin-kk60/README.md)
@@ -0,0 +1,25 @@
1
+ # Troubleshooting
2
+
3
+ | Symptom | Check and action |
4
+ | --- | --- |
5
+ | Skill cannot be found | Check `.agents/skills/colocad/SKILL.md` for Codex/Pi or `.claude/skills/colocad/SKILL.md` for Claude Code; start in that project and refresh/restart discovery. |
6
+ | Skill helper cannot import colocad | Install the pinned package in the current project and run the helper from there. Copy the complete skill folder. |
7
+ | `colocad build` rejects `version: 1` | That CLI expects `format: "colocad/1"`. Use `CadClient` or the skill helper for a kernel model. |
8
+ | Output directory already exists | Pick a new revision destination for the CLI/helper. Keep earlier accepted output. `CadClient.outputRoot` can contain multiple revisions. |
9
+ | Unsupported platform / missing executable | Alpha.3 bundles Linux x64/arm64 and macOS arm64. Check `process.platform`, `process.arch` and the installed `kernel/native` directory. Source builds require a Rust toolchain and the pinned dependency. |
10
+ | Native launch fails | Check `LOCAL_EXECUTION_FAILED`, executable permissions, mount policy and `binary`/`AGENT_CAD_BINARY` overrides. Run the local CLI to isolate harness wiring. |
11
+ | `TIMEOUT` | Inspect the failing feature and workload. Simplify or split unnecessary work; adjust `wallMs` within 1–120,000 only when appropriate. Sandbox memory failures need sandbox diagnostics too. |
12
+ | `RESOURCE_LIMIT` / `OUTPUT_LIMIT` | Inspect capabilities and reduce model/mesh payload. SDK stdin is limited to 32 MiB; the feature-tree CLI accepts 2 MiB. |
13
+ | Unknown/missing parameter | Use an existing finite numeric parameter. `edit()` does not create parameters; update the owned source to add one. |
14
+ | An edit undoes a prior change | You reused stale source. Load the last accepted `model.json` or persist the merged parameters after each successful edit. |
15
+ | Preview succeeds but no STEP in its directory | A cached observation points to `source_artifact_directory`. Retrieve STEP from the source geometry revision. |
16
+ | Cached preview cannot be read | Retain its source directory and files; do not modify cache bytes. Rebuild from the saved model if the cache was pruned or is invalid. |
17
+ | Agent cannot see the rendered image | Attach PNG as image content or invoke the harness's image-reading tool. Printing the local filename alone is insufficient. |
18
+ | Provider rejects tool schema | Preserve root `$defs`; check the provider's schema restrictions. Use skill + shell tools if the provider cannot accept the complete schema. |
19
+ | No editable native SOLIDWORKS tree | STEP is not a feature-history file. The Windows author is experimental; generic Linux native authoring is not complete. |
20
+
21
+ Some low-level failures retain the legacy error code `WORKER_FAILED`. It is an error label in alpha.3, not a requirement to deploy a separate service. Native execution is local.
22
+
23
+ For a useful bug report, include package/platform/Node versions, minimal model JSON, the failed receipt, expected geometry and reproduction command. Remove credentials and private design data. Attach a small STEP and screenshot when shareable. Keep the original file if the failure depends on STEP import; otherwise reduce the model to the failing dependency chain.
24
+
25
+ See [Contributing](../CONTRIBUTING.md) for the test commands and [validation](validation.md) for known limitations.
@@ -0,0 +1,23 @@
1
+ # Release validation
2
+
3
+ The same public build API compiled the two different feature trees in `examples/`. The manifold has one solid with 27 faces and 54 edges. OCCT read its STEP as a valid solid with volume 45,490.923866 mm³. Reducing the blind-port count from four to three restored 226.194671 mm³, matching π × 3² × 8. The rail has rectangular through-slots patterned along Y. Removing one slot restored 405 mm³. The validation script also probes points within and outside the blind ends, the pocket, and the fillet.
4
+
5
+ ![Manifold precision mesh preview](manifold.png)
6
+
7
+ The native Windows author compiled against SOLIDWORKS 2024 interop 32.1.0. Runtime creation, feature edit, force rebuild and reopen in the vendor application remain unverified.
8
+
9
+ The Linux file-format experiment started with a synthesized envelope containing no part geometry or feature tree. On an empty source the pinned Rust encoder refuses synthesis without retained signature tokens. Providing a minimal envelope allowed a cube to round-trip as one solid with six faces. For the actual manifold, its exported STEP contains 54 explicit trim ranges. Of these, 32 are lines delimited by their vertices, 8 are closed full circles and 14 are clamped full-domain NURBS. Checking that the endpoints and natural domains agree permits equivalent vertex-delimited geometry. The experimental re-read then recovered one solid, 27 faces, 54 edges and zero neutral validation findings. This result contains a geometry partition only. Editable fillet selection ownership and native feature-pattern seed references still need to be serialized and independently proven. The CLI intentionally does not release these experimental bytes as an editable part.
10
+
11
+ The packaged npm archive was installed offline and invoked through the sandbox-local Pi bash tool in an Abelien Linux arm64 runner limited to 1 vCPU and 512 MiB. In the [scoped 0.1.0-alpha.2 run](evidence/scoped-runner.json) the manifold build with preview took 272 ms, the rail 84 ms and the pattern-count edit 181 ms. These are single tool-call wall times. The full cgroup peak includes the offline npm install, cache and files staged on tmpfs. See the JSON receipts in [evidence](evidence/).
12
+
13
+ We also tested the first two manifold operations with a freshly generated, matching B-rep and a sketch graph compiled directly from the same job. The independent decode of the experimental bytes recovered seven sketch entities across two sketches, one extrusion and one cut. The native operation-class and driving-scalar counts were both zero. Adding the rim fillet to the full graph produced a native encoder refusal at the edge-selection group. The records are in [native-prefix.json](evidence/native-prefix.json) and [native-full-refusal.txt](evidence/native-full-refusal.txt). These are file-format diagnostics, with no claim of successful rebuild in SOLIDWORKS.
14
+
15
+ The fillet selector separately found all six intended edges in the B-rep recovered for the state immediately preceding the fillet. Both adjacent faces and both endpoints are recorded for each edge. Mapping those input-state identities to persistent SOLIDWORKS operands remains open. In a second diagnostic without the fillet, file readback recovered the linear pattern (four instances along X at 18 mm pitch) and its link to the port-cut seed. Its native operation-class and driving-scalar counts were still zero. See [input-state edges](evidence/historical-selection.json) and [pattern diagnostic](evidence/native-pattern.json).
16
+
17
+ ![Bottom view, showing the four blind bores and the recessed channel](manifold-underside.png)
18
+
19
+ ## npm release 0.1.0-alpha.3
20
+
21
+ The [archive checks and independent STEP measurements](evidence/release-alpha.3.json) cover macOS arm64, Linux arm64 and Linux x64. Both Linux installations ran offline with 1 vCPU and 512 MiB. The x64 check used an emulated x64 environment and exercised the x64 Node executable and native kernel. Each installation used the packaged CLI to build a manifold and the bundled skill to build a six-hole plate, a sleeve pair and a complete 43-solid hand. OCCT reopened all twelve STEP files. The hand report counted 21 measured instances and 22 translated reuses on each platform.
22
+
23
+ For a release, stage the three tested executables and their manifests under `kernel/native/<platform>/`. Record the corresponding SHA-256 values and npm version in `kernel/release.json`. The `prepack` check rejects missing executables and hashes that differ from the recorded build. Run `npm pack`, install that tarball in an empty consumer project on each platform, and run `node /path/to/checkout/test/validation/packed.mjs` from that project. Provide the hand model JSON as an optional argument to exercise all 43 occurrences. Publish that tested tarball directly.
@@ -0,0 +1,55 @@
1
+ # HIWIN KK60: a whole industrial actuator reconstructed from its catalog
2
+
3
+ This example models one complete configuration of a real product: **HIWIN KK60 standard, 5 mm screw lead, 300 mm rail, one normal A block, open, without a motor or switches**. It contains 52 native geometric features, 81 named occurrences and 16 recorded construction/assembly milestones. The product is a catalog-based reconstruction, not an OEM manufacturing model.
4
+
5
+ ![Four synchronized views of actual recorded native construction](../../showcase/hiwin-kk60/modeling.gif)
6
+
7
+ [Complete offline delivery: HTML, STEP and session ZIP](https://github.com/Coloopx/colocad/releases/download/v0.1.0-alpha.4/hiwin-kk60-delivery.zip) · [MP4](../../showcase/hiwin-kk60/modeling.mp4) · [Editable generated model](../../showcase/hiwin-kk60/model.json) · [Independent verification](../../showcase/hiwin-kk60/verification.json) · [Source dimensions and assumptions](sources.json)
8
+
9
+ ## Build, view and export through the CLI
10
+
11
+ From a source checkout with `npm ci` (precompiled native executables must be installed or `npm run build:kernel` run):
12
+
13
+ ```sh
14
+ node examples/hiwin-kk60/run.mjs ./out/hiwin-kk60
15
+ node bin/colocad.mjs view ./out/hiwin-kk60/session
16
+ node bin/colocad.mjs replay ./out/hiwin-kk60/session ./out/hiwin-kk60/review.html
17
+
18
+ # Optional movie tools; CAD and HTML export do not require these.
19
+ npx playwright install chromium
20
+ # Install FFmpeg on the host, then:
21
+ node bin/colocad.mjs render ./out/hiwin-kk60/session ./out/hiwin-kk60/modeling.mp4 \
22
+ --width 1280 --height 800 --fps 15 --seconds-per-step 1.25
23
+ node bin/colocad.mjs render ./out/hiwin-kk60/session ./out/hiwin-kk60/modeling.gif \
24
+ --width 960 --height 600 --fps 10 --seconds-per-step 0.75
25
+ ```
26
+
27
+ With the npm alpha.4 package, the generator is included under `node_modules/@coloopx/colocad/examples/hiwin-kk60/run.mjs`; the CLI is `npx colocad`. The generator requires a new output directory. It writes the actual per-stage sources/receipts/artifacts to `session/`, plus final `model.json` and `hiwin-kk60.step`. `replay` produces one self-contained HTML file, embedding meshes, source, receipts and final STEP. The interactive viewer supports four viewpoints, cutaway, explosion, part selection and the feature journal. Movie export is optional and runs locally; Chromium/FFmpeg have a separate resource cost from geometry builds.
28
+
29
+ The film shows the real intermediate B-reps: rail stock → guide grooves → six counterbores; saddle → nut seat → mounting pattern; stepped shaft → helical cuts; bearing plate and motor support → assembly. It does not interpolate or simulate machining. The final explode/reassemble segment changes displayed placements only. Recorded call times remain visible; the 26-second review is **not** a 26-second build or a build123d comparison.
30
+
31
+ ## How the drawing became CAD in this example
32
+
33
+ The assistant downloaded the [manufacturer's catalog](https://hiwin.com/wp-content/uploads/2026/08/HIWIN-Ballscrew-Driven-Stages-Catalog-1.pdf), read the dimension table with `pdftotext`, rendered PDF page 25 with `pdftoppm`, and inspected enlarged drawing sections. The initial screw-axis interpretation was corrected from 15 to **23 mm** after inspecting SECTION A-A. The catalog was not passed to an automatic colocad image-to-CAD endpoint; no such endpoint is claimed.
34
+
35
+ The assistant then wrote [model.mjs](model.mjs): explicit cross-sections, feature dependencies, cutters and placements. That generator emits the same JSON schema accepted by a harness. `ModelingSession.build` executes each revision in the local Rust kernel. Rendering consumes the resulting saved meshes. This is an observed agent/tool workflow, not evidence that a trained image-to-CAD model reconstructed an arbitrary drawing autonomously.
36
+
37
+ The product's catalog interfaces are the acceptance target: rail length/width, carriage height, hole positions/depths, screw axis, total length and travel. [`sources.json`](sources.json) separates specified numbers, datum interpretations and approximated internals. The one exposed run-time parameter is `travel` (−105…105 mm); its screw rotation is linked at 72 degrees/mm. Other dimensions are explicit source constants or feature values; changing those requires rebuilding and rechecking interfaces. This is not a general KK-series configurator.
38
+
39
+ ## Geometric details and verification
40
+
41
+ The screw's 56-turn groove is actual B-rep subtraction: four cubic lofted circular cutters per turn, repeated at 5 mm pitch. It is an approximation to a helical groove, not the proprietary gothic-arch race. The rail, carriage and motor support have real bores, counterbores, tracks, pockets and datum slots. Bolts include hex sockets. Repeated rolling elements share geometry definitions.
42
+
43
+ Run the independent verifier with a development Python environment containing `cadquery-ocp`:
44
+
45
+ ```sh
46
+ python examples/hiwin-kk60/verify.py ./out/hiwin-kk60/session ./out/hiwin-kk60/verification.json
47
+ ```
48
+
49
+ It reopens every successful STEP in OCCT, checks all solids, counts and volumes, probes the rail counterbores, carriage mounting holes and screw groove/crest, and measures selected rail/carriage overlap at −105/0/+105 mm travel. Tests in `test/kk60.test.mjs` also rebuild both carriage travel endpoints. The recorded result passed all 16 revisions and 64 material probes. Maximum relative volume disagreement was 0.002608%; the three selected rail/carriage overlap volumes were all zero. These checks do not certify every internal fit.
50
+
51
+ Unpublished rolling-element arrangement, bearing sizes, coupling details and nut recirculation are not recovered OEM specifications. The nut is an envelope with a screw bore; recirculation is omitted. Threaded holes are nominal bores; tolerance fits, load rating, fatigue, contact/preload and complete all-pairs interference are not certified. These limits are part of the delivered model, not hidden assumptions.
52
+
53
+ The first full assembly exposed a real library defect: internally generated STEP definitions above 100,000 records were rejected by the assembly writer. Alpha.4 separates the bounded internal export budget (1,000,000 records per definition) from the unchanged external import budget (100,000). A regression test and the full screw assembly cover this fix. The failed original attempt was retained separately during development; it is not counted as a successful build.
54
+
55
+ A complete build with a 640 × 480 preview also passed in a network-disabled Linux arm64 container limited to 1 vCPU and 512 MiB. Native reported total time was 24.192 seconds (one run). Peak memory was not sampled, and no build123d run was performed for this product. [Run evidence](../../showcase/hiwin-kk60/evidence.json).
@@ -0,0 +1,94 @@
1
+ // Catalog interfaces: HIWIN K99TE16-1906 p.22. Internal sections are reconstruction assumptions.
2
+ // X = width, Y = vertical, Z = travel; mm. See sources.json before using for integration.
3
+ export const specification={manufacturer:'HIWIN',series:'KK60 standard',configuration:'5 mm lead / 300 mm rail / A1 / open / no motor',railLength:300,width:60,carriageHeight:33,screwAxisHeight:23,length:370,stroke:210,lead:5,screwDiameter:12};
4
+ export const stages=[
5
+ ['rail-stock','Extrude the U-section rail','geometry'],['rail-races','Cut the four guide raceways','geometry'],['rail-holes','Drill and counterbore the six mounting holes','geometry'],
6
+ ['carriage-stock','Extrude the carriage saddle','geometry'],['carriage-bore','Machine the nut seat and ball tracks','geometry'],['carriage-holes','Drill the M5 mounting pattern and datum slots','geometry'],
7
+ ['screw-blank','Revolve the stepped ballscrew blank','geometry'],['screw-groove','Cut 56 helical turns at 5 mm lead','geometry'],
8
+ ['end-plate','Machine the end bearing plate','geometry'],['motor-bracket','Machine the motor support and register','geometry'],['coupling','Bore and split the coupling hubs','geometry'],
9
+ ['base-assembly','Install the rail and end supports','assembly'],['screw-assembly','Install the ballscrew and support bearings','assembly'],['carriage-installed','Install the carriage and end caps','assembly'],
10
+ ['rolling-assembly','Add the ball nut, guide balls and wipers','assembly'],['complete','Complete the actuator and mounting hardware','assembly'],
11
+ ].map(([id,label,kind])=>({id,label,kind}));
12
+ const p=name=>({param:name}),mul=(a,b)=>({op:'mul',a,b}),add=(a,b)=>({op:'add',a,b});
13
+ export function kk60(stage='complete',{travel=0}={}){
14
+ if(!stages.some(s=>s.id===stage))throw Error('Unknown KK60 stage');
15
+ if(!Number.isFinite(travel)||Math.abs(travel)>105)throw Error('travel must be within -105..105 mm');
16
+ const features=[],all=[],f=(id,op,args)=>(features.push({id,op,...args}),id);
17
+ const box=(id,origin,size)=>f(id,'box',{origin,size});
18
+ const cut=(id,left,right)=>f(id,'cut',{left,right});
19
+ const extrude=(id,points,z,height)=>f(id,'extrude',{profile:{kind:'polygon',points},frame:{origin:[0,0,z],x_axis:[1,0,0],y_axis:[0,1,0]},height});
20
+ const ring=(id,ro,ri,z,h,y=0)=>f(id,'extrude',{profile:{kind:'circle',radius:ro},holes:[{kind:'circle',radius:ri}],frame:{origin:[0,y,z],x_axis:[1,0,0],y_axis:[0,1,0]},height:h});
21
+ const holes=(id,input,positions,r,depth,origin=[0,0,0],axes=[[1,0,0],[0,1,0]],counterbore)=>f(id,'holes',{input,positions,radius:r,depth,frame:{origin,x_axis:axes[0],y_axis:axes[1]},...(counterbore?{counterbore}:{})});
22
+ const faceholes=(id,input,face,positions,r,depth,counterbore)=>f(id,'face_holes',{input,face,positions,radius:r,depth,...(counterbore?{counterbore}:{})});
23
+ const inst=(id,input,translation=[0,0,0],rotation_deg=[0,0,0],phase='complete')=>all.push({id,input,translation,rotation_deg,phase});
24
+ const trackPositions=[[-20.5,12],[-20.5,20],[20.5,12],[20.5,20]];
25
+ const railStock=extrude('railStock',[[-30,0],[30,0],[30,21],[29,22],[21,22],[21,5],[-21,5],[-21,22],[-29,22],[-30,21]],7,300);
26
+ const railRaces=holes('railRaceways',railStock,trackPositions,1.65,302,[0,0,6]);
27
+ // Recessed rail floor is Y=5; explicit inward plane avoids drilling from the top of the sidewalls.
28
+ const railHoles=holes('railMounting',railRaces,[-15,15].flatMap(x=>[57,157,257].map(z=>[x,z])),2.75,6,[0,5,0],[[1,0,0],[0,0,1]],{radius:4.75,depth:4.7});
29
+ const rail=holes('railCoverTaps',railHoles,[-26,26].flatMap(x=>[57,257].map(z=>[x,z])),1.3,4,[0,22,0],[[1,0,0],[0,0,1]]);
30
+ const carriageSection=[[-19.7,8],[19.7,8],[19.7,23],[21,25],[21,32],[20,33],[-20,33],[-21,32],[-21,25],[-19.7,23]];
31
+ const carStock=extrude('carriageStock',carriageSection,-25.5,51);
32
+ const carSeat=holes('carriageNutSeat',carStock,[[0,23]],9.2,53,[0,0,-26.5]);
33
+ const carBore=holes('carriageRaceways',carSeat,trackPositions,1.65,53,[0,0,-26.5]);
34
+ const carHoles=faceholes('carriageMounting',carBore,'pos_y',[-15,15].flatMap(x=>[-15,15].map(z=>[x,z])),2.5,8);
35
+ let car=carHoles;
36
+ for(const z of [-23,23])car=f('datumSlot'+(z<0?'A':'B'),'face_cutout',{input:car,face:'pos_y',center:[0,z],profile:{kind:'rectangle',width:15,depth:5},depth:1.5});
37
+ const capStock=extrude('endCapStock',[[-19.5,8],[19.5,8],[21,25],[21,31.5],[-21,31.5],[-21,25]],0,15.5);
38
+ const capBore=holes('endCapBore',capStock,[[0,23]],6.5,15.5,[0,0,0],undefined,{radius:8.6,depth:1.1});
39
+ const cap=faceholes('endCapWiperSeat',capBore,'pos_z',[[0,23]],8.6,1.1);
40
+ const wiper=ring('wiper',8.5,6.2,0,1,23);
41
+ const nut=ring('ballNut',9,6.05,-21,42,23);
42
+ const shaftBlank=f('shaftBlank','revolve',{profile:{kind:'polygon',points:[[0,-7],[6,-7],[6,286],[4,286],[4,306],[3,306],[3,340],[0,340]]},frame:{origin:[0,0,0],x_axis:[1,0,0],y_axis:[0,0,1]},axis_origin:[0,0,0],axis:[0,0,1],angle_deg:360});
43
+ let screw=shaftBlank;
44
+ // Four cubic lofts approximate a circular helical cutter, then exact native booleans.
45
+ // It is NOT an exact analytical helix, gothic-arch ball race or OEM ground profile.
46
+ for(let q=0;q<4;q++){
47
+ const tool=f('helixQuarter'+q,'profile_loft',{degree:3,sections:Array.from({length:4},(_,i)=>{const theta=(q+i/3)*Math.PI/2;return {profile:{kind:'circle',radius:1},frame:{origin:[6.2*Math.cos(theta),6.2*Math.sin(theta),5+(q+i/3)*1.25],x_axis:[Math.cos(theta),Math.sin(theta),0],y_axis:[0,0,1]}};})});
48
+ const pattern=f('helicalTools'+q,'pattern',{input:tool,positions:Array.from({length:56},(_,i)=>[0,0,i*5])});
49
+ screw=cut('screwGroove'+q,screw,pattern);
50
+ }
51
+ const endStock=box('endPlateStock',[-29.8,.5,0],[59.6,44.5,11]);
52
+ const endBore=holes('endBearingSeat',endStock,[[0,23]],8,13,[0,0,-1]);
53
+ const endPlate=holes('endPlateScrews',endBore,[[-23,9],[23,9],[-23,35],[23,35]],1.5,11,[0,0,0],undefined,{radius:3,depth:3});
54
+ const motorStock=box('motorSupportStock',[-29.8,.5,311],[59.6,44.5,59]);
55
+ const motorWindow=f('motorSupportWindow','face_cutout',{input:motorStock,face:'pos_y',center:[0,340.5],profile:{kind:'rectangle',width:36,depth:39,radius:2},depth:41});
56
+ const motorBore=holes('motorBearingSeat',motorWindow,[[0,23]],10,61,[0,0,310]);
57
+ const motorRegister=faceholes('motorRegister',motorBore,'pos_z',[[0,23]],14,4);
58
+ // Nominal threaded holes: two four-hole patterns on PCD40; no cosmetic thread mesh.
59
+ const motorHoles=faceholes('motorM4Pattern',motorRegister,'pos_z',[45,135,225,315].map(a=>[20*Math.cos(a*Math.PI/180),23+20*Math.sin(a*Math.PI/180)]).filter(([x,y])=>y>.5),2,8);
60
+ const motorM3=faceholes('motorM3Pattern',motorHoles,'pos_z',[30,150,210,330].map(a=>[20*Math.cos(a*Math.PI/180),23+20*Math.sin(a*Math.PI/180)]),1.5,8);
61
+ const motor=faceholes('motorSupportBolts',motorM3,'pos_z',[-23,23].flatMap(x=>[9,35].map(y=>[x,y])),1.5,11,{radius:3,depth:3});
62
+ const couplingStock=ring('couplingHubStock',10,3,0,8);
63
+ const coupling=faceholes('couplingSetScrew',couplingStock,'pos_x',[[0,4]],1.5,7);
64
+ const couplingB=ring('couplingDrivenHub',10,3,0,8);
65
+ const spiderStock=extrude('couplingSpiderStock',Array.from({length:24},(_,i)=>{const a=i*Math.PI/12,r=i%4<2?9.8:6;return [r*Math.cos(a),r*Math.sin(a)];}),0,3);
66
+ const spider=holes('couplingSpider',spiderStock,[[0,0]],3.2,5,[0,0,-1]);
67
+ const boltStock=f('boltStock','revolve',{profile:{kind:'polygon',points:[[0,0],[1.4,0],[1.4,8],[2.7,8],[2.7,10.5],[0,10.5]]},frame:{origin:[0,0,0],x_axis:[1,0,0],y_axis:[0,0,1]},axis_origin:[0,0,0],axis:[0,0,1],angle_deg:360});
68
+ const bolt=f('socketBolt','face_cutout',{input:boltStock,face:'pos_z',center:[0,0],profile:{kind:'polygon',points:Array.from({length:6},(_,i)=>[1.3*Math.cos(i*Math.PI/3),1.3*Math.sin(i*Math.PI/3)])},depth:1.8});
69
+ const smallInner=ring('tailInnerRace',6.4,6,0,5),smallOuter=ring('tailOuterRace',8,7.2,0,5);
70
+ const driveInner=ring('driveInnerRace',5.6,4,0,7),driveOuter=ring('driveOuterRace',10,8.4,0,7);
71
+ const guideBall=f('guideBall','sphere',{center:[0,0,0],radius:1.5});
72
+ const bearingBall=f('bearingBall','sphere',{center:[0,0,0],radius:1.3});
73
+ const tailBall=f('tailBall','sphere',{center:[0,0,0],radius:.35});
74
+ inst('rail-machined',rail,undefined,undefined,'base-assembly');inst('end-bearing-plate',endPlate,undefined,undefined,'base-assembly');inst('motor-bearing-support',motor,undefined,undefined,'base-assembly');
75
+ inst('ballscrew-5mm-lead',screw,[0,23,11],[0,0,mul(p('travel'),72)],'screw-assembly');
76
+ inst('bearing-tail-inner',smallInner,[0,23,4],undefined,'screw-assembly');inst('bearing-tail-outer',smallOuter,[0,23,4],undefined,'screw-assembly');
77
+ inst('bearing-drive-inner',driveInner,[0,23,311],undefined,'screw-assembly');inst('bearing-drive-outer',driveOuter,[0,23,311],undefined,'screw-assembly');
78
+ for(let i=0;i<12;i++){const a=i*Math.PI/6;inst('bearing-drive-ball-'+i,bearingBall,[7*Math.cos(a),23+7*Math.sin(a),314.5],undefined,'screw-assembly');inst('bearing-tail-ball-'+i,tailBall,[6.8*Math.cos(a),23+6.8*Math.sin(a),6.5],undefined,'screw-assembly');}
79
+ const carriageZ=add(157,p('travel'));
80
+ inst('carriage-machined',car,[0,0,carriageZ],undefined,'carriage-installed');
81
+ inst('carriage-end-cap-a',cap,[0,0,add(carriageZ,-41)],undefined,'carriage-installed');inst('carriage-end-cap-b',cap,[0,0,add(carriageZ,25.5)],undefined,'carriage-installed');
82
+ inst('ball-nut',nut,[0,0,carriageZ],undefined,'rolling-assembly');inst('seal-wiper-a',wiper,[0,0,add(carriageZ,-41)],undefined,'rolling-assembly');inst('seal-wiper-b',wiper,[0,0,add(carriageZ,40)],undefined,'rolling-assembly');
83
+ for(let row=0;row<4;row++)for(let i=0;i<8;i++)inst('guide-ball-'+row+'-'+i,guideBall,[...trackPositions[row],add(carriageZ,-21+i*6)],undefined,'rolling-assembly');
84
+ inst('coupling-driven-hub',coupling,[0,23,330]);inst('coupling-spider',spider,[0,23,338]);inst('coupling-motor-hub',couplingB,[0,23,341]);
85
+ for(const x of [-23,23])for(const y of [9,35]){inst('bolt-tail-'+x+'-'+y,bolt,[x,y,10.5],[180,0,0]);inst('bolt-drive-'+x+'-'+y,bolt,[x,y,359.5]);}
86
+ const single={'rail-stock':railStock,'rail-races':railRaces,'rail-holes':rail,'carriage-stock':carStock,'carriage-bore':carBore,'carriage-holes':car,'screw-blank':shaftBlank,'screw-groove':screw,'end-plate':endPlate,'motor-bracket':motor,'coupling':coupling}[stage];
87
+ const at=stages.findIndex(s=>s.id===stage);
88
+ let assembly=all.filter(x=>stages.findIndex(s=>s.id===x.phase)<=at).map(({phase,...x})=>x);
89
+ // Separate inspection revision: carriage envelope at travel endpoints, before installing into whole assembly.
90
+ if(stage==='carriage-installed')assembly=assembly.filter(x=>x.id.startsWith('carriage-'));
91
+ const needed=new Set(single?[single]:assembly.map(x=>x.input));
92
+ for(const feat of [...features].reverse())if(needed.has(feat.id))for(const key of ['input','left','right'])if(feat[key])needed.add(feat[key]);
93
+ return {version:1,units:'mm',parameters:{travel},features:features.filter(x=>needed.has(x.id)),...(single?{output:single}:{assembly})};
94
+ }
@@ -0,0 +1,14 @@
1
+ import { resolve, join } from 'node:path';
2
+ import { writeFile,copyFile } from 'node:fs/promises';
3
+ import { ModelingSession } from '../../src/session.mjs';
4
+ import { kk60, stages } from './model.mjs';
5
+ const directory=resolve(process.argv[2]??'./out/hiwin-kk60');
6
+ const session=await ModelingSession.create(join(directory,'session'),{title:'HIWIN KK60 • catalog-based industrial actuator reconstruction',wallMs:120000});
7
+ for(const stage of stages){
8
+ const result=await session.build({...kk60(stage.id),preview:{chord_mm:.25,view:'iso',width:960,height:640}},stage);
9
+ console.log(JSON.stringify({stage:stage.id,ok:result.ok,solids:result.data?.geometry?.solids,time:result.data?.timing_ms,step:result.session_step,error:result.error}));
10
+ if(!result.ok)throw Error(JSON.stringify(result.error));
11
+ }
12
+ const model=kk60();await writeFile(join(directory,'model.json'),JSON.stringify(model,null,2)+'\n');
13
+ const last=(await session.read()).steps.at(-1);await copyFile(join(session.root,last.artifactDirectory,'model.step'),join(directory,'hiwin-kk60.step'));
14
+ console.log(JSON.stringify({directory,features:model.features.length,instances:model.assembly.length}));