dsh-cad-studio 0.29.0 → 0.30.0

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 +143 -20
  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
 
@@ -1047,7 +1047,11 @@ class FreeCadBridge {
1047
1047
  this.scenes.delete(key)
1048
1048
  for (const [asmId, rec] of [...this.assemblies]) if (rec.sceneId === key) this.assemblies.delete(asmId)
1049
1049
  try { await rm(join(FreeCadBridge.dataDir, 'scenes', `${key}.json`), { force: true }) } catch {}
1050
- if (this.latest && this.latest.id === key) {
1050
+ // Re-point the "latest" pointer whenever it went stale: the deleted row may
1051
+ // be it, and after a fresh process it may be null while the rows still say
1052
+ // otherwise — either way the panel's live tab must not end up pointing at
1053
+ // nothing (it renders an empty viewport and looks like the tool broke).
1054
+ if (!this.latest || this.latest.id === key) {
1051
1055
  const next = this.history[0]
1052
1056
  this.latest = next ? { id: next.id, title: next.title, at: next.at, scene: this.scenes.get(next.id) ?? null } : null
1053
1057
  }
@@ -2269,7 +2273,15 @@ __out = {
2269
2273
  schema: { type: 'object', properties: { available: { type: 'boolean' }, binary: { type: 'string' }, scenes: { type: 'number' }, latest: { type: 'string' } } },
2270
2274
  render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
2271
2275
  },
2272
- 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
+ },
2273
2285
  })
2274
2286
 
2275
2287
  tool({
@@ -2394,8 +2406,9 @@ __out = {
2394
2406
  parameters: {
2395
2407
  type: 'object',
2396
2408
  properties: {
2397
- 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).' },
2398
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.' },
2399
2412
  title: { type: 'string', description: 'New title (rename only).' },
2400
2413
  },
2401
2414
  additionalProperties: false,
@@ -2404,16 +2417,39 @@ __out = {
2404
2417
  schema: { type: 'object', properties: { ok: { type: 'boolean' }, scenes: { type: 'number' } } },
2405
2418
  render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
2406
2419
  },
2407
- execute: async ({ action, id, title }) => {
2420
+ execute: async ({ action, id, title, ids }) => {
2408
2421
  const kind = String(action ?? 'list')
2409
2422
  // A fresh process starts with an empty in-memory list; the rows live in
2410
2423
  // state.json until the next publish hydrates them.
2411
2424
  await bridge.hydrateHistory()
2412
2425
  if (kind === 'list') {
2413
- const rows = bridge.listSceneRows()
2414
- 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 : '' }
2415
2452
  }
2416
- if (kind === 'delete') return bridge.removeScene(id)
2417
2453
  if (kind === 'rename') return bridge.renameScene(id, title)
2418
2454
  return { ok: false, error: `不支持的 action:${kind}(list / delete / rename)` }
2419
2455
  },
@@ -2600,6 +2636,9 @@ if not _shapes:
2600
2636
  const writeShapeFile = (target, src, opts = {}) => {
2601
2637
  const minVolume = Number.isFinite(opts.minVolume) && opts.minVolume > 0 ? Number(opts.minVolume) : 0
2602
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
2603
2642
  const py = `${PRELUDE}
2604
2643
  ${src}
2605
2644
  if not _shapes:
@@ -2615,10 +2654,19 @@ else:
2615
2654
  for _s in _shapes:
2616
2655
  _solids.extend(list(_s.Solids) or [_s])
2617
2656
  _minv = ${minVolume}
2657
+ _UNIFY = ${unify ? 'True' : 'False'}
2618
2658
  _kept = [x for x in _solids if x.Volume >= _minv] if _minv > 0 else _solids
2619
2659
  if not _kept:
2620
2660
  raise RuntimeError("no solids left after minVolume=%.3f (smallest %.3f)" % (_minv, min((x.Volume for x in _solids), default=0.0)))
2621
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
2622
2670
  if _fmt in ("step", "stp"):
2623
2671
  # Part.export([shape]) writes a 1.6 KB STEP that reads back as a NULL shape;
2624
2672
  # Shape.exportStep / compound exportStep is the API that produces a valid file.
@@ -2659,7 +2707,13 @@ else:
2659
2707
  __out = {"ok": True, "path": _target, "format": _fmt, "bytes": os.path.getsize(_target),
2660
2708
  "solids": len(_shapes), "volume": round(sum(float(x.Volume) for x in _shapes), 3),
2661
2709
  "sourceSolids": len(_solids), "sourceVolume": round(sum(float(x.Volume) for x in _solids), 3),
2662
- "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"]}
2663
2717
  if _stl:
2664
2718
  __out["stl"] = {"path": _stl, "bytes": os.path.getsize(_stl)}
2665
2719
  `
@@ -2678,6 +2732,7 @@ else:
2678
2732
  model: { type: 'string', description: 'Export a saved model document by name (feature or script model) instead of a file or a script.' },
2679
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.' },
2680
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.' },
2681
2736
  },
2682
2737
  required: ['target'],
2683
2738
  additionalProperties: false,
@@ -2686,7 +2741,7 @@ else:
2686
2741
  schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, bytes: { type: 'number' } } },
2687
2742
  render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
2688
2743
  },
2689
- execute: async ({ target, source, code, model, minVolume, alsoStl }) => {
2744
+ execute: async ({ target, source, code, model, minVolume, alsoStl, unify }) => {
2690
2745
  if (!target || extOf(target) === '') return { ok: false, error: 'target must be an absolute path with an extension' }
2691
2746
  if (typeof model === 'string' && model) {
2692
2747
  const dirs = bridge.modelsCandidates()
@@ -2698,7 +2753,7 @@ else:
2698
2753
  }
2699
2754
  const src = shapesFrom({ source, code })
2700
2755
  if (!src) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
2701
- const out = await writeShapeFile(target, src, { minVolume, alsoStl })
2756
+ const out = await writeShapeFile(target, src, { minVolume, alsoStl, unify })
2702
2757
  // Keep the two numbers apart on purpose: `volume` is what was written,
2703
2758
  // `sourceVolume` is what the input held. Mixing them is how a batch export
2704
2759
  // gets mistaken for the part it produced.
@@ -3853,10 +3908,12 @@ else:
3853
3908
  parameters: {
3854
3909
  type: 'object',
3855
3910
  properties: {
3856
- action: { type: 'string', enum: ['list', 'relink'], description: 'Default: list.' },
3911
+ action: { type: 'string', enum: ['list', 'relink', 'rebuild'], description: 'Default: list.' },
3857
3912
  assembly: { type: 'string', description: 'Assembly id (asm-1) or unique title. Omitted: every assembly for `list`, newest for `relink`.' },
3858
3913
  part: { type: 'string', description: 'Part name to repoint (relink).' },
3859
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.' },
3860
3917
  },
3861
3918
  additionalProperties: false,
3862
3919
  },
@@ -3864,7 +3921,7 @@ else:
3864
3921
  schema: { type: 'object', properties: { ok: { type: 'boolean' }, models: { type: 'array' }, missing: { type: 'number' } } },
3865
3922
  render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
3866
3923
  },
3867
- execute: async ({ action, assembly, part, path }) => {
3924
+ execute: async ({ action, assembly, part, path, parts, instances }) => {
3868
3925
  const mode = action ?? 'list'
3869
3926
  if (mode === 'list') {
3870
3927
  if (!assembly) await bridge.hydrateAssemblies()
@@ -3881,11 +3938,36 @@ else:
3881
3938
  tracked: Boolean(r.spec),
3882
3939
  files,
3883
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 就能用。' }),
3884
3944
  }
3885
3945
  })
3886
3946
  const missing = models.reduce((n, m) => n + m.missingParts.length, 0)
3887
3947
  return { ok: true, models, missing }
3888
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
+ }
3889
3971
  return relinkPart({ assembly, part, path })
3890
3972
  },
3891
3973
  })
@@ -4507,9 +4589,31 @@ else:
4507
4589
  }
4508
4590
  }
4509
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
+ `
4510
4614
  const code = isFeatures
4511
4615
  ? featuresScript(featureOps(doc), null, { cache, resume, sketches: doc.sketches })
4512
- : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
4616
+ : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n${unifyTail}`
4513
4617
  const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), sketches: doc.sketches ?? {}, tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
4514
4618
  doc.run = (doc.run ?? 0) + 1
4515
4619
  doc.updatedAt = new Date().toISOString()
@@ -4528,6 +4632,7 @@ else:
4528
4632
  doc.stats = {
4529
4633
  volume: out.volume ?? null,
4530
4634
  triangles: row?.triangles ?? null,
4635
+ faces: Number.isFinite(out.faces) ? out.faces : null,
4531
4636
  bounds: out.bounds ?? null,
4532
4637
  sceneId,
4533
4638
  at: doc.updatedAt,
@@ -4563,6 +4668,7 @@ else:
4563
4668
  params: doc.params,
4564
4669
  volume: doc.stats.volume,
4565
4670
  triangles: doc.stats.triangles,
4671
+ faces: doc.stats.faces ?? null,
4566
4672
  sceneId: doc.stats.sceneId,
4567
4673
  published: Boolean(doc.stats.sceneId),
4568
4674
  updatedAt: doc.updatedAt,
@@ -4577,7 +4683,8 @@ else:
4577
4683
  properties: {
4578
4684
  action: { type: 'string', enum: ['list', 'show', 'create', 'update', 'revert', 'delete', 'rename', 'duplicate'], description: 'list / show / create / update / revert / delete / rename / duplicate' },
4579
4685
  name: { type: 'string', description: 'Model name (中英文/数字/下划线/连字符).' },
4580
- 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.' },
4581
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).' },
4582
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).' },
4583
4690
  params: { type: 'object', description: 'Parameter dict. On update these are merged into the existing params (set a key to null to delete it).' },
@@ -5015,7 +5122,15 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5015
5122
  for (const n of names) {
5016
5123
  try {
5017
5124
  const doc = await readModel(n, dir)
5018
- 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 })
5125
+ const row = bridge.history.find((h) => h.docKey === `model:${doc.name}` || h.title === doc.name)
5126
+ models.push({
5127
+ name: doc.name, kind: doc.kind, features: doc.features.length, params: doc.params, runs: doc.run ?? 0,
5128
+ updatedAt: doc.updatedAt ?? '',
5129
+ // A features document records volume/faces at publish time but not the
5130
+ // triangle count; the scene row that publish created does have it.
5131
+ volume: doc.stats?.volume ?? row?.volume ?? null,
5132
+ triangles: doc.stats?.triangles ?? row?.triangles ?? null,
5133
+ })
5019
5134
  } catch { /* a hand-edited file that no longer parses is skipped, not fatal */ }
5020
5135
  }
5021
5136
  models.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
@@ -5041,9 +5156,11 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5041
5156
  if (action === 'create') {
5042
5157
  const key = checkName(args.name)
5043
5158
  const wantFeatures = args.kind === 'features' || Array.isArray(args.features)
5044
- if (!wantFeatures && (typeof args.script !== 'string' || !args.script.trim())) {
5045
- throw new Error('create 需要 script(FreeCAD Python,读 P、写 scene),或用 kind="features" 建特征列表模型')
5159
+ const fromPath = typeof args.from === 'string' && args.from.trim() ? resolve(args.from) : ''
5160
+ if (!wantFeatures && !fromPath && (typeof args.script !== 'string' || !args.script.trim())) {
5161
+ throw new Error('create 需要 script(FreeCAD Python,读 P、写 scene)、from(导入 STEP/IGES/BREP),或用 kind="features" 建特征列表模型')
5046
5162
  }
5163
+ if (fromPath && !existsSync(fromPath)) throw new Error(`找不到要导入的文件:${fromPath}`)
5047
5164
  try {
5048
5165
  await readModel(key, dir)
5049
5166
  throw new Error(`模型已存在:${key}(要改的话用 action=update)`)
@@ -5076,14 +5193,20 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5076
5193
  await journalDocCreate(key, dir, result)
5077
5194
  return await withChanges(doc, by, { ...result, kind: 'features', features: publicFeatures(doc) }, dir)
5078
5195
  }
5196
+ // `from` turns a file into a document instead of a one-shot scene: the
5197
+ // shape is re-read on every rebuild, so params/notes/undo still apply and
5198
+ // a later feature rebuild can replace the import step.
5079
5199
  const doc = {
5080
5200
  name: key,
5081
5201
  kind: 'script',
5082
- script: args.script,
5083
- params: args.params && typeof args.params === 'object' ? args.params : {},
5202
+ script: fromPath
5203
+ ? ['import Part', '_shape = Part.Shape()', '_shape.read(P["source"])', 'scene = _shape'].join('\n')
5204
+ : args.script,
5205
+ params: { ...(fromPath ? { source: fromPath } : {}), ...(args.params && typeof args.params === 'object' ? args.params : {}) },
5084
5206
  run: 0,
5085
5207
  createdAt: new Date().toISOString(),
5086
5208
  history: [],
5209
+ ...(fromPath ? { imported: fromPath } : {}),
5087
5210
  }
5088
5211
  const result = await rebuild(doc, dir, { note: args.note ?? 'create' })
5089
5212
  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.0",
3
+ "version": "0.30.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {