dsh-cad-studio 0.27.2 → 0.29.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 (4) hide show
  1. package/README.md +2 -1
  2. package/client.js +32 -0
  3. package/index.js +215 -13
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -4,7 +4,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
4
4
 
5
5
  ![CAD 工作室面板](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/preview.png)
6
6
 
7
- - Host 侧(`index.js`):18 个工具 + `/cad-studio/*` HTTP 路由 + `freecadcmd` 子进程桥
7
+ - Host 侧(`index.js`):19 个工具 + `/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
 
@@ -26,6 +26,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
26
26
  | 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
27
27
  | 拔模挤出 | `{kind:"extrude", sketch:"S1", h:20, draft:3}` 按 3° 拔模:截面按 `h*tan(3°)` 偏移后 loft 成体,正角度内收、负角度外放 |
28
28
  | 展开图 | `cad_studio_unfold {source, target:"…/net.dxf"}` 把板类零件按共享边摊平成下料图(面片等距铺开,面积与模型一致;孔各自成环;圆柱/圆角等曲面报 `curvedSkipped` 而不是瞎编),可写 DXF 或 SVG |
29
+ | 改动记录 | `cad_studio_changes {model}` 看谁改了什么(会话 / 面板 / 外部);每次写都会涨 `rev` 并留一行,面板「信息」里也能看到。别的工具的结果里会顺带一句「自你上次之后,面板改了 N 处」。0.29.0 起「下一次动手」不再等于「先动手再知情」:人改过之后,会话的**写操作会被拒绝一次**(`needsReview`,不给文件动一下),看清了带 `ifRev=<rev>` 重发才算覆盖(或 `force:true` 硬盖并回报 `overwrote`)|
29
30
  | 打印网格 | `cad_studio_mesh {source, target:"…/x.stl"}` 三角化 + 去重合并点/面、修形变、统一法向,可选 `fillHoles`、`targetSize`(减面);回报修复前后的 facets/points,避免「导出成功但网格是碎的」 |
30
31
  | 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
31
32
  | 面板改草图 | 特征抽屉里点「草图 N」展开:数值约束是可编辑输入框(`distance*`/`radius`/`angle` 按度),改完立刻重解并重建;解不出来就回滚并报错 |
package/client.js CHANGED
@@ -1850,6 +1850,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1850
1850
  const [deps, setDeps] = useState(null)
1851
1851
  const [relinkFor, setRelinkFor] = useState({})
1852
1852
  const [relinkNote, setRelinkNote] = useState('')
1853
+ const [ledger, setLedger] = useState(null)
1853
1854
  // Which document sketch is expanded in the 草图 section.
1854
1855
  const [openSketch, setOpenSketch] = useState('')
1855
1856
  const featTimer = useRef(null)
@@ -1908,11 +1909,22 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1908
1909
  rememberView(tabKey, payloadRef.current)
1909
1910
  showScene(scene, { keepView: true, tabKey })
1910
1911
  }
1912
+ // Change ledger: what the agent (and the person themselves) changed, so
1913
+ // neither side edits blind. Fetched with the deps when the drawer opens.
1914
+ const modelName = payload && String(payload.docKey || '').startsWith('model:') ? String(payload.docKey).slice(6) : ''
1915
+ const loadChanges = async () => {
1916
+ if (!modelName) return setLedger(null)
1917
+ try {
1918
+ const res = await fetch(`${ROUTE}/changes?model=${encodeURIComponent(modelName)}`, { headers: { accept: 'application/json' } })
1919
+ if (res.ok) setLedger(await res.json())
1920
+ } catch {}
1921
+ }
1911
1922
  const loadDeps = async () => {
1912
1923
  try {
1913
1924
  const res = await fetch(`${ROUTE}/deps`, { headers: { accept: 'application/json' } })
1914
1925
  if (res.ok) setDeps(await res.json())
1915
1926
  } catch {}
1927
+ loadChanges()
1916
1928
  }
1917
1929
  const doRelink = async (assembly, part) => {
1918
1930
  const path = (relinkFor[part] ?? '').trim()
@@ -2966,6 +2978,26 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2966
2978
  ] : payload && payload.docKey && String(payload.docKey).startsWith('model:')
2967
2979
  ? [h('div', { key: 'deps-na', style: { ...styles.treeHint, whiteSpace: 'normal', paddingTop: 6 } }, '这个模型是特征建的,没有外部文件依赖')]
2968
2980
  : []),
2981
+ ...(ledger && Array.isArray(ledger.rows) && ledger.rows.length ? [
2982
+ h('div', { key: 'ledger-head', style: { ...styles.infoRow, marginTop: 6 } }, [
2983
+ h('span', { key: 'k', style: styles.infoKey }, '改动记录'),
2984
+ h('span', { key: 'v', style: { ...styles.infoVal, opacity: 0.75 } }, `第 ${ledger.rev} 版`),
2985
+ ]),
2986
+ ...ledger.rows.slice().reverse().map((row) => h('div', {
2987
+ key: `chg-${row.rev}`,
2988
+ style: { display: 'flex', flexDirection: 'column', gap: 1, padding: '4px 0', borderTop: '1px solid rgba(127,127,127,.16)' },
2989
+ 'data-cad-change': row.rev,
2990
+ 'data-cad-change-by': row.by,
2991
+ title: `${row.at} · ${row.kind}`,
2992
+ }, [
2993
+ h('div', { key: 'head', style: { display: 'flex', gap: 6, alignItems: 'baseline', fontSize: 10.5 } }, [
2994
+ h('span', { key: 'who', style: { ...styles.infoKey, flex: '0 0 auto', color: row.by === '会话' ? '#4d6bfe' : undefined } }, row.by),
2995
+ h('span', { key: 'gap', style: { flex: 1 } }, ''),
2996
+ h('span', { key: 'at', style: { ...styles.infoVal, flex: '0 0 auto', opacity: 0.5 } }, String(row.at || '').slice(11, 16)),
2997
+ ]),
2998
+ h('div', { key: 'what', style: { fontSize: 10.5, opacity: 0.85, whiteSpace: 'normal', wordBreak: 'break-word' } }, row.detail),
2999
+ ])),
3000
+ ] : []),
2969
3001
  ]
2970
3002
  : null
2971
3003
 
package/index.js CHANGED
@@ -3620,6 +3620,40 @@ else:
3620
3620
  },
3621
3621
  })
3622
3622
 
3623
+ tool({
3624
+ name: 'cad_studio_changes',
3625
+ description: 'The change ledger of one model: who changed what, when (会话 / 面板 / 外部). Every write — through a tool or through the panel — bumps a revision and appends one readable row. Tool results already carry a digest of what you missed ("自你上次之后,面板改了 N 处"); call this when you want the whole history, e.g. before rewriting a feature a human may have just edited.',
3626
+ parameters: {
3627
+ type: 'object',
3628
+ properties: {
3629
+ model: { type: 'string', description: '模型名' },
3630
+ limit: { type: 'number', description: '最近几条(默认 20,最多 60)' },
3631
+ },
3632
+ required: ['model'],
3633
+ additionalProperties: false,
3634
+ },
3635
+ output: {
3636
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, model: { type: 'string' }, rev: { type: 'number' }, total: { type: 'number' } } },
3637
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
3638
+ },
3639
+ execute: async (args, exec) => {
3640
+ try {
3641
+ const dir = modelsDirFor(exec)
3642
+ const doc = await readModel(args.model, dir)
3643
+ const limit = Number.isFinite(args.limit) ? Math.max(1, Math.min(60, Math.round(args.limit))) : 20
3644
+ return {
3645
+ ok: true,
3646
+ model: doc.name,
3647
+ rev: Number(doc.rev) || 0,
3648
+ total: doc.changes.length,
3649
+ rows: changeRows(doc.changes.slice(-limit)),
3650
+ }
3651
+ } catch (error) {
3652
+ return { ok: false, error: String(error?.message ?? error) }
3653
+ }
3654
+ },
3655
+ })
3656
+
3623
3657
  tool({
3624
3658
  name: 'cad_studio_assembly',
3625
3659
  description: 'Assemble parts by file reference (STEP/IGES/BREP), publish the assembly to the panel, and optionally export it as one STEP. Each part file is read once; instances share the same geometry.',
@@ -4113,6 +4147,12 @@ else:
4113
4147
  doc.tip = typeof doc.tip === 'string' && doc.tip ? doc.tip : null
4114
4148
  doc.undo = Array.isArray(doc.undo) ? doc.undo : []
4115
4149
  doc.redo = Array.isArray(doc.redo) ? doc.redo : []
4150
+ // Change ledger: every write bumps `rev` and appends one readable row, and
4151
+ // `seen` records how far each side (tool vs panel) has caught up. A human's
4152
+ // edit is therefore visible to the agent on its very next tool result.
4153
+ doc.rev = Number.isFinite(doc.rev) ? doc.rev : 0
4154
+ doc.changes = Array.isArray(doc.changes) ? doc.changes : []
4155
+ doc.seen = doc.seen && typeof doc.seen === 'object' && !Array.isArray(doc.seen) ? doc.seen : {}
4116
4156
  for (const f of doc.features) {
4117
4157
  if (!f || typeof f !== 'object') continue
4118
4158
  if (typeof f.suppressed === 'boolean') f.enabled = f.suppressed !== true
@@ -4136,6 +4176,95 @@ else:
4136
4176
  return doc
4137
4177
  }
4138
4178
 
4179
+ /* ------------------------------------------------------------------ */
4180
+ /* Change ledger — who changed what, so the other side finds out. */
4181
+ /* ------------------------------------------------------------------ */
4182
+
4183
+ /** Spoken in the reader's language: a person reads 面板, the agent 会话. */
4184
+ const CHANGE_BY = { agent: '会话', panel: '面板', external: '外部' }
4185
+
4186
+ /** Append one row and bump the revision; callers write the file after this. */
4187
+ const recordChange = (doc, { by, kind, detail }) => {
4188
+ const who = CHANGE_BY[by] ? by : 'agent'
4189
+ // A freshly built document object never went through readModel, so the
4190
+ // ledger fields may not exist yet.
4191
+ if (!Array.isArray(doc.changes)) doc.changes = []
4192
+ if (!doc.seen || typeof doc.seen !== 'object') doc.seen = {}
4193
+ doc.rev = (Number(doc.rev) || 0) + 1
4194
+ doc.changes.push({
4195
+ rev: doc.rev,
4196
+ at: new Date().toISOString(),
4197
+ by: who,
4198
+ kind: String(kind),
4199
+ detail: String(detail || kind).slice(0, 240),
4200
+ })
4201
+ if (doc.changes.length > 60) doc.changes.splice(0, doc.changes.length - 60)
4202
+ return doc.changes[doc.changes.length - 1]
4203
+ }
4204
+
4205
+ /** Rows the given side has not caught up with — never its own. */
4206
+ const pendingChanges = (doc, by) => {
4207
+ const seen = Number((doc.seen || {})[by] ?? 0)
4208
+ return (doc.changes || []).filter((c) => c.rev > seen && c.by !== by)
4209
+ }
4210
+
4211
+ /**
4212
+ * Read-before-write. A digest attached to the result arrives too late when the
4213
+ * very next call is a write — the damage is done before the agent reads it. So
4214
+ * a write from one side is refused once when the other side changed the model
4215
+ * since that side last looked. The agent re-issues with ifRev (the revision it
4216
+ * just saw) or force, which is the explicit "yes, overwrite that".
4217
+ */
4218
+ const foreignWriteGuard = (doc, by, args) => {
4219
+ const pending = pendingChanges(doc, by)
4220
+ if (!pending.length) return null
4221
+ if (args && args.force === true) return { ok: true, rows: changeRows(pending) }
4222
+ const ifRev = Number(args && args.ifRev)
4223
+ if (Number.isFinite(ifRev) && ifRev === Number(doc.rev)) return { ok: true, rows: changeRows(pending) }
4224
+ return { ok: false, rows: changeRows(pending) }
4225
+ }
4226
+
4227
+ /** The refusal a guarded write returns: no file touched, rows in hand. */
4228
+ const guardRefusal = (doc, guard, by) => {
4229
+ const latest = guard.rows[guard.rows.length - 1]
4230
+ return {
4231
+ ok: false,
4232
+ needsReview: true,
4233
+ model: doc.name,
4234
+ conflict: { rev: Number(doc.rev) || 0, rows: guard.rows },
4235
+ hint: `${latest.by}刚在这个模型上改了 ${guard.rows.length} 处(最新一条:${latest.detail}),这次改动没有执行。看清楚了再重发:带 ifRev=${Number(doc.rev) || 0} 表示在最新版上改,或 force=true 表示认可覆盖。`,
4236
+ }
4237
+ }
4238
+
4239
+ /** One line a human can read, so the digest means something without a lookup. */
4240
+ const changeRows = (rows) => rows.map((c) => ({
4241
+ rev: c.rev,
4242
+ at: c.at,
4243
+ by: CHANGE_BY[c.by] ?? c.by,
4244
+ kind: c.kind,
4245
+ detail: c.detail,
4246
+ }))
4247
+
4248
+ /**
4249
+ * Attach "what you missed" to a tool result and mark the caller caught up.
4250
+ * This rides on the result the agent was going to read anyway, so a human
4251
+ * edit reaches it before its next write — no extra round trip and no
4252
+ * message injection into the session.
4253
+ */
4254
+ const withChanges = async (doc, by, out, dir) => {
4255
+ const pending = pendingChanges(doc, by)
4256
+ const rows = changeRows(pending)
4257
+ const digest = { rev: Number(doc.rev) || 0, pending: rows.length, rows }
4258
+ if (rows.length) {
4259
+ const first = rows[0]
4260
+ digest.hint = `自你上次看到这个模型后,${first.by}改了 ${rows.length} 处:${first.detail}${rows.length > 1 ? ' 等' : ''}。先看清楚再动,别把人的改动覆盖掉。`
4261
+ doc.seen = doc.seen && typeof doc.seen === 'object' ? doc.seen : {}
4262
+ doc.seen[by] = doc.rev
4263
+ try { await writeModel(doc, dir) } catch {}
4264
+ }
4265
+ return { ...out, changes: digest }
4266
+ }
4267
+
4139
4268
  /** Public view of a feature list: what the panel renders as editable rows. */
4140
4269
  const publicFeatures = (doc) => doc.features.map((f) => ({
4141
4270
  id: f.id,
@@ -4456,6 +4585,8 @@ else:
4456
4585
  to: { type: 'string', description: 'For action=rename / duplicate: the new model name.' },
4457
4586
  sketches: { type: 'object', description: 'For kind="features": named sketches stored in the document, e.g. {S1:{geometry:[{id:"g1",type:"line",p1:[0,0,0],p2:[80,0,0]}, …],constraints:[…]}}. A feature extrudes/revolves/lofts one with {kind:"extrude",sketch:"S1"}.' },
4458
4587
  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.' },
4588
+ ifRev: { type: 'number', description: 'Write guard. If someone edited this model in the panel since you last saw it, the write is refused once and tells you the revision; re-issue with ifRev=<that revision> to say "I saw those edits, write on top of them".' },
4589
+ force: { type: 'boolean', description: 'Write guard escape hatch: true means "I accept overwriting the panel edits I was just told about". Prefer ifRev — force skips the review.' },
4459
4590
  },
4460
4591
  required: ['action'],
4461
4592
  additionalProperties: false,
@@ -4599,6 +4730,8 @@ else:
4599
4730
 
4600
4731
  const runFeatureAction = async (args, dir) => {
4601
4732
  bridge.noteModelsDir(dir)
4733
+ // Same contract as runDocAction: the entry point states who is writing.
4734
+ const by = args.by === 'panel' ? 'panel' : 'agent'
4602
4735
  const action = String(args.action ?? 'list')
4603
4736
  const doc = await readModel(args.model, dir)
4604
4737
  if (doc.kind !== 'features') {
@@ -4607,6 +4740,10 @@ else:
4607
4740
  if (action === 'list') {
4608
4741
  return { ok: true, model: doc.name, kind: doc.kind, features: publicFeatures(doc), sketches: doc.sketches ?? {}, graph: graphView(doc, { errors: [], executed: null }), stats: doc.stats ?? null }
4609
4742
  }
4743
+ // Every other action writes — including undo/redo, which can undo a human's
4744
+ // edit as easily as the agent's own. Same read-before-write rule as above.
4745
+ const guard = by === 'agent' ? foreignWriteGuard(doc, by, args) : null
4746
+ if (guard && guard.ok === false) return guardRefusal(doc, guard, by)
4610
4747
  if (action === 'sketch') {
4611
4748
  // Sketches are document data (geometry + constraints), so editing one is
4612
4749
  // a document edit: same rollback rule as a feature edit, and the sketch
@@ -4629,8 +4766,9 @@ else:
4629
4766
  doc.history = Array.isArray(doc.history) ? doc.history : []
4630
4767
  doc.history.push({ at: new Date().toISOString(), note: `sketch ${name}`, params: null, run: result.ok !== false })
4631
4768
  doc.history = doc.history.slice(-20)
4769
+ recordChange(doc, { by, kind: 'feature.sketch', detail: `${raw.remove ? '删除' : '改'}草图 ${name}` })
4632
4770
  await writeModel(doc, dir)
4633
- return {
4771
+ return await withChanges(doc, by, {
4634
4772
  ok: true,
4635
4773
  evaluated: result.ok !== false && (result.errors ?? []).length === 0,
4636
4774
  model: doc.name,
@@ -4651,7 +4789,7 @@ else:
4651
4789
  cached: result.cached ?? 0,
4652
4790
  computed: result.computed ?? null,
4653
4791
  revalidated: result.revalidated === true,
4654
- }
4792
+ }, dir)
4655
4793
  }
4656
4794
 
4657
4795
  const snapshot = () => JSON.parse(JSON.stringify({ features: doc.features, tip: doc.tip ?? null }))
@@ -4723,14 +4861,16 @@ else:
4723
4861
  // lives in evaluated/errors/graph. A reorder can legitimately leave the
4724
4862
  // tree unevaluable (a fillet moved above its body) and that must stay
4725
4863
  // visible rather than being rejected — you fix it by reading the graph.
4726
- return {
4864
+ recordChange(doc, { by, kind: `feature.${action}`, detail: `${label}(求值失败)` })
4865
+ await writeModel(doc, dir)
4866
+ return await withChanges(doc, by, {
4727
4867
  ...result,
4728
4868
  ok: true,
4729
4869
  saved: true,
4730
4870
  evaluated: false,
4731
4871
  features: publicFeatures(doc),
4732
4872
  hint: '这条改动已存进文档,但求值失败——看 graph 里哪条是 failed,改好或撤销。',
4733
- }
4873
+ }, dir)
4734
4874
  }
4735
4875
  if (!['undo', 'redo'].includes(action)) {
4736
4876
  doc.undo.push({ at: new Date().toISOString(), action, target: wanted || feature.kind || '', before: undoSnap, after: snapshot() })
@@ -4746,8 +4886,9 @@ else:
4746
4886
  prev: { script: doc.script, params: JSON.parse(JSON.stringify(doc.params)), features: before },
4747
4887
  })
4748
4888
  doc.history = doc.history.slice(-20)
4889
+ recordChange(doc, { by, kind: `feature.${action}`, detail: label })
4749
4890
  await writeModel(doc, dir)
4750
- return {
4891
+ const out = await withChanges(doc, by, {
4751
4892
  ok: true,
4752
4893
  evaluated: result.ok !== false && (result.errors ?? []).length === 0,
4753
4894
  model: doc.name,
@@ -4767,7 +4908,9 @@ else:
4767
4908
  cached: result.cached ?? doc.stats?.cached ?? 0,
4768
4909
  computed: result.computed ?? null,
4769
4910
  revalidated: result.revalidated === true,
4770
- }
4911
+ }, dir)
4912
+ if (guard && guard.rows.length) out.overwrote = guard.rows
4913
+ return out
4771
4914
  }
4772
4915
 
4773
4916
  tool({
@@ -4787,6 +4930,8 @@ else:
4787
4930
  feature: { type: 'object', description: 'add: the feature to append. update/toggle: {id, ...fields to change}. remove/move: {id}.' },
4788
4931
  id: { type: 'string', description: 'Feature id (f1, f2 …); alternative to feature.id.' },
4789
4932
  to: { type: 'integer', description: 'move: target index (0-based). Default: to the end.' },
4933
+ ifRev: { type: 'number', description: 'Write guard: if the panel edited this model since you last saw it, the write is refused once with the revision; re-issue with ifRev=<that revision> to write on top of those edits.' },
4934
+ force: { type: 'boolean', description: 'Write guard escape hatch (accepts overwriting the panel edits you were just told about). Prefer ifRev.' },
4790
4935
  },
4791
4936
  required: ['model', 'action'],
4792
4937
  additionalProperties: false,
@@ -4842,8 +4987,26 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4842
4987
  return { ok: true, model: doc.name, path: target, bytes, valid: bytes > 200, volume: out.volume ?? null }
4843
4988
  }
4844
4989
 
4990
+ /** One readable sentence per doc write, e.g. "改参数 高 从 20 到 30". */
4991
+ const describeDocUpdate = (args, doc) => {
4992
+ const parts = []
4993
+ if (args.params && typeof args.params === 'object') {
4994
+ const keys = Object.keys(args.params)
4995
+ if (keys.length) parts.push(`改参数 ${keys.slice(0, 4).join('、')}${keys.length > 4 ? ` 等 ${keys.length} 个` : ''}`)
4996
+ }
4997
+ if (Array.isArray(args.features)) parts.push(`整体重写特征列表(${args.features.length} 条)`)
4998
+ if (args.sketches) parts.push(`改草图 ${Object.keys(args.sketches).slice(0, 3).join('、')}`)
4999
+ if (args.vars) parts.push('改变量')
5000
+ if (typeof args.script === 'string' && args.script.trim()) parts.push('改脚本')
5001
+ if (!parts.length) parts.push('更新模型')
5002
+ return parts.join(';')
5003
+ }
5004
+
4845
5005
  async function runDocAction(args, dir) {
4846
5006
  bridge.noteModelsDir(dir)
5007
+ // Who is writing. The panel's HTTP routes say so; a tool call is the agent.
5008
+ // Never inferred from the payload shape — the same function serves both.
5009
+ const by = args.by === 'panel' ? 'panel' : 'agent'
4847
5010
  const action = String(args.action ?? '')
4848
5011
  if (action === 'list') {
4849
5012
  await mkdir(dir, { recursive: true })
@@ -4861,7 +5024,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4861
5024
 
4862
5025
  if (action === 'show') {
4863
5026
  const doc = await readModel(args.name, dir)
4864
- return {
5027
+ return await withChanges(doc, by, {
4865
5028
  ok: true,
4866
5029
  name: doc.name,
4867
5030
  kind: doc.kind,
@@ -4872,7 +5035,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4872
5035
  updatedAt: doc.updatedAt ?? '',
4873
5036
  stats: doc.stats ?? null,
4874
5037
  history: doc.history.slice(-10).map((h) => ({ at: h.at, note: h.note ?? '', params: h.params })),
4875
- }
5038
+ }, dir)
4876
5039
  }
4877
5040
 
4878
5041
  if (action === 'create') {
@@ -4908,9 +5071,10 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4908
5071
  const result = await rebuild(doc, dir, { note: args.note ?? 'create' })
4909
5072
  if (result.ok === false) return result
4910
5073
  doc.history.push({ at: doc.updatedAt, note: args.note ?? 'create', params: JSON.parse(JSON.stringify(doc.params)), features: JSON.parse(JSON.stringify(doc.features)), run: doc.run })
5074
+ recordChange(doc, { by, kind: 'doc.create', detail: `新建特征模型,${doc.features.length} 个特征` })
4911
5075
  await writeModel(doc, dir)
4912
5076
  await journalDocCreate(key, dir, result)
4913
- return { ...result, kind: 'features', features: publicFeatures(doc) }
5077
+ return await withChanges(doc, by, { ...result, kind: 'features', features: publicFeatures(doc) }, dir)
4914
5078
  }
4915
5079
  const doc = {
4916
5080
  name: key,
@@ -4924,6 +5088,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4924
5088
  const result = await rebuild(doc, dir, { note: args.note ?? 'create' })
4925
5089
  if (result.ok === false) return result
4926
5090
  doc.history.push({ at: doc.updatedAt, note: args.note ?? 'create', params: JSON.parse(JSON.stringify(doc.params)), run: doc.run })
5091
+ recordChange(doc, { by, kind: 'doc.create', detail: `新建${doc.kind === 'features' ? '特征模型' : '脚本模型'},${doc.features?.length ?? 0} 个特征` })
4927
5092
  await writeModel(doc, dir)
4928
5093
  await journalDocCreate(key, dir, result)
4929
5094
  return result
@@ -4931,6 +5096,8 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4931
5096
 
4932
5097
  if (action === 'update') {
4933
5098
  const doc = await readModel(args.name, dir)
5099
+ const guard = by === 'agent' ? foreignWriteGuard(doc, by, args) : null
5100
+ if (guard && guard.ok === false) return guardRefusal(doc, guard, by)
4934
5101
  if (args.vars !== undefined) doc.vars = normalizeVars(args.vars, doc.vars)
4935
5102
  if (args.sketches !== undefined) doc.sketches = normalizeSketches(args.sketches, doc.sketches)
4936
5103
  const before = {
@@ -4962,12 +5129,17 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4962
5129
  }
4963
5130
  doc.history.push({ at: doc.updatedAt, note: args.note ?? 'update', params: JSON.parse(JSON.stringify(doc.params)), features: JSON.parse(JSON.stringify(doc.features)), run: doc.run, prev: before })
4964
5131
  doc.history = doc.history.slice(-20)
5132
+ recordChange(doc, { by, kind: 'doc.update', detail: describeDocUpdate(args, doc) })
4965
5133
  await writeModel(doc, dir)
4966
- return { ...result, kind: doc.kind, ...(doc.kind === 'features' ? { features: publicFeatures(doc) } : {}) }
5134
+ const out = await withChanges(doc, by, { ...result, kind: doc.kind, ...(doc.kind === 'features' ? { features: publicFeatures(doc) } : {}) }, dir)
5135
+ if (guard && guard.rows.length) out.overwrote = guard.rows
5136
+ return out
4967
5137
  }
4968
5138
 
4969
5139
  if (action === 'revert') {
4970
5140
  const doc = await readModel(args.name, dir)
5141
+ const guard = by === 'agent' ? foreignWriteGuard(doc, by, args) : null
5142
+ if (guard && guard.ok === false) return guardRefusal(doc, guard, by)
4971
5143
  const last = doc.history.pop()
4972
5144
  if (!last) throw new Error(`${doc.name} 没有可回退的历史`)
4973
5145
  if (last.prev) {
@@ -4978,8 +5150,9 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4978
5150
  doc.params = last.params
4979
5151
  }
4980
5152
  const result = await rebuild(doc, dir, { note: `revert to ${last.at}` })
5153
+ recordChange(doc, { by, kind: 'doc.revert', detail: `回退到 ${last.note ?? '上一版'}(${String(last.at).slice(11, 19)})` })
4981
5154
  await writeModel(doc, dir)
4982
- return result
5155
+ return await withChanges(doc, by, result, dir)
4983
5156
  }
4984
5157
 
4985
5158
  if (action === 'delete') {
@@ -5121,6 +5294,35 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5121
5294
  return send(200, JSON.stringify({ runtime, setup, diag, config: { autoOpen: resolved.autoOpen }, latest: null, lastSession: '', running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
5122
5295
  }
5123
5296
  }
5297
+ if (url.pathname === `${ROUTE_PREFIX}/changes`) {
5298
+ // The panel's own copy of the ledger, so a person can see what the agent
5299
+ // did in their absence — the mirror image of the digest the agent gets.
5300
+ try {
5301
+ const u = new URL(url, 'http://127.0.0.1')
5302
+ const model = String(u.searchParams.get('model') || '').trim()
5303
+ if (!model) return send(400, JSON.stringify({ ok: false, error: 'model required' }))
5304
+ if (!bridge.modelsSeen.length) {
5305
+ try {
5306
+ const pointer = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
5307
+ if (typeof pointer.modelsDir === 'string' && pointer.modelsDir) bridge.noteModelsDir(pointer.modelsDir)
5308
+ if (Array.isArray(pointer.modelsDirs)) pointer.modelsDirs.forEach((d) => bridge.noteModelsDir(d))
5309
+ } catch {}
5310
+ }
5311
+ const candidates = resolved.modelsDir ? [resolved.modelsDir, ...bridge.modelsCandidates()] : bridge.modelsCandidates()
5312
+ const modelsDir = candidates.find((d) => existsSync(join(d, `${model}.json`))) || candidates[0]
5313
+ if (!modelsDir) return send(404, JSON.stringify({ ok: false, error: 'no models dir' }))
5314
+ const doc = await readModel(model, modelsDir)
5315
+ return send(200, JSON.stringify({
5316
+ ok: true,
5317
+ model: doc.name,
5318
+ rev: Number(doc.rev) || 0,
5319
+ rows: changeRows(doc.changes.slice(-20)),
5320
+ }))
5321
+ } catch (error) {
5322
+ return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
5323
+ }
5324
+ }
5325
+
5124
5326
  if (url.pathname === `${ROUTE_PREFIX}/scenes`) {
5125
5327
  // Model switcher feed: the persisted history is the truth, so a stale
5126
5328
  // route closure left by a hot reload still lists what is on disk.
@@ -5214,7 +5416,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5214
5416
  }
5215
5417
  const candidates = resolved.modelsDir ? [resolved.modelsDir, ...bridge.modelsCandidates()] : bridge.modelsCandidates()
5216
5418
  const modelsDir = candidates.find((d) => existsSync(join(d, `${body.model}.json`))) || candidates[0] || modelsDirFor(undefined)
5217
- const out = await runDocAction({ action: 'update', name: body.model, params: body.params ?? {} }, modelsDir)
5419
+ const out = await runDocAction({ action: 'update', name: body.model, params: body.params ?? {}, by: 'panel' }, modelsDir)
5218
5420
  const entry = out && out.sceneId ? bridge.history.find((h) => h.id === out.sceneId) : null
5219
5421
  return send(200, JSON.stringify(entry ? { ...out, at: entry.at } : out))
5220
5422
  } catch (error) {
@@ -5243,7 +5445,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
5243
5445
  // actually holds this model (several workspaces may each have one).
5244
5446
  const candidates = resolved.modelsDir ? [resolved.modelsDir, ...bridge.modelsCandidates()] : bridge.modelsCandidates()
5245
5447
  const modelsDir = candidates.find((d) => existsSync(join(d, `${body.model}.json`))) || candidates[0] || modelsDirFor(undefined)
5246
- const result = await runFeatureAction(body, modelsDir)
5448
+ const result = await runFeatureAction({ ...body, by: 'panel' }, modelsDir)
5247
5449
  // Tell the panel when the model was republished, so its poller can
5248
5450
  // recognise the in-place update it triggered itself.
5249
5451
  const entry = result && result.sceneId ? bridge.history.find((h) => h.id === result.sceneId) : null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.27.2",
3
+ "version": "0.29.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {