dsh-cad-studio 0.29.1 → 0.30.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 (3) hide show
  1. package/README.md +4 -3
  2. package/index.js +155 -23
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -18,10 +18,10 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
19
  | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴);`cad_studio_sheet` 正式图纸(图框 + 标题栏 + 三视图 + 尺寸,A4/A3/A2,可出 DXF) |
20
20
  | 装配 | `cad_studio_assembly` 多零件实例、`cad_studio_joint` 关节、`cad_studio_mate` 约束(同心/贴合/距离)、`cad_studio_drive` 驱动、`cad_studio_explode` 爆炸图 |
21
- | 依赖 | `cad_studio_deps` 列出模型的来源 STEP(谁在用、还在不在),`relink` 换路径后原地重建;面板「信息」里能直接填新路径 |
21
+ | 依赖 | `cad_studio_deps` 列出模型的来源 STEP(谁在用、还在不在),`relink` 换路径后原地重建、`rebuild` 给 0.24 之前建的老装配补一次源文件清单;面板「信息」里能直接填新路径 |
22
22
  | 外观 | 面板里改的颜色/显隐/透明度/线框按模型保存(`POST /cad-studio/appearance`),刷新和重启后仍在 |
23
- | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
24
- | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
23
+ | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env`;`cad_studio_doc {action:"create", from:"…/x.step"}` 把已有 STEP 变成可编辑模型文档 |
24
+ | 模型清单 | `cad_studio_scene`(`action: list / delete / rename / prune`,`ids:[…]` 一次删多行)——面板里那条列表就是它;0 体积 0 三角的幽灵行会被标 `stale`,`prune` 一次清掉 |
25
25
  | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
26
26
  | 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
27
27
  | 拔模挤出 | `{kind:"extrude", sketch:"S1", h:20, draft:3}` 按 3° 拔模:截面按 `h*tan(3°)` 偏移后 loft 成体,正角度内收、负角度外放 |
@@ -100,6 +100,7 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
100
100
  - **导出只走 `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`。
101
101
  - **探查脚本别发布场景**。`cad_studio_run` 默认会把绑定的 `scene` 发布成面板里的一行;只是量体积/查干涉的脚本传 `publish: false`,否则模型列表会被探针卡片塞满(实测一次会话攒到 28 行)。已经混进去的用 `cad_studio_scene {action:"delete", id:"scene-12"}` 清。
102
102
  - `cad_studio_export` 的返回里 `volume` / `solids` 是**真正写出去的那一套**,`sourceVolume` / `sourceSolids` 是输入侧的;`minVolume` 会按实体体积过滤(滤掉圆丝、灰尘),`alsoStl` 顺手写一份 STL。
103
+ - **布尔链会留共面裂面,`unify` 默认开**:逐次 `fuse`/`cut` 之后同一平面会留一圈缝,体积不变但面数与文件变大(实测托架 174→64 面、STEP 607 KB→274 KB)。`cad_studio_export` 写文件前对每个实体 `removeSplitter()`,传 `unify:false` 可保留原始拓扑;返回里的 `faces` / `shells` / `fingerprint: {solids, faces, shells, volume}` 就是用来核几何的——**别用 md5**,STEP 头带时间戳,同一件两次导出 md5 也不同。
103
104
  - `cad_studio_assembly` 传 `measure: true` 会回每实例的 bbox/体积/实体数与总体积,`interference: true` 会回真正重叠的实例对(先用包围盒筛,再做布尔交)。
104
105
  - **`fuse` / `cut` / `common` 的 `with` 可以是数组**:U 形围壁写成「一条 `fuse` 外块 + 一条 `cut` 带两个内腔」即可,不必拆成中间状态(中间状态是实心块,顺序错了会削到别处)。
105
106
  - **`extrude` 支持 3D 剖面点与 `dir`**:三角棱柱写 `{kind:"extrude", points:[[0,0,0],[40,0,0],[0,30,0]], dir:[0,0,20]}`,不用再拿 `base`/`h` 手算覆盖范围。
package/index.js CHANGED
@@ -19,7 +19,7 @@ import crypto from 'node:crypto'
19
19
  import { mkdtemp, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from 'node:fs/promises'
20
20
  import { tmpdir } from 'node:os'
21
21
  import { fileURLToPath } from 'node:url'
22
- import { dirname, join } from 'node:path'
22
+ import { dirname, join, resolve } from 'node:path'
23
23
 
24
24
  export const name = 'dsh-cad-studio'
25
25
 
@@ -2273,7 +2273,15 @@ __out = {
2273
2273
  schema: { type: 'object', properties: { available: { type: 'boolean' }, binary: { type: 'string' }, scenes: { type: 'number' }, latest: { type: 'string' } } },
2274
2274
  render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
2275
2275
  },
2276
- execute: async () => bridge.status(),
2276
+ execute: async () => {
2277
+ // The count must come from the same place the panel's list comes from:
2278
+ // `status().scenes` is only what this process published since boot, which
2279
+ // is 0 after a restart while state.json still lists every row.
2280
+ await bridge.hydrateHistory()
2281
+ const rows = bridge.listSceneRows()
2282
+ const base = bridge.status()
2283
+ return { ...base, scenes: rows.length, latest: (bridge.latest && bridge.latest.id) || (rows[0] && rows[0].id) || '' }
2284
+ },
2277
2285
  })
2278
2286
 
2279
2287
  tool({
@@ -2398,8 +2406,9 @@ __out = {
2398
2406
  parameters: {
2399
2407
  type: 'object',
2400
2408
  properties: {
2401
- action: { type: 'string', enum: ['list', 'delete', 'rename'], description: 'list (default) / delete / rename.' },
2409
+ action: { type: 'string', enum: ['list', 'delete', 'rename', 'prune'], description: 'list (default) / delete / rename / prune (drop every row with no geometry).' },
2402
2410
  id: { type: 'string', description: 'Scene id, e.g. scene-12. Required for delete and rename.' },
2411
+ ids: { type: 'array', items: { type: 'string' }, description: 'Delete several rows at once (a refit can leave a dozen); same as calling delete once per id.' },
2403
2412
  title: { type: 'string', description: 'New title (rename only).' },
2404
2413
  },
2405
2414
  additionalProperties: false,
@@ -2408,16 +2417,39 @@ __out = {
2408
2417
  schema: { type: 'object', properties: { ok: { type: 'boolean' }, scenes: { type: 'number' } } },
2409
2418
  render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
2410
2419
  },
2411
- execute: async ({ action, id, title }) => {
2420
+ execute: async ({ action, id, title, ids }) => {
2412
2421
  const kind = String(action ?? 'list')
2413
2422
  // A fresh process starts with an empty in-memory list; the rows live in
2414
2423
  // state.json until the next publish hydrates them.
2415
2424
  await bridge.hydrateHistory()
2416
2425
  if (kind === 'list') {
2417
- const rows = bridge.listSceneRows()
2418
- return { ok: true, scenes: rows.length, latest: bridge.latest ? bridge.latest.id : '', items: rows }
2426
+ const rows = bridge.listSceneRows().map((r) => ({
2427
+ ...r,
2428
+ // A row with no triangles and no volume is a shell: it cannot be opened,
2429
+ // has nothing to relink, and only clutters the panel's model list.
2430
+ stale: (r.triangles ?? 0) === 0 && (r.volume ?? 0) === 0,
2431
+ }))
2432
+ return { ok: true, scenes: rows.length, latest: bridge.latest ? bridge.latest.id : '', stale: rows.filter((r) => r.stale).map((r) => r.id), items: rows }
2433
+ }
2434
+ if (kind === 'delete') {
2435
+ // One id keeps the old return shape ({removed: 'scene-3'}) so existing
2436
+ // callers and scripts do not have to learn a new one.
2437
+ if (!Array.isArray(ids) || !ids.length) return bridge.removeScene(id)
2438
+ const list = ids.map(String)
2439
+ const removed = []
2440
+ const failed = []
2441
+ for (const key of list) {
2442
+ if (!key) continue
2443
+ try { await bridge.removeScene(key); removed.push(key) } catch (err) { failed.push({ id: key, error: String(err?.message ?? err) }) }
2444
+ }
2445
+ return { ok: failed.length === 0, removed, failed, scenes: bridge.history.length, latest: bridge.latest ? bridge.latest.id : '' }
2446
+ }
2447
+ if (kind === 'prune') {
2448
+ const doomed = bridge.listSceneRows().filter((r) => (r.triangles ?? 0) === 0 && (r.volume ?? 0) === 0).map((r) => r.id)
2449
+ const removed = []
2450
+ for (const key of doomed) { try { await bridge.removeScene(key); removed.push(key) } catch { /* keep going: one bad row must not block the rest */ } }
2451
+ return { ok: true, removed, scenes: bridge.history.length, latest: bridge.latest ? bridge.latest.id : '' }
2419
2452
  }
2420
- if (kind === 'delete') return bridge.removeScene(id)
2421
2453
  if (kind === 'rename') return bridge.renameScene(id, title)
2422
2454
  return { ok: false, error: `不支持的 action:${kind}(list / delete / rename)` }
2423
2455
  },
@@ -2604,6 +2636,9 @@ if not _shapes:
2604
2636
  const writeShapeFile = (target, src, opts = {}) => {
2605
2637
  const minVolume = Number.isFinite(opts.minVolume) && opts.minVolume > 0 ? Number(opts.minVolume) : 0
2606
2638
  const alsoStl = Boolean(opts.alsoStl)
2639
+ // Coplanar seams survive a chain of fuse/cut: the solid is right, the face
2640
+ // count (and the STEP size) is 3-6x too big. removeSplitter merges them.
2641
+ const unify = opts.unify !== false
2607
2642
  const py = `${PRELUDE}
2608
2643
  ${src}
2609
2644
  if not _shapes:
@@ -2619,10 +2654,19 @@ else:
2619
2654
  for _s in _shapes:
2620
2655
  _solids.extend(list(_s.Solids) or [_s])
2621
2656
  _minv = ${minVolume}
2657
+ _UNIFY = ${unify ? 'True' : 'False'}
2622
2658
  _kept = [x for x in _solids if x.Volume >= _minv] if _minv > 0 else _solids
2623
2659
  if not _kept:
2624
2660
  raise RuntimeError("no solids left after minVolume=%.3f (smallest %.3f)" % (_minv, min((x.Volume for x in _solids), default=0.0)))
2625
2661
  _shapes = _kept
2662
+ if _UNIFY:
2663
+ _unified = []
2664
+ for _s in _shapes:
2665
+ try:
2666
+ _unified.append(_s.removeSplitter() if hasattr(_s, "removeSplitter") else _s)
2667
+ except Exception:
2668
+ _unified.append(_s)
2669
+ _shapes = _unified
2626
2670
  if _fmt in ("step", "stp"):
2627
2671
  # Part.export([shape]) writes a 1.6 KB STEP that reads back as a NULL shape;
2628
2672
  # Shape.exportStep / compound exportStep is the API that produces a valid file.
@@ -2663,7 +2707,13 @@ else:
2663
2707
  __out = {"ok": True, "path": _target, "format": _fmt, "bytes": os.path.getsize(_target),
2664
2708
  "solids": len(_shapes), "volume": round(sum(float(x.Volume) for x in _shapes), 3),
2665
2709
  "sourceSolids": len(_solids), "sourceVolume": round(sum(float(x.Volume) for x in _solids), 3),
2666
- "filtered": len(_solids) - len(_shapes)}
2710
+ "filtered": len(_solids) - len(_shapes),
2711
+ "faces": sum(len(x.Faces) for x in _shapes),
2712
+ "shells": sum(len(x.Shells) for x in _shapes)}
2713
+ # A geometry fingerprint: identical bytes are not identical geometry (the STEP
2714
+ # header carries a timestamp), so compare these four numbers instead of md5.
2715
+ __out["fingerprint"] = {"solids": __out["solids"], "faces": __out["faces"],
2716
+ "shells": __out["shells"], "volume": __out["volume"]}
2667
2717
  if _stl:
2668
2718
  __out["stl"] = {"path": _stl, "bytes": os.path.getsize(_stl)}
2669
2719
  `
@@ -2682,6 +2732,7 @@ else:
2682
2732
  model: { type: 'string', description: 'Export a saved model document by name (feature or script model) instead of a file or a script.' },
2683
2733
  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.' },
2684
2734
  alsoStl: { type: 'boolean', description: 'Also write an STL next to the target (a light file for viewers that do not read STEP).' },
2735
+ unify: { type: 'boolean', description: 'Merge coplanar seams left by fuse/cut before writing (default true). A boolean chain can leave 174 faces where 64 is right; volume is identical either way, so only faces/bytes show it. Pass false to keep the raw topology.' },
2685
2736
  },
2686
2737
  required: ['target'],
2687
2738
  additionalProperties: false,
@@ -2690,19 +2741,19 @@ else:
2690
2741
  schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, bytes: { type: 'number' } } },
2691
2742
  render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
2692
2743
  },
2693
- execute: async ({ target, source, code, model, minVolume, alsoStl }) => {
2744
+ execute: async ({ target, source, code, model, minVolume, alsoStl, unify }) => {
2694
2745
  if (!target || extOf(target) === '') return { ok: false, error: 'target must be an absolute path with an extension' }
2695
2746
  if (typeof model === 'string' && model) {
2696
2747
  const dirs = bridge.modelsCandidates()
2697
2748
  const dir = dirs.find((d) => existsSync(join(d, `${model}.json`))) || dirs[0]
2698
2749
  const doc = await readModel(model, dir)
2699
2750
  bridge.noteModelsDir(dir)
2700
- const exported = await exportModelStep(doc, target)
2751
+ const exported = await exportModelStep(doc, target, { unify })
2701
2752
  return { ...exported, source: `model:${model}` }
2702
2753
  }
2703
2754
  const src = shapesFrom({ source, code })
2704
2755
  if (!src) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
2705
- const out = await writeShapeFile(target, src, { minVolume, alsoStl })
2756
+ const out = await writeShapeFile(target, src, { minVolume, alsoStl, unify })
2706
2757
  // Keep the two numbers apart on purpose: `volume` is what was written,
2707
2758
  // `sourceVolume` is what the input held. Mixing them is how a batch export
2708
2759
  // gets mistaken for the part it produced.
@@ -3857,10 +3908,12 @@ else:
3857
3908
  parameters: {
3858
3909
  type: 'object',
3859
3910
  properties: {
3860
- action: { type: 'string', enum: ['list', 'relink'], description: 'Default: list.' },
3911
+ action: { type: 'string', enum: ['list', 'relink', 'rebuild'], description: 'Default: list.' },
3861
3912
  assembly: { type: 'string', description: 'Assembly id (asm-1) or unique title. Omitted: every assembly for `list`, newest for `relink`.' },
3862
3913
  part: { type: 'string', description: 'Part name to repoint (relink).' },
3863
3914
  path: { type: 'string', description: 'New file path for that part (relink).' },
3915
+ parts: { type: 'array', items: { type: 'object' }, description: 'rebuild: the source list to record, [{name, path}] — assemblies built before 0.24 have no spec, and their source files cannot be inferred, so they have to be stated once.' },
3916
+ instances: { type: 'array', items: { type: 'object' }, description: 'rebuild: optional placement list [{name, part, at, rot}]; omitted keeps the ones already on the record.' },
3864
3917
  },
3865
3918
  additionalProperties: false,
3866
3919
  },
@@ -3868,7 +3921,7 @@ else:
3868
3921
  schema: { type: 'object', properties: { ok: { type: 'boolean' }, models: { type: 'array' }, missing: { type: 'number' } } },
3869
3922
  render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
3870
3923
  },
3871
- execute: async ({ action, assembly, part, path }) => {
3924
+ execute: async ({ action, assembly, part, path, parts, instances }) => {
3872
3925
  const mode = action ?? 'list'
3873
3926
  if (mode === 'list') {
3874
3927
  if (!assembly) await bridge.hydrateAssemblies()
@@ -3885,11 +3938,36 @@ else:
3885
3938
  tracked: Boolean(r.spec),
3886
3939
  files,
3887
3940
  missingParts: files.filter((f) => !f.exists).map((f) => f.part),
3941
+ // An assembly built before sources were recorded cannot relink: the
3942
+ // part files are unknown, not missing. Say so instead of an empty list.
3943
+ ...(r.spec ? {} : { hint: '这个装配没有记录来源文件(0.24 之前建的)。用 action=rebuild 并给 parts:[{name,path}] 记一次,之后 relink 就能用。' }),
3888
3944
  }
3889
3945
  })
3890
3946
  const missing = models.reduce((n, m) => n + m.missingParts.length, 0)
3891
3947
  return { ok: true, models, missing }
3892
3948
  }
3949
+ if (mode === 'rebuild') {
3950
+ let record
3951
+ try { record = findAssembly(assembly) } catch (error) { return { ok: false, error: String(error?.message ?? error) } }
3952
+ if (!Array.isArray(parts) || !parts.length) return { ok: false, error: 'rebuild 需要 parts:[{name,path}](这个装配的源文件清单)' }
3953
+ const spec = parts.map((raw) => {
3954
+ const name = String(raw?.name ?? '').trim()
3955
+ const file = String(raw?.path ?? '').trim()
3956
+ if (!name) throw new Error('parts 里每一项都要有 name')
3957
+ if (!file || !existsSync(file)) throw new Error(`零件 ${name} 的文件不存在:${file || '(空)'}`)
3958
+ return { name, path: file, ...(raw.color !== undefined ? { color: raw.color } : {}) }
3959
+ })
3960
+ const placed = Array.isArray(instances) && instances.length ? instances : (record.spec?.instances ?? [])
3961
+ if (!placed.length) return { ok: false, error: 'rebuild 还需要 instances(或先有一次用 cad_studio_assembly 建的实例布局)' }
3962
+ const out = await bridge.run(assemblyScript(spec, placed, '', false, false), { title: record.title, docKey: `asm:${record.id}` })
3963
+ if (!out.ok || !out.sceneId) return { ok: false, error: out.error ?? '重新读取文件失败', stderr: out.stderr ?? '' }
3964
+ const scene = bridge.scenes.get(out.sceneId)
3965
+ if (!scene) return { ok: false, error: '重新读取后没有拿到场景' }
3966
+ record.spec = { parts: spec, instances: placed }
3967
+ bridge.rebaseAssembly(record, { title: record.title, sceneId: out.sceneId, scene })
3968
+ const published = await bridge.republishAssembly(record)
3969
+ return { ok: true, assembly: record.id, sceneId: published.id, tracked: true, files: specRows(record).length, instances: placed.length }
3970
+ }
3893
3971
  return relinkPart({ assembly, part, path })
3894
3972
  },
3895
3973
  })
@@ -4511,9 +4589,31 @@ else:
4511
4589
  }
4512
4590
  }
4513
4591
  }
4592
+ // A fuse/cut chain leaves coplanar seams: the volume is right, the face count
4593
+ // and the STEP size are not. Feature chains are emitted clean, script models
4594
+ // are not, so only they get the tail (doc.unify === false opts out).
4595
+ const unifyTail = doc.unify === false ? '' : `
4596
+ try:
4597
+ _sc = globals().get("scene")
4598
+ if _sc is not None and hasattr(_sc, "removeSplitter"):
4599
+ _u = _sc.removeSplitter()
4600
+ if _u is not None and hasattr(_u, "Solids") and len(_u.Solids):
4601
+ scene = _u
4602
+ except Exception:
4603
+ pass
4604
+ try:
4605
+ if globals().get("scene") is not None:
4606
+ _o = globals().get("__out")
4607
+ if not isinstance(_o, dict):
4608
+ _o = {}
4609
+ __out = _o
4610
+ _o["faces"] = len(globals()["scene"].Faces)
4611
+ except Exception:
4612
+ pass
4613
+ `
4514
4614
  const code = isFeatures
4515
4615
  ? featuresScript(featureOps(doc), null, { cache, resume, sketches: doc.sketches })
4516
- : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
4616
+ : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n${unifyTail}`
4517
4617
  const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), sketches: doc.sketches ?? {}, tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
4518
4618
  doc.run = (doc.run ?? 0) + 1
4519
4619
  doc.updatedAt = new Date().toISOString()
@@ -4532,6 +4632,7 @@ else:
4532
4632
  doc.stats = {
4533
4633
  volume: out.volume ?? null,
4534
4634
  triangles: row?.triangles ?? null,
4635
+ faces: Number.isFinite(out.faces) ? out.faces : null,
4535
4636
  bounds: out.bounds ?? null,
4536
4637
  sceneId,
4537
4638
  at: doc.updatedAt,
@@ -4567,6 +4668,7 @@ else:
4567
4668
  params: doc.params,
4568
4669
  volume: doc.stats.volume,
4569
4670
  triangles: doc.stats.triangles,
4671
+ faces: doc.stats.faces ?? null,
4570
4672
  sceneId: doc.stats.sceneId,
4571
4673
  published: Boolean(doc.stats.sceneId),
4572
4674
  updatedAt: doc.updatedAt,
@@ -4581,7 +4683,8 @@ else:
4581
4683
  properties: {
4582
4684
  action: { type: 'string', enum: ['list', 'show', 'create', 'update', 'revert', 'delete', 'rename', 'duplicate'], description: 'list / show / create / update / revert / delete / rename / duplicate' },
4583
4685
  name: { type: 'string', description: 'Model name (中英文/数字/下划线/连字符).' },
4584
- script: { type: 'string', description: 'FreeCAD Python source; reads params from `P`, binds the result to `scene`. Required for create unless kind is "features".' },
4686
+ script: { type: 'string', description: 'FreeCAD Python source; reads params from `P`, binds the result to `scene`. Required for create unless kind is "features" or `from` is given.' },
4687
+ from: { type: 'string', description: 'create-only: import an existing STEP/IGES/BREP file as a script model. The generated script binds `scene` to that shape and the path is kept in params.source, so updates and exports keep working; feature-ise it later by rebuilding it as a feature list.' },
4585
4688
  kind: { type: 'string', enum: ['script', 'features'], description: 'script (default): a Python script + params. features: a declarative feature list you can edit one feature at a time (see cad_studio_features).' },
4586
4689
  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).' },
4587
4690
  params: { type: 'object', description: 'Parameter dict. On update these are merged into the existing params (set a key to null to delete it).' },
@@ -4970,17 +5073,18 @@ else:
4970
5073
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
4971
5074
  }
4972
5075
 
4973
- async function exportModelStep(doc, target) {
5076
+ async function exportModelStep(doc, target, opts = {}) {
4974
5077
  if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
4975
5078
  await mkdir(dirname(target), { recursive: true })
4976
5079
  const head = doc.kind === 'features'
4977
5080
  ? featuresScript(featureOps(doc), target, { sketches: doc.sketches })
4978
5081
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
5082
+ const unify = opts.unify !== false
4979
5083
  const code = doc.kind === 'features'
4980
5084
  ? head
4981
5085
  : `${head}import os as _os
4982
5086
  _os.makedirs(_os.path.dirname(${JSON.stringify(target)}) or ".", exist_ok=True)
4983
- Part.makeCompound([scene]).exportStep(${JSON.stringify(target)})
5087
+ ${unify ? 'try:\n if hasattr(scene, "removeSplitter"):\n _u = scene.removeSplitter()\n if _u is not None and len(_u.Solids):\n scene = _u\nexcept Exception:\n pass\n' : ''}Part.makeCompound([scene]).exportStep(${JSON.stringify(target)})
4984
5088
  __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scene.Volume, 3),
4985
5089
  "bytes": _os.path.getsize(${JSON.stringify(target)})}`
4986
5090
  // publish:false — an export is a product, not a new row in the model list.
@@ -4988,7 +5092,19 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4988
5092
  if (out.ok === false) return { ...out, model: doc.name, path: target }
4989
5093
  let bytes = Number(out.bytes ?? 0)
4990
5094
  try { bytes = (await stat(target)).size } catch {}
4991
- return { ok: true, model: doc.name, path: target, bytes, valid: bytes > 200, volume: out.volume ?? null }
5095
+ // Read the written file back once: the return has to say what was actually
5096
+ // exported (solids/faces/shells), not what the script intended. Callers used
5097
+ // to have to start a second kernel just to count faces.
5098
+ let geom = null
5099
+ try {
5100
+ const probe = await bridge.run(`${PRELUDE}\n_s = Part.Shape()\n_s.read(${JSON.stringify(target)})\n__out = {"ok": True, "solids": len(_s.Solids), "faces": len(_s.Faces), "shells": len(_s.Shells), "volume": round(_s.Volume, 3)}\n`, { title: 'read back', publish: false })
5101
+ if (probe.ok && Number.isFinite(probe.faces)) geom = probe
5102
+ } catch { /* the export itself succeeded; the readback is extra evidence */ }
5103
+ return {
5104
+ ok: true, model: doc.name, path: target, bytes, valid: bytes > 200,
5105
+ volume: geom?.volume ?? out.volume ?? null,
5106
+ ...(geom ? { solids: geom.solids, faces: geom.faces, shells: geom.shells, fingerprint: { solids: geom.solids, faces: geom.faces, shells: geom.shells, volume: geom.volume } } : {}),
5107
+ }
4992
5108
  }
4993
5109
 
4994
5110
  /** One readable sentence per doc write, e.g. "改参数 高 从 20 到 30". */
@@ -5019,7 +5135,15 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5019
5135
  for (const n of names) {
5020
5136
  try {
5021
5137
  const doc = await readModel(n, dir)
5022
- models.push({ name: doc.name, kind: doc.kind, features: doc.features.length, params: doc.params, runs: doc.run ?? 0, updatedAt: doc.updatedAt ?? '', volume: doc.stats?.volume ?? null, triangles: doc.stats?.triangles ?? null })
5138
+ const row = bridge.history.find((h) => h.docKey === `model:${doc.name}` || h.title === doc.name)
5139
+ models.push({
5140
+ name: doc.name, kind: doc.kind, features: doc.features.length, params: doc.params, runs: doc.run ?? 0,
5141
+ updatedAt: doc.updatedAt ?? '',
5142
+ // A features document records volume/faces at publish time but not the
5143
+ // triangle count; the scene row that publish created does have it.
5144
+ volume: doc.stats?.volume ?? row?.volume ?? null,
5145
+ triangles: doc.stats?.triangles ?? row?.triangles ?? null,
5146
+ })
5023
5147
  } catch { /* a hand-edited file that no longer parses is skipped, not fatal */ }
5024
5148
  }
5025
5149
  models.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
@@ -5045,9 +5169,11 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5045
5169
  if (action === 'create') {
5046
5170
  const key = checkName(args.name)
5047
5171
  const wantFeatures = args.kind === 'features' || Array.isArray(args.features)
5048
- if (!wantFeatures && (typeof args.script !== 'string' || !args.script.trim())) {
5049
- throw new Error('create 需要 script(FreeCAD Python,读 P、写 scene),或用 kind="features" 建特征列表模型')
5172
+ const fromPath = typeof args.from === 'string' && args.from.trim() ? resolve(args.from) : ''
5173
+ if (!wantFeatures && !fromPath && (typeof args.script !== 'string' || !args.script.trim())) {
5174
+ throw new Error('create 需要 script(FreeCAD Python,读 P、写 scene)、from(导入 STEP/IGES/BREP),或用 kind="features" 建特征列表模型')
5050
5175
  }
5176
+ if (fromPath && !existsSync(fromPath)) throw new Error(`找不到要导入的文件:${fromPath}`)
5051
5177
  try {
5052
5178
  await readModel(key, dir)
5053
5179
  throw new Error(`模型已存在:${key}(要改的话用 action=update)`)
@@ -5080,14 +5206,20 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5080
5206
  await journalDocCreate(key, dir, result)
5081
5207
  return await withChanges(doc, by, { ...result, kind: 'features', features: publicFeatures(doc) }, dir)
5082
5208
  }
5209
+ // `from` turns a file into a document instead of a one-shot scene: the
5210
+ // shape is re-read on every rebuild, so params/notes/undo still apply and
5211
+ // a later feature rebuild can replace the import step.
5083
5212
  const doc = {
5084
5213
  name: key,
5085
5214
  kind: 'script',
5086
- script: args.script,
5087
- params: args.params && typeof args.params === 'object' ? args.params : {},
5215
+ script: fromPath
5216
+ ? ['import Part', '_shape = Part.Shape()', '_shape.read(P["source"])', 'scene = _shape'].join('\n')
5217
+ : args.script,
5218
+ params: { ...(fromPath ? { source: fromPath } : {}), ...(args.params && typeof args.params === 'object' ? args.params : {}) },
5088
5219
  run: 0,
5089
5220
  createdAt: new Date().toISOString(),
5090
5221
  history: [],
5222
+ ...(fromPath ? { imported: fromPath } : {}),
5091
5223
  }
5092
5224
  const result = await rebuild(doc, dir, { note: args.note ?? 'create' })
5093
5225
  if (result.ok === false) return result
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.29.1",
3
+ "version": "0.30.1",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {