dsh-cad-studio 0.3.1 → 0.4.1

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 (4) hide show
  1. package/README.md +55 -7
  2. package/client.js +4 -1
  3. package/index.js +138 -13
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**,并在 Web 右栏提供一个只读+轻交互的 3D 面板。
4
4
 
5
- ![面板](docs/preview.png)
5
+ ![CAD 工作室面板](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/preview.png)
6
6
 
7
- - Host 侧(`index.js`):14 个工具 + `/cad-studio/*` HTTP 路由 + `freecadcmd` 子进程桥
7
+ - Host 侧(`index.js`):16 个工具 + `/cad-studio/*` HTTP 路由 + `freecadcmd` 子进程桥
8
8
  - 客户端侧(`client.js`):右栏页签「CAD 工作室」,three.js 视口 + 图标条浮层(零件 / 特征 / 选中项 / 运动 / 视图 / 模型 / 信息)
9
9
  - 数据:`<modelsDir>/<名字>.json` 存模型工程(脚本或声明式特征 + 参数 + 20 条历史);场景网格落 `$TMPDIR/dsh-cad-studio/{state.json,scenes/*.json}`
10
10
 
@@ -14,11 +14,12 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
14
14
  |---|---|
15
15
  | 建模 | `cad_studio_feature` 声明式特征(box/cylinder/sphere/cone/torus/extrude/revolve/fuse/cut/common/fillet/chamfer/shell/pattern/translate/rotate/mirror);`cad_studio_run` 跑任意 FreeCAD Python |
16
16
  | 工程文件 | `cad_studio_doc` 存 `script` 或 `features` 两种模型;`cad_studio_features` 改一条特征→整表重算(0.2–0.6 s),失败整表回滚 |
17
- | 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随) |
17
+ | 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随);`measure:true` 回每实例体积/包围盒,`interference:true` 回真正重叠的实例对 |
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
19
  | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴) |
20
20
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
21
21
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
22
+ | 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
22
23
  | 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
23
24
  | 自检/安装 | `cad_studio_setup`:报告 freecadcmd 是否可用、版本、包管理器与可执行命令;`action=install` 直接装 |
24
25
  | 面板 | 多页签(上限 5,各自记住相机与配色)、点选联动、色块换色、显隐、透明度、线框、隔离、标准视图、网格/轮廓/光影开关 |
@@ -55,12 +56,48 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
55
56
 
56
57
  `autoOpen: 'session'` 的判据是宿主侧的两个信号:这个会话最近一次发布过场景(`lastSession`),或它拥有更早发布过的场景。也就是说——只有真正在这里建过模的对话,右栏才会自动让出位置;别的对话不受打扰。
57
58
 
58
- ## 两个容易踩的接口约定
59
+ ## 接口约定与踩过的坑
59
60
 
60
61
  - **导出只走 `cad_studio_export`**。在 `cad_studio_run` 里直接 `Part.export([compound], path)` 会写出一个 1.6 KB 的 STEP 壳子,读回来是空形状,而脚本本身不报错。要么用 `cad_studio_export`,要么给 `cad_studio_run` 传 `check: ["/path/out.step"]`——它会在跑完后把这个文件读回来,回报 `{bytes, solids, volume, valid}`,壳子会显示 `valid:false`。
61
62
  - **探查脚本别发布场景**。`cad_studio_run` 默认会把绑定的 `scene` 发布成面板里的一行;只是量体积/查干涉的脚本传 `publish: false`,否则模型列表会被探针卡片塞满(实测一次会话攒到 28 行)。已经混进去的用 `cad_studio_scene {action:"delete", id:"scene-12"}` 清。
62
63
  - `cad_studio_export` 的返回里 `volume` / `solids` 是**真正写出去的那一套**,`sourceVolume` / `sourceSolids` 是输入侧的;`minVolume` 会按实体体积过滤(滤掉圆丝、灰尘),`alsoStl` 顺手写一份 STL。
63
64
  - `cad_studio_assembly` 传 `measure: true` 会回每实例的 bbox/体积/实体数与总体积,`interference: true` 会回真正重叠的实例对(先用包围盒筛,再做布尔交)。
65
+ - **`fuse` / `cut` / `common` 的 `with` 可以是数组**:U 形围壁写成「一条 `fuse` 外块 + 一条 `cut` 带两个内腔」即可,不必拆成中间状态(中间状态是实心块,顺序错了会削到别处)。
66
+ - **`extrude` 支持 3D 剖面点与 `dir`**:三角棱柱写 `{kind:"extrude", points:[[0,0,0],[40,0,0],[0,30,0]], dir:[0,0,20]}`,不用再拿 `base`/`h` 手算覆盖范围。
67
+ - 特征参数在 `normalizeFeature` 阶段就校验,报错带行号与名字:`特征 f10(倒角_左后) cut:需要 with 子图元(…)`——不会再从 FreeCAD 里冒出一句 `第 10 步(cut)失败:'with'`。
68
+ - 删掉的面板行不会被下一次发布「复活」:`persist()` 会跟磁盘对账,只保留磁盘上还有的、或本进程发布过的行。
69
+
70
+ ## 截图
71
+
72
+ 都来自一个**测试实例**(合成的 `体验_特征 / 体验_参数化 / 体验_装配` 三个演示模型),并且**只截取面板元素**——图里没有真实工作区、会话或文件路径。
73
+
74
+ **装配 + 视口**:零件按实例配色,左侧图标条、页签、坐标轴、网格、等轴视图。
75
+
76
+ ![装配与视口](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/preview.png)
77
+
78
+ **选中项**:视口点选 ↔ 列表联动;改色、显隐、透明度、隔离、线框、副本同透明度、重置。
79
+
80
+ ![选中项](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/props.png)
81
+
82
+ **声明式特征**:一条特征一行,改数值即整表重算;眼睛跳过该步,↑↓ 调顺序,× 删除。
83
+
84
+ ![特征列表](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/features.png)
85
+
86
+ **参数化脚本**:改 `params` 就重跑脚本,原地更新同一个场景(不新增模型行)。
87
+
88
+ ![参数](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/params.png)
89
+
90
+ **关节与爆炸**:每个关节都有数值框(可精确输入 0°)、归零按钮和滑杆;爆炸图一个滑杆。
91
+
92
+ ![关节与爆炸](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/motion.png)
93
+
94
+ **多页签**:最多 5 个模型页签,各自记住相机与配色;`+` 新增页签,文件夹图标切换当前页签。
95
+
96
+ ![多页签](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/tabs.png)
97
+
98
+ 图标条(4× 放大):立方体=零件、台阶=特征、滑杆=选中项、环形箭头=运动、相机=视图、文件夹=模型、ⓘ=信息。
99
+
100
+ <img src="https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/rail.png" width="58" alt="图标条">
64
101
 
65
102
  ## 场景 JSON 协议
66
103
 
@@ -79,11 +116,22 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
79
116
  ## 开发
80
117
 
81
118
  ```bash
82
- node test/harness.mjs # 133 条回归:无浏览器,stub cordis ctx 直接调工具
83
- node test/stale-bridge.mjs # 热重载后旧 bridge 实例自愈
119
+ # 165 条回归:无浏览器,stub cordis ctx 直接调工具
120
+ rm -rf /tmp/cad-h && mkdir -p /tmp/cad-h && TMPDIR=/tmp/cad-h node test/harness.mjs
121
+ node test/stale-bridge.mjs # 热重载后旧 bridge 实例自愈
122
+
123
+ # 在一台测试实例上造三个"什么都能试"的模型(体验_特征 / 体验_参数化 / 体验_装配)
124
+ node scripts/dev-playground.mjs
125
+ # 把这条实例的模型列表收敛回这几个演示模型(探针跑多了会攒出几十行)
126
+ node scripts/dev-keep-demos.mjs --dry # 先看要删哪些
127
+ node scripts/dev-keep-demos.mjs
128
+ # 重截 README 的截图(只截 [data-cad-panel-root],需要能访问测试实例)
129
+ node scripts/shots.mjs --url http://127.0.0.1:3201 --token-file /tmp/dev-token.txt
84
130
  ```
85
131
 
86
- `test/replicate.mjs`、`scripts/*.mjs` 是我自己造场景/验证用的夹具,按需改路径。
132
+ > `TMPDIR` 必须指到临时目录:harness 会清空 `$TMPDIR/dsh-cad-studio`,指到默认位置就会把线上实例的场景缓存一起删掉。
133
+
134
+ `test/replicate.mjs`、`scripts/*.mjs` 是造场景/验证用的夹具,按需改路径。截图脚本用 `window.__cadStudioAutoOpen.open()` 打开面板——宿主的页签启动器在不同版本里位置会变,这个钩子稳定些。
87
135
 
88
136
  ## 已知限制
89
137
 
package/client.js CHANGED
@@ -2668,7 +2668,10 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2668
2668
  try {
2669
2669
  Object.defineProperty(window, '__cadStudioAutoOpen', {
2670
2670
  configurable: true,
2671
- get: () => ({ ...autoOpenTrace, mode: cadAutoOpen, session: panelSession }),
2671
+ // `open()` is for tooling: it is how a screenshot script (or a user
2672
+ // who closed the pane) brings the tab back without hunting for the
2673
+ // host's own launcher.
2674
+ get: () => ({ ...autoOpenTrace, mode: cadAutoOpen, session: panelSession, open: () => openPane(0) }),
2672
2675
  })
2673
2676
  } catch (err) { /* a stale definition from a previous apply is fine */ }
2674
2677
 
package/index.js CHANGED
@@ -18,7 +18,7 @@ import { existsSync } from 'node:fs'
18
18
  import { mkdtemp, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from 'node:fs/promises'
19
19
  import { tmpdir } from 'node:os'
20
20
  import { fileURLToPath } from 'node:url'
21
- import { join } from 'node:path'
21
+ import { dirname, join } from 'node:path'
22
22
 
23
23
  export const name = 'dsh-cad-studio'
24
24
 
@@ -331,6 +331,9 @@ class FreeCadBridge {
331
331
  this.latest = undefined
332
332
  this.seq = 0
333
333
  this.history = []
334
+ // Ids this process published since boot: a row that is neither here nor on
335
+ // disk was deleted on purpose and must not be resurrected by the next write.
336
+ this.touched = new Set()
334
337
  /** Assemblies keep their base placements so joints can re-place instances. */
335
338
  this.assemblies = new Map()
336
339
  this.assemblySeq = 0
@@ -399,6 +402,21 @@ class FreeCadBridge {
399
402
  const n = Number(String(rec.id).replace(/\D+/g, ''))
400
403
  if (Number.isFinite(n)) this.assemblySeq = Math.max(this.assemblySeq, n)
401
404
  }
405
+ // A row deleted from state.json (by hand or by another process) must stay
406
+ // deleted: without this, the next publish wrote the whole in-memory history
407
+ // back and undid the prune — which is exactly what the reviewer hit twice.
408
+ let diskIds = null
409
+ try {
410
+ const prev = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
411
+ diskIds = new Set((Array.isArray(prev.history) ? prev.history : []).map((h) => h.id))
412
+ } catch {}
413
+ if (diskIds) {
414
+ this.history = this.history.filter((h) => diskIds.has(h.id) || this.touched.has(h.id))
415
+ if (this.latest && !this.history.some((h) => h.id === this.latest.id)) {
416
+ const next = this.history[0]
417
+ this.latest = next ? { id: next.id, title: next.title, at: next.at, scene: this.scenes.get(next.id) ?? null } : null
418
+ }
419
+ }
402
420
  const latest = this.latest
403
421
  if (latest) await writeFile(join(dir, 'scenes', `${latest.id}.json`), JSON.stringify(latest.scene), 'utf8')
404
422
  const pointer = {
@@ -523,6 +541,7 @@ class FreeCadBridge {
523
541
  volume,
524
542
  ...(docKey ? { docKey } : {}),
525
543
  }
544
+ this.touched.add(id)
526
545
  this.history = [stats, ...this.history.filter((h) => h.id !== id)].slice(0, 30)
527
546
  this.latest = { id, title, at: stats.at, scene }
528
547
  // Persist so a restarted process (and any stale route closure left by a
@@ -866,9 +885,15 @@ def _prim(op):
866
885
  return Part.makeTorus(float(op["r1"]), float(op["r2"]), at, _dir(op.get("axis")))
867
886
  if k == "extrude":
868
887
  base = float(op.get("base", 0.0))
869
- h = float(op["h"])
870
- ps = [Vector(float(p[0]), float(p[1]), base) for p in op["points"]]
871
- return Part.Face(Part.makePolygon(ps + [ps[0]])).extrude(Vector(0.0, 0.0, h))
888
+ h = float(op.get("h", 0.0))
889
+ # Points may be 2D (z = base) or 3D; dir replaces the +Z extrusion,
890
+ # which is what a chamfer prism or a slanted rib actually needs.
891
+ pts = [tuple(p) for p in op["points"]]
892
+ ps = [Vector(float(q[0]), float(q[1]), float(q[2]) if len(q) > 2 else base) for q in pts]
893
+ vec = _v3(op.get("dir"), (0.0, 0.0, h)) if op.get("dir") else Vector(0.0, 0.0, h)
894
+ if abs(vec.Length) < 1e-9:
895
+ raise RuntimeError("extrude 需要 h 或 dir(当前的挤出向量长度为 0)")
896
+ return Part.Face(Part.makePolygon(ps + [ps[0]])).extrude(vec)
872
897
  if k == "revolve":
873
898
  ps = [Vector(float(p[0]), 0.0, float(p[1])) for p in op["points"]]
874
899
  ang = float(op.get("angle", 360.0))
@@ -883,8 +908,14 @@ for _idx, _op in enumerate(_OPS):
883
908
  _s = _prim(_op)
884
909
  _shape = _s if _shape is None else _shape.fuse(_s)
885
910
  elif _k in ("fuse", "cut", "common"):
886
- _s = _prim(_op["with"])
887
- _shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
911
+ # A U-shaped wall is one feature, not two: with takes a list, and
912
+ # the tools are combined in order against the running shape.
913
+ _ws = _op["with"]
914
+ if not isinstance(_ws, (list, tuple)):
915
+ _ws = [_ws]
916
+ for _w in _ws:
917
+ _s = _prim(_w)
918
+ _shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
888
919
  elif _k == "fillet":
889
920
  _shape = _shape.makeFillet(float(_op["r"]), _shape.Edges)
890
921
  elif _k == "chamfer":
@@ -926,7 +957,10 @@ for _idx, _op in enumerate(_OPS):
926
957
  else:
927
958
  raise RuntimeError("未知特征:" + str(_k))
928
959
  except Exception as _e:
929
- raise RuntimeError("第 %d 步(%s)失败:%s" % (_idx + 1, _k, _e))
960
+ # Name the feature, not just its position: "step 10 (cut) failed: 'with'"
961
+ # told the caller nothing about which row to fix.
962
+ raise RuntimeError("第 %d 步 · 特征 %s(%s,%s)失败:%s" % (
963
+ _idx + 1, _op.get("_id", "?"), _op.get("_label") or "-", _k, _e))
930
964
 
931
965
  if _shape is None:
932
966
  raise RuntimeError("ops 为空:至少给一个图元")
@@ -1181,6 +1215,9 @@ __out = {
1181
1215
  },
1182
1216
  execute: async ({ action, id, title }) => {
1183
1217
  const kind = String(action ?? 'list')
1218
+ // A fresh process starts with an empty in-memory list; the rows live in
1219
+ // state.json until the next publish hydrates them.
1220
+ await bridge.hydrateHistory()
1184
1221
  if (kind === 'list') {
1185
1222
  const rows = bridge.listSceneRows()
1186
1223
  return { ok: true, scenes: rows.length, latest: bridge.latest ? bridge.latest.id : '', items: rows }
@@ -1427,6 +1464,7 @@ else:
1427
1464
  target: { type: 'string', description: 'Absolute output path; the extension picks the format (.step/.stp/.brep/.iges/.igs/.stl).' },
1428
1465
  source: { type: 'string', description: 'Existing model file to export (STEP/IGES/BREP/STL).' },
1429
1466
  code: { type: 'string', description: 'FreeCAD Python that produces the geometry; bind `scene` or `export_shapes`.' },
1467
+ model: { type: 'string', description: 'Export a saved model document by name (feature or script model) instead of a file or a script.' },
1430
1468
  minVolume: { type: 'number', description: 'Drop solids smaller than this (mm³). Use it to keep round wires and dust out of a print file; the return says how many were filtered.' },
1431
1469
  alsoStl: { type: 'boolean', description: 'Also write an STL next to the target (a light file for viewers that do not read STEP).' },
1432
1470
  },
@@ -1437,8 +1475,16 @@ else:
1437
1475
  schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, bytes: { type: 'number' } } },
1438
1476
  render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
1439
1477
  },
1440
- execute: async ({ target, source, code, minVolume, alsoStl }) => {
1478
+ execute: async ({ target, source, code, model, minVolume, alsoStl }) => {
1441
1479
  if (!target || extOf(target) === '') return { ok: false, error: 'target must be an absolute path with an extension' }
1480
+ if (typeof model === 'string' && model) {
1481
+ const dirs = bridge.modelsCandidates()
1482
+ const dir = dirs.find((d) => existsSync(join(d, `${model}.json`))) || dirs[0]
1483
+ const doc = await readModel(model, dir)
1484
+ bridge.noteModelsDir(dir)
1485
+ const exported = await exportModelStep(doc, target)
1486
+ return { ...exported, source: `model:${model}` }
1487
+ }
1442
1488
  const src = shapesFrom({ source, code })
1443
1489
  if (!src) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
1444
1490
  const out = await writeShapeFile(target, src, { minVolume, alsoStl })
@@ -1974,7 +2020,7 @@ if _TARGET:
1974
2020
  /** Feature objects to flat ops (`{kind, ...params}`) for the Python emitter. */
1975
2021
  const featureOps = (doc) => doc.features
1976
2022
  .filter((f) => f.enabled !== false)
1977
- .map((f) => ({ kind: f.kind, ...(f.params ?? {}) }))
2023
+ .map((f) => ({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' }))
1978
2024
 
1979
2025
  const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled']
1980
2026
 
@@ -1996,10 +2042,46 @@ if _TARGET:
1996
2042
  if (hit) maxId = Math.max(maxId, Number(hit[1]))
1997
2043
  }
1998
2044
  const id = /^f\d+$/.test(String(raw.id ?? '')) ? String(raw.id) : `f${maxId + 1}`
2045
+ const label = String(raw.label ?? '').slice(0, 40)
2046
+ // Validate here, not in FreeCAD: a missing `with` used to surface as
2047
+ // "第 10 步(cut)失败:'with'" — a KeyError with no idea which row to fix.
2048
+ const num = (v) => typeof v === 'number' && Number.isFinite(v)
2049
+ const pos = (v) => num(v) && v > 0
2050
+ const triple = (v) => Array.isArray(v) && v.length === 3 && v.every(num)
2051
+ const where = `特征 ${id}${label ? `(${label})` : ''} ${kind}`
2052
+ const need = (cond, hint) => {
2053
+ if (!cond) throw new Error(`${where}:${hint}`)
2054
+ }
2055
+ const tool = (v) => v && typeof v === 'object' && ['box', 'cylinder', 'sphere', 'cone', 'torus', 'extrude', 'revolve'].includes(String(v.kind))
2056
+ const withs = params.with
2057
+ if (kind === 'box') need(triple(params.size) && params.size.every(pos), '需要 size:[dx,dy,dz](三个正数)')
2058
+ else if (kind === 'cylinder') need(pos(params.r) && pos(params.h), '需要 r>0 与 h>0')
2059
+ else if (kind === 'sphere') need(pos(params.r), '需要 r>0')
2060
+ else if (kind === 'cone') need(num(params.r1) && num(params.r2) && pos(params.h), '需要 r1 / r2 / h>0')
2061
+ else if (kind === 'torus') need(pos(params.r1) && pos(params.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
2062
+ else if (kind === 'extrude') {
2063
+ const points = Array.isArray(params.points) ? params.points : []
2064
+ need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点)')
2065
+ need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
2066
+ need(pos(params.h) || triple(params.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
2067
+ } else if (kind === 'revolve') {
2068
+ const points = Array.isArray(params.points) ? params.points : []
2069
+ need(points.length >= 2, '需要 points(至少 2 个 [x,z] 剖面点)')
2070
+ } else if (kind === 'fuse' || kind === 'cut' || kind === 'common') {
2071
+ const list = Array.isArray(withs) ? withs : withs ? [withs] : []
2072
+ need(list.length > 0, `需要 with 子图元({kind:"box",size:[…]},或用数组一次减/并多个)`)
2073
+ need(list.every(tool), 'with 里的每一项都要是图元(box/cylinder/sphere/cone/torus/extrude/revolve),且带 kind')
2074
+ } else if (kind === 'fillet') need(pos(params.r), '需要 r>0')
2075
+ else if (kind === 'chamfer') need(pos(params.d), '需要 d>0')
2076
+ else if (kind === 'shell') need(pos(params.t), '需要 t>0(壁厚)')
2077
+ else if (kind === 'pattern_linear') need(triple(params.delta) && num(params.count) && params.count >= 2, '需要 delta:[dx,dy,dz] 与 count>=2')
2078
+ else if (kind === 'pattern_circular') need(num(params.count) && params.count >= 2, '需要 count>=2')
2079
+ else if (kind === 'translate') need(triple(params.v), '需要 v:[dx,dy,dz]')
2080
+ else if (kind === 'rotate') need(num(params.deg), '需要 deg(角度)')
1999
2081
  return {
2000
2082
  id,
2001
2083
  kind,
2002
- label: String(raw.label ?? '').slice(0, 40),
2084
+ label,
2003
2085
  params: JSON.parse(JSON.stringify(params)),
2004
2086
  enabled: raw.enabled !== false,
2005
2087
  }
@@ -2026,11 +2108,15 @@ if _TARGET:
2026
2108
  sceneId: doc.stats?.sceneId || '',
2027
2109
  })
2028
2110
  if (out.ok === false) return { ...out, name: doc.name, params: doc.params }
2111
+ // run() returns volume/bounds but not triangle count, so read it back from
2112
+ // the row that was just published (a null here forced the panel to guess).
2113
+ const sceneId = out.sceneId ?? ''
2114
+ const row = sceneId ? bridge.history.find((h) => h.id === sceneId) : null
2029
2115
  doc.stats = {
2030
2116
  volume: out.volume ?? null,
2031
- triangles: out.triangles ?? null,
2117
+ triangles: row?.triangles ?? null,
2032
2118
  bounds: out.bounds ?? null,
2033
- sceneId: out.sceneId ?? '',
2119
+ sceneId,
2034
2120
  at: doc.updatedAt,
2035
2121
  }
2036
2122
  if (note) doc.note = note
@@ -2062,6 +2148,7 @@ if _TARGET:
2062
2148
  features: { type: 'array', items: { type: 'object' }, description: 'For kind="features": the initial feature list, each {kind, label?, params?} (flat params such as {kind:"box", size:[60,40,20]} also work).' },
2063
2149
  params: { type: 'object', description: 'Parameter dict. On update these are merged into the existing params (set a key to null to delete it).' },
2064
2150
  note: { type: 'string', description: 'What this revision changed (kept in history).' },
2151
+ export: { type: 'string', description: 'Also write the model out as STEP at this path (create / update / show). Saves the caller from re-implementing the feature emitter.' },
2065
2152
  },
2066
2153
  required: ['action'],
2067
2154
  additionalProperties: false,
@@ -2072,7 +2159,19 @@ if _TARGET:
2072
2159
  },
2073
2160
  execute: async (args, exec) => {
2074
2161
  try {
2075
- return await runDocAction(args, modelsDirFor(exec))
2162
+ const dir = modelsDirFor(exec)
2163
+ const out = await runDocAction(args, dir)
2164
+ if (args && typeof args.export === 'string' && args.export && args.name) {
2165
+ // A feature model is the source of truth; the STEP is a product. Do it
2166
+ // here so the caller never has to copy the emitter to their side.
2167
+ try {
2168
+ const doc = await readModel(args.name, dir)
2169
+ out.exported = await exportModelStep(doc, args.export)
2170
+ } catch (error) {
2171
+ out.exportError = String(error?.message ?? error)
2172
+ }
2173
+ }
2174
+ return out
2076
2175
  } catch (err) {
2077
2176
  // Tool errors are data, not exceptions: the agent needs to read the
2078
2177
  // message and try something else, and a throw would also skip cleanup.
@@ -2192,6 +2291,32 @@ if _TARGET:
2192
2291
  },
2193
2292
  })
2194
2293
 
2294
+ /**
2295
+ * Turn a model document into a STEP file without the caller re-implementing
2296
+ * the emitter. A feature model runs its own `featuresScript` (which already
2297
+ * knows how to export); a script model gets three extra lines appended.
2298
+ */
2299
+ async function exportModelStep(doc, target) {
2300
+ if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
2301
+ await mkdir(dirname(target), { recursive: true })
2302
+ const head = doc.kind === 'features'
2303
+ ? featuresScript(featureOps(doc), target)
2304
+ : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
2305
+ const code = doc.kind === 'features'
2306
+ ? head
2307
+ : `${head}import os as _os
2308
+ _os.makedirs(_os.path.dirname(${JSON.stringify(target)}) or ".", exist_ok=True)
2309
+ Part.makeCompound([scene]).exportStep(${JSON.stringify(target)})
2310
+ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scene.Volume, 3),
2311
+ "bytes": _os.path.getsize(${JSON.stringify(target)})}`
2312
+ // publish:false — an export is a product, not a new row in the model list.
2313
+ const out = await bridge.run(code, { title: `${doc.name} → STEP`, publish: false })
2314
+ if (out.ok === false) return { ...out, model: doc.name, path: target }
2315
+ let bytes = Number(out.bytes ?? 0)
2316
+ try { bytes = (await stat(target)).size } catch {}
2317
+ return { ok: true, model: doc.name, path: target, bytes, valid: bytes > 200, volume: out.volume ?? null }
2318
+ }
2319
+
2195
2320
  async function runDocAction(args, dir) {
2196
2321
  bridge.noteModelsDir(dir)
2197
2322
  const action = String(args.action ?? '')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {