@qmingjun/dsh-eda-mcp 0.0.0-stage → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/AGENTS.md +63 -0
  2. package/CHANGELOG.md +792 -0
  3. package/CONTRIBUTING.md +154 -0
  4. package/LICENSE +55 -0
  5. package/README.md +290 -2
  6. package/README.zh.md +449 -0
  7. package/cordis.patch.yml +7 -0
  8. package/docs/design-rules.md +254 -0
  9. package/docs/dsh-version-sweep.md +73 -0
  10. package/docs/pitfalls.md +99 -0
  11. package/docs/project-status.md +100 -0
  12. package/docs/release.md +215 -0
  13. package/docs/schematic-workflow.md +297 -0
  14. package/docs/tools.md +184 -0
  15. package/jlc-extension/api-bridge.js +879 -0
  16. package/jlc-extension/extension.json +104 -0
  17. package/lib/bridge.mjs +4179 -0
  18. package/lib/client.js +1605 -0
  19. package/lib/extension-digest.json +6 -0
  20. package/lib/index.js +1261 -0
  21. package/package.json +144 -4
  22. package/src/bridge/design-intake.ts +133 -0
  23. package/src/bridge/design-rules.ts +228 -0
  24. package/src/bridge/eda-launch.ts +267 -0
  25. package/src/bridge/extension-package.ts +35 -0
  26. package/src/bridge/index.ts +3576 -0
  27. package/src/bridge/netlist-erc.ts +305 -0
  28. package/src/bridge/schematic-audit.ts +131 -0
  29. package/src/bridge/workflow-guide.ts +65 -0
  30. package/src/bridge-diagnostics.ts +185 -0
  31. package/src/client/EdaMcpSettingsCard.tsx +571 -0
  32. package/src/client/index.ts +40 -0
  33. package/src/client/locales.ts +83 -0
  34. package/src/client/settings-scope.ts +160 -0
  35. package/src/config-values.ts +60 -0
  36. package/src/guidance.ts +35 -0
  37. package/src/index.ts +365 -0
  38. package/src/loopback.ts +48 -0
  39. package/src/node-runtime.ts +120 -0
  40. package/src/routes.ts +377 -0
  41. package/src/skills-content.ts +309 -0
  42. package/src/skills.ts +91 -0
  43. package/test/config-values.test.ts +60 -0
  44. package/test/design-intake.test.ts +40 -0
  45. package/test/design-rules.test.ts +72 -0
  46. package/test/eda-launch.test.ts +114 -0
  47. package/test/extension-package.test.ts +27 -0
  48. package/test/extension-routes.test.ts +116 -0
  49. package/test/netlist-erc.test.ts +90 -0
  50. package/test/node-runtime.test.ts +65 -0
  51. package/test/schematic-audit.test.ts +71 -0
  52. package/test/seams.test.ts +164 -0
  53. package/test/skills.test.ts +68 -0
@@ -0,0 +1,3576 @@
1
+ // @ts-nocheck -- the bridge is authored as dependency-free JS and bundled by esbuild; runtime tests cover it.
2
+ import { createHash } from 'node:crypto'
3
+ import { execFileSync, spawn } from 'node:child_process'
4
+ import { existsSync, statSync } from 'node:fs'
5
+ import { readFile } from 'node:fs/promises'
6
+ import { mkdir, unlink, writeFile } from 'node:fs/promises'
7
+ import { tmpdir } from 'node:os'
8
+ import { basename, join } from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
11
+ import type { Socket } from 'node:net'
12
+ import { createInterface } from 'node:readline'
13
+ import { buildLaunchArgs, buildLaunchScript, decodeRegistryOutput, resolveExecutable, type LaunchProbe } from './eda-launch.ts'
14
+ import { buildIntake } from './design-intake.ts'
15
+ import { auditSchematicGeometry } from './schematic-audit.ts'
16
+ import { runNetlistErc } from './netlist-erc.ts'
17
+ import { compareDigest, extensionDownloadUrl, extensionZipName, sha256Of } from './extension-package.ts'
18
+ import {
19
+ ANNULUS_MIN_MM, BOARD_OUTLINE_WIDTH_MIL, MIN_TRACK_WIDTH_MIL, POUR_CLEARANCE_MIN_MIL,
20
+ POUR_CLEARANCE_RECOMMENDED_MIL, SILKSCREEN_HEIGHT_MIN_MM, SILKSCREEN_WIDTH_MIN_MM,
21
+ TRACK_WIDTH_MIL, VIA_HOLE_ABSOLUTE_MIN_MM, VIA_HOLE_MIN_MM, VIA_SIZES_MM,
22
+ assertNetName, checkNetName, checkTrackWidth, checkVia, classifyNet, milToMm, suggestTrackWidthMil,
23
+ } from './design-rules.ts'
24
+ import { WORKFLOW_GUIDE, WORKFLOW_SUMMARY } from './workflow-guide.ts'
25
+
26
+ const VERSION = '0.4.9'
27
+ const WS_PORT = Number(process.env.DSH_EDA_MCP_WS_PORT ?? 39009)
28
+ const WS_HOST = '127.0.0.1'
29
+ const ALLOW_RAW_API = (process.env.DSH_EDA_MCP_ALLOW_RAW_API ?? '1') !== '0'
30
+ // Automatic layout/routing is opt-in: placing parts and routing by hand is the
31
+ // default working style (visual PNG check beats letting the app rearrange a sheet).
32
+ const ALLOW_AUTO_LAYOUT = (process.env.DSH_EDA_ALLOW_AUTO_LAYOUT ?? '0') === '1'
33
+ const TOOL_TIMEOUT_MS = Number(process.env.DSH_EDA_MCP_TOOL_TIMEOUT_MS ?? 60000)
34
+
35
+ const MCP_UNITS_PER_INCH = 100
36
+
37
+ const PAPER_SIZES = {
38
+ A4: {
39
+ name: 'A4',
40
+ widthInch: 11.7,
41
+ heightInch: 8.25,
42
+ frame: { left: 0, bottom: 0, right: 1170, top: 825 },
43
+ titleBlock: { left: 460, bottom: 10, right: 1160, top: 190 },
44
+ },
45
+ }
46
+
47
+ const DEFAULT_PAPER = 'A4'
48
+
49
+ function paperOf(name) {
50
+ const key = String(name ?? DEFAULT_PAPER).toUpperCase()
51
+ return PAPER_SIZES[key] ?? PAPER_SIZES[DEFAULT_PAPER]
52
+ }
53
+
54
+ function safeAreas(paperName) {
55
+ const paper = paperOf(paperName)
56
+ return {
57
+ main: { left: 40, bottom: 200, right: paper.frame.right - 40, top: paper.frame.top - 25 },
58
+ lowerLeft: { left: 40, bottom: 40, right: paper.titleBlock.left - 20, top: paper.titleBlock.top - 10 },
59
+ }
60
+ }
61
+
62
+ /** Decode a text payload that may arrive as UTF-16LE (BOM or interleaved NULs). */
63
+ function decodeTextPayload(value) {
64
+ const text = typeof value === 'string' ? value : ''
65
+ if (text === '') return text
66
+ // Three shapes reach us: an already-decoded string with a U+FEFF prefix, the raw
67
+ // BOM bytes mangled into the characters 0xFF 0xFE, and a null-interleaved UTF-16
68
+ // body without a BOM. Measured on EDA 3.2.186 the CSV BOM arrives mangled, which
69
+ // the first version of this helper missed.
70
+ if (text.charCodeAt(0) === 0xfeff) return text.slice(1)
71
+ if (text.charCodeAt(0) === 0xff && text.charCodeAt(1) === 0xfe) {
72
+ return Buffer.from(text.slice(2), 'latin1').toString('utf16le')
73
+ }
74
+ if (text.length > 3 && text.charCodeAt(1) === 0 && text.charCodeAt(3) === 0) {
75
+ return Buffer.from(text, 'latin1').toString('utf16le')
76
+ }
77
+ return text
78
+ }
79
+
80
+ function checkPointInFrame(x, y, paperName, margin = 0) {
81
+ const paper = paperOf(paperName)
82
+ const f = paper.frame
83
+ if (x < f.left + margin || x > f.right - margin || y < f.bottom + margin || y > f.top - margin) {
84
+ return 'point (' + x + ', ' + y + ') is outside the ' + paper.name + ' frame ' + f.left + '..' + f.right + ' x ' + f.bottom + '..' + f.top + ' (MCP units, 0.01 inch)'
85
+ }
86
+ return undefined
87
+ }
88
+
89
+ function checkPointAgainstTitleBlock(x, y, paperName, margin = 0) {
90
+ const paper = paperOf(paperName)
91
+ const t = paper.titleBlock
92
+ if (x > t.left - margin && x < t.right + margin && y > t.bottom - margin && y < t.top + margin) {
93
+ return 'point (' + x + ', ' + y + ') overlaps the title block ' + t.left + '..' + t.right + ' x ' + t.bottom + '..' + t.top + ' (MCP units)'
94
+ }
95
+ return undefined
96
+ }
97
+
98
+ function checkBBoxInFrame(bbox, paperName, margin = 0) {
99
+ const paper = paperOf(paperName)
100
+ const f = paper.frame
101
+ if (bbox.minX < f.left + margin || bbox.maxX > f.right - margin || bbox.minY < f.bottom + margin || bbox.maxY > f.top - margin) {
102
+ return 'bounding box [' + bbox.minX + ',' + bbox.minY + ']..[' + bbox.maxX + ',' + bbox.maxY + '] is outside the ' + paper.name + ' frame'
103
+ }
104
+ const t = paper.titleBlock
105
+ if (bbox.maxX > t.left - margin && bbox.minX < t.right + margin && bbox.maxY > t.bottom - margin && bbox.minY < t.top + margin) {
106
+ return 'bounding box [' + bbox.minX + ',' + bbox.minY + ']..[' + bbox.maxX + ',' + bbox.maxY + '] overlaps the title block'
107
+ }
108
+ return undefined
109
+ }
110
+
111
+ const ALLOWED_API = new Set([
112
+ 'sch_Document.save',
113
+ 'sch_Document.navigateToCoordinates',
114
+ 'sch_Document.navigateToRegion',
115
+ 'sch_Document.getPrimitiveAtPoint',
116
+ 'sch_Document.getPrimitivesInRegion',
117
+ 'sch_Document.autoLayout',
118
+ 'sch_Document.autoRouting',
119
+ 'sch_Drc.check',
120
+ 'sch_Net.getAllNets',
121
+ 'sch_Net.getCurrentProjectAllNets',
122
+ 'sch_Net.getAllNetsName',
123
+ 'sch_Net.getNet',
124
+ 'sch_ManufactureData.getNetlistFile',
125
+ 'sch_ManufactureData.getBomFile',
126
+ 'sch_Primitive.getPrimitivesBBox',
127
+ 'sch_PrimitiveComponent.create',
128
+ 'sch_PrimitiveComponent.createNetFlag',
129
+ 'sch_PrimitiveComponent.createNetPort',
130
+ 'sch_PrimitiveComponent.createShortCircuitFlag',
131
+ 'sch_PrimitiveComponent.delete',
132
+ 'sch_PrimitiveComponent.modify',
133
+ 'sch_PrimitiveComponent.get',
134
+ 'sch_PrimitiveComponent.getAll',
135
+ 'sch_PrimitiveComponent.getAllPrimitiveId',
136
+ 'sch_PrimitiveComponent.getAllPinsByPrimitiveId',
137
+ 'sch_PrimitiveComponent.getAllPropertyNames',
138
+ 'sch_PrimitiveWire.create',
139
+ 'sch_PrimitiveWire.delete',
140
+ 'sch_PrimitiveWire.modify',
141
+ 'sch_PrimitiveWire.get',
142
+ 'sch_PrimitiveWire.getAll',
143
+ 'sch_PrimitiveWire.getAllPrimitiveId',
144
+ 'sch_PrimitiveRectangle.create',
145
+ 'sch_PrimitiveRectangle.delete',
146
+ 'sch_PrimitiveRectangle.modify',
147
+ 'sch_PrimitiveRectangle.get',
148
+ 'sch_PrimitiveRectangle.getAll',
149
+ 'sch_PrimitiveRectangle.getAllPrimitiveId',
150
+ 'sch_PrimitiveCircle.create',
151
+ 'sch_PrimitiveCircle.delete',
152
+ 'sch_PrimitiveCircle.modify',
153
+ 'sch_PrimitiveCircle.get',
154
+ 'sch_PrimitiveCircle.getAll',
155
+ 'sch_PrimitiveCircle.getAllPrimitiveId',
156
+ 'sch_PrimitiveArc.create',
157
+ 'sch_PrimitiveArc.delete',
158
+ 'sch_PrimitiveArc.modify',
159
+ 'sch_PrimitiveArc.get',
160
+ 'sch_PrimitiveArc.getAll',
161
+ 'sch_PrimitiveArc.getAllPrimitiveId',
162
+ 'sch_PrimitivePolygon.create',
163
+ 'sch_PrimitivePolygon.delete',
164
+ 'sch_PrimitivePolygon.modify',
165
+ 'sch_PrimitivePolygon.get',
166
+ 'sch_PrimitivePolygon.getAll',
167
+ 'sch_PrimitivePolygon.getAllPrimitiveId',
168
+ 'sch_PrimitiveText.create',
169
+ 'sch_PrimitiveText.delete',
170
+ 'sch_PrimitiveText.modify',
171
+ 'sch_PrimitiveText.get',
172
+ 'sch_PrimitiveText.getAll',
173
+ 'sch_PrimitiveText.getAllPrimitiveId',
174
+ 'sch_PrimitivePin.get',
175
+ 'sch_PrimitivePin.modify',
176
+ 'lib_Device.search',
177
+ 'lib_Device.getByLcscIds',
178
+ 'lib_Symbol.search',
179
+ 'lib_Footprint.search',
180
+ 'dmt_Schematic.getCurrentSchematicInfo',
181
+ 'dmt_Schematic.getCurrentSchematicPageInfo',
182
+ 'dmt_Schematic.getCurrentSchematicAllSchematicPagesInfo',
183
+ 'dmt_Schematic.getSchematicInfo',
184
+ 'dmt_Schematic.getSchematicPageInfo',
185
+ 'dmt_Schematic.getAllSchematicPagesInfo',
186
+ 'dmt_Board.createBoard',
187
+ 'dmt_Board.getAllBoardsInfo',
188
+ 'dmt_Board.getCurrentBoardInfo',
189
+ 'dmt_EditorControl.getSplitScreenTree',
190
+ 'dmt_EditorControl.getTabsBySplitScreenId',
191
+ 'dmt_EditorControl.openDocument',
192
+ 'dmt_EditorControl.activateDocument',
193
+ 'dmt_EditorControl.zoomToRegion',
194
+ 'dmt_EditorControl.zoomToAllPrimitives',
195
+ 'dmt_EditorControl.getCurrentRenderedAreaImage',
196
+ 'dmt_EditorControl.generateIndicatorMarkers',
197
+ 'dmt_EditorControl.removeIndicatorMarkers',
198
+ 'pcb_Document.save',
199
+ 'pcb_Document.importChanges',
200
+ 'pcb_Document.getPrimitivesInRegion',
201
+ 'pcb_Document.navigateToRegion',
202
+ 'pcb_Document.navigateToCoordinates',
203
+ 'pcb_Document.zoomToBoardOutline',
204
+ 'pcb_Document.getCanvasOrigin',
205
+ 'pcb_Primitive.getPrimitivesBBox',
206
+ 'pcb_PrimitiveComponent.create',
207
+ 'pcb_PrimitiveComponent.getAll',
208
+ 'pcb_PrimitiveComponent.getAllPrimitiveId',
209
+ 'pcb_PrimitiveComponent.getAllPinsByPrimitiveId',
210
+ 'pcb_PrimitiveLine.create',
211
+ 'pcb_PrimitiveVia.create',
212
+ 'pcb_Net.getAllNets',
213
+ 'pcb_Net.getAllNetsName',
214
+ 'pcb_Layer.getAllLayers',
215
+ 'pcb_Layer.getCurrentLayer',
216
+ 'pcb_PrimitiveComponent.modify',
217
+ 'pcb_PrimitiveComponent.delete',
218
+ 'pcb_PrimitiveLine.getAll',
219
+ 'pcb_PrimitiveLine.getAllPrimitiveId',
220
+ 'pcb_PrimitiveLine.modify',
221
+ 'pcb_PrimitiveLine.delete',
222
+ 'pcb_PrimitiveVia.getAll',
223
+ 'pcb_PrimitiveVia.getAllPrimitiveId',
224
+ 'pcb_PrimitiveVia.modify',
225
+ 'pcb_PrimitiveVia.delete',
226
+ 'pcb_PrimitivePolyline.create',
227
+ 'pcb_PrimitivePolyline.modify',
228
+ 'pcb_PrimitivePolyline.delete',
229
+ 'pcb_PrimitivePolyline.getAll',
230
+ 'pcb_PrimitivePolyline.getAllPrimitiveId',
231
+ 'pcb_Document.clearRouting',
232
+ 'pcb_PrimitiveRegion.create',
233
+ 'pcb_PrimitiveRegion.getAll',
234
+ 'pcb_PrimitiveRegion.getAllPrimitiveId',
235
+ 'pcb_PrimitiveRegion.modify',
236
+ 'pcb_PrimitiveRegion.delete',
237
+ 'pcb_MathPolygon.createPolygon',
238
+ 'pcb_PrimitivePour.create',
239
+ 'pcb_PrimitivePour.modify',
240
+ 'pcb_PrimitivePour.delete',
241
+ 'pcb_PrimitivePour.getAll',
242
+ 'pcb_PrimitivePour.getAllPrimitiveId',
243
+ 'pcb_Drc.check',
244
+ 'pcb_Drc.getCurrentRuleConfiguration',
245
+ 'pcb_Drc.getCurrentRuleConfigurationName',
246
+ 'pcb_Drc.getRealTimeDrcStatus',
247
+ 'pcb_Drc.startRealTimeDrc',
248
+ 'pcb_Drc.stopRealTimeDrc',
249
+ 'sch_PrimitiveAttribute.createNetLabel',
250
+ 'sch_PrimitiveAttribute.modify',
251
+ 'sch_PrimitiveAttribute.delete',
252
+ 'sch_PrimitiveAttribute.getAll',
253
+ 'sch_Netlist.getNetlist',
254
+ 'dmt_SelectControl.getCurrentDocumentInfo',
255
+ 'pcb_PrimitiveComponent.getAllPinsByPrimitiveId',
256
+ 'pcb_Document.autoLayout',
257
+ 'pcb_Document.autoRouting',
258
+ 'pcb_ManufactureData.getGerberFile',
259
+ ])
260
+
261
+ function objectSchema(properties, required = []) {
262
+ return { type: 'object', properties, required, additionalProperties: false }
263
+ }
264
+
265
+ const TOOLS = [
266
+ { name: 'eda_status', description: 'Get the dsh-eda-mcp bridge status and how many JLCEDA Pro bridge extensions are connected.', inputSchema: objectSchema({}) },
267
+ { name: 'eda_list_projects', description: 'List project UUIDs in the workspace (dmt_Project.getAllProjectsUuid). resolveNames=true (default) also reads getProjectInfo per project so callers can match by friendly name.', inputSchema: objectSchema({ teamUuid: { type: 'string' }, folderUuid: { type: 'string' }, workspaceUuid: { type: 'string' }, resolveNames: { type: 'boolean' }, limit: { type: 'integer' } }) },
268
+ { name: 'eda_get_project', description: 'Read the current project (dmt_Project.getCurrentProjectInfo): uuid, friendly name, folder/team and other brief fields.', inputSchema: objectSchema({}) },
269
+ { name: 'eda_open_project', description: 'Open a project by uuid, or by friendly name when only a name is known (the name is resolved through getAllProjectsUuid + getProjectInfo, exact match first, then case-insensitive substring).', inputSchema: objectSchema({ uuid: { type: 'string' }, name: { type: 'string' } }) },
270
+ { name: 'eda_create_project', description: 'Create a project (dmt_Project.createProject) and return its uuid; open=true (default false) also opens it. friendlyName is required; name and folder/team default to the app defaults.', inputSchema: objectSchema({ friendlyName: { type: 'string' }, name: { type: 'string' }, teamUuid: { type: 'string' }, folderUuid: { type: 'string' }, description: { type: 'string' }, open: { type: 'boolean' } }, ['friendlyName']) },
271
+ { name: 'eda_get_workspace', description: 'Read the current workspace and team (dmt_Workspace.getCurrentWorkspaceInfo / dmt_Team.getCurrentTeamInfo). Needed before creating a project, which requires a team (and usually a folder) uuid.', inputSchema: objectSchema({}) },
272
+ { name: 'eda_list_teams', description: 'List teams (dmt_Team.getAllTeamsInfo), optionally including the teams this account is involved in.', inputSchema: objectSchema({ involved: { type: 'boolean' } }) },
273
+ { name: 'eda_list_folders', description: 'List folder uuids of one team (dmt_Folder.getAllFoldersUuid), optionally resolved through getFolderInfo.', inputSchema: objectSchema({ teamUuid: { type: 'string' }, resolveNames: { type: 'boolean', } }) },
274
+ { name: 'eda_delete_project', description: 'Delete a project (dmt_Project.deleteProject) by uuid or friendly name.', inputSchema: objectSchema({ uuid: { type: 'string' }, name: { type: 'string' } }) },
275
+ { name: 'eda_modify_project', description: 'Rename a project or change its description (dmt_Project.modifyProjectFriendlyName / modifyProjectDescription), addressed by uuid or current friendly name.', inputSchema: objectSchema({ uuid: { type: 'string' }, name: { type: 'string' }, friendlyName: { type: 'string' }, description: { type: 'string' } }) },
276
+ { name: 'eda_copy_project', description: 'Copy a project (dmt_Project.copyProject), optionally into another team/folder and with a new friendly name; returns the new uuid.', inputSchema: objectSchema({ sourceUuid: { type: 'string' }, sourceName: { type: 'string' }, targetTeamUuid: { type: 'string' }, targetFolderUuid: { type: 'string' }, newFriendlyName: { type: 'string' }, newName: { type: 'string' } }) },
277
+ { name: 'eda_close_document', description: 'Close one editor tab (dmt_EditorControl.closeDocument).', inputSchema: objectSchema({ tabId: { type: 'string' } }, ['tabId']) },
278
+ { name: 'eda_export_project', description: 'Export a project file (sys_FileManager.getProjectFile / getProjectFileByProjectUuid). With outPath the bridge writes the bytes to disk and returns the path; without it the base64 payload is returned only when inline=true.', inputSchema: objectSchema({ uuid: { type: 'string' }, fileName: { type: 'string' }, fileType: { type: 'string', enum: ['epro', 'epro2'] }, outPath: { type: 'string' }, inline: { type: 'boolean' } }) },
279
+ { name: 'eda_import_project', description: 'Import a local project file (.eprj2/.epro/...) into a team (sys_FileManager.importProjectByProjectFile with a saveTo target). teamUuid is required in local mode: without a target team the app imports nothing. Returns whether the import actually landed.', inputSchema: objectSchema({ path: { type: 'string' }, teamUuid: { type: 'string' }, folderUuid: { type: 'string' }, friendlyName: { type: 'string' }, fileType: { type: 'string' }, open: { type: 'boolean' } }, ['path']) },
280
+ { name: 'eda_close', description: 'Close JLCEDA Pro gracefully (taskkill /T on Windows, SIGTERM elsewhere), then force-kill if it is still running after waitMs (default 8000). Returns the remaining process count.', inputSchema: objectSchema({ force: { type: 'boolean' }, waitMs: { type: 'integer' } }) },
281
+ { name: 'eda_launch', description: 'Launch JLCEDA Pro (EasyEDA Pro), optionally opening a .eprj2/.eprj project, then wait until the bridge extension connects. The executable is resolved from DSH_EDA_EXECUTABLE/JLCEDA_EXECUTABLE, the registry handler the installer registered, conventional install directories, then PATH - so it works on any machine without configuration.', inputSchema: objectSchema({ project: { type: 'string' }, executable: { type: 'string' }, waitForExtension: { type: 'boolean' }, timeoutMs: { type: 'integer' } }) },
282
+ { name: 'eda_get_page_info', description: 'Return the current schematic page, the A4 frame range, the title-block keep-out range, and the recommended safe placement areas. All coordinates are MCP units (0.01 inch).', inputSchema: objectSchema({ paper: { type: 'string' } }) },
283
+ { name: 'eda_get_schematic_pages', description: 'List the schematic pages of the current schematic, or fetch one page by uuid.', inputSchema: objectSchema({ pageUuid: { type: 'string' } }) },
284
+ { name: 'eda_search_components', description: 'Search JLCEDA library devices by keyword. Returns candidate components with uuid/libraryUuid needed by eda_place_component.', inputSchema: objectSchema({ keyword: { type: 'string' }, limit: { type: 'integer' } }, ['keyword']) },
285
+ { name: 'eda_place_component', description: 'Place a JLCEDA library component on the active schematic page. Coordinates are MCP units (0.01 inch), origin at the lower-left of the A4 frame. Placement is rejected when the symbol leaves the frame or overlaps the title block unless allowOutsideFrame is true.', inputSchema: objectSchema({
286
+ libraryUuid: { type: 'string' }, uuid: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' },
287
+ subPartName: { type: 'string' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, mirror: { type: 'boolean' },
288
+ addIntoBom: { type: 'boolean' }, addIntoPcb: { type: 'boolean' },
289
+ designator: { type: 'string' }, value: { type: 'string' }, name: { type: 'string' },
290
+ paper: { type: 'string' }, allowOutsideFrame: { type: 'boolean' },
291
+ }, ['libraryUuid', 'uuid', 'x', 'y']) },
292
+ { name: 'eda_place_net_flag', description: 'Place a power/ground net flag (VCC/GND etc.) on the active schematic page.', inputSchema: objectSchema({ identification: { type: 'string', enum: ['Power', 'Ground', 'AnalogGround', 'ProtectGround'] }, net: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, mirror: { type: 'boolean' }, paper: { type: 'string' }, allowOutsideFrame: { type: 'boolean' } }, ['identification', 'net', 'x', 'y']) },
293
+ { name: 'eda_place_net_port', description: 'Place a net port on the active schematic page.', inputSchema: objectSchema({ direction: { type: 'string', enum: ['IN', 'OUT', 'BI'] }, net: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, mirror: { type: 'boolean' }, paper: { type: 'string' }, allowOutsideFrame: { type: 'boolean' } }, ['direction', 'net', 'x', 'y']) },
294
+ { name: 'eda_get_pins', description: 'List pins of one schematic component in a single round trip, including pinName and pinNumber (no per-pin sch_PrimitivePin.get needed). Use the returned primitiveId with eda_place_net_flag_at_pin, eda_place_net_label_at_pin, or eda_set_no_connect.', inputSchema: objectSchema({ componentPrimitiveId: { type: 'string' } }, ['componentPrimitiveId']) },
295
+ { name: 'eda_place_net_flag_at_pin', description: 'Place a power/ground net flag at a pin WITHOUT covering the symbol: the pin direction is read from the pin rotation, a stub wire of stubLength MCP units (default 20) is drawn outwards from the pin with the net name, and the flag is placed at its end. Pass offsetX/offsetY to place it manually (that disables the stub) or stubLength=0 for the old on-pin behaviour.', inputSchema: objectSchema({ pinPrimitiveId: { type: 'string' }, identification: { type: 'string', enum: ['Power', 'Ground', 'AnalogGround', 'ProtectGround'] }, net: { type: 'string' }, stubLength: { type: 'number' }, offsetX: { type: 'number' }, offsetY: { type: 'number' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, mirror: { type: 'boolean' }, color: { type: 'string' }, lineWidth: { type: 'integer' }, lineType: { type: 'integer' }, paper: { type: 'string' }, allowOutsideFrame: { type: 'boolean' } }, ['pinPrimitiveId', 'identification', 'net']) },
296
+ { name: 'eda_place_net_label_at_pin', description: 'Place a REAL net label at a pin (sch_PrimitiveAttribute.createNetLabel; falls back to text and reports method) WITHOUT covering the symbol: a stub wire of stubLength MCP units (default 20) is drawn outwards along the pin direction and the label goes at its end. offsetX/offsetY place it manually (disables the stub); stubLength=0 keeps the old on-pin behaviour.', inputSchema: objectSchema({ pinPrimitiveId: { type: 'string' }, net: { type: 'string' }, stubLength: { type: 'number' }, offsetX: { type: 'number' }, offsetY: { type: 'number' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, fontSize: { type: 'number' }, color: { type: 'string' }, lineWidth: { type: 'integer' }, lineType: { type: 'integer' }, paper: { type: 'string' }, allowOutsideFrame: { type: 'boolean' } }, ['pinPrimitiveId', 'net']) },
297
+ { name: 'eda_set_no_connect', description: 'Set or clear the no-connect flag on one or more schematic pins via sch_PrimitivePin.modify.', inputSchema: objectSchema({ primitiveIds: { type: 'array', items: { type: 'string' } }, noConnected: { type: 'boolean' } }, ['primitiveIds']) },
298
+ { name: 'eda_draw_wire', description: 'Draw a schematic wire (polyline). Coordinates are MCP units (0.01 inch). IMPORTANT: the net argument only sticks on a floating wire — as soon as an endpoint touches a pin, EDA recomputes the net from connectivity and the name you passed is overwritten (measured: TESTNET merged into LED_A). To join same-named nets across regions use eda_place_net_port or a net label; do not rely on two distantly drawn wires sharing a name.', inputSchema: objectSchema({ points: { type: 'array', items: { type: 'number' } }, net: { type: 'string' }, color: { type: 'string' }, lineWidth: { type: 'integer', minimum: 1, maximum: 10 }, lineType: { type: 'integer', enum: [0, 1, 2, 3] } }, ['points']) },
299
+ { name: 'eda_draw_rectangle', description: 'Draw a rectangle. topLeftY is the UPPER y coordinate (max y); height extends downward. Coordinates are MCP units.', inputSchema: objectSchema({ topLeftX: { type: 'number' }, topLeftY: { type: 'number' }, width: { type: 'number' }, height: { type: 'number' }, cornerRadius: { type: 'number' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, color: { type: 'string' }, fillColor: { type: 'string' }, lineWidth: { type: 'integer', minimum: 1, maximum: 10 }, lineType: { type: 'integer', enum: [0, 1, 2, 3] }, fillStyle: { type: 'string' } }, ['topLeftX', 'topLeftY', 'width', 'height']) },
300
+ { name: 'eda_draw_functional_box', description: 'Draw a dashed functional-group box around one group of components, with an optional label. Margins and coordinates are MCP units; default margin 1 unit (about 0.254 mm).', inputSchema: objectSchema({ componentIds: { type: 'array', items: { type: 'string' } }, label: { type: 'string' }, margin: { type: 'number' }, color: { type: 'string' }, lineWidth: { type: 'integer', minimum: 1, maximum: 10 }, lineType: { type: 'integer', enum: [0, 1, 2, 3] } }) },
301
+ { name: 'eda_draw_circle', description: 'Draw a circle. Coordinates are MCP units.', inputSchema: objectSchema({ centerX: { type: 'number' }, centerY: { type: 'number' }, radius: { type: 'number' }, color: { type: 'string' }, fillColor: { type: 'string' }, lineWidth: { type: 'integer', minimum: 1, maximum: 10 }, lineType: { type: 'integer', enum: [0, 1, 2, 3] }, fillStyle: { type: 'string' } }, ['centerX', 'centerY', 'radius']) },
302
+ { name: 'eda_draw_text', description: 'Draw text. Coordinates are MCP units.', inputSchema: objectSchema({ x: { type: 'number' }, y: { type: 'number' }, content: { type: 'string' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, textColor: { type: 'string' }, fontName: { type: 'string' }, fontSize: { type: 'number' }, bold: { type: 'boolean' }, italic: { type: 'boolean' }, underLine: { type: 'boolean' }, alignMode: { type: 'integer', minimum: 1, maximum: 9 } }, ['x', 'y', 'content']) },
303
+ { name: 'eda_save_document', description: 'Save the active schematic document.', inputSchema: objectSchema({}) },
304
+ { name: 'eda_zoom_to_fit', description: 'Zoom to fit all primitives in the active document.', inputSchema: objectSchema({ tabId: { type: 'string' } }) },
305
+ { name: 'eda_zoom_to_region', description: 'Zoom to a region. Schematic coordinates are MCP units.', inputSchema: objectSchema({ left: { type: 'number' }, right: { type: 'number' }, top: { type: 'number' }, bottom: { type: 'number' }, tabId: { type: 'string' } }, ['left', 'right', 'top', 'bottom']) },
306
+ { name: 'eda_get_components', description: 'List components on the active schematic page (or all pages). Returns designator, value, x, y, rotation and bounding box when available.', inputSchema: objectSchema({ allSchematicPages: { type: 'boolean' }, includeBounds: { type: 'boolean' } }) },
307
+ { name: 'eda_get_wires', description: 'List wires on the active schematic page.', inputSchema: objectSchema({}) },
308
+ { name: 'eda_get_nets', description: 'List nets of the current schematic project. Uses sch_Net.* first; when the schematic is not the active document those APIs return [] and this tool falls back to parsing sch_Netlist.getNetlist, reporting which source was used.', inputSchema: objectSchema({ name: { type: 'string' }, parseNetlist: { type: 'boolean' } }) },
309
+ { name: 'eda_get_active_document', description: 'Return the document/tab that is currently active (documentType, uuid, tabId, parent project). Most tab-dependent APIs (sch_Net.*, netlist export, DRC) only work when the matching document is active - use eda_open_document to switch.', inputSchema: objectSchema({}) },
310
+ { name: 'eda_open_document', description: 'Open/activate a document tab by uuid (dmt_EditorControl.openDocument). Works for a schematic page or a PCB, so tab-dependent APIs can run.', inputSchema: objectSchema({ documentUuid: { type: 'string' }, splitScreenId: { type: 'string' } }, ['documentUuid']) },
311
+ { name: 'eda_get_net_labels', description: 'List every label-like primitive on the active schematic page: attribute primitives (netlabel/netport/netflag) PLUS plain texts left by the createNetLabel fallback, so they can be audited and deleted. Reports kind/primitiveId/net per entry.', inputSchema: objectSchema({ parentPrimitiveId: { type: 'string' } }) },
312
+ { name: 'eda_place_net_label', description: 'Place a net label at x/y. The real API (sch_PrimitiveAttribute.createNetLabel) is probed once per session; when the build never answers, a plain TEXT label is placed instead, which carries no electrical meaning and must be paired with a stub wire. Pass probe:true to re-check.', inputSchema: objectSchema({ x: { type: 'number' }, y: { type: 'number' }, net: { type: 'string' }, fontSize: { type: 'number' }, rotation: { type: 'integer', enum: [0, 90, 180, 270] }, probe: { type: 'boolean' }, textLabel: { type: 'boolean' } }, ['x', 'y', 'net']) },
313
+ { name: 'eda_place_net_labels', description: 'Place many net labels in ONE call (per-pin or by coordinate) and report done/failed per item: a 133-label schematic used to exceed the caller timeout with no progress. items: [{ pinPrimitiveId, net, stubLength?, offsetX?, offsetY? }] or [{ x, y, net, fontSize? }].', inputSchema: objectSchema({ items: { type: 'array', items: { type: 'object', additionalProperties: true } }, probe: { type: 'boolean' }, textLabel: { type: 'boolean' }, concurrency: { type: 'integer', minimum: 1, maximum: 8 } }, ['items']) },
314
+ { name: 'eda_run_drc', description: 'Run schematic DRC with includeVerboseError. On EDA 3.2.186 the app still returns AGGREGATED entries ({type:"warn",count:N}) with no primitiveId/coordinates, so entries are reported as-is and raw keeps the untouched payload; expect counts plus a hint until the app exposes details.', inputSchema: objectSchema({ strict: { type: 'boolean' } }) },
315
+ { name: 'eda_auto_layout', description: 'Run schematic auto-layout (sch_Document.autoLayout). DISABLED by default: automated layout is not used unless the user asks for it. Pass force:true only then.', inputSchema: objectSchema({ uuids: { type: 'array', items: { type: 'string' } }, force: { type: 'boolean' } }) },
316
+ { name: 'eda_auto_route', description: 'Run schematic auto-routing (sch_Document.autoRouting). DISABLED by default: route by hand unless the user explicitly asks. Pass force:true only then.', inputSchema: objectSchema({ uuids: { type: 'array', items: { type: 'string' } }, force: { type: 'boolean' } }) },
317
+ { name: 'eda_export_netlist', description: 'Export the schematic netlist as text (default JLCEDA format). Returns null when no schematic is active - check eda_get_active_document / open the schematic page first.', inputSchema: objectSchema({ type: { type: 'string' } }) },
318
+ { name: 'eda_export_bom', description: 'Export the schematic BOM. csv is decoded from UTF-16 to readable text; xlsx returns a base64 data URL.', inputSchema: objectSchema({ format: { type: 'string', enum: ['csv', 'xlsx'] } }) },
319
+ { name: 'eda_move_component', description: 'Move/rotate/mirror a schematic component (sch_PrimitiveComponent.modify) without deleting and re-placing it, so the designator and value survive.', inputSchema: objectSchema({ primitiveId: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, rotation: { type: 'number' }, mirror: { type: 'boolean' } }, ['primitiveId']) },
320
+ { name: 'pcb_draw_text', description: 'Put text on a PCB layer - silkscreen by default (3 top silk / 4 bottom silk). Use it for pin functions, board markings, version and fabrication notes; silkscreen text must not cover pads.', inputSchema: objectSchema({ x: { type: 'number' }, y: { type: 'number' }, text: { type: 'string' }, layer: { type: 'string' }, fontSize: { type: 'number' }, lineWidth: { type: 'number' }, rotation: { type: 'number' }, mirror: { type: 'boolean' }, alignMode: { type: 'integer' }, locked: { type: 'boolean' } }, ['x', 'y', 'text']) },
321
+ { name: 'pcb_draw_mounting_hole', description: 'Place a NON-plated mounting hole or a slot (pcb_PrimitivePad with metallization:false). shape "round" is a drill-sized hole, shape "slot" an oval cut-out. Use this for mounting holes and connector slots instead of hacking the board outline.', inputSchema: objectSchema({ x: { type: 'number' }, y: { type: 'number' }, diameter: { type: 'number' }, shape: { type: 'string', enum: ['round', 'slot'] }, slotLength: { type: 'number' }, rotation: { type: 'number' }, plated: { type: 'boolean' }, annulus: { type: 'number' }, padNumber: { type: 'string' }, layer: { type: 'string' } }, ['x', 'y', 'diameter']) },
322
+ { name: 'eda_schematic_audit', description: "Geometry audit of the active schematic page (the netlist ERC only judges connectivity): symbols outside the frame, symbols overlapping the title block, body-on-body symbol overlap, off-grid placement, and labels anchored inside a symbol body. Read-only; pair it with eda_netlist_erc before routing.", inputSchema: objectSchema({ grid: { type: 'number' }, includeOk: { type: 'boolean' } }) },
323
+ { name: 'eda_delivery_checklist', description: "Delivery checklist: run connectivity (eda_netlist_erc), PCB audit + DRC, Gerber export and BOM export in ONE read-only call and report per-step pass/fail with counts. It switches to the schematic and the PCB itself (switchDocuments:false keeps the current document and reports the other steps as skipped). verdict is pass / incomplete / fail; pass outPath to also write a Markdown report you can hand to a reviewer.", inputSchema: objectSchema({ outPath: { type: 'string' }, pcbDrc: { type: 'boolean' }, switchDocuments: { type: 'boolean' } }) },
324
+ { name: 'eda_design_intake', description: "Requirement intake for a new board: call it BEFORE placing anything when the request is vague (for example: draw me an X board). Without answers it returns the questions in 6 sections (power, core, IO, mechanical, process, delivery), each marked critical or fallback-able with the reason it changes the drawing; pass answers:{questionId:value} to record them and see what is still missing. Ask the user with ask_user_question for the critical ones instead of guessing.", inputSchema: objectSchema({ answers: { type: 'object', additionalProperties: true }, reset: { type: 'boolean' } }) },
325
+ { name: 'eda_netlist_erc', description: 'Read-only electrical smoke test over the schematic NETLIST (no application DRC needed): duplicate designators, unconnected pins, single-endpoint nets, shorted parts, power rails and decoupling, USB D+/D- pair, crystal (two nets + load caps + reaches the MCU), reset RC, BOOT pull resistor, Type-C CC pull-downs. DRC can be clean while the circuit is still wrong; these failures all show up in the netlist. Pass includeOk:true to see passing checks too.', inputSchema: objectSchema({ includeOk: { type: 'boolean' } }) },
326
+ { name: 'eda_pcb_canvas_origin', description: 'Read (or align) the PCB canvas origin and convert points between the two coordinate spaces. JLCEDA displays CANVAS coordinates in its UI but every API takes DATA coordinates; the two differ by this offset, so a coordinate read off the screen will land somewhere else unless you convert or align. align:true calls setCanvasOrigin(0,0) so the display matches the API.', inputSchema: objectSchema({ align: { type: 'boolean' }, offsetX: { type: 'number' }, offsetY: { type: 'number' }, point: { type: 'object', additionalProperties: true } }) },
327
+ { name: 'eda_capture', description: 'Render the active document to a PNG (dmt_EditorControl.getCurrentRenderedAreaImage) and write it to outPath or return a data URL. Use it to LOOK at the sheet/board instead of trusting coordinate math. The PNG is a scratch file: read it, then call eda_capture({cleanup:true}) to delete every capture path this session wrote.', inputSchema: objectSchema({ outPath: { type: 'string' }, inline: { type: 'boolean' }, cleanup: { type: 'boolean' } }) },
328
+ { name: 'eda_workflow_guide', description: 'Return the schematic working standard: grid-aligned manual placement, signal flow, when net labels/ports are required (a wire net name is overridden by connectivity), net-label fallback behaviour, batch placement and the verification order. Read it before laying out a sheet.', inputSchema: objectSchema({}) },
329
+ { name: 'eda_extension_package', description: 'Report the extension zip this plugin ships (absolute path, bytes, sha256) and, with download:true, fetch the copy served at the download base URL and compare the two byte for byte. On a match the served file is saved to outDir (default: the temp directory) so it can be imported into JLCEDA Pro; on a mismatch nothing is written and the tool says to re-upload. base defaults to DSH_EDA_EXTENSION_BASE or the project download server.', inputSchema: objectSchema({ download: { type: 'boolean' }, outDir: { type: 'string' }, base: { type: 'string' } }, []) },
330
+ { name: 'eda_list_api_methods', description: 'Ask the CONNECTED EXTENSION for the API methods it accepts right now (dsh.internal.listApiMethods) and report source/version/counts. Falls back to the bridge copy with stale:true only when the extension is an older zip. Use refresh:true to re-query.', inputSchema: objectSchema({ refresh: { type: 'boolean' } }) },
331
+ { name: 'eda_delete_primitive', description: 'Delete a schematic primitive by kind and primitive id. Net ports, net flags and net labels are attribute primitives and need kind "netport"/"netflag"/"netlabel"; the text fallback labels are kind "text".', inputSchema: objectSchema({ kind: { type: 'string', enum: ['component', 'wire', 'rectangle', 'circle', 'arc', 'polygon', 'text', 'netport', 'netflag', 'netlabel'] }, primitiveId: { type: 'string' } }, ['kind', 'primitiveId']) },
332
+ { name: 'eda_create_board', description: 'Create a board linking a schematic and a PCB (dmt_Board.createBoard).', inputSchema: objectSchema({ schematicUuid: { type: 'string' }, pcbUuid: { type: 'string' } }) },
333
+ { name: 'eda_api_call', description: 'Call an allow-listed JLCEDA Pro extension API method directly.', inputSchema: objectSchema({ method: { type: 'string' }, args: { type: 'array' } }, ['method', 'args']) },
334
+ { name: 'pcb_get_components', description: 'List PCB components (mil). includePins=true also reads pcb_PrimitiveComponent.getAllPinsByPrimitiveId per component, which is the accurate pad/net source; the fast summary pad list can be stale.', inputSchema: objectSchema({ layer: { type: ['string', 'integer'] }, locked: { type: 'boolean' }, includeBounds: { type: 'boolean' }, includePins: { type: 'boolean' } }) },
335
+ { name: 'pcb_get_nets', description: 'List PCB nets. Set detail=true for full net info.', inputSchema: objectSchema({ detail: { type: 'boolean' }, name: { type: 'string' } }) },
336
+ { name: 'pcb_get_layers', description: 'List PCB layers.', inputSchema: objectSchema({}) },
337
+ { name: 'pcb_place_component', description: 'Place a PCB component/footprint. Coordinates are mil.', inputSchema: objectSchema({ libraryUuid: { type: 'string' }, uuid: { type: 'string' }, layer: { type: ['string', 'integer'] }, x: { type: 'number' }, y: { type: 'number' }, rotation: { type: 'number' } }, ['libraryUuid', 'uuid', 'layer', 'x', 'y']) },
338
+ { name: 'pcb_draw_track', description: 'Draw a PCB track segment. Coordinates are mil. lineWidth defaults to the role-based rule value (signal 6 mil / power 16 mil / GND 16 mil) and is rejected below the 6 mil (0.15 mm) design minimum unless force=true.', inputSchema: objectSchema({ net: { type: 'string' }, layer: { type: ['string', 'integer'] }, startX: { type: 'number' }, startY: { type: 'number' }, endX: { type: 'number' }, endY: { type: 'number' }, lineWidth: { type: 'number' }, force: { type: 'boolean' } }, ['net', 'layer', 'startX', 'startY', 'endX', 'endY']) },
339
+ { name: 'pcb_draw_via', description: 'Place a PCB via. Coordinates and sizes are mil. holeDiameter/diameter default to a standard drill pair (0.2/0.4 mm signal, 0.3/0.6 mm power); the annular ring must be >= 0.2 mm and the hole >= 0.2 mm, and a hole below 0.3 mm (free-prototyping bound) is reported as a warning.', inputSchema: objectSchema({ net: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, holeDiameter: { type: 'number' }, diameter: { type: 'number' }, viaType: { type: 'integer', enum: [0, 1, 2] }, force: { type: 'boolean' } }, ['net', 'x', 'y']) },
340
+ { name: 'pcb_draw_board_outline', description: 'Create a closed board outline on the BoardOutline layer (layer 11) from a flat [x1,y1,x2,y2,...] point list in mil. Implemented as ONE pcb_PrimitivePolyline built from a pcb_MathPolygon polygon - the primitive JLCEDA itself stores for a board outline. pcb_PrimitiveLine cannot create it (that API is a copper track and rejects layer 11).', inputSchema: objectSchema({ points: { type: 'array', items: { type: 'number' } }, lineWidth: { type: 'number' }, net: { type: 'string' }, locked: { type: 'boolean' } }, ['points']) },
341
+ { name: 'pcb_draw_polyline', description: 'Create a closed polyline (pcb_PrimitivePolyline) on any line layer: board outline 11, silkscreen 3/4, assembly 9/10, mechanical 14, document 13, copper 1/2. points is a flat [x1,y1,x2,y2,...] array in mil and is closed automatically.', inputSchema: objectSchema({ points: { type: 'array', items: { type: 'number' } }, layer: { type: ['string', 'integer'] }, net: { type: 'string' }, lineWidth: { type: 'number' }, locked: { type: 'boolean' } }, ['points', 'layer']) },
342
+ { name: 'pcb_save_document', description: 'Save the active PCB document.', inputSchema: objectSchema({}) },
343
+ { name: 'pcb_import_changes', description: 'Import schematic changes into the active PCB (pcb_Document.importChanges). DEFAULT IS ASYNCHRONOUS because the call opens EDA own sync-confirmation dialog and blocks until the user answers it: the import runs as a background job, the tool returns immediately with componentsBefore, and the answer is detected by eda_pcb_wait_for_components. wait=true blocks instead (only when no dialog appears).', inputSchema: objectSchema({ schematicUuid: { type: 'string' }, wait: { type: 'boolean' }, timeoutMs: { type: 'integer' } }) },
344
+ { name: 'eda_pcb_wait_for_components', description: 'Low-frequency poll (default every 5 s, minimum 3 s) that treats "new PCB components appeared" as "the user clicked OK in the schematic-sync confirmation dialog". Returns confirmed/waitedMs/newComponentIds, or confirmed=false after maxWaitMs (default 45 s) so the caller can ask the user and call again.', inputSchema: objectSchema({ pollIntervalMs: { type: 'integer', minimum: 3000 }, maxWaitMs: { type: 'integer' }, baseline: { type: 'array', items: { type: 'string' } } }) },
345
+ { name: 'pcb_get_primitives_in_region', description: 'List PCB primitives inside a region. Coordinates are mil.', inputSchema: objectSchema({ left: { type: 'number' }, right: { type: 'number' }, top: { type: 'number' }, bottom: { type: 'number' }, leftToRight: { type: 'boolean' } }, ['left', 'right', 'top', 'bottom']) },
346
+ { name: 'pcb_navigate_to_region', description: 'Navigate the PCB canvas to a region. Coordinates are mil.', inputSchema: objectSchema({ left: { type: 'number' }, right: { type: 'number' }, top: { type: 'number' }, bottom: { type: 'number' } }, ['left', 'right', 'top', 'bottom']) },
347
+ // ---- eda_pcb_* aliases and new PCB tools ----
348
+ { name: 'eda_pcb_get_components', description: 'Alias of pcb_get_components. List PCB components (mil).', inputSchema: objectSchema({ layer: { type: ['string', 'integer'] }, locked: { type: 'boolean' }, includeBounds: { type: 'boolean' } }) },
349
+ { name: 'eda_pcb_get_nets', description: 'Alias of pcb_get_nets.', inputSchema: objectSchema({ detail: { type: 'boolean' }, name: { type: 'string' } }) },
350
+ { name: 'eda_pcb_get_layers', description: 'Alias of pcb_get_layers.', inputSchema: objectSchema({}) },
351
+ { name: 'eda_pcb_place_component', description: 'Alias of pcb_place_component.', inputSchema: objectSchema({ libraryUuid: { type: 'string' }, uuid: { type: 'string' }, layer: { type: ['string', 'integer'] }, x: { type: 'number' }, y: { type: 'number' }, rotation: { type: 'number' } }, ['libraryUuid', 'uuid', 'layer', 'x', 'y']) },
352
+ { name: 'eda_pcb_move_component', description: 'Move/rotate/modify an existing PCB component (pcb_PrimitiveComponent.modify). Coordinates are mil.', inputSchema: objectSchema({ primitiveId: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, rotation: { type: 'number' }, layer: { type: ['string', 'integer'] }, locked: { type: 'boolean' }, designator: { type: 'string' }, name: { type: 'string' } }, ['primitiveId']) },
353
+ { name: 'eda_pcb_delete_component', description: 'Delete a PCB component (pcb_PrimitiveComponent.delete).', inputSchema: objectSchema({ primitiveId: { type: 'string' } }, ['primitiveId']) },
354
+ { name: 'eda_pcb_draw_track', description: 'Alias of pcb_draw_track.', inputSchema: objectSchema({ net: { type: 'string' }, layer: { type: ['string', 'integer'] }, startX: { type: 'number' }, startY: { type: 'number' }, endX: { type: 'number' }, endY: { type: 'number' }, lineWidth: { type: 'number' } }, ['net', 'layer', 'startX', 'startY', 'endX', 'endY']) },
355
+ { name: 'eda_pcb_get_tracks', description: 'List PCB tracks (pcb_PrimitiveLine.getAll). Optional net/layer/locked filters.', inputSchema: objectSchema({ net: { type: 'string' }, layer: { type: ['string', 'integer'] }, locked: { type: 'boolean' } }) },
356
+ { name: 'eda_pcb_modify_track', description: 'Modify a PCB track (pcb_PrimitiveLine.modify). Coordinates are mil.', inputSchema: objectSchema({ primitiveId: { type: 'string' }, net: { type: 'string' }, layer: { type: ['string', 'integer'] }, startX: { type: 'number' }, startY: { type: 'number' }, endX: { type: 'number' }, endY: { type: 'number' }, lineWidth: { type: 'number' }, locked: { type: 'boolean' } }, ['primitiveId']) },
357
+ { name: 'eda_pcb_delete_track', description: 'Delete a PCB track (pcb_PrimitiveLine.delete).', inputSchema: objectSchema({ primitiveId: { type: 'string' } }, ['primitiveId']) },
358
+ { name: 'eda_pcb_draw_via', description: 'Alias of pcb_draw_via.', inputSchema: objectSchema({ net: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, holeDiameter: { type: 'number' }, diameter: { type: 'number' }, viaType: { type: 'integer', enum: [0, 1, 2] } }, ['net', 'x', 'y', 'holeDiameter', 'diameter']) },
359
+ { name: 'eda_pcb_get_vias', description: 'List PCB vias (pcb_PrimitiveVia.getAll). Optional net/locked filters.', inputSchema: objectSchema({ net: { type: 'string' }, locked: { type: 'boolean' } }) },
360
+ { name: 'eda_pcb_delete_via', description: 'Delete a PCB via (pcb_PrimitiveVia.delete).', inputSchema: objectSchema({ primitiveId: { type: 'string' } }, ['primitiveId']) },
361
+ { name: 'eda_pcb_create_region', description: 'Create a PCB region (pcb_PrimitiveRegion.create). points is a flat [x1,y1,x2,y2,...] array in mil and is closed automatically. Allowed layers are copper only: top(1), bottom(2), inner(15-44) and multi(12) - the official API type is TPCB_LayersOfRegion = copper | MULTI, so the board-outline layer (11) is rejected. ruleType uses EPCB_PrimitiveRegionRuleType: 2 noComponents, 5 noWires, 6 noFills, 7 noPours, 8 noInnerElectricalLayers, 9 followRegionRule.', inputSchema: objectSchema({ layer: { type: ['string', 'integer'] }, points: { type: 'array', items: { type: 'number' } }, ruleType: { type: 'array', items: { type: 'integer' } }, regionName: { type: 'string' }, lineWidth: { type: 'number' }, locked: { type: 'boolean' } }, ['layer', 'points']) },
362
+ { name: 'eda_pcb_draw_board_outline', description: 'Alias-style name for pcb_draw_board_outline: draws a closed board outline as line segments on layer 11 (mil).', inputSchema: objectSchema({ points: { type: 'array', items: { type: 'number' } }, lineWidth: { type: 'number' } }, ['points']) },
363
+ { name: 'eda_pcb_get_polylines', description: 'List PCB polylines (pcb_PrimitivePolyline.getAll) - board outline, silkscreen shapes, mechanical drawings. Optional net/layer/locked filters.', inputSchema: objectSchema({ net: { type: 'string' }, layer: { type: ['string', 'integer'] }, locked: { type: 'boolean' } }) },
364
+ { name: 'eda_pcb_delete_polyline', description: 'Delete a PCB polyline (pcb_PrimitivePolyline.delete).', inputSchema: objectSchema({ primitiveId: { type: 'string' } }, ['primitiveId']) },
365
+ { name: 'eda_pcb_clear_routing', description: 'Clear PCB routing. DEFAULT IS A BACKGROUND JOB (pcb_Document.clearRouting): clearing a whole board easily exceeds the MCP timeout while EDA keeps working, so the tool returns immediately and you poll eda_pcb_job_status until running=false. With an older EDA extension it automatically degrades to bounded batches (see batchSize) that you repeat until done=true. type: all | net | connection (net/connection act on the current selection). mode=batched forces the batched path; net/layer filter it.', inputSchema: objectSchema({ type: { type: 'string', enum: ['all', 'net', 'connection'] }, wait: { type: 'boolean' }, mode: { type: 'string', enum: ['native', 'batched'] }, net: { type: 'string' }, layer: { type: ['string', 'integer'] }, batchSize: { type: 'integer', minimum: 1, maximum: 2000 }, timeoutMs: { type: 'integer' } }) },
366
+ { name: 'eda_pcb_create_pour', description: 'Create a copper pour (覆铜, pcb_MathPolygon.createPolygon + pcb_PrimitivePour.create). points is a flat [x1,y1,x2,y2,...] array in mil, closed automatically. layer must be a copper layer (top 1 / bottom 2 / inner 15-44). pourFillMethod: 45grid | 90grid | solid.', inputSchema: objectSchema({ net: { type: 'string' }, layer: { type: ['string', 'integer'] }, points: { type: 'array', items: { type: 'number' } }, pourFillMethod: { type: 'string', enum: ['45grid', '90grid', 'solid'] }, preserveSilos: { type: 'boolean' }, pourName: { type: 'string' }, pourPriority: { type: 'integer' }, lineWidth: { type: 'number' }, locked: { type: 'boolean' } }, ['net', 'layer', 'points']) },
367
+ { name: 'eda_pcb_get_pours', description: 'List PCB copper pours (pcb_PrimitivePour.getAll). Optional net/layer/locked filters.', inputSchema: objectSchema({ net: { type: 'string' }, layer: { type: ['string', 'integer'] }, locked: { type: 'boolean' } }) },
368
+ { name: 'eda_pcb_delete_pour', description: 'Delete a copper pour (pcb_PrimitivePour.delete).', inputSchema: objectSchema({ primitiveId: { type: 'string' } }, ['primitiveId']) },
369
+ { name: 'eda_pcb_run_drc', description: 'Run PCB DRC (pcb_Drc.check). includeVerboseError=true returns the verbose error array (strict=true also reports warnings). Set userInterface=true only if the user should see the DRC panel.', inputSchema: objectSchema({ strict: { type: 'boolean' }, userInterface: { type: 'boolean' }, includeVerboseError: { type: 'boolean' } }) },
370
+ { name: 'eda_pcb_get_drc_rules', description: 'Return the current PCB DRC rule configuration name and content.', inputSchema: objectSchema({}) },
371
+ { name: 'eda_pcb_set_net_track_width', description: 'Set the track width of every existing track of one net (iterates pcb_PrimitiveLine.getAll + pcb_PrimitiveLine.modify). Use it to thicken power/GND nets after auto-routing.', inputSchema: objectSchema({ net: { type: 'string' }, lineWidth: { type: 'number' }, layer: { type: ['string', 'integer'] } }, ['net', 'lineWidth']) },
372
+ { name: 'eda_design_audit', description: 'Read-only audit of the active PCB against docs/design-rules.md: per-net track widths (min 6 mil, role suggestions), via drill/annular ring, net-name legality, board outline, copper pour, and PCB DRC. Returns violations, warnings, a checklist, the per-net minimum widths, and the rule values used. drc=false skips the DRC run.', inputSchema: objectSchema({ net: { type: 'string' }, drc: { type: 'boolean' } }) },
373
+ { name: 'eda_pcb_get_regions', description: 'List PCB regions (pcb_PrimitiveRegion.getAll). layer must be a copper layer (top 1 / bottom 2 / inner 15-44) or MULTI 12.', inputSchema: objectSchema({ layer: { type: ['string', 'integer'] }, ruleType: { type: 'array', items: { type: 'integer' } }, locked: { type: 'boolean' } }) },
374
+ { name: 'eda_pcb_delete_region', description: 'Delete a PCB region (pcb_PrimitiveRegion.delete).', inputSchema: objectSchema({ primitiveId: { type: 'string' } }, ['primitiveId']) },
375
+ { name: 'eda_pcb_auto_place', description: 'Run PCB auto-layout (pcb_Document.autoLayout). Blocking by default (layout is fast); pass wait=false to start it as a background job and poll eda_pcb_job_status.', inputSchema: objectSchema({ wait: { type: 'boolean' }, timeoutMs: { type: 'integer' } }) },
376
+ { name: 'eda_pcb_job_status', description: 'Poll the background PCB job started by eda_pcb_auto_route (or eda_pcb_auto_place with wait=false): running, elapsedMs, result, error. EDA keeps its own progress bar while running.', inputSchema: objectSchema({}) },
377
+ { name: 'eda_pcb_auto_route', description: 'Start PCB auto-routing (pcb_Document.autoRouting). DEFAULT IS ASYNCHRONOUS: the call returns as soon as EDA starts routing (EDA shows its own progress bar) and you poll eda_pcb_job_status until running=false - a long routing job must NOT be awaited, otherwise the MCP call times out while EDA keeps working. Without nets/RoutingNets the bridge enumerates every net, because this EDA build fails every net (success=false, duration=0) when routingRange is empty. wait=true blocks until done (only for small jobs). cornerStyle: 0=45deg, 1=90deg; optimization: 1=completion, 0=faster; existingPrimitiveMode: keep|remove.', inputSchema: objectSchema({ nets: { type: 'array', items: { type: 'string' } }, RoutingNets: { type: ['array', 'string'] }, ignoreNets: { type: 'array', items: { type: 'string' } }, layers: { type: 'array', items: { type: 'integer' } }, cornerStyle: { type: 'integer', enum: [0, 1] }, optimization: { type: 'integer', enum: [0, 1] }, existingPrimitiveMode: { type: 'string', enum: ['keep', 'remove'] }, wait: { type: 'boolean' }, timeoutMs: { type: 'integer' }, props: { type: 'object' } }) },
378
+ { name: 'eda_pcb_export_gerber', description: 'Export PCB Gerber (pcb_ManufactureData.getGerberFile). Returns { name, size, dataUrl } - the zip is base64 encoded, so large boards can produce a big payload.', inputSchema: objectSchema({ fileName: { type: 'string' }, colorSilkscreen: { type: 'boolean' }, unit: { type: 'string', enum: ['mm', 'inch'] }, integerNumber: { type: 'integer' }, decimalNumber: { type: 'integer' }, other: { type: 'object' }, layers: { type: 'array' }, objects: { type: 'array' } }) },
379
+ { name: 'eda_pcb_save_document', description: 'Alias of pcb_save_document.', inputSchema: objectSchema({}) },
380
+ { name: 'eda_pcb_import_changes', description: 'Alias of pcb_import_changes.', inputSchema: objectSchema({ schematicUuid: { type: 'string' } }) },
381
+ { name: 'eda_pcb_get_primitives_in_region', description: 'Alias of pcb_get_primitives_in_region.', inputSchema: objectSchema({ left: { type: 'number' }, right: { type: 'number' }, top: { type: 'number' }, bottom: { type: 'number' }, leftToRight: { type: 'boolean' } }, ['left', 'right', 'top', 'bottom']) },
382
+ { name: 'eda_pcb_navigate_to_region', description: 'Alias of pcb_navigate_to_region.', inputSchema: objectSchema({ left: { type: 'number' }, right: { type: 'number' }, top: { type: 'number' }, bottom: { type: 'number' } }, ['left', 'right', 'top', 'bottom']) },
383
+ ]
384
+
385
+ function toolResult(value) {
386
+ return { content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }] }
387
+ }
388
+
389
+ function toolError(message) {
390
+ return { content: [{ type: 'text', text: message }], isError: true }
391
+ }
392
+
393
+ const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
394
+
395
+ function parseFrame(buffer) {
396
+ if (buffer.length < 2) return undefined
397
+ const fin = (buffer[0] & 0x80) !== 0
398
+ const opcode = buffer[0] & 0x0f
399
+ const masked = (buffer[1] & 0x80) !== 0
400
+ let length = buffer[1] & 0x7f
401
+ let offset = 2
402
+ if (length === 126) {
403
+ if (buffer.length < offset + 2) return undefined
404
+ length = buffer.readUInt16BE(offset)
405
+ offset += 2
406
+ } else if (length === 127) {
407
+ if (buffer.length < offset + 8) return undefined
408
+ const big = buffer.readBigUInt64BE(offset)
409
+ if (big > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error('websocket frame too large')
410
+ length = Number(big)
411
+ offset += 8
412
+ }
413
+ let maskKey
414
+ if (masked) {
415
+ if (buffer.length < offset + 4) return undefined
416
+ maskKey = buffer.subarray(offset, offset + 4)
417
+ offset += 4
418
+ }
419
+ if (buffer.length < offset + length) return undefined
420
+ const payload = Buffer.from(buffer.subarray(offset, offset + length))
421
+ if (maskKey !== undefined) {
422
+ for (let i = 0; i < payload.length; i++) payload[i] ^= maskKey[i % 4]
423
+ }
424
+ return { fin, opcode, payload, consumed: offset + length }
425
+ }
426
+
427
+ function encodeFrame(opcode, payload, fin = true) {
428
+ const header = Buffer.alloc(payload.length < 126 ? 2 : payload.length < 65536 ? 4 : 10)
429
+ header[0] = (fin ? 0x80 : 0) | opcode
430
+ if (payload.length < 126) header[1] = payload.length
431
+ else if (payload.length < 65536) { header[1] = 126; header.writeUInt16BE(payload.length, 2) }
432
+ else { header[1] = 127; header.writeBigUInt64BE(BigInt(payload.length), 2) }
433
+ return Buffer.concat([header, payload])
434
+ }
435
+
436
+ class WsConnection {
437
+ constructor(socket) {
438
+ this.socket = socket
439
+ this.ready = false
440
+ this.buffer = Buffer.alloc(0)
441
+ this.fragments = []
442
+ }
443
+ sendText(text) {
444
+ if (this.socket.destroyed) return
445
+ this.socket.write(encodeFrame(0x1, Buffer.from(text, 'utf8')))
446
+ }
447
+ sendControl(opcode, payload) {
448
+ if (this.socket.destroyed) return
449
+ this.socket.write(encodeFrame(opcode, payload))
450
+ }
451
+ close() {
452
+ try { this.sendControl(0x8, Buffer.alloc(0)) } catch { /* ignore */ }
453
+ this.socket.destroy()
454
+ }
455
+ handleData(chunk) {
456
+ // Liveness: a page that navigates away leaves a half-open socket that still
457
+ // looks ready, so every timestamp counts, not just pongs.
458
+ this.lastSeenAt = Date.now()
459
+ this.buffer = Buffer.concat([this.buffer, chunk])
460
+ for (;;) {
461
+ const frame = parseFrame(this.buffer)
462
+ if (frame === undefined) return
463
+ this.buffer = this.buffer.subarray(frame.consumed)
464
+ this.handleFrame(frame)
465
+ }
466
+ }
467
+ handleFrame(frame) {
468
+ if (frame.opcode === 0x8) { this.close(); return }
469
+ if (frame.opcode === 0x9) { this.sendControl(0xa, frame.payload); return }
470
+ if (frame.opcode === 0xa) return
471
+ if (frame.opcode === 0x0 || frame.opcode === 0x1 || frame.opcode === 0x2) {
472
+ this.fragments.push(frame.payload)
473
+ if (!frame.fin) return
474
+ const payload = Buffer.concat(this.fragments)
475
+ this.fragments = []
476
+ if (frame.opcode === 0x1 || frame.opcode === 0x0) this.emitText(payload.toString('utf8'))
477
+ }
478
+ }
479
+ emitText(text) {
480
+ let message
481
+ try { message = JSON.parse(text) } catch { return }
482
+ if (message === null || typeof message !== 'object') return
483
+ if (message.type === 'hello') {
484
+ this.ready = true
485
+ if (typeof message.version === 'string') this.extensionVersion = message.version
486
+ return
487
+ }
488
+ if (message.type === 'ping') { this.sendText(JSON.stringify({ type: 'pong' })); return }
489
+ if (typeof message.id === 'number' && typeof message.ok === 'boolean') {
490
+ const pending = pendingCalls.get(message.id)
491
+ if (pending === undefined) return
492
+ pendingCalls.delete(message.id)
493
+ clearTimeout(pending.timer)
494
+ if (message.ok) pending.resolve(message.result)
495
+ else pending.reject(new Error(message.error && message.error.message ? message.error.message : 'JLCEDA bridge call failed'))
496
+ }
497
+ }
498
+ }
499
+
500
+ const clients = new Set()
501
+ const pendingCalls = new Map()
502
+ // Baseline for the schematic -> PCB sync confirmation flow: the import triggers
503
+ // EDA's own confirmation dialog, so "did the user confirm?" is answered by
504
+ // watching whether new PCB components appear (low-frequency polling).
505
+ let pcbComponentBaseline = null
506
+ // Net-label capability, probed once per session (null = unknown), plus the plain
507
+ // texts placed while the real net-label API was unavailable: without this registry
508
+ // those labels could not be listed or cleaned up.
509
+ let netLabelSupport = null
510
+ const placedTextLabels = []
511
+
512
+ function sleep(ms) {
513
+ return new Promise(resolve => setTimeout(resolve, ms))
514
+ }
515
+
516
+ async function pcbComponentIds(timeoutMs) {
517
+ const raw = await callExtension('pcb_PrimitiveComponent.getAllPrimitiveId', [], timeoutMs)
518
+ return Array.isArray(raw) ? raw.map(String) : []
519
+ }
520
+ let nextCallId = 1
521
+
522
+ /**
523
+ * The extension's own allow-list, cached per connected extension version.
524
+ *
525
+ * The bridge holds a copy (ALLOWED_API) for documentation and offline hints, but
526
+ * that copy drifts: gating eda_api_call on it rejected methods the extension
527
+ * actually accepts (dmt_Project.* among them) and eda_list_api_methods then
528
+ * reported the wrong capability boundary. Ask the extension instead.
529
+ */
530
+ let extensionApiCache = null
531
+
532
+ /** Confirmed design parameters for this session (see eda_design_intake). */
533
+ let designBrief = null
534
+
535
+ /** Capture PNGs written this session, so eda_capture({cleanup:true}) can delete them. */
536
+ const capturedFiles = []
537
+
538
+ async function extensionApiMethods(timeoutMs, refresh = false) {
539
+ if (!refresh && extensionApiCache !== null) return extensionApiCache
540
+ try {
541
+ const raw = await callExtension('dsh.internal.listApiMethods', [], Math.min(timeoutMs, 5000))
542
+ const record = asRecord(raw)
543
+ const allowed = Array.isArray(record.allowed) ? record.allowed.map(String) : []
544
+ const files = Array.isArray(record.files) ? record.files.map(String) : []
545
+ if (allowed.length === 0 && files.length === 0) return undefined
546
+ extensionApiCache = {
547
+ version: typeof record.version === 'string' ? record.version : null,
548
+ allowed,
549
+ files,
550
+ all: [...allowed, ...files].sort(),
551
+ allowedSet: new Set(allowed),
552
+ fileSet: new Set(files),
553
+ }
554
+ return extensionApiCache
555
+ } catch {
556
+ // Older extension without the helper: fall back to the local copy, flagged.
557
+ return undefined
558
+ }
559
+ }
560
+
561
+ /** A socket that has been silent this long is treated as dead even if it never closed. */
562
+ const CLIENT_STALE_MS = 60000
563
+
564
+ /** Ready clients, freshest first. Stale sockets are used only as a last resort. */
565
+ function pickClients() {
566
+ const now = Date.now()
567
+ const ready = [...clients].filter(client => client.ready)
568
+ const fresh = ready.filter(client => now - (client.lastSeenAt ?? 0) < CLIENT_STALE_MS)
569
+ const pool = fresh.length > 0 ? fresh : ready
570
+ return pool.sort((left, right) => (right.lastSeenAt ?? 0) - (left.lastSeenAt ?? 0))
571
+ }
572
+
573
+ /** Read-only calls may be repeated on another page; a write must never be. */
574
+ function isIdempotentRead(method) {
575
+ const fn = method.slice(method.lastIndexOf('.') + 1).toLowerCase()
576
+ return fn.startsWith('get') || fn.startsWith('is') || fn.startsWith('has') || fn.startsWith('list') || fn.startsWith('search')
577
+ }
578
+
579
+ function sendToClient(client, method, args, timeoutMs) {
580
+ const id = nextCallId++
581
+ return new Promise((resolve, reject) => {
582
+ const timer = setTimeout(() => {
583
+ pendingCalls.delete(id)
584
+ reject(new Error('JLCEDA bridge call timed out after ' + timeoutMs + 'ms: ' + method))
585
+ }, timeoutMs)
586
+ pendingCalls.set(id, { resolve, reject, timer })
587
+ client.sendText(JSON.stringify({ id, method, args }))
588
+ })
589
+ }
590
+
591
+ async function callExtension(method, args, timeoutMs) {
592
+ const pool = pickClients()
593
+ if (pool.length === 0) {
594
+ throw new Error('JLCEDA bridge extension is not connected. Open JLCEDA Pro, import dsh-eda-bridge-extension-' + VERSION + '.zip, enable "Allow interactive with external", and keep a schematic or PCB page open.')
595
+ }
596
+ const deadline = Date.now() + timeoutMs
597
+ let lastError
598
+ for (const client of pool) {
599
+ const remaining = deadline - Date.now()
600
+ if (remaining <= 100) break
601
+ try {
602
+ return await sendToClient(client, method, args, remaining)
603
+ } catch (error) {
604
+ lastError = error
605
+ // A different error means the page answered; retrying would only repeat it.
606
+ if (!isIdempotentRead(method) || !/timed out/.test(String((error as Error)?.message))) throw error
607
+ }
608
+ }
609
+ throw lastError ?? new Error('JLCEDA bridge call timed out after ' + timeoutMs + 'ms: ' + method)
610
+ }
611
+
612
+ function asRecord(value) {
613
+ if (value === null || typeof value !== 'object') return {}
614
+ return value
615
+ }
616
+
617
+ function flattenPoints(points) {
618
+ const flat = []
619
+ if (!Array.isArray(points)) return flat
620
+ for (const item of points) {
621
+ if (Array.isArray(item)) flat.push(...item.map(Number))
622
+ else flat.push(Number(item))
623
+ }
624
+ return flat
625
+ }
626
+
627
+ function primitiveKindToClass(kind) {
628
+ switch (kind) {
629
+ case 'component': return 'sch_PrimitiveComponent'
630
+ case 'wire': return 'sch_PrimitiveWire'
631
+ case 'rectangle': return 'sch_PrimitiveRectangle'
632
+ case 'circle': return 'sch_PrimitiveCircle'
633
+ case 'arc': return 'sch_PrimitiveArc'
634
+ case 'polygon': return 'sch_PrimitivePolygon'
635
+ case 'text': return 'sch_PrimitiveText'
636
+ default: throw new Error('unknown primitive kind: ' + kind)
637
+ }
638
+ }
639
+
640
+ function pickValue(raw, ...keys) {
641
+ for (const key of keys) {
642
+ if (raw && raw[key] !== undefined && raw[key] !== null) return raw[key]
643
+ }
644
+ return undefined
645
+ }
646
+
647
+ function summarizePrimitive(raw) {
648
+ if (raw === null || typeof raw !== 'object') return { value: raw }
649
+ const summary = {}
650
+ const primitiveId = pickValue(raw, 'PrimitiveId', 'primitiveId', '$id')
651
+ const primitiveType = pickValue(raw, 'PrimitiveType', 'primitiveType')
652
+ const x = pickValue(raw, 'X', 'x', 'CenterX', 'centerX', 'StartX', 'startX')
653
+ const y = pickValue(raw, 'Y', 'y', 'CenterY', 'centerY', 'StartY', 'startY')
654
+ const rotation = pickValue(raw, 'Rotation', 'rotation')
655
+ if (primitiveId !== undefined) summary.primitiveId = primitiveId
656
+ if (primitiveType !== undefined) summary.primitiveType = primitiveType
657
+ if (x !== undefined) summary.x = x
658
+ if (y !== undefined) summary.y = y
659
+ if (rotation !== undefined) summary.rotation = rotation
660
+ for (const key of ['Designator', 'Name', 'Content', 'Net', 'ComponentType', 'Layer', 'LayerId']) {
661
+ const value = raw[key]
662
+ if (value !== undefined) summary[key.charAt(0).toLowerCase() + key.slice(1)] = value
663
+ }
664
+ const other = raw.OtherProperty ?? raw.otherProperty
665
+ if (other !== undefined) summary.otherProperty = other
666
+ const value = (other && (other.Value ?? other.value)) ?? raw.Value
667
+ if (value !== undefined) summary.value = value
668
+ return summary
669
+ }
670
+
671
+ async function mapLimit(items, limit, fn) {
672
+ const results = new Array(items.length)
673
+ let cursor = 0
674
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
675
+ for (;;) {
676
+ const index = cursor++
677
+ if (index >= items.length) return
678
+ results[index] = await fn(items[index], index)
679
+ }
680
+ })
681
+ await Promise.all(workers)
682
+ return results
683
+ }
684
+
685
+ function extractPrimitiveId(result) {
686
+ if (result === null || typeof result !== 'object') return undefined
687
+ return pickValue(result, 'PrimitiveId', 'primitiveId')
688
+ }
689
+
690
+ async function bboxOf(primitiveIds, timeoutMs) {
691
+ if (primitiveIds.length === 0) return undefined
692
+ const raw = await callExtension('sch_Primitive.getPrimitivesBBox', [primitiveIds], timeoutMs)
693
+ if (raw === null || typeof raw !== 'object') return undefined
694
+ const minX = Number(raw.minX)
695
+ const minY = Number(raw.minY)
696
+ const maxX = Number(raw.maxX)
697
+ const maxY = Number(raw.maxY)
698
+ if (![minX, minY, maxX, maxY].every(Number.isFinite)) return undefined
699
+ return { minX, minY, maxX, maxY }
700
+ }
701
+
702
+ const PCB_LAYERS = {
703
+ top: 1, bottom: 2, topSilkscreen: 3, bottomSilkscreen: 4,
704
+ topSolderMask: 5, bottomSolderMask: 6, topPasteMask: 7, bottomPasteMask: 8,
705
+ topAssembly: 9, bottomAssembly: 10, boardOutline: 11, multi: 12, document: 13, mechanical: 14,
706
+ }
707
+
708
+ function resolvePcbLayer(value) {
709
+ if (typeof value === 'number' && Number.isFinite(value)) return value
710
+ if (typeof value === 'string') {
711
+ const key = value.trim()
712
+ if (/^[0-9]+$/.test(key)) return Number(key)
713
+ const lower = key.charAt(0).toLowerCase() + key.slice(1)
714
+ if (PCB_LAYERS[lower] !== undefined) return PCB_LAYERS[lower]
715
+ const upper = key.toUpperCase()
716
+ if (upper === 'TOP') return 1
717
+ if (upper === 'BOTTOM') return 2
718
+ if (upper === 'BOARD_OUTLINE') return 11
719
+ }
720
+ return undefined
721
+ }
722
+
723
+ const PCB_TOOL_ALIASES = {
724
+ eda_pcb_get_components: 'pcb_get_components',
725
+ eda_pcb_get_nets: 'pcb_get_nets',
726
+ eda_pcb_get_layers: 'pcb_get_layers',
727
+ eda_pcb_place_component: 'pcb_place_component',
728
+ eda_pcb_draw_track: 'pcb_draw_track',
729
+ eda_pcb_draw_via: 'pcb_draw_via',
730
+ eda_pcb_save_document: 'pcb_save_document',
731
+ eda_pcb_import_changes: 'pcb_import_changes',
732
+ eda_pcb_get_primitives_in_region: 'pcb_get_primitives_in_region',
733
+ eda_pcb_navigate_to_region: 'pcb_navigate_to_region',
734
+ eda_pcb_draw_board_outline: 'pcb_draw_board_outline',
735
+ }
736
+
737
+ // TPCB_LayersOfRegion = copper layer | MULTI(12). The board-outline layer (11)
738
+ // and the silkscreen/mechanical layers are not valid region layers.
739
+ function isRegionLayer(layer) {
740
+ return layer === 1 || layer === 2 || layer === 12 || (layer >= 15 && layer <= 44)
741
+ }
742
+
743
+ function resolveRegionLayer(value, tool) {
744
+ const layer = resolvePcbLayer(value)
745
+ if (layer === undefined) throw new Error(tool + ' requires a valid layer')
746
+ if (!isRegionLayer(layer)) {
747
+ throw new Error(tool + ': layer ' + layer + ' cannot hold a region (official type TPCB_LayersOfRegion = copper top/bottom/inner(15-44) | MULTI(12))')
748
+ }
749
+ return layer
750
+ }
751
+
752
+ // TPCB_PolygonSourceArray: [x1, y1, 'L', x2, y2, x3, y3, ...]; the first and
753
+ // last point are joined automatically, so the closing point must not repeat.
754
+ /** Netlist as a parsed object, for tools that inspect it (eda_netlist_erc). */
755
+ /** Serialized design brief inside the project description, so it survives a session. */
756
+ const BRIEF_TAG = '[dsh-eda-spec]'
757
+ function briefBlock(brief) {
758
+ return BRIEF_TAG + ' ' + JSON.stringify(brief)
759
+ }
760
+ /** Sidecar file for the design brief, next to a local project directory. */
761
+ function specFilePath(project) {
762
+ const dir = String(project?.teamUuid ?? '')
763
+ const uuid = String(project?.uuid ?? '')
764
+ if (dir === '' || uuid === '') return ''
765
+ if (!/^[A-Za-z]:[\\/]/.test(dir) && !dir.startsWith('/')) return ''
766
+ return join(dir, '.dsh-eda-spec', uuid + '.json')
767
+ }
768
+
769
+ function parseBriefBlock(description) {
770
+ const text = typeof description === 'string' ? description : ''
771
+ const index = text.indexOf(BRIEF_TAG)
772
+ if (index < 0) return null
773
+ const body = text.slice(index + BRIEF_TAG.length).trim()
774
+ const close = body.indexOf('}')
775
+ try {
776
+ const parsed = JSON.parse(close < 0 ? body : body.slice(0, close + 1))
777
+ return parsed !== null && typeof parsed === 'object' ? parsed : null
778
+ } catch { return null }
779
+ }
780
+
781
+ async function fetchParsedNetlist(timeoutMs) {
782
+ const payload = await callExtension('sch_ManufactureData.getNetlistFile', [undefined, undefined], timeoutMs)
783
+ const text = typeof payload === 'string'
784
+ ? payload
785
+ : (payload !== null && typeof payload === 'object' && typeof payload.text === 'string' ? payload.text : undefined)
786
+ if (text === undefined) return null
787
+ try { return JSON.parse(text) } catch { return null }
788
+ }
789
+
790
+ function buildPolygonSource(points) {
791
+ const source = [points[0], points[1], 'L']
792
+ for (let i = 2; i < points.length; i += 2) source.push(points[i], points[i + 1])
793
+ return source
794
+ }
795
+
796
+
797
+ /**
798
+ * Directory that holds the packaged artifacts: the bridge runs from <package>/lib/bridge.mjs,
799
+ * so its grandparent is the package root both for a published install and for the repo.
800
+ */
801
+ function packageRoot(): string {
802
+ return fileURLToPath(new URL('../', import.meta.url))
803
+ }
804
+
805
+ function requireFlatPoints(value, tool) {
806
+ const points = flattenPoints(value)
807
+ if (points.length < 6 || points.length % 2 !== 0 || !points.every(Number.isFinite)) {
808
+ throw new Error(tool + ': points must be a flat array of finite numbers shaped [x1,y1,x2,y2,...] with at least 3 points')
809
+ }
810
+ if (points.length >= 8 && points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) {
811
+ points.length -= 2
812
+ }
813
+ return points
814
+ }
815
+
816
+ /** EDA pin rotation -> outward direction (0=+x right, 90=+y up, 180=-x, 270=-y). */
817
+ function pinDirection(rotation) {
818
+ const normalized = ((Math.round(Number(rotation) / 90) * 90) % 360 + 360) % 360
819
+ if (normalized === 90) return { dx: 0, dy: 1 }
820
+ if (normalized === 180) return { dx: -1, dy: 0 }
821
+ if (normalized === 270) return { dx: 0, dy: -1 }
822
+ return { dx: 1, dy: 0 }
823
+ }
824
+
825
+ const DOCUMENT_TYPES = {
826
+ '-1': 'HOME', 0: 'BLANK', 1: 'SCHEMATIC_PAGE', 2: 'SYMBOL_COMPONENT', 3: 'PCB', 5: 'PROJECT',
827
+ 12: 'PCB_2D_PREVIEW', 15: 'PCB_3D_PREVIEW', 18: 'SYMBOL_NET_FLAG', 19: 'SYMBOL_NET_PORT',
828
+ 20: 'SYMBOL_DRAWING', 21: 'SYMBOL_NON_ELECTRICAL', 26: 'PANEL', 27: 'PANEL_3D_PREVIEW',
829
+ }
830
+
831
+ /**
832
+ * Place a net label. sch_PrimitiveAttribute.createNetLabel is the real net-label
833
+ * primitive (it participates in the netlist) but it is documented as "ADD since
834
+ * EDA v4", so older builds are handled with a plain text label fallback.
835
+ */
836
+ const NET_EMPTY_HINT = 'sch_Net.* returned no nets. Those APIs only report the ACTIVE document, so the schematic page must be the active tab: call eda_get_active_document, then eda_open_document with the schematic page uuid (eda_get_schematic_pages) and retry.'
837
+
838
+ /** Fallback for tab-dependent sch_Net APIs: parse the project netlist text. */
839
+ /**
840
+ * Bounded-batch routing removal used when the connected EDA extension has no
841
+ * background-job helper: one call deletes at most batchSize primitives, so the
842
+ * MCP call always returns well inside the tool timeout and the caller loops.
843
+ */
844
+ /** Read a PCB primitive list, turning the tab-dependent null failure into a clear error. */
845
+ async function pcbPrimitiveList(method, callArgs, timeoutMs) {
846
+ try {
847
+ const raw = await callExtension(method, callArgs, timeoutMs)
848
+ return Array.isArray(raw) ? raw : []
849
+ } catch (error) {
850
+ const message = error instanceof Error ? error.message : String(error)
851
+ if (/null|undefined|map/i.test(message)) {
852
+ throw new Error('PCB primitives could not be read (' + message + '). The PCB document is probably not the active tab: bring the PCB page to the front (eda_get_active_document / eda_open_document) and retry.')
853
+ }
854
+ throw error
855
+ }
856
+ }
857
+
858
+ /**
859
+ * Audit the active PCB against `docs/design-rules.md`. Read-only: it never edits
860
+ * the board, it reports what a reviewer would flag and what the tool defaults
861
+ * would have produced.
862
+ */
863
+ async function auditPcb(args, timeoutMs) {
864
+ const netFilter = args.net === undefined ? undefined : String(args.net)
865
+ const tracks = await pcbPrimitiveList('pcb_PrimitiveLine.getAll', [netFilter, undefined, undefined], timeoutMs)
866
+ const vias = await pcbPrimitiveList('pcb_PrimitiveVia.getAll', [netFilter, undefined], timeoutMs)
867
+ const pours = await pcbPrimitiveList('pcb_PrimitivePour.getAll', [netFilter, undefined, undefined], timeoutMs)
868
+ const outline = await pcbPrimitiveList('pcb_PrimitivePolyline.getAll', [undefined, PCB_LAYERS.boardOutline, undefined], timeoutMs)
869
+ // Same call shape as pcb_get_components: with a bare [undefined, undefined] the app
870
+ // returns an empty list here, which silently disabled the mechanical checks below.
871
+ const pcbComponents = await callExtension('pcb_PrimitiveComponent.getAll', [resolvePcbLayer(undefined), undefined], timeoutMs)
872
+ .then((raw) => (Array.isArray(raw) ? raw : []))
873
+ .catch(() => [])
874
+
875
+ const violations = []
876
+ const warnings = []
877
+ const add = (bucket, rule, message, samples) => {
878
+ const entry = bucket.find(item => item.rule === rule)
879
+ if (entry === undefined) bucket.push({ rule, message, count: 1, samples: samples.slice(0, 5) })
880
+ else { entry.count += 1; if (entry.samples.length < 5) entry.samples.push(samples[0]) }
881
+ }
882
+
883
+ // §5.1 track width per net role
884
+ const widthByNet = new Map()
885
+ for (const track of tracks) {
886
+ const record = asRecord(track)
887
+ const net = String(pickValue(record, 'Net', 'net') ?? '')
888
+ const width = Number(pickValue(record, 'LineWidth', 'lineWidth'))
889
+ if (!Number.isFinite(width) || width <= 0) continue
890
+ const seen = widthByNet.get(net)
891
+ if (seen === undefined || width < seen) widthByNet.set(net, width)
892
+ const check = checkTrackWidth(net, width, false)
893
+ if (!check.ok) add(violations, 'track-width-min', check.errors.join('; '), [pickValue(record, 'PrimitiveId', 'primitiveId')])
894
+ else if (check.warnings.length > 0) add(warnings, 'track-width-role', check.warnings.join('; '), [pickValue(record, 'PrimitiveId', 'primitiveId')])
895
+ }
896
+
897
+ // §5.2 via drill / annular ring
898
+ for (const via of vias) {
899
+ const record = asRecord(via)
900
+ const net = String(pickValue(record, 'Net', 'net') ?? '')
901
+ const hole = Number(pickValue(record, 'HoleDiameter', 'holeDiameter'))
902
+ const pad = Number(pickValue(record, 'Diameter', 'diameter'))
903
+ if (!Number.isFinite(hole) || !Number.isFinite(pad)) continue
904
+ const check = checkVia(net, hole, pad, false)
905
+ if (!check.ok) add(violations, 'via-geometry', check.errors.join('; '), [pickValue(record, 'PrimitiveId', 'primitiveId')])
906
+ else if (check.warnings.length > 0) add(warnings, 'via-standard', check.warnings.join('; '), [pickValue(record, 'PrimitiveId', 'primitiveId')])
907
+ }
908
+
909
+ // §2.1 net naming
910
+ let netNames = []
911
+ try { netNames = await callExtension('pcb_Net.getAllNetsName', [], timeoutMs) } catch { netNames = [] }
912
+ if (!Array.isArray(netNames)) netNames = []
913
+ for (const name of netNames) {
914
+ const text = String(name)
915
+ const check = checkNetName(text)
916
+ if (!check.ok) add(violations, 'net-name', check.errors.join('; '), [text])
917
+ else if (check.warnings.length > 0) add(warnings, 'net-name-style', check.warnings.join('; '), [text])
918
+ }
919
+
920
+ // §7.2 board outline, §5.4 copper pour
921
+ if (outline.length === 0) violations.push({ rule: 'board-outline', message: 'No board outline on layer 11: auto-routing and Gerber export need a closed outline (pcb_draw_board_outline)', count: 1, samples: [] })
922
+ if (pours.length === 0) warnings.push({ rule: 'copper-pour', message: 'No copper pour: a GND pour on the top/bottom layer is the recommended way to carry ground (eda_pcb_create_pour)', count: 1, samples: [] })
923
+
924
+ // Reference practice (measured on the official JLCEDA example board: 19 silkscreen
925
+ // strings, a copper pour, no thin 6 mil traces). Board identity/fab text and
926
+ // mounting holes are cheap and always expected on a real board.
927
+ try {
928
+ const silk = await callExtension('pcb_PrimitiveString.getAll', [PCB_LAYERS.topSilkscreen], timeoutMs)
929
+ const silkCount = Array.isArray(silk) ? silk.length : 0
930
+ if (silkCount === 0) {
931
+ warnings.push({ rule: 'silkscreen-text', message: 'No silkscreen text primitive: the official example board carries 19 (function labels, version, fab notes). Add board identity and pin functions with pcb_draw_text.' })
932
+ }
933
+ } catch {
934
+ // A missing read is not a design defect; skip silently.
935
+ }
936
+ try {
937
+ const pads = await callExtension('pcb_PrimitivePad.getAll', [PCB_LAYERS.multi], timeoutMs)
938
+ const holes = (Array.isArray(pads) ? pads : []).filter((pad) => (pad?.metallization ?? pad?.Metallization) === false)
939
+ // pcb_PrimitivePolyline.getAll items carry { polygon: { polygon: [x,y,'L',...] } }, so the
940
+ // width has to be read from the flat source array (a point-object version never existed).
941
+ const flatX = []
942
+ for (const entry of outline) {
943
+ const source = entry?.polygon?.polygon ?? entry?.Polygon?.polygon ?? []
944
+ for (let i = 0; i + 1 < source.length; i += 2) {
945
+ if (typeof source[i] === 'number') flatX.push(source[i])
946
+ }
947
+ }
948
+ const wide = flatX.length > 0 ? Math.max(...flatX) - Math.min(...flatX) : 0
949
+ if (holes.length === 0 && wide > 1200) {
950
+ warnings.push({ rule: 'mounting-hole', message: 'No non-plated mounting hole on a board wider than 1200 mil: use pcb_draw_mounting_hole (3.2 mm) in the corners.' })
951
+ }
952
+ } catch {
953
+ // Same: optional read.
954
+ }
955
+
956
+ // §5.5 mechanical sanity: overlapping bodies, parts hanging off the board, and
957
+ // mounting holes punched through copper or a component.
958
+ const boundsOfComponent = (entry) => {
959
+ const x = Number(entry?.x ?? entry?.X)
960
+ const y = Number(entry?.y ?? entry?.Y)
961
+ const w = Number(entry?.width ?? entry?.Width)
962
+ const h = Number(entry?.height ?? entry?.Height)
963
+ if (![x, y, w, h].every(Number.isFinite) || w <= 0 || h <= 0) return undefined
964
+ return { left: x - w / 2, right: x + w / 2, bottom: y - h / 2, top: y + h / 2 }
965
+ }
966
+ const bodies = pcbComponents.map((entry) => ({
967
+ name: String(entry?.designator ?? entry?.Designator ?? entry?.primitiveId ?? '?'),
968
+ bounds: boundsOfComponent(entry),
969
+ })).filter((entry) => entry.bounds !== undefined)
970
+ if (bodies.length >= 2) {
971
+ for (let i = 0; i < bodies.length; i++) {
972
+ for (let j = i + 1; j < bodies.length; j++) {
973
+ const a = bodies[i].bounds
974
+ const b = bodies[j].bounds
975
+ const sharedX = Math.min(a.right, b.right) - Math.max(a.left, b.left)
976
+ const sharedY = Math.min(a.top, b.top) - Math.max(a.bottom, b.bottom)
977
+ if (sharedX > 2 && sharedY > 2) add(violations, 'component-overlap', 'Two component bodies overlap; a placement collision here becomes a placement error at assembly.', [bodies[i].name + ' x ' + bodies[j].name])
978
+ }
979
+ }
980
+ }
981
+ const outlineX = []
982
+ const outlineY = []
983
+ for (const entry of outline) {
984
+ const source = entry?.polygon?.polygon ?? entry?.Polygon?.polygon ?? []
985
+ for (let i = 0; i + 1 < source.length; i += 2) {
986
+ if (typeof source[i] === 'number') { outlineX.push(source[i]); outlineY.push(source[i + 1]) }
987
+ }
988
+ }
989
+ if (bodies.length > 0 && outlineX.length >= 3) {
990
+ const box = { left: Math.min(...outlineX), right: Math.max(...outlineX), bottom: Math.min(...outlineY), top: Math.max(...outlineY) }
991
+ for (const body of bodies) {
992
+ const b = body.bounds
993
+ if (b.left < box.left - 5 || b.right > box.right + 5 || b.bottom < box.bottom - 5 || b.top > box.top + 5) {
994
+ add(warnings, 'component-off-board', 'A component body extends past the board outline; on a real assembly it either hangs in the air or collides with the enclosure.', [body.name])
995
+ }
996
+ }
997
+ }
998
+
999
+ // §6.3 DRC
1000
+ let drc = { ran: false, reason: null, violationCount: null }
1001
+ if (args.drc !== false) {
1002
+ try {
1003
+ const outcome = await callExtension('pcb_Drc.check', [true, false, true], toolTimeout(args, timeoutMs))
1004
+ drc = { ran: true, reason: null, violationCount: Array.isArray(outcome) ? outcome.length : (outcome === true ? 0 : null) }
1005
+ } catch (error) {
1006
+ drc = { ran: false, reason: error instanceof Error ? error.message : String(error), violationCount: null }
1007
+ }
1008
+ }
1009
+ if (drc.ran && drc.violationCount !== null && drc.violationCount > 0) {
1010
+ violations.push({ rule: 'drc', message: `PCB DRC reports ${drc.violationCount} violation(s)`, count: drc.violationCount, samples: [] })
1011
+ }
1012
+
1013
+ const checklist = [
1014
+ { item: '板框存在(层 11 闭合折线)', status: outline.length > 0 ? 'pass' : 'fail' },
1015
+ { item: '走线宽度 ≥ ' + MIN_TRACK_WIDTH_MIL + ' mil(0.15 mm)', status: violations.some(item => item.rule === 'track-width-min') ? 'fail' : 'pass' },
1016
+ { item: '过孔孔径/焊环合规(≥' + VIA_HOLE_MIN_MM + ' mm 建议,焊环 ≥' + ANNULUS_MIN_MM + ' mm)', status: violations.some(item => item.rule === 'via-geometry') ? 'fail' : 'pass' },
1017
+ { item: '网络名仅含可解析字符', status: violations.some(item => item.rule === 'net-name') ? 'fail' : 'pass' },
1018
+ { item: 'GND 铺铜', status: pours.length > 0 ? 'pass' : 'warn' },
1019
+ { item: 'PCB DRC', status: drc.violationCount === 0 ? 'pass' : (drc.violationCount === null ? 'unknown' : 'fail') },
1020
+ ]
1021
+
1022
+ return {
1023
+ ok: violations.length === 0,
1024
+ counts: { tracks: tracks.length, vias: vias.length, pours: pours.length, outlinePolylines: outline.length, nets: netNames.length, componentsRead: pcbComponents.length },
1025
+ minWidthByNet: Object.fromEntries([...widthByNet.entries()].map(([net, width]) => [net, { widthMil: width, role: classifyNet(net), suggestedMil: suggestTrackWidthMil(net) }])),
1026
+ violations, warnings, checklist, drc,
1027
+ rules: {
1028
+ minTrackMil: MIN_TRACK_WIDTH_MIL,
1029
+ trackWidthTiers: TRACK_WIDTH_MIL,
1030
+ viaSizesMm: VIA_SIZES_MM,
1031
+ viaHoleMinMm: VIA_HOLE_MIN_MM,
1032
+ annulusMinMm: ANNULUS_MIN_MM,
1033
+ pourClearanceMil: { required: POUR_CLEARANCE_MIN_MIL, recommended: POUR_CLEARANCE_RECOMMENDED_MIL },
1034
+ silkscreenMinMm: { height: SILKSCREEN_HEIGHT_MIN_MM, width: SILKSCREEN_WIDTH_MIN_MM },
1035
+ boardOutlineWidthMil: BOARD_OUTLINE_WIDTH_MIL,
1036
+ },
1037
+ }
1038
+ }
1039
+
1040
+ /**
1041
+ * Real probe for `resolveExecutable`: filesystem existence plus `reg query`.
1042
+ * Kept separate from the pure resolver so the resolution order stays testable.
1043
+ */
1044
+ function launchProbe() {
1045
+ const cache = new Map()
1046
+ return {
1047
+ platform: process.platform,
1048
+ env: process.env,
1049
+ exists(path) {
1050
+ try { return statSync(path).isFile() } catch { return false }
1051
+ },
1052
+ registryQuery(key, valueName) {
1053
+ if (process.platform !== 'win32') return undefined
1054
+ // `undefined` (list every value) and `''` (the default value) are different
1055
+ // queries and must not share a cache entry.
1056
+ const cacheKey = key + '|' + (valueName === undefined ? 'LIST' : (valueName === '' ? 'DEFAULT' : 'V:' + valueName))
1057
+ if (cache.has(cacheKey)) return cache.get(cacheKey)
1058
+ let output
1059
+ try {
1060
+ // `reg query <key>` alone prints only the default value, so listing a key
1061
+ // (valueName undefined) needs `/s`; a single value uses `/v`, and the
1062
+ // default value uses `/ve`.
1063
+ const extra = valueName === undefined ? ['/s'] : (valueName === '' ? ['/ve'] : ['/v', valueName])
1064
+ const raw = execFileSync('reg', ['query', key, ...extra], {
1065
+ timeout: 5000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'],
1066
+ })
1067
+ output = decodeRegistryOutput(raw)
1068
+ } catch {
1069
+ output = undefined
1070
+ }
1071
+ cache.set(cacheKey, output)
1072
+ return output
1073
+ },
1074
+ }
1075
+ }
1076
+
1077
+ /** How many processes currently run that image name (Windows tasklist). */
1078
+ function processCountByName(imageName) {
1079
+ if (process.platform !== 'win32') {
1080
+ // pgrep exits non-zero when nothing matches, which is the "closed" case.
1081
+ try {
1082
+ const out = execFileSync('pgrep', ['-f', imageName], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })
1083
+ return out.split(/\r?\n/).filter(line => line.trim() !== '').length
1084
+ } catch {
1085
+ return 0
1086
+ }
1087
+ }
1088
+ try {
1089
+ const out = execFileSync('tasklist', ['/FI', 'IMAGENAME eq ' + imageName, '/FO', 'CSV', '/NH'], {
1090
+ encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'],
1091
+ })
1092
+ return out.split(/\r?\n/).filter(line => line.trim().startsWith('"')).length
1093
+ } catch {
1094
+ return 0
1095
+ }
1096
+ }
1097
+
1098
+ /** Ask the app to close (/T closes the renderer children too); force kills it. */
1099
+ function terminateByName(imageName, force) {
1100
+ if (process.platform === 'win32') {
1101
+ execFileSync('taskkill', ['/IM', imageName, '/T'].concat(force ? ['/F'] : []), {
1102
+ timeout: 10000, stdio: ['ignore', 'ignore', 'ignore'],
1103
+ })
1104
+ return
1105
+ }
1106
+ execFileSync('pkill', [force ? '-9' : '-TERM', '-f', imageName], { timeout: 10000, stdio: ['ignore', 'ignore', 'ignore'] })
1107
+ }
1108
+
1109
+ /** Wait (bounded) until at least one EDA extension reports ready. */
1110
+ async function waitForExtensionConnection(timeoutMs) {
1111
+ const started = Date.now()
1112
+ const readyCount = () => pickClients().length
1113
+ while (Date.now() - started < timeoutMs) {
1114
+ if (readyCount() > 0) return { connected: true, clients: readyCount(), waitedMs: Date.now() - started }
1115
+ await new Promise(resolve => setTimeout(resolve, 500))
1116
+ }
1117
+ return { connected: false, clients: readyCount(), waitedMs: Date.now() - started }
1118
+ }
1119
+
1120
+ async function clearRoutingBatched(args, type, timeoutMs) {
1121
+ if (type === 'connection') throw new Error('eda_pcb_clear_routing: type=connection needs the EDA user interface; use type=all/net with mode=batched')
1122
+ const net = args.net === undefined ? undefined : String(args.net)
1123
+ const layer = args.layer === undefined ? undefined : resolvePcbLayer(args.layer)
1124
+ if (args.layer !== undefined && layer === undefined) throw new Error('eda_pcb_clear_routing: invalid layer ' + String(args.layer))
1125
+ const batchSize = Math.max(1, Math.min(2000, Number(args.batchSize ?? 200) || 200))
1126
+ const tracks = await pcbPrimitiveList('pcb_PrimitiveLine.getAll', [net, layer, undefined], timeoutMs)
1127
+ const vias = await pcbPrimitiveList('pcb_PrimitiveVia.getAll', [net, undefined], timeoutMs)
1128
+ const trackIds = (Array.isArray(tracks) ? tracks : []).map(item => pickValue(asRecord(item), 'PrimitiveId', 'primitiveId')).filter(id => typeof id === 'string')
1129
+ const viaIds = (Array.isArray(vias) ? vias : []).map(item => pickValue(asRecord(item), 'PrimitiveId', 'primitiveId')).filter(id => typeof id === 'string')
1130
+ const batch = [...trackIds.map(id => ({ kind: 'track', id })), ...viaIds.map(id => ({ kind: 'via', id }))].slice(0, batchSize)
1131
+ let deleted = 0
1132
+ const failed = []
1133
+ for (const item of batch) {
1134
+ try {
1135
+ await callExtension(item.kind === 'track' ? 'pcb_PrimitiveLine.delete' : 'pcb_PrimitiveVia.delete', [item.id], timeoutMs)
1136
+ deleted += 1
1137
+ } catch (error) {
1138
+ failed.push({ primitiveId: item.id, error: error instanceof Error ? error.message : String(error) })
1139
+ }
1140
+ }
1141
+ const remaining = trackIds.length + viaIds.length - deleted
1142
+ return {
1143
+ mode: 'batched', type, net: net ?? null, layer: layer ?? null, batchSize,
1144
+ matched: trackIds.length + viaIds.length, deleted, remaining, done: remaining <= 0, failed,
1145
+ hint: remaining <= 0 ? 'Routing cleared.' : 'Call eda_pcb_clear_routing again (same arguments) until done=true.',
1146
+ }
1147
+ }
1148
+
1149
+ async function parseNetlist(previous, timeoutMs) {
1150
+ let text
1151
+ try {
1152
+ text = await callExtension('sch_Netlist.getNetlist', [undefined], timeoutMs)
1153
+ } catch (error) {
1154
+ return { source: 'sch_Net.*', count: Array.isArray(previous) ? previous.length : 0, nets: previous, hint: NET_EMPTY_HINT, netlistError: error instanceof Error ? error.message : String(error) }
1155
+ }
1156
+ if (typeof text !== 'string' || text.trim() === '') {
1157
+ return { source: 'sch_Net.*', count: Array.isArray(previous) ? previous.length : 0, nets: previous, hint: NET_EMPTY_HINT }
1158
+ }
1159
+ const byNet = new Map()
1160
+ // JLCEDA netlist lines look like: NET "GND" (R1.2 U3.1 ...)
1161
+ for (const match of text.matchAll(/NET\s+"?([^"\s()]+)"?\s*\(([^)]*)\)/gi)) {
1162
+ const name = match[1]
1163
+ const pins = match[2].split(/\s+/).map(part => part.trim()).filter(part => part !== '')
1164
+ const existing = byNet.get(name)
1165
+ if (existing === undefined) byNet.set(name, pins)
1166
+ else byNet.set(name, [...new Set([...existing, ...pins])])
1167
+ }
1168
+ const nets = [...byNet.entries()].map(([net, pins]) => ({ net, pins, pinCount: pins.length }))
1169
+ return { source: 'sch_Netlist.getNetlist', count: nets.length, nets, netlistBytes: text.length }
1170
+ }
1171
+
1172
+ async function placeNetLabel(net, x, y, fontSize, timeoutMs, options = {}) {
1173
+ if (net === '' || net === 'undefined') throw new Error('a net name is required')
1174
+ assertNetName(String(net), 'eda_place_net_label')
1175
+ const size = fontSize === undefined ? 12 : Number(fontSize)
1176
+ if (options.probe === true) netLabelSupport = null
1177
+ let failure = null
1178
+ // The capability is probed ONCE per session: on JLCEDA Pro 3.2.186 createNetLabel
1179
+ // exists but never resolves, and paying the 4s timeout for every one of hundreds
1180
+ // of labels is what turned a 133-label run into 15 minutes.
1181
+ if (netLabelSupport !== false) {
1182
+ try {
1183
+ const raw = await callExtension('sch_PrimitiveAttribute.createNetLabel', [x, y, net], Math.min(timeoutMs, 4000))
1184
+ if (raw === undefined || raw === null) throw new Error('createNetLabel returned nothing')
1185
+ netLabelSupport = true
1186
+ return { method: 'netLabel', net, x, y, label: summarizePrimitive(raw) }
1187
+ } catch (error) {
1188
+ const message = error instanceof Error ? error.message : String(error)
1189
+ if (!/not found|not available|not allowed|timed out|timeout|nothing|undefined/i.test(message)) throw error
1190
+ failure = message
1191
+ netLabelSupport = false
1192
+ }
1193
+ }
1194
+ // The stub wire (drawn by the *_at_pin callers) already carries the net; a text
1195
+ // label on top of it is pure clutter, so it is opt-in.
1196
+ if (options.textLabel !== true) {
1197
+ return { method: 'stub', net, x, y, created: false, warning: 'createNetLabel is unavailable on this EDA build (' + (failure ?? 'probe already failed this session') + '); the net is carried by the stub wire, and no text label was added (pass textLabel:true if you want one).' }
1198
+ }
1199
+ const raw = await callExtension('sch_PrimitiveText.create', [x, y, net, 0, null, null, size, false, false, false, 1], timeoutMs)
1200
+ const label = summarizePrimitive(raw)
1201
+ if (label.primitiveId !== undefined) {
1202
+ placedTextLabels.push({ net: String(net), x, y, primitiveId: label.primitiveId })
1203
+ if (placedTextLabels.length > 2000) placedTextLabels.shift()
1204
+ }
1205
+ return {
1206
+ method: 'text', net, x, y, created: label.primitiveId !== undefined,
1207
+ warning: 'createNetLabel is unavailable on this EDA build (' + (failure ?? 'probe already failed this session') +
1208
+ '), so a plain TEXT label was placed: it carries no electrical meaning. The stub wire drawn by the caller is what joins the net; eda_get_net_labels lists these texts by name and id.',
1209
+ ...(label.primitiveId === undefined
1210
+ ? { hint: 'No label primitive was created: the schematic page must be the ACTIVE document (sch_PrimitiveText.create is tab-dependent). Use eda_get_active_document / eda_open_document, then retry.' }
1211
+ : {}),
1212
+ label,
1213
+ }
1214
+ }
1215
+
1216
+ /** Place a net flag or net label at a pin, pushing it outwards with a stub wire. */
1217
+ async function placeAtPin(toolName, args, timeoutMs) {
1218
+ const pinPrimitiveId = String(args.pinPrimitiveId ?? '')
1219
+ if (pinPrimitiveId === '') throw new Error('pinPrimitiveId is required')
1220
+ const isFlag = toolName === 'eda_place_net_flag_at_pin'
1221
+ assertNetName(String(args.net ?? ''), toolName)
1222
+ const pin = await callExtension('sch_PrimitivePin.get', [pinPrimitiveId], timeoutMs)
1223
+ const pinRecord = asRecord(pin)
1224
+ const pinX = Number(pickValue(pinRecord, 'X', 'x'))
1225
+ const pinY = Number(pickValue(pinRecord, 'Y', 'y'))
1226
+ if (!Number.isFinite(pinX) || !Number.isFinite(pinY)) throw new Error('could not read pin position for ' + pinPrimitiveId)
1227
+ const pinRotation = Number(pickValue(pinRecord, 'Rotation', 'rotation') ?? 0)
1228
+ const direction = pinDirection(pinRotation)
1229
+ const explicitOffset = args.offsetX !== undefined || args.offsetY !== undefined
1230
+ // Placing a flag/label exactly ON the pin covers the symbol. Default: push it
1231
+ // outwards along the pin direction and keep connectivity with a short stub wire.
1232
+ const stubLength = args.stubLength === undefined
1233
+ ? (explicitOffset ? 0 : 20)
1234
+ : Math.max(0, Number(args.stubLength))
1235
+ const x = pinX + direction.dx * stubLength + Number(args.offsetX ?? 0)
1236
+ const y = pinY + direction.dy * stubLength + Number(args.offsetY ?? 0)
1237
+ if (args.allowOutsideFrame !== true) {
1238
+ const problem = checkPointInFrame(x, y, args.paper, 5) ?? checkPointAgainstTitleBlock(x, y, args.paper, 5)
1239
+ if (problem !== undefined) {
1240
+ throw new Error(toolName + ' refused: ' + problem + ' - reduce stubLength or pass offsetX/offsetY to place it elsewhere.')
1241
+ }
1242
+ }
1243
+ let stub
1244
+ if (stubLength > 0 && typeof args.net === 'string' && args.net !== '') {
1245
+ stub = summarizePrimitive(await callExtension('sch_PrimitiveWire.create', [
1246
+ [pinX, pinY, x, y], String(args.net), args.color === undefined ? undefined : String(args.color),
1247
+ args.lineWidth === undefined ? undefined : Number(args.lineWidth), args.lineType === undefined ? undefined : Number(args.lineType),
1248
+ ], timeoutMs))
1249
+ }
1250
+ const placement = { pin: { primitiveId: pinPrimitiveId, x: pinX, y: pinY, rotation: pinRotation }, direction, stubLength, x, y, stub }
1251
+ if (isFlag) {
1252
+ const flag = await callExtension('sch_PrimitiveComponent.createNetFlag', [
1253
+ String(args.identification), String(args.net), x, y,
1254
+ args.rotation === undefined ? pinRotation : Number(args.rotation), Boolean(args.mirror ?? false),
1255
+ ], timeoutMs)
1256
+ return { ...placement, flag: summarizePrimitive(flag) }
1257
+ }
1258
+ const label = await placeNetLabel(String(args.net), x, y, args.fontSize, timeoutMs)
1259
+ return { ...label, ...placement }
1260
+ }
1261
+
1262
+ /**
1263
+ * True when the connected EDA extension build does not implement a dsh.internal.*
1264
+ * helper (older zip still imported). Callers then fall back to the synchronous API.
1265
+ */
1266
+ function isInternalHelperMissing(error) {
1267
+ const message = error instanceof Error ? error.message : String(error)
1268
+ if (/unsupported job kind/i.test(message)) return true
1269
+ return /not allowed|not found|not available/i.test(message) && /dsh\.internal|API method/i.test(message)
1270
+ }
1271
+
1272
+ /** Per-call timeout override for long operations (auto-routing, Gerber export, DRC). */
1273
+ function toolTimeout(args, fallback) {
1274
+ const value = Number(args.timeoutMs)
1275
+ return Number.isFinite(value) && value > 0 ? Math.max(value, fallback) : fallback
1276
+ }
1277
+
1278
+ function pickDefined(source, keys) {
1279
+ const out = {}
1280
+ for (const key of keys) {
1281
+ const value = source[key]
1282
+ if (value !== undefined && value !== null) out[key] = value
1283
+ }
1284
+ return out
1285
+ }
1286
+
1287
+ /** Resolve a project uuid from { uuid } or { name } (exact match first, then case-insensitive substring). */
1288
+ async function resolveProjectUuid(args, timeoutMs) {
1289
+ const direct = args.uuid === undefined ? '' : String(args.uuid).trim()
1290
+ if (direct !== '') return { uuid: direct, matched: null }
1291
+ const name = args.name === undefined ? '' : String(args.name).trim()
1292
+ if (name === '') throw new Error('provide uuid or name')
1293
+ const unfiltered = await callExtension('dmt_Project.getAllProjectsUuid', [], toolTimeout(args, timeoutMs))
1294
+ const candidates = Array.isArray(unfiltered) ? unfiltered.map(String) : []
1295
+ // Local directories are modelled as teams, so an unfiltered listing is empty;
1296
+ // collect every team's projects before giving up on the name.
1297
+ if (candidates.length === 0) {
1298
+ const teams = await callExtension('dmt_Team.getAllTeamsInfo', [], toolTimeout(args, timeoutMs)).catch(() => [])
1299
+ const seen = new Set()
1300
+ for (const team of Array.isArray(teams) ? teams : []) {
1301
+ const teamUuid = String(pickValue(asRecord(team), 'uuid', 'Uuid') ?? '')
1302
+ if (teamUuid === '') continue
1303
+ const owned = await callExtension('dmt_Project.getAllProjectsUuid', [teamUuid], toolTimeout(args, timeoutMs)).catch(() => [])
1304
+ for (const uuid of Array.isArray(owned) ? owned.map(String) : []) {
1305
+ if (seen.has(uuid)) continue
1306
+ seen.add(uuid)
1307
+ candidates.push(uuid)
1308
+ }
1309
+ }
1310
+ }
1311
+ const resolved = []
1312
+ for (const candidate of candidates) {
1313
+ try {
1314
+ const info = asRecord(await callExtension('dmt_Project.getProjectInfo', [candidate], toolTimeout(args, timeoutMs)))
1315
+ resolved.push({ uuid: candidate, friendly: String(pickValue(info, 'FriendlyName', 'friendlyName', 'Name', 'name') ?? '') })
1316
+ } catch {
1317
+ resolved.push({ uuid: candidate, friendly: '' })
1318
+ }
1319
+ }
1320
+ const matched = resolved.find(item => item.friendly === name)
1321
+ ?? resolved.find(item => item.friendly.toLowerCase().includes(name.toLowerCase()))
1322
+ ?? null
1323
+ if (matched === null) {
1324
+ throw new Error('no project matches "' + name + '"; known names: ' +
1325
+ resolved.map(item => item.friendly || item.uuid).slice(0, 20).join(', '))
1326
+ }
1327
+ return { uuid: matched.uuid, matched }
1328
+ }
1329
+
1330
+ /** Wait (bounded) until getCurrentProjectInfo reports the expected project uuid. */
1331
+ async function waitForActiveProject(uuid, timeoutMs = 4000) {
1332
+ const deadline = Date.now() + timeoutMs
1333
+ let lastActive = null
1334
+ for (;;) {
1335
+ try {
1336
+ const info = asRecord(await callExtension('dmt_Project.getCurrentProjectInfo', [], 3000))
1337
+ lastActive = String(pickValue(info, 'uuid', 'Uuid') ?? '') || null
1338
+ if (lastActive === uuid) return { active: true, project: info }
1339
+ } catch {
1340
+ // The app answers undefined while the project is switching.
1341
+ }
1342
+ if (Date.now() > deadline) return { active: false, project: null, lastActive }
1343
+ await sleep(400)
1344
+ }
1345
+ }
1346
+
1347
+ /** Collect the internal ids a project owns (schematic / page / pcb uuids). */
1348
+ function internalIdsOf(info) {
1349
+ const ids = new Set()
1350
+ const boards = Array.isArray(asRecord(info).data) ? asRecord(info).data : []
1351
+ for (const board of boards) {
1352
+ const record = asRecord(board)
1353
+ const boardUuid = String(pickValue(record, 'uuid', 'Uuid') ?? '')
1354
+ if (boardUuid !== '') ids.add(boardUuid)
1355
+ for (const docKey of ['schematic', 'pcb']) {
1356
+ const doc = asRecord(record[docKey])
1357
+ const docUuid = String(pickValue(doc, 'uuid', 'Uuid') ?? '')
1358
+ if (docUuid !== '') ids.add(docUuid)
1359
+ const pages = Array.isArray(doc.pages) ? doc.pages : []
1360
+ for (const page of pages) {
1361
+ const pageUuid = String(pickValue(asRecord(page), 'uuid', 'Uuid') ?? '')
1362
+ if (pageUuid !== '') ids.add(pageUuid)
1363
+ }
1364
+ }
1365
+ }
1366
+ return ids
1367
+ }
1368
+
1369
+ /**
1370
+ * Refuse PCB writes on a net the board does not have.
1371
+ *
1372
+ * Measured on 3.2.186: pcb_PrimitiveLine.create happily accepts an arbitrary net
1373
+ * name and the board then carries a phantom net (which DRC reports as a netlist
1374
+ * error). force:true is the documented escape hatch.
1375
+ */
1376
+ async function assertKnownPcbNet(toolName, net, timeoutMs, force) {
1377
+ const name = String(net ?? '').trim()
1378
+ if (name === '') throw new Error(toolName + ' requires a net name')
1379
+ if (force === true) return
1380
+ let names
1381
+ try {
1382
+ const raw = await callExtension('pcb_Net.getAllNetsName', [], Math.min(timeoutMs, 8000))
1383
+ names = new Set((Array.isArray(raw) ? raw : []).map(value => String(value)))
1384
+ } catch {
1385
+ // The PCB tab may not be active yet; let the write itself decide.
1386
+ return
1387
+ }
1388
+ if (names.size === 0) return
1389
+ if (names.has(name)) return
1390
+ const sample = [...names].slice(0, 12).join(', ')
1391
+ throw new Error(toolName + ': net "' + name + '" is not on this PCB (' + names.size + ' nets: ' + sample +
1392
+ '…). A write on an unknown net creates a phantom net that DRC reports as a netlist error; pass force:true if that is really intended.')
1393
+ }
1394
+
1395
+ async function executeTool(name, rawArgs, timeoutMs) {
1396
+ const args = asRecord(rawArgs)
1397
+ const tool = PCB_TOOL_ALIASES[name] ?? name
1398
+
1399
+ switch (tool) {
1400
+ case 'eda_status': {
1401
+ const ready = pickClients()
1402
+ // Every EDA page keeps its own socket, so several clients can disagree: list
1403
+ // them all and judge the bridge as outdated when ANY of them is not on VERSION.
1404
+ const versions = ready.map(client => (typeof client.extensionVersion === 'string' ? client.extensionVersion : null))
1405
+ const extensionVersion = versions.find(value => typeof value === 'string') ?? null
1406
+ const stale = versions.filter(value => value !== VERSION)
1407
+ return {
1408
+ ok: true, bridgeVersion: VERSION, wsPort: WS_PORT, allowRawApi: ALLOW_RAW_API,
1409
+ connectedClients: ready.length,
1410
+ extensionVersion: extensionVersion ?? null,
1411
+ extensionVersions: versions,
1412
+ versionMismatch: stale.length > 0,
1413
+ mcpUnits: '0.01 inch', defaultPaper: DEFAULT_PAPER,
1414
+ hint: ready.length === 0
1415
+ ? 'No JLCEDA extension is connected. Open JLCEDA Pro and click DSH MCP -> connect, or re-import dsh-eda-bridge-extension-' + VERSION + '.zip.'
1416
+ : (stale.length > 0
1417
+ ? 'Connected EDA extension ' + stale.join(', ') + ' does not match bridge ' + VERSION +
1418
+ '. In JLCEDA Pro remove the OLD dsh-eda-bridge extension first, import dsh-eda-bridge-extension-' + VERSION + '.zip again, then restart the app; a simple reload keeps the old copy.'
1419
+ : 'ok'),
1420
+ }
1421
+ }
1422
+
1423
+ case 'eda_close_document':
1424
+ return await callExtension('dmt_EditorControl.closeDocument', [String(args.tabId ?? '')], timeoutMs)
1425
+
1426
+ case 'eda_export_project': {
1427
+ const result = await callExtension('dsh.internal.exportProjectFile', [
1428
+ args.uuid === undefined ? null : String(args.uuid),
1429
+ args.fileName === undefined ? undefined : String(args.fileName),
1430
+ undefined,
1431
+ args.fileType === undefined ? undefined : String(args.fileType),
1432
+ ], toolTimeout(args, timeoutMs))
1433
+ const base64 = typeof result?.base64 === 'string' ? result.base64 : ''
1434
+ const outPath = args.outPath === undefined ? '' : String(args.outPath).trim()
1435
+ if (outPath !== '') {
1436
+ await writeFile(outPath, Buffer.from(base64, 'base64'))
1437
+ return { ok: true, written: outPath, name: result?.name ?? null, size: base64 === '' ? 0 : Buffer.from(base64, 'base64').length }
1438
+ }
1439
+ if (args.inline !== true) {
1440
+ return { ok: true, name: result?.name ?? null, base64Length: base64.length, hint: 'Pass outPath to write the file, or inline=true to receive the base64 payload.' }
1441
+ }
1442
+ return { ok: true, name: result?.name ?? null, base64 }
1443
+ }
1444
+
1445
+ case 'eda_import_project': {
1446
+ const path = String(args.path ?? '').trim()
1447
+ if (path === '') throw new Error('eda_import_project requires path')
1448
+ let bytes
1449
+ try { bytes = await readFile(path) } catch {
1450
+ throw new Error('eda_import_project: cannot read "' + path + '"')
1451
+ }
1452
+ // importProjectByProjectFile only lands anything when the target team is given
1453
+ // (saveTo); without it the app answers undefined and nothing is imported.
1454
+ let teamUuid = args.teamUuid === undefined ? '' : String(args.teamUuid).trim()
1455
+ if (teamUuid === '') {
1456
+ const current = await callExtension('dmt_Team.getCurrentTeamInfo', [], timeoutMs).catch(() => undefined)
1457
+ teamUuid = String(pickValue(asRecord(current), 'uuid', 'Uuid') ?? '')
1458
+ }
1459
+ if (teamUuid === '') {
1460
+ throw new Error('eda_import_project needs teamUuid: the app imports nothing without a target team. Use a team uuid from eda_list_teams (local mode reports project directories) or the teamUuid of an existing project (eda_list_projects).')
1461
+ }
1462
+ const saveTo: Record<string, unknown> = { operation: 'New Project', newProjectOwnerTeamUuid: teamUuid }
1463
+ if (args.folderUuid !== undefined) saveTo.newProjectOwnerFolderUuid = String(args.folderUuid)
1464
+ if (args.friendlyName !== undefined) saveTo.newProjectFriendlyName = String(args.friendlyName)
1465
+ const imported = await callExtension('dsh.internal.importProjectFile', [
1466
+ bytes.toString('base64'),
1467
+ basename(path),
1468
+ args.fileType === undefined ? undefined : String(args.fileType),
1469
+ saveTo,
1470
+ ], toolTimeout(args, timeoutMs))
1471
+ const raw = imported?.result ?? imported
1472
+ const uuid = typeof raw === 'string' ? raw : (typeof raw?.uuid === 'string' ? raw.uuid : undefined)
1473
+ const landed = raw !== null && raw !== undefined
1474
+ let opened = false
1475
+ if (args.open === true && uuid !== undefined) {
1476
+ try {
1477
+ await callExtension('dmt_Project.openProject', [uuid], timeoutMs)
1478
+ // Same as eda_open_project: trust the observed state, not the return value.
1479
+ opened = (await waitForActiveProject(uuid, 4000)).active
1480
+ } catch {
1481
+ opened = false
1482
+ }
1483
+ }
1484
+ // Import copies the file verbatim, so schematic/page/pcb uuids inside the new
1485
+ // project can collide with the source. Detect it and say so instead of leaving a
1486
+ // silent data-integrity trap.
1487
+ let collisions = null
1488
+ if (landed && uuid !== undefined && args.checkCollisions !== false) {
1489
+ try {
1490
+ const mine = await callExtension('dmt_Project.getProjectInfo', [uuid], toolTimeout(args, timeoutMs))
1491
+ const myIds = internalIdsOf(mine)
1492
+ const others = await callExtension('dmt_Project.getAllProjectsUuid', [], toolTimeout(args, timeoutMs))
1493
+ const list = (Array.isArray(others) ? others.map(String) : []).filter(other => other !== uuid).slice(0, 20)
1494
+ collisions = []
1495
+ for (const other of list) {
1496
+ const info = await callExtension('dmt_Project.getProjectInfo', [other], timeoutMs).catch(() => undefined)
1497
+ const shared = [...internalIdsOf(info)].filter(sharedId => myIds.has(sharedId))
1498
+ if (shared.length > 0) {
1499
+ collisions.push({ projectUuid: other, friendlyName: pickValue(asRecord(info), 'friendlyName', 'FriendlyName') ?? null, sharedIds: shared })
1500
+ }
1501
+ }
1502
+ } catch {
1503
+ collisions = null
1504
+ }
1505
+ }
1506
+ return {
1507
+ ok: landed,
1508
+ imported: landed,
1509
+ name: basename(path),
1510
+ size: bytes.length,
1511
+ teamUuid,
1512
+ uuid: uuid ?? null,
1513
+ opened,
1514
+ collisions,
1515
+ result: raw ?? null,
1516
+ hint: landed ? null : 'The app returned nothing: the import did not create a project. That means this build ignores the saveTo target (same limitation as createProject), so import cannot be used to create projects here.',
1517
+ }
1518
+ }
1519
+
1520
+ case 'eda_close': {
1521
+ const resolved = resolveExecutable(launchProbe(), {
1522
+ executable: args.executable === undefined ? undefined : String(args.executable),
1523
+ })
1524
+ const imageName = resolved === undefined ? 'lceda-pro.exe' : basename(resolved.executable)
1525
+ const before = processCountByName(imageName)
1526
+ const waitMs = Number.isFinite(Number(args.waitMs)) ? Math.max(1000, Number(args.waitMs)) : 8000
1527
+ let error = null
1528
+ try {
1529
+ terminateByName(imageName, false)
1530
+ } catch (failure) {
1531
+ error = failure instanceof Error ? failure.message : String(failure)
1532
+ }
1533
+ const started = Date.now()
1534
+ let remaining = processCountByName(imageName)
1535
+ while (remaining > 0 && Date.now() - started < waitMs) {
1536
+ await new Promise(resolve => setTimeout(resolve, 500))
1537
+ remaining = processCountByName(imageName)
1538
+ }
1539
+ let forced = false
1540
+ if (remaining > 0) {
1541
+ try {
1542
+ terminateByName(imageName, true)
1543
+ forced = true
1544
+ await new Promise(resolve => setTimeout(resolve, 1500))
1545
+ remaining = processCountByName(imageName)
1546
+ } catch (failure) {
1547
+ error = error ?? (failure instanceof Error ? failure.message : String(failure))
1548
+ }
1549
+ }
1550
+ const connected = pickClients().length
1551
+ return {
1552
+ ok: remaining <= 0,
1553
+ closed: remaining <= 0,
1554
+ forced,
1555
+ imageName,
1556
+ processesBefore: before,
1557
+ processesAfter: remaining,
1558
+ connectedClients: connected,
1559
+ waitedMs: Date.now() - started,
1560
+ error,
1561
+ }
1562
+ }
1563
+
1564
+ case 'eda_list_projects': {
1565
+ // Omit the filters entirely when they are not given: the official API treats a
1566
+ // literal null as a filter value and the call does not resolve.
1567
+ const filters = []
1568
+ if (args.teamUuid !== undefined) filters.push(String(args.teamUuid))
1569
+ if (args.folderUuid !== undefined || args.workspaceUuid !== undefined) filters.push(args.folderUuid === undefined ? null : String(args.folderUuid))
1570
+ if (args.workspaceUuid !== undefined) filters.push(String(args.workspaceUuid))
1571
+ let uuids = await callExtension('dmt_Project.getAllProjectsUuid', filters, toolTimeout(args, timeoutMs))
1572
+ let list = Array.isArray(uuids) ? uuids.map(String) : []
1573
+ let aggregated = false
1574
+ // In semi-offline mode the app models each local project directory as a
1575
+ // "team", so an unfiltered call returns nothing; walk the teams instead.
1576
+ if (list.length === 0 && filters.length === 0) {
1577
+ const teams = await callExtension('dmt_Team.getAllTeamsInfo', [], toolTimeout(args, timeoutMs)).catch(() => [])
1578
+ const seen = new Set()
1579
+ for (const team of Array.isArray(teams) ? teams : []) {
1580
+ const teamUuid = String(pickValue(asRecord(team), 'uuid', 'Uuid') ?? '')
1581
+ if (teamUuid === '') continue
1582
+ const owned = await callExtension('dmt_Project.getAllProjectsUuid', [teamUuid], toolTimeout(args, timeoutMs)).catch(() => [])
1583
+ for (const uuid of Array.isArray(owned) ? owned.map(String) : []) {
1584
+ if (seen.has(uuid)) continue
1585
+ seen.add(uuid)
1586
+ list.push(uuid)
1587
+ }
1588
+ }
1589
+ aggregated = true
1590
+ }
1591
+ if (args.resolveNames === false) return { count: list.length, uuids: list, aggregated }
1592
+ const limit = Number.isFinite(Number(args.limit)) ? Math.max(1, Number(args.limit)) : list.length
1593
+ const projects = []
1594
+ for (const uuid of list.slice(0, limit)) {
1595
+ try {
1596
+ // Verbatim: project records carry unstable keys and summarising them
1597
+ // produced empty objects.
1598
+ projects.push(await callExtension('dmt_Project.getProjectInfo', [uuid], toolTimeout(args, timeoutMs)))
1599
+ } catch {
1600
+ projects.push({ uuid })
1601
+ }
1602
+ }
1603
+ return { count: list.length, resolved: projects.length, aggregated, projects }
1604
+ }
1605
+
1606
+ case 'eda_get_project': {
1607
+ const project = await callExtension('dmt_Project.getCurrentProjectInfo', [], timeoutMs)
1608
+ return project === undefined || project === null
1609
+ ? { project: null, hint: 'No project is open: JLCEDA Pro is on the HOME page. Use eda_list_projects + eda_open_project, or open one in the app.' }
1610
+ : project
1611
+ }
1612
+
1613
+ case 'eda_open_project': {
1614
+ const resolvedProject = await resolveProjectUuid(args, timeoutMs)
1615
+ const uuid = resolvedProject.uuid
1616
+ const returned = await callExtension('dmt_Project.openProject', [uuid], toolTimeout(args, timeoutMs))
1617
+ // openProject returned false on the first call although the switch had already
1618
+ // happened, so report what the app actually has open instead of its boolean.
1619
+ const activation = await waitForActiveProject(uuid, args.verifyMs === undefined ? 4000 : Number(args.verifyMs))
1620
+ return {
1621
+ opened: activation.active,
1622
+ openReturned: returned !== false,
1623
+ uuid,
1624
+ matched: resolvedProject.matched,
1625
+ current: activation.active ? summarizePrimitive(activation.project) : null,
1626
+ ...(activation.active ? {} : { hint: 'The project did not become active within the verification window (last active: ' + (activation.lastActive ?? 'unknown') + '); it may still be loading, or the app refused the switch.' }),
1627
+ }
1628
+ }
1629
+
1630
+ case 'eda_get_workspace': {
1631
+ const workspace = await callExtension('dmt_Workspace.getCurrentWorkspaceInfo', [], timeoutMs).catch(() => undefined)
1632
+ const team = await callExtension('dmt_Team.getCurrentTeamInfo', [], timeoutMs).catch(() => undefined)
1633
+ // Team/workspace payloads are small and their field names are unstable, so
1634
+ // they are returned verbatim: summarising them produced empty objects.
1635
+ return {
1636
+ workspace: workspace === undefined ? null : workspace,
1637
+ team: team === undefined ? null : team,
1638
+ hint: workspace === undefined && team === undefined
1639
+ ? 'No workspace/team is available: start JLCEDA Pro and sign in to a JLC account. Workspace projects cannot be created or listed without one.'
1640
+ : 'ok',
1641
+ }
1642
+ }
1643
+
1644
+ case 'eda_list_teams': {
1645
+ const teams = await callExtension(args.involved === true ? 'dmt_Team.getAllInvolvedTeamInfo' : 'dmt_Team.getAllTeamsInfo', [], toolTimeout(args, timeoutMs))
1646
+ const list = Array.isArray(teams) ? teams : []
1647
+ return { count: list.length, teams: list }
1648
+ }
1649
+
1650
+ case 'eda_list_folders': {
1651
+ const teamUuid = args.teamUuid === undefined ? '' : String(args.teamUuid).trim()
1652
+ let resolvedTeam = teamUuid
1653
+ if (resolvedTeam === '') {
1654
+ const current = await callExtension('dmt_Team.getCurrentTeamInfo', [], timeoutMs).catch(() => undefined)
1655
+ resolvedTeam = String(pickValue(asRecord(current), 'Uuid', 'uuid') ?? '')
1656
+ }
1657
+ if (resolvedTeam === '') throw new Error('eda_list_folders needs teamUuid (eda_list_teams shows them)')
1658
+ // The app throws a bare TypeError when the team is not a real uuid (the local
1659
+ // directories reported by eda_list_teams are paths), so say what to pass.
1660
+ let uuids
1661
+ try {
1662
+ uuids = await callExtension('dmt_Folder.getAllFoldersUuid', [resolvedTeam], toolTimeout(args, timeoutMs))
1663
+ } catch (failure) {
1664
+ throw new Error('eda_list_folders: the app rejected team "' + resolvedTeam + '" (' +
1665
+ (failure instanceof Error ? failure.message : String(failure)) +
1666
+ '); pass the uuid from a project record (eda_list_projects) or eda_list_teams')
1667
+ }
1668
+ const list = Array.isArray(uuids) ? uuids.map(String) : []
1669
+ if (args.resolveNames === false) return { teamUuid: resolvedTeam, count: list.length, uuids: list }
1670
+ const folders = []
1671
+ for (const folderUuid of list.slice(0, 20)) {
1672
+ try {
1673
+ folders.push({ folderUuid, info: await callExtension('dmt_Folder.getFolderInfo', [resolvedTeam, folderUuid], timeoutMs) })
1674
+ } catch {
1675
+ folders.push({ folderUuid, info: null })
1676
+ }
1677
+ }
1678
+ return { teamUuid: resolvedTeam, count: list.length, folders }
1679
+ }
1680
+
1681
+ case 'eda_delete_project': {
1682
+ const resolvedProject = await resolveProjectUuid(args, timeoutMs)
1683
+ const deleted = await callExtension('dmt_Project.deleteProject', [resolvedProject.uuid], toolTimeout(args, timeoutMs))
1684
+ const ok = deleted !== false
1685
+ return {
1686
+ deleted: ok,
1687
+ uuid: resolvedProject.uuid,
1688
+ matched: resolvedProject.matched,
1689
+ hint: ok ? null : 'The app returned false and the project still exists: this build refuses deleteProject for local projects (verified with the project open and after switching away), so remove it in the app.',
1690
+ }
1691
+ }
1692
+
1693
+ case 'eda_modify_project': {
1694
+ const resolvedProject = await resolveProjectUuid(args, timeoutMs)
1695
+ const changes = []
1696
+ if (args.friendlyName !== undefined) {
1697
+ changes.push(['friendlyName', await callExtension('dmt_Project.modifyProjectFriendlyName', [resolvedProject.uuid, String(args.friendlyName)], timeoutMs)])
1698
+ }
1699
+ if (args.description !== undefined) {
1700
+ changes.push(['description', await callExtension('dmt_Project.modifyProjectDescription', [resolvedProject.uuid, String(args.description)], timeoutMs)])
1701
+ }
1702
+ if (changes.length === 0) throw new Error('eda_modify_project requires friendlyName or description')
1703
+ return {
1704
+ ok: changes.every(([, value]) => value !== false),
1705
+ uuid: resolvedProject.uuid,
1706
+ matched: resolvedProject.matched,
1707
+ applied: changes.map(([field, value]) => ({ field, ok: value !== false })),
1708
+ }
1709
+ }
1710
+
1711
+ case 'eda_copy_project': {
1712
+ const source = await resolveProjectUuid({
1713
+ uuid: args.sourceUuid, name: args.sourceName,
1714
+ }, timeoutMs)
1715
+ // copyProject answered nothing for every argument combination on 3.2.186, and
1716
+ // returning {copied:false} with no reason left the caller guessing.
1717
+ let copyRaw
1718
+ try {
1719
+ copyRaw = await callExtension('dmt_Project.copyProject', [
1720
+ source.uuid,
1721
+ args.targetTeamUuid === undefined ? undefined : String(args.targetTeamUuid),
1722
+ args.targetFolderUuid === undefined ? undefined : String(args.targetFolderUuid),
1723
+ args.newFriendlyName === undefined ? undefined : String(args.newFriendlyName),
1724
+ args.newName === undefined ? undefined : String(args.newName),
1725
+ ], toolTimeout(args, timeoutMs))
1726
+ } catch (failure) {
1727
+ throw new Error('eda_copy_project failed: ' + (failure instanceof Error ? failure.message : String(failure)))
1728
+ }
1729
+ const copyUuid = typeof copyRaw === 'string' ? copyRaw : String(pickValue(asRecord(copyRaw), 'uuid', 'Uuid') ?? '')
1730
+ return {
1731
+ copied: copyUuid !== '',
1732
+ sourceUuid: source.uuid,
1733
+ uuid: copyUuid === '' ? null : copyUuid,
1734
+ raw: copyRaw ?? null,
1735
+ hint: copyUuid === ''
1736
+ ? 'The app returned no uuid and created nothing: copyProject does not work on this build for local projects (same family as createProject/deleteProject). Duplicate it in the app, or export with eda_export_project and import it back with eda_import_project to get an independent copy.'
1737
+ : null,
1738
+ }
1739
+ return { copied: typeof uuid === 'string' && uuid !== '', sourceUuid: source.uuid, uuid: uuid ?? null }
1740
+ }
1741
+
1742
+ case 'eda_create_project': {
1743
+ const friendlyName = String(args.friendlyName ?? '').trim()
1744
+ if (friendlyName === '') throw new Error('eda_create_project requires friendlyName')
1745
+ // createProject needs an owning team: default to the current one instead of
1746
+ // passing undefined, which the app answers with an empty uuid.
1747
+ let teamUuid = args.teamUuid === undefined ? '' : String(args.teamUuid).trim()
1748
+ let teamSource = 'argument'
1749
+ if (teamUuid === '') {
1750
+ const current = await callExtension('dmt_Team.getCurrentTeamInfo', [], timeoutMs).catch(() => undefined)
1751
+ teamUuid = String(pickValue(asRecord(current), 'Uuid', 'uuid') ?? '')
1752
+ teamSource = teamUuid === '' ? 'unavailable' : 'current-team'
1753
+ }
1754
+ if (teamUuid === '') {
1755
+ throw new Error('eda_create_project: no team is available (sign in to a JLC account in JLCEDA Pro, or pass teamUuid from eda_list_teams)')
1756
+ }
1757
+ const folderUuid = args.folderUuid === undefined ? '' : String(args.folderUuid).trim()
1758
+ const uuid = await callExtension('dmt_Project.createProject', [
1759
+ friendlyName,
1760
+ args.name === undefined ? undefined : String(args.name),
1761
+ teamUuid,
1762
+ folderUuid === '' ? undefined : folderUuid,
1763
+ args.description === undefined ? undefined : String(args.description),
1764
+ ], toolTimeout(args, timeoutMs))
1765
+ if (typeof uuid !== 'string' || uuid === '') {
1766
+ throw new Error('eda_create_project: the app returned no project uuid (team ' + teamUuid + ' from ' + teamSource + '; the app may have shown a dialog or rejected the name)')
1767
+ }
1768
+ let opened = false
1769
+ if (args.open === true) {
1770
+ try {
1771
+ await callExtension('dmt_Project.openProject', [uuid], timeoutMs)
1772
+ opened = (await waitForActiveProject(uuid, 4000)).active
1773
+ } catch {
1774
+ opened = false
1775
+ }
1776
+ }
1777
+ return { created: true, uuid, friendlyName, teamUuid, teamSource, folderUuid: folderUuid === '' ? null : folderUuid, opened }
1778
+ }
1779
+
1780
+ case 'eda_launch': {
1781
+ const probe = launchProbe()
1782
+ const resolved = resolveExecutable(probe, {
1783
+ executable: args.executable === undefined ? undefined : String(args.executable),
1784
+ project: args.project === undefined ? undefined : String(args.project),
1785
+ })
1786
+ if (resolved === undefined) {
1787
+ throw new Error([
1788
+ 'eda_launch: could not find the JLCEDA Pro executable on this machine.',
1789
+ 'Set `DSH_EDA_EXECUTABLE` (or the plugin setting edaExecutable) to the full path of lceda-pro.exe.',
1790
+ 'Searched: DSH_EDA_EXECUTABLE / JLCEDA_EXECUTABLE, the registry handler registered for .eprj2/.eprj,',
1791
+ 'conventional install directories under Program Files / LOCALAPPDATA / the system drive, and PATH.',
1792
+ ].join(' '))
1793
+ }
1794
+
1795
+ const alreadyConnected = pickClients().length
1796
+ const project = args.project === undefined ? undefined : String(args.project)
1797
+ if (project !== undefined && project !== '') {
1798
+ try { if (!statSync(project).isFile()) throw new Error('not a file') } catch {
1799
+ throw new Error('eda_launch: project "' + project + '" does not exist or is not a file')
1800
+ }
1801
+ }
1802
+
1803
+ // On Windows a direct spawn (and even ShellExecute) makes lceda-pro.exe start
1804
+ // and quit immediately, while the same executable works when the desktop
1805
+ // shell launches it. Explorer runs in the interactive desktop, so the launch
1806
+ // is handed to it through a tiny script that starts the app (with the project
1807
+ // when given). Other platforms spawn the resolved command directly.
1808
+ const plan = buildLaunchArgs(process.platform, resolved.executable, project)
1809
+ let child
1810
+ let via = 'direct'
1811
+ if (process.platform === 'win32') {
1812
+ try {
1813
+ const scriptPath = join(tmpdir(), 'dsh-eda-launch-' + process.pid + '-' + Date.now() + '.cmd')
1814
+ await writeFile(scriptPath, buildLaunchScript(resolved.executable, project), 'utf8')
1815
+ child = spawn(process.env.SystemRoot ? join(process.env.SystemRoot, 'explorer.exe') : 'explorer.exe', [scriptPath], {
1816
+ detached: true, stdio: 'ignore', windowsHide: false,
1817
+ })
1818
+ via = 'explorer'
1819
+ } catch {
1820
+ child = spawn(plan.command, plan.args, { detached: true, stdio: 'ignore', windowsHide: false })
1821
+ via = 'direct'
1822
+ }
1823
+ } else {
1824
+ child = spawn(plan.command, plan.args, { detached: true, stdio: 'ignore', windowsHide: false })
1825
+ }
1826
+ child.unref()
1827
+
1828
+ const shouldWait = args.waitForExtension !== false
1829
+ const timeoutMs = Number.isFinite(Number(args.timeoutMs)) ? Math.max(1000, Number(args.timeoutMs)) : 30000
1830
+ const waited = shouldWait
1831
+ ? await waitForExtensionConnection(timeoutMs)
1832
+ : { connected: alreadyConnected > 0, clients: alreadyConnected, waitedMs: 0 }
1833
+
1834
+ return {
1835
+ ok: true,
1836
+ launched: true,
1837
+ pid: child.pid ?? null,
1838
+ via,
1839
+ executable: resolved.executable,
1840
+ source: resolved.source,
1841
+ project: project ?? null,
1842
+ // Verified on JLCEDA Pro 3.2.186: the app starts but ignores the project
1843
+ // argument passed on the command line (it opens on HOME), so the caller must
1844
+ // not assume the project was opened.
1845
+ projectOpenedByArgument: false,
1846
+ projectNote: project === undefined || project === ''
1847
+ ? null
1848
+ : 'The app was started with the project path, but this JLCEDA Pro build ignores it and opens on HOME; open the project from the app itself.',
1849
+ target: { command: plan.command, args: plan.args },
1850
+ connected: waited.connected,
1851
+ connectedClients: waited.clients,
1852
+ waitedMs: waited.waitedMs,
1853
+ hint: waited.connected
1854
+ ? 'JLCEDA is connected; the eda_* tools can be used now.'
1855
+ : 'The app was started but no EDA extension connected yet. In JLCEDA Pro: 扩展 → DSH MCP → 连接 (and enable “允许外部交互”); the extension must be imported once from dsh-eda-bridge-extension-' + VERSION + '.zip.',
1856
+ }
1857
+ }
1858
+
1859
+ case 'eda_get_page_info': {
1860
+ const paper = paperOf(args.paper)
1861
+ let page
1862
+ try { page = await callExtension('dmt_Schematic.getCurrentSchematicPageInfo', [], timeoutMs) } catch { page = undefined }
1863
+ return {
1864
+ page,
1865
+ units: { mcp: '0.01 inch', internal: 'inch', factor: MCP_UNITS_PER_INCH },
1866
+ paper: paper.name,
1867
+ frame: paper.frame,
1868
+ titleBlock: paper.titleBlock,
1869
+ safeAreas: safeAreas(paper.name),
1870
+ note: 'Coordinates are MCP units (0.01 inch). Frame origin is the lower-left corner, y grows upward. Title-block overlap is rejected by eda_place_component.',
1871
+ }
1872
+ }
1873
+
1874
+ case 'eda_get_schematic_pages': {
1875
+ if (typeof args.pageUuid === 'string' && args.pageUuid !== '') {
1876
+ return await callExtension('dmt_Schematic.getSchematicPageInfo', [args.pageUuid], timeoutMs)
1877
+ }
1878
+ return await callExtension('dmt_Schematic.getCurrentSchematicAllSchematicPagesInfo', [], timeoutMs)
1879
+ }
1880
+
1881
+ case 'eda_search_components': {
1882
+ const keyword = String(args.keyword ?? '')
1883
+ if (keyword.trim() === '') throw new Error('keyword is required')
1884
+ const limit = Math.max(1, Math.min(50, Number(args.limit ?? 20)))
1885
+ return await callExtension('lib_Device.search', [keyword, undefined, undefined, undefined, limit, 1], timeoutMs)
1886
+ }
1887
+
1888
+ case 'eda_place_component': {
1889
+ const x = Number(args.x)
1890
+ const y = Number(args.y)
1891
+ const paper = args.paper
1892
+ const allowOutside = args.allowOutsideFrame === true
1893
+ if (!allowOutside) {
1894
+ const problem = checkPointInFrame(x, y, paper, 5) ?? checkPointAgainstTitleBlock(x, y, paper, 5)
1895
+ if (problem !== undefined) throw new Error('eda_place_component refused: ' + problem)
1896
+ }
1897
+ const component = { libraryUuid: String(args.libraryUuid), uuid: String(args.uuid) }
1898
+ const result = await callExtension('sch_PrimitiveComponent.create', [
1899
+ component, x, y, args.subPartName, Number(args.rotation ?? 0), Boolean(args.mirror ?? false),
1900
+ args.addIntoBom === undefined ? true : Boolean(args.addIntoBom),
1901
+ args.addIntoPcb === undefined ? true : Boolean(args.addIntoPcb),
1902
+ ], timeoutMs)
1903
+ const primitiveId = extractPrimitiveId(result)
1904
+ if (primitiveId !== undefined && (args.designator !== undefined || args.value !== undefined || args.name !== undefined)) {
1905
+ const otherProperty = {}
1906
+ if (args.value !== undefined) otherProperty.Value = String(args.value)
1907
+ const property = {}
1908
+ if (args.designator !== undefined) property.designator = String(args.designator)
1909
+ if (args.name !== undefined) property.name = String(args.name)
1910
+ if (Object.keys(otherProperty).length > 0) property.otherProperty = otherProperty
1911
+ await callExtension('sch_PrimitiveComponent.modify', [primitiveId, property], timeoutMs)
1912
+ }
1913
+ if (primitiveId !== undefined && !allowOutside) {
1914
+ const bbox = await bboxOf([primitiveId], timeoutMs)
1915
+ if (bbox !== undefined) {
1916
+ const problem = checkBBoxInFrame(bbox, paper, 0)
1917
+ if (problem !== undefined) {
1918
+ try { await callExtension('sch_PrimitiveComponent.delete', [primitiveId], timeoutMs) } catch { /* best effort */ }
1919
+ throw new Error('eda_place_component rolled back: ' + problem + '. Move the component into a safe area or pass allowOutsideFrame=true.')
1920
+ }
1921
+ }
1922
+ }
1923
+ // Soft gate (no block): a vague request ("draw me an X board") must not turn into
1924
+ // guessed parameters. The first placement reports the missing questions instead.
1925
+ if (designBrief === null) {
1926
+ const intake = buildIntake(null)
1927
+ return {
1928
+ primitiveId,
1929
+ result,
1930
+ intakeWarning: {
1931
+ message: 'No design parameters confirmed this session: supply, MCU, clocks, connectors, board size, layer count and fabrication were not agreed. Confirm them with eda_design_intake + ask_user_question before continuing, or the board may be electrically correct and practically wrong.',
1932
+ criticalCount: intake.criticalCount,
1933
+ firstMissing: intake.missingCritical.slice(0, 8),
1934
+ },
1935
+ }
1936
+ }
1937
+ return { primitiveId, result }
1938
+ }
1939
+
1940
+ case 'eda_place_net_flag': {
1941
+ const x = Number(args.x)
1942
+ const y = Number(args.y)
1943
+ assertNetName(String(args.net), 'eda_place_net_flag')
1944
+ if (args.allowOutsideFrame !== true) {
1945
+ const problem = checkPointInFrame(x, y, args.paper, 5) ?? checkPointAgainstTitleBlock(x, y, args.paper, 5)
1946
+ if (problem !== undefined) throw new Error('eda_place_net_flag refused: ' + problem)
1947
+ }
1948
+ return await callExtension('sch_PrimitiveComponent.createNetFlag', [
1949
+ String(args.identification), String(args.net), x, y, Number(args.rotation ?? 0), Boolean(args.mirror ?? false),
1950
+ ], timeoutMs)
1951
+ }
1952
+
1953
+ case 'eda_place_net_port': {
1954
+ const x = Number(args.x)
1955
+ const y = Number(args.y)
1956
+ assertNetName(String(args.net), 'eda_place_net_port')
1957
+ if (args.allowOutsideFrame !== true) {
1958
+ const problem = checkPointInFrame(x, y, args.paper, 5) ?? checkPointAgainstTitleBlock(x, y, args.paper, 5)
1959
+ if (problem !== undefined) throw new Error('eda_place_net_port refused: ' + problem)
1960
+ }
1961
+ return await callExtension('sch_PrimitiveComponent.createNetPort', [
1962
+ String(args.direction), String(args.net), x, y, Number(args.rotation ?? 0), Boolean(args.mirror ?? false),
1963
+ ], timeoutMs)
1964
+ }
1965
+
1966
+ case 'eda_get_pins': {
1967
+ const componentPrimitiveId = String(args.componentPrimitiveId ?? '')
1968
+ if (componentPrimitiveId === '') throw new Error('componentPrimitiveId is required')
1969
+ // One call already returns pinName/pinNumber (ISCH_PrimitiveComponentPin);
1970
+ // summarising it used to drop exactly those fields, forcing one sch_PrimitivePin.get
1971
+ // round trip per pin (135 of them for a mid-size schematic).
1972
+ const raw = await callExtension('sch_PrimitiveComponent.getAllPinsByPrimitiveId', [componentPrimitiveId], timeoutMs)
1973
+ if (!Array.isArray(raw)) return raw
1974
+ return raw.map((entry) => {
1975
+ const record = asRecord(entry)
1976
+ return {
1977
+ primitiveId: pickValue(record, 'PrimitiveId', 'primitiveId'),
1978
+ pinNumber: pickValue(record, 'PinNumber', 'pinNumber') ?? null,
1979
+ pinName: pickValue(record, 'PinName', 'pinName') ?? null,
1980
+ x: pickValue(record, 'X', 'x'),
1981
+ y: pickValue(record, 'Y', 'y'),
1982
+ rotation: pickValue(record, 'Rotation', 'rotation') ?? 0,
1983
+ pinLength: pickValue(record, 'PinLength', 'pinLength') ?? null,
1984
+ noConnected: pickValue(record, 'NoConnected', 'noConnected') ?? null,
1985
+ }
1986
+ })
1987
+ }
1988
+
1989
+ case 'eda_place_net_flag_at_pin':
1990
+ case 'eda_place_net_label_at_pin':
1991
+ return await placeAtPin(name, args, timeoutMs)
1992
+
1993
+ case 'eda_place_net_label': {
1994
+ const x = Number(args.x)
1995
+ const y = Number(args.y)
1996
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error('eda_place_net_label requires numeric x/y')
1997
+ return await placeNetLabel(String(args.net), x, y, args.fontSize, timeoutMs, {
1998
+ probe: args.probe === true, textLabel: args.textLabel === true,
1999
+ })
2000
+ }
2001
+
2002
+ case 'eda_place_net_labels': {
2003
+ // One MCP round trip for many labels: a 133-label schematic used to exceed the
2004
+ // caller's timeout with no way to learn what had already been placed.
2005
+ const items = Array.isArray(args.items) ? args.items.map(asRecord) : []
2006
+ if (items.length === 0) throw new Error('eda_place_net_labels requires items: [{ pinPrimitiveId, net }] or [{ x, y, net }]')
2007
+ // Measured on 3.2.186: one label costs ~2 s (the app writes per primitive), so a
2008
+ // sequential 133-label run still took minutes. Items are independent, so run them
2009
+ // with bounded concurrency; results keep the caller's order.
2010
+ const concurrency = Number.isFinite(Number(args.concurrency)) ? Math.max(1, Math.min(8, Number(args.concurrency))) : 4
2011
+ const results = await mapLimit(items, concurrency, async (item) => {
2012
+ const net = item.net === undefined ? '' : String(item.net)
2013
+ try {
2014
+ const placed = item.pinPrimitiveId !== undefined
2015
+ ? await placeAtPin('eda_place_net_label_at_pin', { ...item, net }, timeoutMs)
2016
+ : await placeNetLabel(net, Number(item.x), Number(item.y), item.fontSize, timeoutMs, {
2017
+ probe: args.probe === true, textLabel: args.textLabel === true,
2018
+ })
2019
+ return { ok: true, net, ...placed }
2020
+ } catch (error) {
2021
+ return { ok: false, net, error: error instanceof Error ? error.message : String(error) }
2022
+ }
2023
+ })
2024
+ const done = results.filter(entry => entry.ok).length
2025
+ return {
2026
+ total: items.length,
2027
+ done,
2028
+ failed: items.length - done,
2029
+ method: netLabelSupport === true ? 'netLabel' : 'text',
2030
+ results,
2031
+ }
2032
+ }
2033
+
2034
+ case 'eda_get_net_labels': {
2035
+ // Enumerate every label-like primitive: net labels/flags/ports are attribute
2036
+ // primitives, while the text fallback (createNetLabel unavailable) lands in
2037
+ // sch_PrimitiveText. Listing only attributes reported count:0 right after a
2038
+ // successful placement, so the labels could not be found or cleaned up.
2039
+ const attributes = await callExtension('sch_PrimitiveAttribute.getAll', [
2040
+ args.parentPrimitiveId === undefined ? undefined : String(args.parentPrimitiveId),
2041
+ ], timeoutMs).catch(() => [])
2042
+ const texts = args.parentPrimitiveId === undefined
2043
+ ? await callExtension('sch_PrimitiveText.getAll', [], timeoutMs).catch(() => [])
2044
+ : []
2045
+ const entries = []
2046
+ for (const entry of Array.isArray(attributes) ? attributes : []) {
2047
+ const record = asRecord(entry)
2048
+ entries.push({
2049
+ primitiveId: pickValue(record, 'PrimitiveId', 'primitiveId'),
2050
+ kind: String(pickValue(record, 'PrimitiveType', 'primitiveType', 'Type', 'type') ?? 'attribute'),
2051
+ net: pickValue(record, 'Net', 'net') ?? null,
2052
+ userValue: pickValue(record, 'UserValue', 'userValue', 'Value', 'value') ?? null,
2053
+ x: pickValue(record, 'X', 'x'),
2054
+ y: pickValue(record, 'Y', 'y'),
2055
+ })
2056
+ }
2057
+ for (const entry of Array.isArray(texts) ? texts : []) {
2058
+ const record = asRecord(entry)
2059
+ const content = String(pickValue(record, 'Content', 'content', 'Text', 'text') ?? '')
2060
+ if (content === '') continue
2061
+ entries.push({
2062
+ primitiveId: pickValue(record, 'PrimitiveId', 'primitiveId'),
2063
+ kind: 'text',
2064
+ net: content,
2065
+ userValue: content,
2066
+ x: pickValue(record, 'X', 'x'),
2067
+ y: pickValue(record, 'Y', 'y'),
2068
+ })
2069
+ }
2070
+ return {
2071
+ count: entries.length,
2072
+ attributeCount: Array.isArray(attributes) ? attributes.length : 0,
2073
+ textCount: Array.isArray(texts) ? texts.length : 0,
2074
+ sessionTextLabels: placedTextLabels.length,
2075
+ note: 'kind "text" entries are plain texts (no electrical meaning). Delete any entry with eda_delete_primitive(kind: "netlabel"|"netport"|"netflag"|"text", primitiveId).',
2076
+ labels: entries,
2077
+ }
2078
+ }
2079
+
2080
+ case 'eda_get_active_document': {
2081
+ const info = await callExtension('dmt_SelectControl.getCurrentDocumentInfo', [], timeoutMs)
2082
+ const record = asRecord(info)
2083
+ const type = Number(record.documentType)
2084
+ return { document: info, documentTypeName: DOCUMENT_TYPES[type] ?? String(record.documentType ?? 'unknown'), documentType: record.documentType }
2085
+ }
2086
+
2087
+ case 'eda_open_document': {
2088
+ const documentUuid = String(args.documentUuid ?? '')
2089
+ if (documentUuid === '') throw new Error('documentUuid is required')
2090
+ const raw = await callExtension('dmt_EditorControl.openDocument', [
2091
+ documentUuid, args.splitScreenId === undefined ? undefined : String(args.splitScreenId),
2092
+ ], timeoutMs)
2093
+ // Measured on 3.2.186: from a freshly launched app sitting on HOME, openDocument
2094
+ // answers without creating a tab, so callers thought the page was active and every
2095
+ // tab-dependent call then returned empty. Verify instead of trusting it.
2096
+ await sleep(600)
2097
+ let tabIds = []
2098
+ try {
2099
+ const tree = asRecord(await callExtension('dmt_EditorControl.getSplitScreenTree', [], Math.min(timeoutMs, 4000)))
2100
+ tabIds = (Array.isArray(tree.tabs) ? tree.tabs : []).map(tab => String(pickValue(asRecord(tab), 'tabId') ?? ''))
2101
+ } catch { /* the tree is only a hint */ }
2102
+ let activeUuid = ''
2103
+ try {
2104
+ const info = asRecord(await callExtension('dmt_SelectControl.getCurrentDocumentInfo', [], Math.min(timeoutMs, 4000)))
2105
+ activeUuid = String(pickValue(info, 'uuid', 'Uuid') ?? '')
2106
+ } catch { /* ignore */ }
2107
+ // "opened" must mean "this document is now the active one": right after an app
2108
+ // restart the call answers success while the Start Page (tab_page1) stays active,
2109
+ // and a length-based guess reported opened:true for it.
2110
+ const activeIsTarget = activeUuid === documentUuid
2111
+ const tabOpened = activeIsTarget || tabIds.some(tab => tab.startsWith(documentUuid + '@'))
2112
+ return {
2113
+ ...(raw !== null && typeof raw === 'object' ? raw : { result: raw ?? null }),
2114
+ opened: tabOpened,
2115
+ activated: activeIsTarget,
2116
+ activeDocumentUuid: activeUuid || null,
2117
+ tabIds,
2118
+ hint: tabOpened
2119
+ ? null
2120
+ : 'The app accepted openDocument but the document is not active (activeDocumentUuid=' +
2121
+ (activeUuid || 'unknown') + ', tabs: ' + (tabIds.join(', ') || 'none') +
2122
+ '). After an app restart the editor sits on the Start Page: open the project first'
2123
+ + ' (eda_open_project), then open the document. This build cannot open a document from the HOME screen programmatically, so never assume a page is active without checking activeDocumentUuid.',
2124
+ }
2125
+ }
2126
+
2127
+ case 'eda_set_no_connect': {
2128
+ const ids = Array.isArray(args.primitiveIds) ? args.primitiveIds.map(String) : []
2129
+ if (ids.length === 0) throw new Error('primitiveIds is required')
2130
+ const noConnected = args.noConnected === undefined ? true : Boolean(args.noConnected)
2131
+ const results = await mapLimit(ids, 8, async (id) => {
2132
+ try { return { id, ok: true, result: await callExtension('sch_PrimitivePin.modify', [id, { noConnected }], timeoutMs) } }
2133
+ catch (error) { return { id, ok: false, error: error instanceof Error ? error.message : String(error) } }
2134
+ })
2135
+ return { noConnected, results }
2136
+ }
2137
+
2138
+ case 'eda_draw_wire': {
2139
+ const points = flattenPoints(args.points)
2140
+ if (points.length < 4 || points.length % 2 !== 0) throw new Error('points must be a flat array with an even length >= 4')
2141
+ if (args.net !== undefined && String(args.net) !== '') assertNetName(String(args.net), 'eda_draw_wire')
2142
+ const wire = await callExtension('sch_PrimitiveWire.create', [
2143
+ points, args.net, args.color,
2144
+ args.lineWidth === undefined ? undefined : Number(args.lineWidth),
2145
+ args.lineType === undefined ? undefined : Number(args.lineType),
2146
+ ], timeoutMs)
2147
+ const warnings = args.net === undefined || String(args.net) === '' ? [] : checkNetName(String(args.net)).warnings
2148
+ return warnings.length === 0 ? wire : { created: wire, rules: { warnings } }
2149
+ }
2150
+
2151
+ case 'eda_draw_rectangle':
2152
+ return await callExtension('sch_PrimitiveRectangle.create', [
2153
+ Number(args.topLeftX), Number(args.topLeftY), Number(args.width), Number(args.height),
2154
+ args.cornerRadius === undefined ? undefined : Number(args.cornerRadius),
2155
+ args.rotation === undefined ? undefined : Number(args.rotation),
2156
+ args.color, args.fillColor,
2157
+ args.lineWidth === undefined ? undefined : Number(args.lineWidth),
2158
+ args.lineType === undefined ? undefined : Number(args.lineType),
2159
+ args.fillStyle,
2160
+ ], timeoutMs)
2161
+
2162
+ case 'eda_draw_functional_box': {
2163
+ const margin = args.margin === undefined ? 1 : Number(args.margin)
2164
+ let ids = Array.isArray(args.componentIds) ? args.componentIds.map(String) : []
2165
+ if (ids.length === 0) {
2166
+ const all = await callExtension('sch_PrimitiveComponent.getAll', ['part', false], timeoutMs)
2167
+ if (Array.isArray(all)) ids = all.map((item) => extractPrimitiveId(item)).filter((id) => typeof id === 'string')
2168
+ }
2169
+ if (ids.length === 0) throw new Error('no components found to box')
2170
+ const bbox = await bboxOf(ids, timeoutMs)
2171
+ if (bbox === undefined) throw new Error('could not compute component bounding box')
2172
+ const left = bbox.minX - margin
2173
+ const right = bbox.maxX + margin
2174
+ const bottom = bbox.minY - margin
2175
+ const top = bbox.maxY + margin
2176
+ const rectangle = await callExtension('sch_PrimitiveRectangle.create', [
2177
+ left, top, right - left, top - bottom, 0, 0, args.color ?? null, 'none',
2178
+ args.lineWidth === undefined ? 1 : Number(args.lineWidth),
2179
+ args.lineType === undefined ? 1 : Number(args.lineType), 'None',
2180
+ ], timeoutMs)
2181
+ let label
2182
+ if (typeof args.label === 'string' && args.label.trim() !== '') {
2183
+ label = await callExtension('sch_PrimitiveText.create', [
2184
+ left + 4, top - 14, args.label, 0, null, null, 12, false, false, false, 1,
2185
+ ], timeoutMs)
2186
+ }
2187
+ return { bbox, box: { left, right, bottom, top }, rectangle, label }
2188
+ }
2189
+
2190
+ case 'eda_draw_circle':
2191
+ return await callExtension('sch_PrimitiveCircle.create', [
2192
+ Number(args.centerX), Number(args.centerY), Number(args.radius), args.color, args.fillColor,
2193
+ args.lineWidth === undefined ? undefined : Number(args.lineWidth),
2194
+ args.lineType === undefined ? undefined : Number(args.lineType), args.fillStyle,
2195
+ ], timeoutMs)
2196
+
2197
+ case 'eda_draw_text':
2198
+ return await callExtension('sch_PrimitiveText.create', [
2199
+ Number(args.x), Number(args.y), String(args.content), Number(args.rotation ?? 0),
2200
+ args.textColor, args.fontName,
2201
+ args.fontSize === undefined ? undefined : Number(args.fontSize),
2202
+ Boolean(args.bold ?? false), Boolean(args.italic ?? false), Boolean(args.underLine ?? false),
2203
+ args.alignMode === undefined ? undefined : Number(args.alignMode),
2204
+ ], timeoutMs)
2205
+
2206
+ case 'eda_save_document':
2207
+ return await callExtension('sch_Document.save', [], timeoutMs)
2208
+
2209
+ case 'eda_zoom_to_fit': {
2210
+ // The API reported bounds outside the sheet (left:-340, bottom:-772.9 on A4),
2211
+ // which is useless for a caller that wants to know what it is looking at.
2212
+ // Clamp the region to the page frame and re-apply it.
2213
+ const raw = await callExtension('dmt_EditorControl.zoomToAllPrimitives', [args.tabId], timeoutMs)
2214
+ const record = asRecord(raw)
2215
+ const left = Number(pickValue(record, 'left', 'Left'))
2216
+ const right = Number(pickValue(record, 'right', 'Right'))
2217
+ const bottom = Number(pickValue(record, 'bottom', 'Bottom'))
2218
+ const top = Number(pickValue(record, 'top', 'Top'))
2219
+ if (![left, right, bottom, top].every(value => Number.isFinite(value))) return raw
2220
+ const frame = paperOf(args.paper).frame
2221
+ const clamped = {
2222
+ left: Math.max(frame.left, left), right: Math.min(frame.right, right),
2223
+ bottom: Math.max(frame.bottom, bottom), top: Math.min(frame.top, top),
2224
+ }
2225
+ if (clamped.left >= clamped.right || clamped.bottom >= clamped.top) {
2226
+ return { ...record, requested: { left, right, bottom, top }, clamped: null, note: 'the primitive bounds do not overlap the page frame' }
2227
+ }
2228
+ await callExtension('dmt_EditorControl.zoomToRegion', [
2229
+ clamped.left, clamped.right, clamped.top, clamped.bottom, args.tabId,
2230
+ ], timeoutMs)
2231
+ return { ...record, requested: { left, right, bottom, top }, clamped }
2232
+ }
2233
+
2234
+ case 'eda_zoom_to_region':
2235
+ return await callExtension('dmt_EditorControl.zoomToRegion', [
2236
+ Number(args.left), Number(args.right), Number(args.top), Number(args.bottom), args.tabId,
2237
+ ], timeoutMs)
2238
+
2239
+ case 'eda_get_components': {
2240
+ const raw = await callExtension('sch_PrimitiveComponent.getAll', ['part', Boolean(args.allSchematicPages ?? false)], timeoutMs)
2241
+ if (!Array.isArray(raw)) return raw
2242
+ const summarized = raw.map(summarizePrimitive)
2243
+ if (args.includeBounds === false) return summarized
2244
+ return await mapLimit(summarized, 8, async (item) => {
2245
+ const id = typeof item.primitiveId === 'string' ? item.primitiveId : undefined
2246
+ if (id === undefined) return item
2247
+ try {
2248
+ const bbox = await bboxOf([id], timeoutMs)
2249
+ return bbox === undefined ? item : { ...item, bbox, width: bbox.maxX - bbox.minX, height: bbox.maxY - bbox.minY }
2250
+ } catch { return item }
2251
+ })
2252
+ }
2253
+
2254
+ case 'eda_get_wires': {
2255
+ const raw = await callExtension('sch_PrimitiveWire.getAll', [], timeoutMs)
2256
+ if (Array.isArray(raw)) return raw.map(summarizePrimitive)
2257
+ return raw
2258
+ }
2259
+
2260
+ case 'eda_get_nets': {
2261
+ if (typeof args.name === 'string' && args.name !== '') {
2262
+ const single = await callExtension('sch_Net.getNet', [args.name], timeoutMs)
2263
+ if (single !== undefined && single !== null) return { source: 'sch_Net.getNet', net: single }
2264
+ return { source: 'sch_Net.getNet', net: null, hint: NET_EMPTY_HINT }
2265
+ }
2266
+ const project = await callExtension('sch_Net.getCurrentProjectAllNets', [], timeoutMs)
2267
+ if (Array.isArray(project) && project.length > 0) return { source: 'sch_Net.getCurrentProjectAllNets', count: project.length, nets: project }
2268
+ const all = await callExtension('sch_Net.getAllNets', [], timeoutMs)
2269
+ if (Array.isArray(all) && all.length > 0) return { source: 'sch_Net.getAllNets', count: all.length, nets: all }
2270
+ if (args.parseNetlist === false) return { source: 'sch_Net.*', count: 0, nets: [], hint: NET_EMPTY_HINT }
2271
+ const parsed = await parseNetlist(Array.isArray(all) ? all : project, timeoutMs)
2272
+ return parsed
2273
+ }
2274
+
2275
+ case 'eda_run_drc': {
2276
+ // includeVerboseError:true makes the API return one record per problem; the
2277
+ // boolean overload only said "something is wrong" and gave nothing to locate.
2278
+ const verbose = await callExtension('sch_Drc.check', [
2279
+ args.strict === undefined ? true : Boolean(args.strict), false, true,
2280
+ ], toolTimeout(args, timeoutMs))
2281
+ if (Array.isArray(verbose)) {
2282
+ return {
2283
+ ok: verbose.length === 0,
2284
+ count: verbose.length,
2285
+ entries: verbose.map((entry) => {
2286
+ const record = asRecord(entry)
2287
+ return {
2288
+ type: pickValue(record, 'Type', 'type', 'Level', 'level') ?? null,
2289
+ message: pickValue(record, 'Message', 'message', 'Error', 'error', 'Description', 'description') ?? null,
2290
+ primitiveId: pickValue(record, 'PrimitiveId', 'primitiveId') ?? null,
2291
+ x: pickValue(record, 'X', 'x') ?? null,
2292
+ y: pickValue(record, 'Y', 'y') ?? null,
2293
+ raw: entry,
2294
+ }
2295
+ }),
2296
+ hint: 'EDA 3.2.186 returns AGGREGATED entries only (e.g. {type:"warn",count:1}) even with includeVerboseError, so message/primitiveId stay null — "raw" carries exactly what the app sent. Per-problem coordinates are not available on this build; use eda_pcb_run_drc for the PCB side and the DRC panel for details.',
2297
+ }
2298
+ }
2299
+ return { ok: Boolean(verbose), count: null, entries: [], raw: verbose }
2300
+ }
2301
+
2302
+ case 'eda_auto_layout':
2303
+ case 'eda_auto_route': {
2304
+ // Standing rule from the user: do not auto-lay-out or auto-route unless asked.
2305
+ if (ALLOW_AUTO_LAYOUT !== true && args.force !== true) {
2306
+ throw new Error(name + ' is disabled by policy (settings allowAutoLayoutRouting=false, env DSH_EDA_ALLOW_AUTO_LAYOUT). Do NOT retry with force:true unless the user explicitly asked for automatic layout/routing.',
2307
+ '',
2308
+ 'Do this instead, in order:',
2309
+ '1. eda_get_active_document — make sure a schematic page is active (eda_open_document if not).',
2310
+ '2. eda_get_page_info — read the A4 frame and the safe areas before placing anything.',
2311
+ '3. eda_get_components — see what is already placed and where (x/y + bounding boxes) to avoid overlap.',
2312
+ '4. Place or move parts yourself on a 10-unit grid: eda_place_component for new ones, eda_move_component (keeps designator/value) to re-grid existing ones. Signal flow left to right, power rails on top, ground at the bottom, >=20 units between symbols for wires and labels.',
2313
+ '5. Connect with eda_draw_wire for local nets; for anything that spans the sheet use eda_place_net_port or a net label (a wire net name is overridden by connectivity once an endpoint touches a pin).',
2314
+ '6. Verify: eda_export_netlist (every net should have >=2 endpoints) and eda_run_drc (per-problem entries). For a visual check export the canvas to an image and look at it, rather than letting EDA rearrange the sheet.',
2315
+ '7. Call eda_workflow_guide for the full standard.',)
2316
+ }
2317
+ const payload = Array.isArray(args.uuids) ? { uuids: args.uuids.map(String) } : undefined
2318
+ return await callExtension(name === 'eda_auto_layout' ? 'sch_Document.autoLayout' : 'sch_Document.autoRouting', [payload], toolTimeout(args, timeoutMs))
2319
+ }
2320
+
2321
+ case 'eda_export_netlist': {
2322
+ const payload = await callExtension('sch_ManufactureData.getNetlistFile', [
2323
+ undefined, typeof args.type === 'string' && args.type !== '' ? args.type : undefined,
2324
+ ], toolTimeout(args, timeoutMs))
2325
+ const text = typeof payload === 'string'
2326
+ ? payload
2327
+ : (payload !== null && typeof payload === 'object' && typeof payload.text === 'string' ? payload.text : undefined)
2328
+ if (text === undefined) return { parsed: false, netlist: payload ?? null }
2329
+ if (args.format === 'text') return { parsed: false, netlistText: text, bytes: text.length }
2330
+ // The API hands back a JSON document; returning it as an escaped string forced
2331
+ // callers to parse twice (and once more through the MCP envelope).
2332
+ try {
2333
+ return { parsed: true, bytes: text.length, netlist: JSON.parse(text) }
2334
+ } catch {
2335
+ return { parsed: false, bytes: text.length, netlistText: text }
2336
+ }
2337
+ }
2338
+
2339
+ case 'eda_export_bom': {
2340
+ const format = args.format === 'xlsx' ? 'xlsx' : 'csv'
2341
+ const payload = await callExtension('sch_ManufactureData.getBomFile', [undefined, format], toolTimeout(args, timeoutMs))
2342
+ if (format === 'xlsx') return payload
2343
+ const raw = typeof payload === 'string'
2344
+ ? payload
2345
+ : (payload !== null && typeof payload === 'object' && typeof payload.text === 'string' ? payload.text : '')
2346
+ // Measured: with the PCB active the export answers null and this used to return
2347
+ // { bom: '', encoding: 'unknown' }, which reads like an empty BOM instead of the
2348
+ // real cause. Say it plainly, like eda_export_netlist does.
2349
+ if (raw === '') {
2350
+ throw new Error('eda_export_bom: no BOM data (the schematic page must be the active document; ' +
2351
+ 'call eda_get_active_document, then eda_open_document on the schematic page and retry)')
2352
+ }
2353
+ // The extension (0.4.1+) decodes text payloads with the encoding named by their BOM;
2354
+ // decodeTextPayload stays as a fallback for older extensions.
2355
+ const encoding = payload !== null && typeof payload === 'object' ? payload.encoding : undefined
2356
+ return { format, bom: decodeTextPayload(raw), encoding: encoding ?? 'unknown' }
2357
+ }
2358
+
2359
+ case 'eda_delete_primitive': {
2360
+ const kind = String(args.kind)
2361
+ // Net ports / flags / labels are attribute primitives; without these kinds the
2362
+ // only way to remove one was to remember the id from the placement call.
2363
+ const className = kind === 'netport' || kind === 'netflag' || kind === 'netlabel'
2364
+ ? 'sch_PrimitiveAttribute'
2365
+ : primitiveKindToClass(kind)
2366
+ return await callExtension(className + '.delete', [String(args.primitiveId)], timeoutMs)
2367
+ }
2368
+
2369
+ case 'eda_move_component':
2370
+ // Schematic parts could only be moved through raw sch_PrimitiveComponent.modify.
2371
+ return await callExtension('sch_PrimitiveComponent.modify', [String(args.primitiveId), {
2372
+ x: args.x === undefined ? undefined : Number(args.x),
2373
+ y: args.y === undefined ? undefined : Number(args.y),
2374
+ rotation: args.rotation === undefined ? undefined : Number(args.rotation),
2375
+ mirror: args.mirror === undefined ? undefined : Boolean(args.mirror),
2376
+ }], timeoutMs)
2377
+
2378
+ case 'eda_extension_package': {
2379
+ // The package ships only lib/extension-digest.json (no zip): the artifact itself lives on
2380
+ // the download server. The expected digest comes from that manifest, so a served copy can
2381
+ // be verified even on a machine that has never had a local zip.
2382
+ const manifestPath = join(packageRoot(), 'lib', 'extension-digest.json')
2383
+ let expected: { version?: string; file?: string; bytes?: number; sha256?: string } = {}
2384
+ try {
2385
+ expected = JSON.parse(await readFile(manifestPath, 'utf8')) as typeof expected
2386
+ } catch {
2387
+ expected = {}
2388
+ }
2389
+ const version = typeof expected.version === 'string' && expected.version !== '' ? expected.version : VERSION
2390
+ const expectedSha256 = typeof expected.sha256 === 'string' ? expected.sha256 : ''
2391
+ const localPath = join(packageRoot(), extensionZipName(version))
2392
+ const localSource = existsSync(localPath) ? localPath : null
2393
+ const localBytes = localSource === null ? null : await readFile(localSource)
2394
+ const base = typeof args.base === 'string' && args.base !== ''
2395
+ ? args.base
2396
+ : (process.env.DSH_EDA_EXTENSION_BASE ?? 'http://159.75.130.207/eda/')
2397
+ const url = extensionDownloadUrl(base, version)
2398
+ const report = {
2399
+ version,
2400
+ expected: { bytes: Number(expected.bytes ?? 0), sha256: expectedSha256, manifest: manifestPath },
2401
+ localZip: localSource === null
2402
+ ? null
2403
+ : { path: localSource, bytes: localBytes!.byteLength, sha256: sha256Of(localBytes!) },
2404
+ url,
2405
+ }
2406
+ if (args.download !== true) return report
2407
+ const response = await fetch(url, { signal: AbortSignal.timeout(30000) })
2408
+ if (!response.ok) {
2409
+ const throttled = response.status === 429
2410
+ return {
2411
+ ...report,
2412
+ verified: 'unverified',
2413
+ httpStatus: response.status,
2414
+ error: throttled
2415
+ ? 'the download server throttled this IP (HTTP 429, 5 downloads/min per IP — burst 5). Wait about a minute and retry; nothing is wrong with the zip or the upload.'
2416
+ : 'download failed: HTTP ' + response.status + ' from ' + url,
2417
+ }
2418
+ }
2419
+ const remoteBytes = new Uint8Array(await response.arrayBuffer())
2420
+ const remoteSha256 = sha256Of(remoteBytes)
2421
+ const verdict = compareDigest(expectedSha256, remoteSha256)
2422
+ const result: Record<string, unknown> = {
2423
+ ...report,
2424
+ served: { url, bytes: remoteBytes.byteLength, sha256: remoteSha256 },
2425
+ verified: verdict,
2426
+ }
2427
+ if (verdict === 'match') {
2428
+ const outDir = typeof args.outDir === 'string' && args.outDir !== '' ? args.outDir : tmpdir()
2429
+ await mkdir(outDir, { recursive: true })
2430
+ const savedPath = join(outDir, extensionZipName(version))
2431
+ await writeFile(savedPath, remoteBytes)
2432
+ result.savedPath = savedPath
2433
+ result.next = 'In JLCEDA Pro: 扩展 → 导入扩展 → select this zip → restart the application (not a reload).'
2434
+ } else if (verdict === 'mismatch') {
2435
+ result.next = 'The served copy differs from the digest this plugin was built with (wire version ' + version +
2436
+ '). Do not import it: re-upload ' + extensionZipName(version) + ' from the build output to the download server.'
2437
+ } else {
2438
+ result.next = 'No expected digest in ' + manifestPath + '; rebuild the plugin so it records one.'
2439
+ }
2440
+ return result
2441
+ }
2442
+
2443
+ case 'eda_list_api_methods': {
2444
+ // Ask the running extension first: its answer is the real capability boundary.
2445
+ const live = await extensionApiMethods(timeoutMs, args.refresh === true)
2446
+ if (live !== undefined) {
2447
+ return {
2448
+ source: 'extension',
2449
+ extensionVersion: live.version,
2450
+ count: live.all.length,
2451
+ allowedCount: live.allowed.length,
2452
+ fileCount: live.files.length,
2453
+ fileMethods: live.files,
2454
+ methods: live.all,
2455
+ note: 'This is the list the connected extension enforces (dsh.internal.listApiMethods). sendable:true means eda_api_call will forward it.',
2456
+ }
2457
+ }
2458
+ return {
2459
+ source: 'bridge-local-copy',
2460
+ stale: true,
2461
+ count: ALLOWED_API.size,
2462
+ methods: [...ALLOWED_API].sort(),
2463
+ note: 'The connected extension does not expose its list (older zip), so this is the bridge copy — it may be narrower than what the extension accepts. eda_api_call forwards unknown methods and reports the extension verdict, so try the call instead of trusting this list.',
2464
+ }
2465
+ }
2466
+
2467
+ case 'pcb_draw_text': {
2468
+ const text = String(args.text ?? '')
2469
+ if (text.trim() === '') throw new Error('pcb_draw_text requires text')
2470
+ if (text.length > 200) throw new Error('pcb_draw_text: longer than 200 characters is probably a mistake; split it')
2471
+ const silkLayer = args.layer === undefined ? PCB_LAYERS.topSilkscreen : resolvePcbLayer(args.layer)
2472
+ const fontSize = args.fontSize === undefined ? 40 : Number(args.fontSize)
2473
+ // pcb_PrimitiveString is the PCB text primitive (silkscreen / assembly / document).
2474
+ return await callExtension('pcb_PrimitiveString.create', [
2475
+ silkLayer, Number(args.x), Number(args.y), text, 'Arial', fontSize,
2476
+ args.lineWidth === undefined ? Math.max(6, Math.round(fontSize / 6)) : Number(args.lineWidth),
2477
+ args.alignMode === undefined ? 1 : Number(args.alignMode),
2478
+ args.rotation === undefined ? 0 : Number(args.rotation),
2479
+ false, 0, Boolean(args.mirror ?? false), Boolean(args.locked ?? false),
2480
+ ], timeoutMs)
2481
+ }
2482
+
2483
+ case 'pcb_draw_mounting_hole': {
2484
+ const holeX = Number(args.x)
2485
+ const holeY = Number(args.y)
2486
+ const holeDiameter = Number(args.diameter)
2487
+ if (![holeX, holeY, holeDiameter].every(value => Number.isFinite(value)) || holeDiameter <= 0) {
2488
+ throw new Error('pcb_draw_mounting_hole requires numeric x/y and a positive diameter (mil)')
2489
+ }
2490
+ if (holeDiameter < 20) throw new Error('pcb_draw_mounting_hole: ' + holeDiameter + ' mil is smaller than any drill (>= 20 mil)')
2491
+ const holeShape = String(args.shape ?? 'round')
2492
+ const holeRotation = args.rotation === undefined ? 0 : Number(args.rotation)
2493
+ // Mounting holes are non-plated by default: metallization:false, no net, no pad copper.
2494
+ const metallization = args.plated === true
2495
+ let holeSpec
2496
+ if (holeShape === 'slot') {
2497
+ const slotLength = args.slotLength === undefined ? holeDiameter * 2 : Number(args.slotLength)
2498
+ if (!Number.isFinite(slotLength) || slotLength <= holeDiameter) {
2499
+ throw new Error('pcb_draw_mounting_hole: slotLength must exceed the slot width (diameter)')
2500
+ }
2501
+ holeSpec = ['SLOT', holeDiameter, slotLength]
2502
+ } else {
2503
+ holeSpec = ['ROUND', holeDiameter]
2504
+ }
2505
+ const holeLayer = args.layer === undefined ? PCB_LAYERS.multi : resolvePcbLayer(args.layer)
2506
+ // The pad shape is mandatory: without it the app answers "无法创建焊盘图元".
2507
+ // A non-plated hole is a pad with metallization:false and pad == hole (plus an
2508
+ // optional annulus), so the drill and the mask aperture line up.
2509
+ const annulus = args.annulus === undefined ? 0 : Number(args.annulus)
2510
+ if (!Number.isFinite(annulus) || annulus < 0) throw new Error('pcb_draw_mounting_hole: annulus must be >= 0 (mil)')
2511
+ const slotLengthValue = args.slotLength === undefined ? holeDiameter * 2 : Number(args.slotLength)
2512
+ // The app accepts an ELLIPSE pad for a SLOT hole (major axis = slot length);
2513
+ // OBLONG/RECTANGLE pads are rejected with "无法创建焊盘图元".
2514
+ const padShape = holeShape === 'slot'
2515
+ ? ['ELLIPSE', slotLengthValue + annulus * 2, holeDiameter + annulus * 2]
2516
+ : ['ELLIPSE', holeDiameter + annulus * 2, holeDiameter + annulus * 2]
2517
+ return await callExtension('pcb_PrimitivePad.create', [
2518
+ holeLayer, String(args.padNumber ?? ''), holeX, holeY, holeRotation, padShape, undefined, holeSpec,
2519
+ 0, 0, 0, metallization, undefined, undefined, undefined, undefined, false,
2520
+ ], timeoutMs)
2521
+ }
2522
+
2523
+ case 'eda_schematic_audit': {
2524
+ const paper = paperOf(args.paper)
2525
+ const frame = paper.frame
2526
+ const frameArea = (frame.right - frame.left) * (frame.top - frame.bottom)
2527
+ const rawList = await callExtension('sch_PrimitiveComponent.getAll', [], timeoutMs)
2528
+ const list = Array.isArray(rawList) ? rawList.slice(0, 200) : []
2529
+ const components = []
2530
+ let droppedSheetPrimitives = 0
2531
+ for (let index = 0; index < list.length; index += 1) {
2532
+ const entry = list[index] ?? {}
2533
+ const designator = String(entry.designator ?? entry.Designator ?? entry.Name ?? entry.name ?? ('#' + index))
2534
+ const id = String(entry.primitiveId ?? entry.PrimitiveId ?? '')
2535
+ let bounds
2536
+ if (id !== '') {
2537
+ const box = await bboxOf([id], timeoutMs)
2538
+ if (box !== undefined) bounds = { left: box.minX, right: box.maxX, bottom: box.minY, top: box.maxY }
2539
+ }
2540
+ // Frame / title-block primitives live in the same list and their box is the whole
2541
+ // sheet (measured: one entry reported 0..1170 x 0..825 and then 'overlapped'
2542
+ // every symbol and the title block).
2543
+ if (bounds !== undefined) {
2544
+ const boundsArea = (bounds.right - bounds.left) * (bounds.top - bounds.bottom)
2545
+ if (boundsArea > frameArea * 0.4) { bounds = undefined; droppedSheetPrimitives += 1 }
2546
+ }
2547
+ components.push({ designator, x: Number(entry.x ?? entry.X ?? 0), y: Number(entry.y ?? entry.Y ?? 0), bounds })
2548
+ }
2549
+ const report = auditSchematicGeometry({
2550
+ components,
2551
+ frame,
2552
+ titleBlock: paper.titleBlock,
2553
+ grid: args.grid === undefined ? 10 : Number(args.grid),
2554
+ })
2555
+ const checks = args.includeOk === true ? report.checks : report.checks.filter(check => check.status !== 'pass')
2556
+ return {
2557
+ ok: report.ok,
2558
+ counts: report.counts,
2559
+ componentCount: report.componentCount,
2560
+ boxesRead: components.filter(component => component.bounds !== undefined).length,
2561
+ droppedSheetPrimitives,
2562
+ checks,
2563
+ notes: droppedSheetPrimitives > 0
2564
+ ? ['Skipped ' + droppedSheetPrimitives + ' primitive(s) whose box covers the whole sheet (frame/title block); counting them made every symbol look overlapped.']
2565
+ : [],
2566
+ }
2567
+ }
2568
+
2569
+ case 'eda_delivery_checklist': {
2570
+ // One call that proves the board is ready. Two of the four steps only work with the
2571
+ // schematic active and two only with the PCB active, so the checklist switches
2572
+ // documents itself (switchDocuments:false keeps whatever is open).
2573
+ const steps = []
2574
+ const startedAt = new Date().toISOString()
2575
+ const project = await callExtension('dmt_Project.getCurrentProjectInfo', [], timeoutMs).catch(() => null)
2576
+ const boards = Array.isArray(project?.data) ? project.data : []
2577
+ const schematicPage = boards[0]?.schematic?.page?.[0]?.uuid ?? ''
2578
+ const pcbUuid = boards.find((board) => board?.pcb?.uuid)?.pcb?.uuid ?? ''
2579
+ // Document switching used to be the default and hung the call (openDocument + a
2580
+ // page load blocked the following netlist export). Default is now 'run with the
2581
+ // document this step needs active'; switchDocuments:true still tries to switch.
2582
+ const switchDocuments = args.switchDocuments !== false
2583
+ const documentType = async () => {
2584
+ try {
2585
+ const info = await callExtension('dmt_SelectControl.getCurrentDocumentInfo', [], timeoutMs)
2586
+ return Number(info?.documentType)
2587
+ } catch { return NaN }
2588
+ }
2589
+ const activate = async (uuid) => {
2590
+ if (typeof uuid !== 'string' || uuid === '') return false
2591
+ try {
2592
+ await callExtension('dmt_EditorControl.openDocument', [uuid], timeoutMs)
2593
+ // Give the editor a beat before the next API needs the page.
2594
+ await new Promise(resolve => setTimeout(resolve, 1500))
2595
+ return true
2596
+ } catch { return false }
2597
+ }
2598
+
2599
+ let netlistErc = null
2600
+ // Step documents: schematic steps need documentType 1, PCB steps need 3.
2601
+ const onSchematic = switchDocuments ? await activate(schematicPage) : (await documentType()) === 1
2602
+ if (!onSchematic) {
2603
+ steps.push({ step: 'netlist-erc', document: 'schematic', ok: false, skipped: 'schematic page is not the active document' })
2604
+ steps.push({ step: 'bom', document: 'schematic', ok: false, skipped: 'schematic page is not the active document' })
2605
+ } else {
2606
+ try {
2607
+ const parsedNetlist = await fetchParsedNetlist(timeoutMs)
2608
+ netlistErc = runNetlistErc(parsedNetlist)
2609
+ steps.push({
2610
+ step: 'netlist-erc',
2611
+ document: 'schematic',
2612
+ ok: netlistErc.ok,
2613
+ detail: netlistErc.counts,
2614
+ failing: netlistErc.checks.filter(check => check.status === 'fail').map(check => check.id),
2615
+ })
2616
+ } catch (error) {
2617
+ steps.push({ step: 'netlist-erc', document: 'schematic', ok: false, error: error instanceof Error ? error.message : String(error) })
2618
+ }
2619
+ }
2620
+
2621
+ let bom = null
2622
+ if (onSchematic) {
2623
+ try {
2624
+ const payload = await callExtension('sch_ManufactureData.getBomFile', [undefined, 'csv'], timeoutMs)
2625
+ const text = typeof payload === 'string' ? payload : (typeof payload?.text === 'string' ? payload.text : '')
2626
+ const lines = text === '' ? 0 : text.split(/\r?\n/).filter(line => line.trim() !== '').length
2627
+ bom = { rows: Math.max(0, lines - 1), ok: lines > 1 }
2628
+ steps.push({ step: 'bom', document: 'schematic', ok: bom.ok, detail: { rows: bom.rows }, ...(bom.ok ? {} : { error: 'no BOM rows exported' }) })
2629
+ } catch (error) {
2630
+ steps.push({ step: 'bom', document: 'schematic', ok: false, error: error instanceof Error ? error.message : String(error) })
2631
+ }
2632
+ }
2633
+ const onPcb = switchDocuments ? await activate(pcbUuid) : (await documentType()) === 3
2634
+ let pcbAudit = null
2635
+ if (!onPcb) {
2636
+ steps.push({ step: 'pcb-audit', document: 'pcb', ok: false, skipped: 'PCB is not the active document' })
2637
+ steps.push({ step: 'gerber', document: 'pcb', ok: false, skipped: 'PCB is not the active document' })
2638
+ } else {
2639
+ try {
2640
+ pcbAudit = await auditPcb({ drc: args.pcbDrc !== false }, timeoutMs)
2641
+ steps.push({
2642
+ step: 'pcb-audit',
2643
+ document: 'pcb',
2644
+ ok: (pcbAudit.violations ?? []).length === 0,
2645
+ detail: { violations: pcbAudit.violations?.length ?? null, warnings: pcbAudit.warnings?.length ?? null, drc: pcbAudit.drc },
2646
+ failing: (pcbAudit.violations ?? []).map(entry => entry.rule),
2647
+ })
2648
+ } catch (error) {
2649
+ steps.push({ step: 'pcb-audit', document: 'pcb', ok: false, error: error instanceof Error ? error.message : String(error) })
2650
+ }
2651
+ }
2652
+
2653
+ let gerber = null
2654
+ if (onPcb) {
2655
+ try {
2656
+ const payload = await callExtension('pcb_ManufactureData.getGerberFile', [undefined, undefined, undefined, undefined, undefined, undefined], timeoutMs)
2657
+ const bytes = payload && typeof payload === 'object'
2658
+ ? Number(payload.size ?? payload.bytes ?? 0)
2659
+ : (typeof payload === 'string' ? payload.length : 0)
2660
+ gerber = { bytes, ok: bytes > 1000 }
2661
+ steps.push({ step: 'gerber', document: 'pcb', ok: gerber.ok, detail: { bytes } })
2662
+ } catch (error) {
2663
+ steps.push({ step: 'gerber', document: 'pcb', ok: false, error: error instanceof Error ? error.message : String(error) })
2664
+ }
2665
+ }
2666
+
2667
+ const failedSteps = steps.filter(step => step.ok !== true && step.skipped === undefined)
2668
+ const skippedSteps = steps.filter(step => step.ok !== true && step.skipped !== undefined)
2669
+ const verdict = failedSteps.length > 0 ? 'fail' : (skippedSteps.length > 0 ? 'incomplete' : 'pass')
2670
+ const report = {
2671
+ ok: verdict === 'pass',
2672
+ verdict,
2673
+ failedSteps: failedSteps.map(step => step.step),
2674
+ skippedSteps: skippedSteps.map(step => step.step),
2675
+ next: verdict === 'pass'
2676
+ ? 'Every step passed: the board can be ordered.'
2677
+ : (verdict === 'incomplete'
2678
+ ? 'Run the checklist again with the other document active (' + skippedSteps.map(step => step.document).filter((value, index, all) => all.indexOf(value) === index).join(', ') + ' needed).'
2679
+ : 'Fix the failing steps first; skipped steps are listed separately.'),
2680
+ startedAt,
2681
+ finishedAt: new Date().toISOString(),
2682
+ documents: { schematicPage, pcb: pcbUuid, switched: switchDocuments },
2683
+ netlistErc: netlistErc === null ? null : { ok: netlistErc.ok, counts: netlistErc.counts, componentCount: netlistErc.componentCount, netCount: netlistErc.netCount },
2684
+ pcbAudit: pcbAudit === null ? null : { violations: pcbAudit.violations, warnings: pcbAudit.warnings },
2685
+ gerber,
2686
+ bom,
2687
+ }
2688
+
2689
+ const outPath = args.outPath === undefined ? '' : String(args.outPath).trim()
2690
+ if (outPath !== '') {
2691
+ const markdown = [
2692
+ '# 交付检查报告',
2693
+ '',
2694
+ '- 开始:' + report.startedAt,
2695
+ '- 结束:' + report.finishedAt,
2696
+ '- 结论:' + (report.ok ? 'PASS(可以下单)' : 'FAIL(有未通过项)'),
2697
+ '- 原理图页:' + (schematicPage || '未取到'),
2698
+ '- PCB:' + (pcbUuid || '未取到'),
2699
+ '',
2700
+ '| 步骤 | 文档 | 结果 | 说明 |',
2701
+ '|---|---|---|---|',
2702
+ ...steps.map(step => '| ' + step.step + ' | ' + step.document + ' | ' + (step.ok === true ? 'PASS' : 'FAIL') + ' | ' + JSON.stringify(step.detail ?? step.error ?? {}) + ' |'),
2703
+ '',
2704
+ '## 电气检查(eda_netlist_erc)',
2705
+ '',
2706
+ ...(netlistErc === null ? ['(未执行)'] : netlistErc.checks.map(check => '- [' + check.status + '] ' + check.id + ':' + check.message)),
2707
+ '',
2708
+ '## PCB 审计',
2709
+ '',
2710
+ ...(pcbAudit === null ? ['(未执行)'] : [
2711
+ '- 违规:' + (pcbAudit.violations ?? []).length,
2712
+ '- 警告:' + (pcbAudit.warnings ?? []).length,
2713
+ ...(pcbAudit.violations ?? []).map(entry => ' - ' + entry.rule + ':' + entry.message),
2714
+ ...(pcbAudit.warnings ?? []).map(entry => ' - (warn) ' + entry.rule + ':' + entry.message),
2715
+ ]),
2716
+ '',
2717
+ '## 制造文件',
2718
+ '',
2719
+ '- Gerber:' + (gerber === null ? '未导出' : gerber.bytes + ' 字节'),
2720
+ '- BOM:' + (bom === null ? '未导出' : bom.rows + ' 行'),
2721
+ '',
2722
+ ].join('\n')
2723
+ await writeFile(outPath, markdown)
2724
+ report.reportPath = outPath
2725
+ }
2726
+ return report
2727
+ }
2728
+
2729
+
2730
+ case 'eda_design_intake': {
2731
+ if (args.reset === true) designBrief = null
2732
+ if (designBrief === null) {
2733
+ try {
2734
+ const project = await callExtension('dmt_Project.getCurrentProjectInfo', [], timeoutMs)
2735
+ const stored = parseBriefBlock(project?.description)
2736
+ if (stored !== null) designBrief = stored
2737
+ } catch { /* no project open: session-only */ }
2738
+ }
2739
+ const answers = args.answers !== undefined && args.answers !== null ? args.answers : null
2740
+ const answersReport = buildIntake(answers)
2741
+ const merged = { ...(designBrief ?? {}), ...answersReport.brief }
2742
+ const mergedReport = buildIntake(merged)
2743
+ let persisted = false
2744
+ let persistVia = 'none'
2745
+ let persistPath = ''
2746
+ if (Object.keys(merged).length > 0) {
2747
+ designBrief = merged
2748
+ if (answers !== null) {
2749
+ try {
2750
+ const project = await callExtension('dmt_Project.getCurrentProjectInfo', [], timeoutMs)
2751
+ const projectUuid = String(project?.uuid ?? '')
2752
+ const existing = typeof project?.description === 'string' ? project.description : ''
2753
+ const index = existing.indexOf(BRIEF_TAG)
2754
+ const base = index < 0 ? existing : existing.slice(0, index).trimEnd()
2755
+ const next = (base === '' ? '' : base + '\n') + briefBlock(merged)
2756
+ // The description write is inert on this build (measured: returns false and
2757
+ // the description stays empty), so fall back to a sidecar file next to the
2758
+ // local project directory and verify whichever path was used.
2759
+ let stored = false
2760
+ if (projectUuid !== '') {
2761
+ try {
2762
+ await callExtension('dmt_Project.modifyProjectDescription', [projectUuid, next], timeoutMs)
2763
+ const readBack = await callExtension('dmt_Project.getCurrentProjectInfo', [], timeoutMs)
2764
+ stored = String(readBack?.description ?? '').includes(BRIEF_TAG)
2765
+ if (stored) persistVia = 'description'
2766
+ } catch { stored = false }
2767
+ }
2768
+ if (!stored) {
2769
+ const sidecar = specFilePath(project)
2770
+ if (sidecar !== '') {
2771
+ await mkdir(join(sidecar, '..'), { recursive: true })
2772
+ await writeFile(sidecar, JSON.stringify({ projectUuid, brief: merged }, null, 2) + '\n')
2773
+ const check = JSON.parse(await readFile(sidecar, 'utf8'))
2774
+ stored = check !== null && typeof check === 'object' && Object.keys(merged).every(key => check.brief?.[key] === merged[key])
2775
+ if (stored) { persistVia = 'file'; persistPath = sidecar }
2776
+ }
2777
+ }
2778
+ persisted = stored === true
2779
+ } catch { persisted = false }
2780
+ }
2781
+ }
2782
+ return {
2783
+ ready: mergedReport.ready,
2784
+ questionCount: mergedReport.questionCount,
2785
+ criticalCount: mergedReport.criticalCount,
2786
+ answered: mergedReport.answered,
2787
+ missingCritical: mergedReport.missingCritical,
2788
+ unknownAnswerKeys: mergedReport.unknownAnswerKeys,
2789
+ brief: mergedReport.brief,
2790
+ hydratedFromProject: answers === null && designBrief !== null,
2791
+ persisted,
2792
+ persistVia,
2793
+ persistPath,
2794
+ sections: mergedReport.sections.filter(section => section.questions.some(question => mergedReport.brief[question.id] === undefined)),
2795
+ next: mergedReport.ready
2796
+ ? 'All critical parameters are known: lay out the schematic, then eda_netlist_erc before routing.'
2797
+ : 'Ask the user for the missing critical parameters with ask_user_question, grouped by section, before placing parts. Do not invent values.',
2798
+ }
2799
+ }
2800
+
2801
+ case 'eda_netlist_erc': {
2802
+ const netlistData = await fetchParsedNetlist(timeoutMs)
2803
+ const report = runNetlistErc(netlistData)
2804
+ const listed = args.includeOk === true ? report.checks : report.checks.filter(check => check.status !== 'pass')
2805
+ return {
2806
+ ok: report.ok,
2807
+ counts: report.counts,
2808
+ componentCount: report.componentCount,
2809
+ netCount: report.netCount,
2810
+ checks: listed,
2811
+ hint: report.ok
2812
+ ? 'No electrical failure found. This is a smoke test, not a simulation: run eda_run_drc and review the schematic as well.'
2813
+ : 'Fix the failing checks before routing; eda_run_drc on this build only returns aggregated counts, so this list is the actionable signal.',
2814
+ }
2815
+ }
2816
+
2817
+ case 'eda_pcb_canvas_origin': {
2818
+ // The UI shows canvas coordinates while every API uses data coordinates.
2819
+ const setTo = args.align === true
2820
+ ? [0, 0]
2821
+ : (args.offsetX === undefined && args.offsetY === undefined ? null : [Number(args.offsetX ?? 0), Number(args.offsetY ?? 0)])
2822
+ let aligned = null
2823
+ if (setTo !== null) aligned = await callExtension('pcb_Document.setCanvasOrigin', setTo, timeoutMs)
2824
+ const origin = await callExtension('pcb_Document.getCanvasOrigin', [], timeoutMs)
2825
+ const out = {
2826
+ canvasOrigin: origin,
2827
+ aligned,
2828
+ note: 'JLCEDA displays canvas coordinates; APIs use data coordinates. align:true sets the offset to zero so both agree.',
2829
+ }
2830
+ const point = args.point
2831
+ if (point !== null && typeof point === 'object') {
2832
+ const px = Number(point.x)
2833
+ const py = Number(point.y)
2834
+ if (Number.isFinite(px) && Number.isFinite(py)) {
2835
+ out.point = {
2836
+ input: { x: px, y: py },
2837
+ canvasToData: await callExtension('pcb_Document.convertCanvasOriginToDataOrigin', [px, py], timeoutMs),
2838
+ dataToCanvas: await callExtension('pcb_Document.convertDataOriginToCanvasOrigin', [px, py], timeoutMs),
2839
+ }
2840
+ }
2841
+ }
2842
+ return out
2843
+ }
2844
+
2845
+ case 'eda_capture': {
2846
+ // Captures are scratch files: remember every path written so a later call can
2847
+ // delete them (cleanup:true) instead of leaving PNGs in the temp directory.
2848
+ if (args.cleanup === true) {
2849
+ const removed = []
2850
+ const failed = []
2851
+ for (const file of capturedFiles.splice(0, capturedFiles.length)) {
2852
+ try { await unlink(file); removed.push(file) } catch { failed.push(file) }
2853
+ }
2854
+ return { ok: failed.length === 0, removed, failed, hint: 'Capture files are scratch: delete them as soon as you have looked at the image.' }
2855
+ }
2856
+ // Geometry math is no substitute for looking at the document.
2857
+ const captured = await callExtension('dmt_EditorControl.getCurrentRenderedAreaImage', [], toolTimeout(args, timeoutMs))
2858
+ const dataUrl = typeof captured === 'string'
2859
+ ? captured
2860
+ : (captured !== null && typeof captured === 'object' && typeof captured.dataUrl === 'string' ? captured.dataUrl : '')
2861
+ if (dataUrl === '') throw new Error('eda_capture: the app returned no image (is a document tab active?)')
2862
+ const base64 = dataUrl.includes(',') ? dataUrl.slice(dataUrl.indexOf(',') + 1) : dataUrl
2863
+ const pngBytes = Buffer.from(base64, 'base64')
2864
+ const capturePath = args.outPath === undefined ? '' : String(args.outPath).trim()
2865
+ if (capturePath !== '') {
2866
+ await writeFile(capturePath, pngBytes)
2867
+ capturedFiles.push(capturePath)
2868
+ return {
2869
+ ok: true, written: capturePath, bytes: pngBytes.length,
2870
+ hint: 'Read the file with the image reader, then call eda_capture({cleanup:true}) so the scratch PNG does not linger.',
2871
+ }
2872
+ }
2873
+ if (args.inline === true) return { ok: true, bytes: pngBytes.length, dataUrl }
2874
+ return { ok: true, bytes: pngBytes.length, dataUrlPrefix: dataUrl.slice(0, 32), hint: 'Pass outPath to save a PNG, or inline:true to receive the data URL.' }
2875
+ }
2876
+
2877
+ case 'eda_workflow_guide':
2878
+ return { summary: WORKFLOW_SUMMARY, guide: WORKFLOW_GUIDE, autoLayoutAllowed: ALLOW_AUTO_LAYOUT }
2879
+
2880
+ case 'eda_create_board':
2881
+ return await callExtension('dmt_Board.createBoard', [args.schematicUuid, args.pcbUuid], timeoutMs)
2882
+
2883
+ case 'eda_api_call': {
2884
+ if (!ALLOW_RAW_API) throw new Error('eda_api_call is disabled by settings (allowRawApi=false)')
2885
+ const method = String(args.method ?? '')
2886
+ // No local gate: the extension enforces its own allow-list, and gating here
2887
+ // with a drifted copy rejected methods that actually worked. Forward and
2888
+ // translate the extension's refusal into something actionable.
2889
+ try {
2890
+ return await callExtension(method, Array.isArray(args.args) ? args.args : [], timeoutMs)
2891
+ } catch (failure) {
2892
+ const message = failure instanceof Error ? failure.message : String(failure)
2893
+ if (!/not allowed/i.test(message)) throw failure
2894
+ const live = await extensionApiMethods(timeoutMs, true)
2895
+ const hint = live === undefined
2896
+ ? 'The connected extension rejected it and does not expose its list (older zip); eda_list_api_methods then shows the bridge copy, which may be narrower than reality.'
2897
+ : 'The extension enforces ' + live.all.length + ' methods right now (eda_list_api_methods source:"extension").'
2898
+ throw new Error('API method not allowed: ' + method + '. ' + hint +
2899
+ ' Wrapped helpers usually exist: eda_get_pins (pins), eda_place_net_labels (labels), eda_pcb_* (PCB primitives).')
2900
+ }
2901
+ }
2902
+
2903
+ case 'pcb_get_components': {
2904
+ const layer = resolvePcbLayer(args.layer)
2905
+ const raw = await callExtension('pcb_PrimitiveComponent.getAll', [layer, args.locked === undefined ? undefined : Boolean(args.locked)], timeoutMs)
2906
+ if (!Array.isArray(raw)) return raw
2907
+ const summarized = raw.map(summarizePrimitive)
2908
+ const enrich = async (item) => {
2909
+ const id = typeof item.primitiveId === 'string' ? item.primitiveId : undefined
2910
+ if (id === undefined) return item
2911
+ let enriched = item
2912
+ if (args.includePins === true) {
2913
+ try {
2914
+ // getAllPinsByPrimitiveId is the accurate pad/net source; the pads that
2915
+ // ride along with the component object can lag behind a netlist import.
2916
+ const pins = await callExtension('pcb_PrimitiveComponent.getAllPinsByPrimitiveId', [id], timeoutMs)
2917
+ if (Array.isArray(pins)) {
2918
+ enriched = {
2919
+ ...enriched,
2920
+ pins: pins.map(pin => summarizePrimitive(pin)),
2921
+ padNets: pins.map(pin => {
2922
+ const record = asRecord(pin)
2923
+ return { num: pickValue(record, 'Number', 'number', 'num', 'PadNumber'), net: pickValue(record, 'Net', 'net') }
2924
+ }).filter(entry => entry.num !== undefined || entry.net !== undefined),
2925
+ }
2926
+ }
2927
+ } catch { /* keep the summary */ }
2928
+ }
2929
+ if (args.includeBounds === false) return enriched
2930
+ try {
2931
+ const bboxRaw = await callExtension('pcb_Primitive.getPrimitivesBBox', [[id]], timeoutMs)
2932
+ const record = asRecord(bboxRaw)
2933
+ if (!Number.isFinite(Number(record.minX))) return enriched
2934
+ return { ...enriched, bbox: record, width: Number(record.maxX) - Number(record.minX), height: Number(record.maxY) - Number(record.minY) }
2935
+ } catch { return enriched }
2936
+ }
2937
+ return await mapLimit(summarized, 8, enrich)
2938
+ }
2939
+
2940
+ case 'pcb_get_nets': {
2941
+ if (typeof args.name === 'string' && args.name !== '') return await callExtension('pcb_Net.getAllNets', [], timeoutMs)
2942
+ if (args.detail === true) return await callExtension('pcb_Net.getAllNets', [], timeoutMs)
2943
+ return await callExtension('pcb_Net.getAllNetsName', [], timeoutMs)
2944
+ }
2945
+
2946
+ case 'pcb_get_layers':
2947
+ return await callExtension('pcb_Layer.getAllLayers', [], timeoutMs)
2948
+
2949
+ case 'pcb_place_component': {
2950
+ const layer = resolvePcbLayer(args.layer)
2951
+ if (layer === undefined) throw new Error('pcb_place_component requires a valid layer')
2952
+ return await callExtension('pcb_PrimitiveComponent.create', [
2953
+ { libraryUuid: String(args.libraryUuid), uuid: String(args.uuid) }, layer, Number(args.x), Number(args.y),
2954
+ args.rotation === undefined ? undefined : Number(args.rotation),
2955
+ ], timeoutMs)
2956
+ }
2957
+
2958
+ case 'pcb_draw_track': {
2959
+ const layer = resolvePcbLayer(args.layer)
2960
+ if (layer === undefined) throw new Error('pcb_draw_track requires a valid layer')
2961
+ const net = String(args.net)
2962
+ assertNetName(net, 'pcb_draw_track')
2963
+ await assertKnownPcbNet('pcb_draw_track', net, timeoutMs, args.force === true)
2964
+ // Width defaults to the role-based suggestion and is checked against the
2965
+ // 0.15 mm design minimum (docs/design-rules.md §5.1); force overrides.
2966
+ const width = checkTrackWidth(net, args.lineWidth === undefined ? undefined : Number(args.lineWidth), args.force === true)
2967
+ if (!width.ok) throw new Error('pcb_draw_track: ' + width.errors.join('; '))
2968
+ const created = await callExtension('pcb_PrimitiveLine.create', [
2969
+ net, layer, Number(args.startX), Number(args.startY), Number(args.endX), Number(args.endY),
2970
+ width.widthMil,
2971
+ ], timeoutMs)
2972
+ return { created, rules: { net, role: width.role, widthMil: width.widthMil, suggestedMil: width.suggestedMil, warnings: width.warnings } }
2973
+ }
2974
+
2975
+ case 'pcb_draw_via': {
2976
+ const net = String(args.net)
2977
+ assertNetName(net, 'pcb_draw_via')
2978
+ await assertKnownPcbNet('pcb_draw_via', net, timeoutMs, args.force === true)
2979
+ // Defaults follow the standard drill pairs; geometry is checked in mm.
2980
+ const role = classifyNet(net)
2981
+ const defaultVia = role === 'signal' ? VIA_SIZES_MM[0] : VIA_SIZES_MM[1]
2982
+ const hole = args.holeDiameter === undefined ? defaultVia.hole * 39.37007874015748 : Number(args.holeDiameter)
2983
+ const pad = args.diameter === undefined ? defaultVia.pad * 39.37007874015748 : Number(args.diameter)
2984
+ const via = checkVia(net, hole, pad, args.force === true)
2985
+ if (!via.ok) throw new Error('pcb_draw_via: ' + via.errors.join('; '))
2986
+ const created = await callExtension('pcb_PrimitiveVia.create', [
2987
+ net, Number(args.x), Number(args.y), hole, pad,
2988
+ args.viaType === undefined ? undefined : Number(args.viaType),
2989
+ ], timeoutMs)
2990
+ return {
2991
+ created,
2992
+ rules: {
2993
+ net, role, holeMm: Number(via.holeMm.toFixed(3)), padMm: Number(via.padMm.toFixed(3)),
2994
+ annulusMm: Number(via.annulusMm.toFixed(3)), warnings: via.warnings,
2995
+ },
2996
+ }
2997
+ }
2998
+
2999
+ case 'pcb_draw_board_outline': {
3000
+ const points = requireFlatPoints(args.points, tool)
3001
+ const lineWidth = args.lineWidth === undefined ? 10 : Number(args.lineWidth)
3002
+ if (!Number.isFinite(lineWidth) || lineWidth <= 0) throw new Error(tool + ': lineWidth must be a positive number')
3003
+ // A board outline is stored as ONE pcb_PrimitivePolyline whose polygon is
3004
+ // built from a TPCB_PolygonSourceArray (verified against JLCEDA project
3005
+ // files: ["POLY", id, 0, "", 11, 10, [x,y,"L",...], 1]). pcb_PrimitiveLine
3006
+ // is a copper track and refuses layer 11.
3007
+ const raw = await callExtension('dsh.internal.polylineCreate', [
3008
+ args.net === undefined ? '' : String(args.net),
3009
+ PCB_LAYERS.boardOutline,
3010
+ buildPolygonSource(points),
3011
+ lineWidth,
3012
+ args.locked === undefined ? undefined : Boolean(args.locked),
3013
+ ], timeoutMs)
3014
+ return {
3015
+ layer: 'BoardOutline', layerId: PCB_LAYERS.boardOutline, lineWidth,
3016
+ pointCount: points.length / 2, closed: true, polyline: summarizePrimitive(raw),
3017
+ }
3018
+ }
3019
+
3020
+ case 'pcb_draw_polyline': {
3021
+ const layer = resolvePcbLayer(args.layer)
3022
+ if (layer === undefined) throw new Error('pcb_draw_polyline requires a valid layer')
3023
+ const points = requireFlatPoints(args.points, 'pcb_draw_polyline')
3024
+ const lineWidth = args.lineWidth === undefined ? 10 : Number(args.lineWidth)
3025
+ if (!Number.isFinite(lineWidth) || lineWidth <= 0) throw new Error('pcb_draw_polyline: lineWidth must be a positive number')
3026
+ const raw = await callExtension('dsh.internal.polylineCreate', [
3027
+ args.net === undefined ? '' : String(args.net), layer, buildPolygonSource(points), lineWidth,
3028
+ args.locked === undefined ? undefined : Boolean(args.locked),
3029
+ ], timeoutMs)
3030
+ return { layer, layerId: layer, lineWidth, pointCount: points.length / 2, closed: true, polyline: summarizePrimitive(raw) }
3031
+ }
3032
+
3033
+ case 'eda_pcb_get_polylines': {
3034
+ const raw = await callExtension('pcb_PrimitivePolyline.getAll', [
3035
+ args.net === undefined ? undefined : String(args.net),
3036
+ args.layer === undefined ? undefined : resolvePcbLayer(args.layer),
3037
+ args.locked === undefined ? undefined : Boolean(args.locked),
3038
+ ], timeoutMs)
3039
+ if (!Array.isArray(raw)) return raw
3040
+ return { count: raw.length, polylines: raw.map(summarizePrimitive) }
3041
+ }
3042
+
3043
+ case 'eda_pcb_delete_polyline':
3044
+ return await callExtension('pcb_PrimitivePolyline.delete', [String(args.primitiveId)], timeoutMs)
3045
+
3046
+ case 'eda_pcb_clear_routing': {
3047
+ const type = args.type === undefined ? 'all' : String(args.type)
3048
+ if (type !== 'all' && type !== 'net' && type !== 'connection') throw new Error('eda_pcb_clear_routing: type must be all, net or connection')
3049
+ if (args.mode === 'batched') return await clearRoutingBatched(args, type, timeoutMs)
3050
+ if (args.wait === true) {
3051
+ return { mode: 'native', type, result: await callExtension('pcb_Document.clearRouting', [type], toolTimeout(args, timeoutMs)) }
3052
+ }
3053
+ // Clearing every track of a big board easily exceeds any MCP timeout while
3054
+ // EDA keeps working, so the native clear runs as a background job.
3055
+ try {
3056
+ const started = asRecord(await callExtension('dsh.internal.jobStart', ['clearRouting', type], timeoutMs))
3057
+ const running = started.started === true || started.alreadyRunning === true
3058
+ return {
3059
+ mode: 'native', started: started.started === true, alreadyRunning: started.alreadyRunning === true, running, type,
3060
+ startedAt: started.startedAt ?? null,
3061
+ hint: 'EDA is clearing the routing in the background. Poll eda_pcb_job_status until running=false (do not raise timeouts).',
3062
+ }
3063
+ } catch (error) {
3064
+ if (!isInternalHelperMissing(error)) throw error
3065
+ // Older EDA extension without the background-job helper: delete primitives
3066
+ // in bounded batches instead, so no single call can time out.
3067
+ const first = await clearRoutingBatched(args, type, timeoutMs)
3068
+ return { ...first, backgroundUnavailable: true, hint: 'The imported EDA extension has no background-job helper, so routing is deleted in bounded batches: call eda_pcb_clear_routing again until done=true.' }
3069
+ }
3070
+ }
3071
+
3072
+ case 'pcb_save_document':
3073
+ return await callExtension('pcb_Document.save', [], timeoutMs)
3074
+
3075
+ case 'pcb_import_changes': {
3076
+ const uuid = args.schematicUuid === undefined || args.schematicUuid === null ? null : String(args.schematicUuid)
3077
+ if (args.wait === true) {
3078
+ return await callExtension('pcb_Document.importChanges', [uuid === null ? undefined : uuid], toolTimeout(args, timeoutMs))
3079
+ }
3080
+ // The import opens EDA's own "sync schematic changes" confirmation dialog and
3081
+ // blocks until the user answers it, so it is fired as a background job and the
3082
+ // user's confirmation is detected by polling for newly imported components.
3083
+ pcbComponentBaseline = await pcbComponentIds(timeoutMs)
3084
+ let started
3085
+ try {
3086
+ started = asRecord(await callExtension('dsh.internal.jobStart', ['importChanges', uuid], timeoutMs))
3087
+ } catch (error) {
3088
+ if (!isInternalHelperMissing(error)) throw error
3089
+ // Older EDA extension: no background job helper, so the sync must be awaited.
3090
+ const result = await callExtension('pcb_Document.importChanges', [uuid === null ? undefined : uuid], toolTimeout(args, timeoutMs))
3091
+ const after = await pcbComponentIds(timeoutMs)
3092
+ return {
3093
+ triggered: true, backgroundUnavailable: true, importResult: result,
3094
+ componentsBefore: pcbComponentBaseline.length, componentsAfter: after.length,
3095
+ confirmedYet: after.length > pcbComponentBaseline.length,
3096
+ hint: 'The imported EDA extension has no background-job helper, so the sync was awaited. Re-import dsh-eda-bridge-extension-' + VERSION + '.zip to use the async + polling flow.',
3097
+ }
3098
+ }
3099
+ return {
3100
+ triggered: started.started === true || started.alreadyRunning === true,
3101
+ alreadyRunning: started.alreadyRunning === true,
3102
+ confirmedYet: false,
3103
+ componentsBefore: pcbComponentBaseline.length,
3104
+ hint: 'EDA is showing the sync confirmation dialog. Ask the user to click OK, then call eda_pcb_wait_for_components (low-frequency polling; it returns confirmed=true as soon as new PCB components appear).',
3105
+ }
3106
+ }
3107
+
3108
+ case 'eda_pcb_wait_for_components': {
3109
+ const interval = Math.max(3000, Number(args.pollIntervalMs ?? 5000) || 5000)
3110
+ const maxWait = Math.min(Math.max(Number(args.maxWaitMs ?? 45000) || 45000, interval), 300000)
3111
+ if (pcbComponentBaseline === null) pcbComponentBaseline = await pcbComponentIds(timeoutMs)
3112
+ const baseline = args.baselineIds === undefined && Array.isArray(args.baseline) ? args.baseline.map(String) : pcbComponentBaseline
3113
+ let waited = 0
3114
+ let ids = await pcbComponentIds(timeoutMs)
3115
+ while (true) {
3116
+ const fresh = ids.filter(id => !baseline.includes(id))
3117
+ if (fresh.length > 0) {
3118
+ return {
3119
+ confirmed: true, componentsBefore: baseline.length, componentsAfter: ids.length,
3120
+ newComponentIds: fresh, waitedMs: waited, pollIntervalMs: interval,
3121
+ hint: 'The user confirmed the sync and the PCB now has the new components. Save the PCB (pcb_save_document) before continuing.',
3122
+ }
3123
+ }
3124
+ if (waited >= maxWait) {
3125
+ return {
3126
+ confirmed: false, componentsBefore: baseline.length, componentsAfter: ids.length,
3127
+ waitedMs: waited, pollIntervalMs: interval,
3128
+ hint: 'Still no new PCB components - the user has not answered the sync dialog yet (or nothing changed). Ask them to click OK in EDA and call this tool again; polling runs at a deliberately low rate.',
3129
+ }
3130
+ }
3131
+ await sleep(interval)
3132
+ waited += interval
3133
+ ids = await pcbComponentIds(timeoutMs)
3134
+ }
3135
+ }
3136
+
3137
+ case 'pcb_get_primitives_in_region':
3138
+ return await callExtension('pcb_Document.getPrimitivesInRegion', [
3139
+ Number(args.left), Number(args.right), Number(args.top), Number(args.bottom),
3140
+ args.leftToRight === undefined ? undefined : Boolean(args.leftToRight),
3141
+ ], timeoutMs)
3142
+
3143
+ case 'pcb_navigate_to_region':
3144
+ return await callExtension('pcb_Document.navigateToRegion', [
3145
+ Number(args.left), Number(args.right), Number(args.top), Number(args.bottom),
3146
+ ], timeoutMs)
3147
+
3148
+ case 'eda_pcb_move_component': {
3149
+ const property = pickDefined({
3150
+ x: args.x === undefined ? undefined : Number(args.x),
3151
+ y: args.y === undefined ? undefined : Number(args.y),
3152
+ rotation: args.rotation === undefined ? undefined : Number(args.rotation),
3153
+ layer: args.layer === undefined ? undefined : resolvePcbLayer(args.layer),
3154
+ designator: args.designator,
3155
+ name: args.name,
3156
+ primitiveLock: args.locked === undefined ? undefined : Boolean(args.locked),
3157
+ }, ['x', 'y', 'rotation', 'layer', 'designator', 'name', 'primitiveLock'])
3158
+ const keys = Object.keys(property)
3159
+ if (keys.length === 0) throw new Error('eda_pcb_move_component requires at least one of x, y, rotation, layer, designator, name, locked')
3160
+ for (const key of ['x', 'y', 'rotation']) {
3161
+ if (property[key] !== undefined && !Number.isFinite(property[key])) throw new Error('eda_pcb_move_component: ' + key + ' must be a finite number')
3162
+ }
3163
+ if (args.layer !== undefined && property.layer === undefined) throw new Error('eda_pcb_move_component: invalid layer ' + String(args.layer))
3164
+ const raw = await callExtension('pcb_PrimitiveComponent.modify', [String(args.primitiveId), property], timeoutMs)
3165
+ return summarizePrimitive(raw)
3166
+ }
3167
+
3168
+ case 'eda_pcb_delete_component':
3169
+ return await callExtension('pcb_PrimitiveComponent.delete', [String(args.primitiveId)], timeoutMs)
3170
+
3171
+ case 'eda_pcb_get_tracks': {
3172
+ const raw = await pcbPrimitiveList('pcb_PrimitiveLine.getAll', [
3173
+ args.net === undefined ? undefined : String(args.net),
3174
+ args.layer === undefined ? undefined : resolvePcbLayer(args.layer),
3175
+ args.locked === undefined ? undefined : Boolean(args.locked),
3176
+ ], timeoutMs)
3177
+ return { count: raw.length, tracks: raw.map(summarizePrimitive) }
3178
+ }
3179
+
3180
+ case 'eda_pcb_modify_track': {
3181
+ const layer = args.layer === undefined ? undefined : resolvePcbLayer(args.layer)
3182
+ if (args.layer !== undefined && layer === undefined) throw new Error('eda_pcb_modify_track: invalid layer ' + String(args.layer))
3183
+ const property = pickDefined({
3184
+ net: args.net,
3185
+ layer,
3186
+ startX: args.startX === undefined ? undefined : Number(args.startX),
3187
+ startY: args.startY === undefined ? undefined : Number(args.startY),
3188
+ endX: args.endX === undefined ? undefined : Number(args.endX),
3189
+ endY: args.endY === undefined ? undefined : Number(args.endY),
3190
+ lineWidth: args.lineWidth === undefined ? undefined : Number(args.lineWidth),
3191
+ primitiveLock: args.locked === undefined ? undefined : Boolean(args.locked),
3192
+ }, ['net', 'layer', 'startX', 'startY', 'endX', 'endY', 'lineWidth', 'primitiveLock'])
3193
+ const keys = Object.keys(property)
3194
+ if (keys.length === 0) throw new Error('eda_pcb_modify_track requires at least one of net, layer, startX, startY, endX, endY, lineWidth, locked')
3195
+ for (const key of ['startX', 'startY', 'endX', 'endY', 'lineWidth']) {
3196
+ if (property[key] !== undefined && !Number.isFinite(property[key])) throw new Error('eda_pcb_modify_track: ' + key + ' must be a finite number')
3197
+ }
3198
+ const raw = await callExtension('pcb_PrimitiveLine.modify', [String(args.primitiveId), property], timeoutMs)
3199
+ return summarizePrimitive(raw)
3200
+ }
3201
+
3202
+ case 'eda_pcb_delete_track':
3203
+ return await callExtension('pcb_PrimitiveLine.delete', [String(args.primitiveId)], timeoutMs)
3204
+
3205
+ case 'eda_pcb_get_vias': {
3206
+ const raw = await pcbPrimitiveList('pcb_PrimitiveVia.getAll', [
3207
+ args.net === undefined ? undefined : String(args.net),
3208
+ args.locked === undefined ? undefined : Boolean(args.locked),
3209
+ ], timeoutMs)
3210
+ return { count: raw.length, vias: raw.map(summarizePrimitive) }
3211
+ }
3212
+
3213
+ case 'eda_pcb_delete_via':
3214
+ return await callExtension('pcb_PrimitiveVia.delete', [String(args.primitiveId)], timeoutMs)
3215
+
3216
+
3217
+ case 'eda_pcb_create_pour': {
3218
+ const layer = resolveRegionLayer(args.layer, 'eda_pcb_create_pour')
3219
+ const points = requireFlatPoints(args.points, 'eda_pcb_create_pour')
3220
+ assertNetName(String(args.net), 'eda_pcb_create_pour')
3221
+ const fill = args.pourFillMethod === undefined ? undefined : String(args.pourFillMethod)
3222
+ if (fill !== undefined && fill !== '45grid' && fill !== '90grid' && fill !== 'solid') throw new Error('eda_pcb_create_pour: pourFillMethod must be 45grid, 90grid or solid')
3223
+ // This build rejects pour creation ("无法创建覆铜边框图元") independently of the
3224
+ // fill method, so probe the polygon alone first: that separates "my points are
3225
+ // wrong" from "the app refuses pours through the API".
3226
+ let polygonOk = false
3227
+ try {
3228
+ const probe = await callExtension('pcb_MathPolygon.createPolygon', [buildPolygonSource(points)], timeoutMs)
3229
+ polygonOk = probe !== undefined && probe !== null
3230
+ } catch {
3231
+ polygonOk = false
3232
+ }
3233
+ // A conservative retry once, then a diagnosis the caller can act on.
3234
+ const attempt = async (fillMethod, preserveSilos) => callExtension('dsh.internal.pourCreate', [
3235
+ String(args.net), layer, buildPolygonSource(points), fillMethod,
3236
+ preserveSilos,
3237
+ args.pourName === undefined ? undefined : String(args.pourName),
3238
+ args.pourPriority === undefined ? undefined : Number(args.pourPriority),
3239
+ args.lineWidth === undefined ? undefined : Number(args.lineWidth),
3240
+ args.locked === undefined ? undefined : Boolean(args.locked),
3241
+ ], timeoutMs)
3242
+ let raw
3243
+ let retried = false
3244
+ try {
3245
+ raw = await attempt(fill, args.preserveSilos === undefined ? undefined : Boolean(args.preserveSilos))
3246
+ } catch (firstFailure) {
3247
+ retried = true
3248
+ try {
3249
+ raw = await attempt('solid', false)
3250
+ } catch (secondFailure) {
3251
+ const detail = secondFailure instanceof Error ? secondFailure.message : String(secondFailure)
3252
+ throw new Error('eda_pcb_create_pour failed twice (first: ' +
3253
+ (firstFailure instanceof Error ? firstFailure.message : String(firstFailure)) + '; retry: ' + detail + '). ' +
3254
+ 'polygonStage=' + (polygonOk ? 'ok' : 'failed') + ': ' +
3255
+ (polygonOk
3256
+ ? 'the app accepted the outline but refused the pour itself, and so does the complex polygon the docs require (createComplexPolygon); single and complex polygons, every net/layer/fill combination, all refused, so pour creation is an application limit on this build, not a coordinate problem. ' +
3257
+ 'Pour by hand in the PCB editor (覆铜 → select GND → top + bottom); eda_design_audit reports it as a warn until then.'
3258
+ : 'the outline polygon was rejected too: check that every point is inside the board outline and flat [x1,y1,...].') +
3259
+ ' retried=' + retried)
3260
+ }
3261
+ }
3262
+ return {
3263
+ net: String(args.net), layer, layerId: layer, pointCount: points.length / 2, pour: summarizePrimitive(raw), retried,
3264
+ rules: {
3265
+ clearanceMil: { required: POUR_CLEARANCE_MIN_MIL, recommended: POUR_CLEARANCE_RECOMMENDED_MIL },
3266
+ note: 'The pour/clearance value lives in the board design rules, not in this call: set it in 设计 → 设计规则 (recommended ' + POUR_CLEARANCE_RECOMMENDED_MIL + ' mil) and remove islands before exporting.',
3267
+ },
3268
+ }
3269
+ }
3270
+
3271
+ case 'eda_pcb_get_pours': {
3272
+ const raw = await callExtension('pcb_PrimitivePour.getAll', [
3273
+ args.net === undefined ? undefined : String(args.net),
3274
+ args.layer === undefined ? undefined : resolveRegionLayer(args.layer, 'eda_pcb_get_pours'),
3275
+ args.locked === undefined ? undefined : Boolean(args.locked),
3276
+ ], timeoutMs)
3277
+ if (!Array.isArray(raw)) return raw
3278
+ return { count: raw.length, pours: raw.map(summarizePrimitive) }
3279
+ }
3280
+
3281
+ case 'eda_pcb_delete_pour':
3282
+ return await callExtension('pcb_PrimitivePour.delete', [String(args.primitiveId)], timeoutMs)
3283
+
3284
+ case 'eda_pcb_run_drc': {
3285
+ const strict = args.strict === undefined ? true : Boolean(args.strict)
3286
+ const userInterface = args.userInterface === undefined ? false : Boolean(args.userInterface)
3287
+ const verbose = args.includeVerboseError === undefined ? true : Boolean(args.includeVerboseError)
3288
+ const callTimeout = toolTimeout(args, timeoutMs)
3289
+ const result = await callExtension('pcb_Drc.check', [strict, userInterface, verbose], callTimeout)
3290
+ if (Array.isArray(result)) {
3291
+ return { checkPassed: result.length === 0, violationCount: result.length, violations: result, strict, userInterface }
3292
+ }
3293
+ return { checkPassed: result === true, result, strict, userInterface }
3294
+ }
3295
+
3296
+ case 'eda_pcb_get_drc_rules': {
3297
+ const name = await callExtension('pcb_Drc.getCurrentRuleConfigurationName', [], timeoutMs)
3298
+ let configuration
3299
+ try { configuration = await callExtension('pcb_Drc.getCurrentRuleConfiguration', [], timeoutMs) } catch { configuration = undefined }
3300
+ const realTime = await (async () => { try { return await callExtension('pcb_Drc.getRealTimeDrcStatus', [], timeoutMs) } catch { return undefined } })()
3301
+ return { ruleConfigurationName: name ?? null, configuration: configuration ?? null, realTimeDrcRunning: realTime ?? null }
3302
+ }
3303
+
3304
+ case 'eda_pcb_set_net_track_width': {
3305
+ const net = String(args.net)
3306
+ const lineWidth = Number(args.lineWidth)
3307
+ if (!Number.isFinite(lineWidth) || lineWidth <= 0) throw new Error('eda_pcb_set_net_track_width: lineWidth must be a positive number (mil)')
3308
+ const width = checkTrackWidth(net, lineWidth, args.force === true)
3309
+ if (!width.ok) throw new Error('eda_pcb_set_net_track_width: ' + width.errors.join('; '))
3310
+ const layer = args.layer === undefined ? undefined : resolvePcbLayer(args.layer)
3311
+ if (args.layer !== undefined && layer === undefined) throw new Error('eda_pcb_set_net_track_width: invalid layer ' + String(args.layer))
3312
+ const raw = await callExtension('pcb_PrimitiveLine.getAll', [net, layer, undefined], timeoutMs)
3313
+ if (!Array.isArray(raw)) return raw
3314
+ const ids = raw.map(track => pickValue(asRecord(track), 'PrimitiveId', 'primitiveId')).filter(id => typeof id === 'string')
3315
+ const results = await mapLimit(ids, 8, async (id) => {
3316
+ try {
3317
+ await callExtension('pcb_PrimitiveLine.modify', [id, { lineWidth }], timeoutMs)
3318
+ return { primitiveId: id, ok: true }
3319
+ } catch (error) {
3320
+ return { primitiveId: id, ok: false, error: error instanceof Error ? error.message : String(error) }
3321
+ }
3322
+ })
3323
+ const failed = results.filter(item => item.ok === false)
3324
+ return { net, lineWidth, layer: layer ?? null, matched: ids.length, updated: ids.length - failed.length, failed, results: args.verbose === true ? results : undefined }
3325
+ }
3326
+
3327
+ case 'eda_design_audit':
3328
+ return await auditPcb(args, timeoutMs)
3329
+
3330
+ case 'eda_pcb_get_regions': {
3331
+ const raw = await callExtension('pcb_PrimitiveRegion.getAll', [
3332
+ args.layer === undefined ? undefined : resolveRegionLayer(args.layer, 'eda_pcb_get_regions'),
3333
+ Array.isArray(args.ruleType) ? args.ruleType.map(Number) : undefined,
3334
+ args.locked === undefined ? undefined : Boolean(args.locked),
3335
+ ], timeoutMs)
3336
+ if (!Array.isArray(raw)) return raw
3337
+ return { count: raw.length, regions: raw.map(summarizePrimitive) }
3338
+ }
3339
+
3340
+ case 'eda_pcb_create_region': {
3341
+ const layer = resolveRegionLayer(args.layer, 'eda_pcb_create_region')
3342
+ const points = requireFlatPoints(args.points, 'eda_pcb_create_region')
3343
+ const ruleType = Array.isArray(args.ruleType) && args.ruleType.length > 0 ? args.ruleType.map(Number) : undefined
3344
+ const lineWidth = args.lineWidth === undefined ? undefined : Number(args.lineWidth)
3345
+ const raw = await callExtension('dsh.internal.pcbCreateRegion', [
3346
+ layer, buildPolygonSource(points), ruleType,
3347
+ args.regionName === undefined ? undefined : String(args.regionName), lineWidth,
3348
+ args.locked === undefined ? undefined : Boolean(args.locked),
3349
+ ], timeoutMs)
3350
+ return { pointCount: points.length / 2, region: summarizePrimitive(raw) }
3351
+ }
3352
+
3353
+ case 'eda_pcb_delete_region':
3354
+ return await callExtension('pcb_PrimitiveRegion.delete', [String(args.primitiveId)], timeoutMs)
3355
+
3356
+ case 'eda_pcb_auto_place': {
3357
+ if (args.wait === false) {
3358
+ let started
3359
+ try {
3360
+ started = asRecord(await callExtension('dsh.internal.jobStart', ['autoLayout', null], timeoutMs))
3361
+ } catch (error) {
3362
+ if (!isInternalHelperMissing(error)) throw error
3363
+ const blocking = await callExtension('pcb_Document.autoLayout', [], toolTimeout(args, timeoutMs))
3364
+ return { backgroundUnavailable: true, result: blocking, hint: 'The imported EDA extension has no background-job helper, so layout was awaited.' }
3365
+ }
3366
+ return { started: started.started === true, alreadyRunning: started.alreadyRunning === true, running: started.started === true || started.alreadyRunning === true, hint: 'Poll eda_pcb_job_status until running=false.' }
3367
+ }
3368
+ return await callExtension('pcb_Document.autoLayout', [], toolTimeout(args, timeoutMs))
3369
+ }
3370
+
3371
+ case 'eda_pcb_job_status': {
3372
+ const status = asRecord(await callExtension('dsh.internal.jobStatus', [], timeoutMs))
3373
+ if (status.job === null && status.running === false) {
3374
+ return { running: false, job: null, hint: 'No background PCB job has been started in this EDA session (or the extension was reloaded).' }
3375
+ }
3376
+ const finished = asRecord(status.result)
3377
+ const failed = Array.isArray(finished.failedNets) ? finished.failedNets : []
3378
+ if (typeof status.result === 'boolean') {
3379
+ return {
3380
+ ...status, error,
3381
+ hint: status.result === true
3382
+ ? 'Finished: EDA reported the operation succeeded. Routing is cleared - re-run eda_pcb_auto_route when you want to route again.'
3383
+ : 'Finished, but EDA reported failure (nothing was cleared or the operation was rejected).',
3384
+ }
3385
+ }
3386
+ const error = status.error === null || status.error === undefined ? null : String(status.error)
3387
+ const hint = status.running === true
3388
+ ? 'Still running in EDA; poll again in ~10 s.'
3389
+ : (error !== null
3390
+ ? 'The job failed: ' + error
3391
+ : (finished.success === false
3392
+ ? 'Finished with success=false. duration=0 means the engine refused to start (check that the board outline is one closed polyline on layer 11, that design rules exist, and that nets really have unrouted connections).'
3393
+ : (failed.length > 0 ? 'Finished with ' + failed.length + ' unrouted net(s); re-run only those nets, then run eda_pcb_run_drc.' : 'Finished. Next: eda_pcb_run_drc, then eda_pcb_set_net_track_width for power/GND nets.')))
3394
+ return { ...status, error, hint }
3395
+ }
3396
+
3397
+ case 'eda_pcb_auto_route': {
3398
+ const extra = args.props === undefined || args.props === null ? {} : asRecord(args.props)
3399
+ // The official doc example uses "nets" but the shipped implementation only
3400
+ // reads "RoutingNets", so both are accepted here.
3401
+ const explicit = args.RoutingNets ?? args.nets ?? extra.RoutingNets ?? extra.nets
3402
+ let requested
3403
+ const explicitEmpty = Array.isArray(explicit) && explicit.length === 0
3404
+ if (explicit !== undefined && explicit !== null && !explicitEmpty) requested = explicit
3405
+ else {
3406
+ // Every net must be passed explicitly: with an empty routingRange this EDA
3407
+ // build answers success=false, duration=0 and fails every net.
3408
+ const names = await callExtension('pcb_Net.getAllNetsName', [], timeoutMs)
3409
+ if (!Array.isArray(names) || names.length === 0) {
3410
+ throw new Error('eda_pcb_auto_route: the active PCB reports no nets. Either the PCB document is not the active tab (PCB APIs only work while the PCB page is in front - check eda_get_active_document / eda_open_document), or the schematic changes have not been imported yet (pcb_import_changes).')
3411
+ }
3412
+ requested = names.map(String)
3413
+ }
3414
+ const extraProps = Object.fromEntries(Object.entries(extra).filter(([key]) => key !== 'nets' && key !== 'RoutingNets'))
3415
+ const props = { RoutingNets: requested, ...extraProps }
3416
+ if (args.ignoreNets !== undefined) props.ignoreNets = args.ignoreNets
3417
+ if (args.layers !== undefined) props.layers = args.layers
3418
+ if (args.cornerStyle !== undefined) props.cornerStyle = args.cornerStyle
3419
+ if (args.optimization !== undefined) props.optimization = args.optimization
3420
+ if (args.existingPrimitiveMode !== undefined) props.existingPrimitiveMode = args.existingPrimitiveMode
3421
+ if (args.wait !== true) {
3422
+ let started
3423
+ try {
3424
+ started = asRecord(await callExtension('dsh.internal.jobStart', ['autoRoute', props], timeoutMs))
3425
+ } catch (error) {
3426
+ if (!isInternalHelperMissing(error)) throw error
3427
+ // Older EDA extension without the background-job helper: fall back to the
3428
+ // blocking call (which may hit the tool timeout for large boards).
3429
+ const blocking = asRecord(await callExtension('pcb_Document.autoRouting', [props], toolTimeout(args, timeoutMs)))
3430
+ return { ...blocking, backgroundUnavailable: true, props, hint: 'The imported EDA extension has no background-job helper, so routing was awaited. Re-import dsh-eda-bridge-extension-' + VERSION + '.zip to get the async + polling flow.' }
3431
+ }
3432
+ const running = started.started === true || started.alreadyRunning === true
3433
+ return {
3434
+ started: started.started === true, alreadyRunning: started.alreadyRunning === true, running,
3435
+ startedAt: started.startedAt ?? null, requestedNets: Array.isArray(requested) ? requested.length : 0, props,
3436
+ hint: started.started === true
3437
+ ? 'EDA is routing in the background (its progress bar is visible in the PCB editor). Poll eda_pcb_job_status until running=false, then run eda_pcb_run_drc. Do not raise timeouts - the job outlives the MCP call.'
3438
+ : 'A PCB job is already running; poll eda_pcb_job_status.',
3439
+ }
3440
+ }
3441
+ const result = await callExtension('pcb_Document.autoRouting', [props], toolTimeout(args, timeoutMs))
3442
+ const record = asRecord(result)
3443
+ const failed = Array.isArray(record.failedNets) ? record.failedNets : []
3444
+ const requestedCount = Array.isArray(requested) ? requested.length : 0
3445
+ const hint = record.success === true
3446
+ ? (failed.length === 0 ? 'ok' : 'The router returned success but left ' + failed.length + ' net(s) unrouted.')
3447
+ : 'The router failed. duration=0 means it refused to start: check that the board outline is a single closed polyline on layer 11 (use pcb_draw_board_outline / eda_pcb_get_polylines), that the design rules are configured, and that the nets really have unrouted connections.'
3448
+ return { ...record, requestedNets: requestedCount, props, hint }
3449
+ }
3450
+
3451
+ case 'eda_pcb_export_gerber': {
3452
+ const unit = args.unit === undefined ? undefined : String(args.unit)
3453
+ if (unit !== undefined && unit !== 'mm' && unit !== 'inch') throw new Error('eda_pcb_export_gerber: unit must be "mm" or "inch"')
3454
+ const digitalFormat = args.integerNumber === undefined && args.decimalNumber === undefined ? undefined : {
3455
+ integerNumber: args.integerNumber === undefined ? 4 : Number(args.integerNumber),
3456
+ decimalNumber: args.decimalNumber === undefined ? 4 : Number(args.decimalNumber),
3457
+ }
3458
+ const payload = await callExtension('pcb_ManufactureData.getGerberFile', [
3459
+ args.fileName === undefined ? undefined : String(args.fileName),
3460
+ args.colorSilkscreen === undefined ? undefined : Boolean(args.colorSilkscreen),
3461
+ unit,
3462
+ digitalFormat,
3463
+ args.other === undefined ? undefined : asRecord(args.other),
3464
+ Array.isArray(args.layers) ? args.layers : undefined,
3465
+ Array.isArray(args.objects) ? args.objects : undefined,
3466
+ ], timeoutMs)
3467
+ if (payload === null || payload === undefined) throw new Error('eda_pcb_export_gerber: the API returned no file (is a PCB document active?)')
3468
+ return payload
3469
+ }
3470
+
3471
+ default:
3472
+ throw new Error('unknown tool: ' + name)
3473
+ }
3474
+ }
3475
+
3476
+ function writeJson(value) {
3477
+ process.stdout.write(JSON.stringify(value) + '\n')
3478
+ }
3479
+
3480
+ async function handleJsonRpc(message) {
3481
+ if (message === null || typeof message !== 'object') return
3482
+ if (message.jsonrpc !== '2.0') return
3483
+ if (message.id !== undefined && message.method !== undefined) {
3484
+ try {
3485
+ const result = await handleMethod(message.method, message.params ?? {}, message.id)
3486
+ if (result !== undefined) writeJson({ jsonrpc: '2.0', id: message.id, result })
3487
+ } catch (error) {
3488
+ writeJson({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } })
3489
+ }
3490
+ } else if (message.method !== undefined) {
3491
+ try { await handleMethod(message.method, message.params ?? {}, undefined) } catch { /* notifications best-effort */ }
3492
+ }
3493
+ }
3494
+
3495
+ async function handleMethod(method, params, _id) {
3496
+ if (method === 'initialize') {
3497
+ const protocolVersion = params && params.protocolVersion ? params.protocolVersion : '2024-11-05'
3498
+ return { protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'dsh-eda-mcp-bridge', version: VERSION } }
3499
+ }
3500
+ if (method === 'notifications/initialized') return undefined
3501
+ if (method === 'notifications/cancelled') return undefined
3502
+ if (method === 'ping') return {}
3503
+ if (method === 'tools/list') return { tools: TOOLS }
3504
+ if (method === 'tools/call') {
3505
+ const name = String((params && params.name) || '')
3506
+ const args = (params && params.arguments) || {}
3507
+ try { return toolResult(await executeTool(name, args, TOOL_TIMEOUT_MS)) }
3508
+ catch (error) { return toolError(error instanceof Error ? error.message : String(error)) }
3509
+ }
3510
+ throw new Error('method not found: ' + method)
3511
+ }
3512
+
3513
+ const server = createServer((req, res) => {
3514
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
3515
+ if (req.method === 'GET' && url.pathname === '/healthz') {
3516
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
3517
+ res.end(JSON.stringify({ status: 'ok', version: VERSION, clients: pickClients().length }))
3518
+ return
3519
+ }
3520
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
3521
+ res.end('not found')
3522
+ })
3523
+
3524
+ server.on('upgrade', (req, socket) => {
3525
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
3526
+ if (url.pathname !== '/ws') { socket.destroy(); return }
3527
+ const key = req.headers['sec-websocket-key']
3528
+ if (typeof key !== 'string' || key.length === 0) { socket.destroy(); return }
3529
+ const accept = createHash('sha1').update(key + WS_GUID).digest('base64')
3530
+ socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ' + accept + '\r\n\r\n')
3531
+ const client = new WsConnection(socket)
3532
+ clients.add(client)
3533
+ socket.on('data', (chunk) => { client.handleData(chunk) })
3534
+ socket.on('close', () => { clients.delete(client) })
3535
+ socket.on('error', () => { clients.delete(client) })
3536
+ })
3537
+
3538
+ server.on('error', (error) => {
3539
+ process.stderr.write('[dsh-eda-mcp] bridge ' + VERSION + ' failed to listen on ' + WS_HOST + ':' + WS_PORT + ' (' +
3540
+ (error && error.code ? error.code : String(error)) + '). Another dsh-eda-mcp bridge process is probably still running; ' +
3541
+ 'stop the stale process (netstat -ano | findstr ' + WS_PORT + ') and reconnect.\n')
3542
+ })
3543
+
3544
+ server.listen(WS_PORT, WS_HOST, () => {
3545
+ process.stderr.write('[dsh-eda-mcp] bridge ' + VERSION + ' listening on ws://' + WS_HOST + ':' + WS_PORT + '/ws\n')
3546
+ })
3547
+
3548
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity })
3549
+ rl.on('line', (line) => {
3550
+ try { void handleJsonRpc(JSON.parse(line)) } catch { /* ignore malformed stdin lines */ }
3551
+ })
3552
+
3553
+ let shuttingDown = false
3554
+ /**
3555
+ * Exit as soon as the host lets go of stdin.
3556
+ *
3557
+ * The desktop app allows the whole host shutdown 5 s and refuses to install an
3558
+ * update unless the host reports a clean exit, so the bridge must never sit in a
3559
+ * closing state: sockets are dialled closed best-effort and the process leaves on
3560
+ * the next tick instead of waiting for a server-close callback that a live
3561
+ * WebSocket can hold open forever.
3562
+ */
3563
+ function shutdown() {
3564
+ if (shuttingDown) return
3565
+ shuttingDown = true
3566
+ try { for (const client of clients) client.close() } catch { /* best effort */ }
3567
+ clients.clear()
3568
+ try { server.close() } catch { /* the OS releases the port on exit */ }
3569
+ process.exit(0)
3570
+ }
3571
+
3572
+ process.stdin.on('end', shutdown)
3573
+ process.stdin.on('close', shutdown)
3574
+ process.on('disconnect', shutdown)
3575
+ process.on('SIGTERM', shutdown)
3576
+ process.on('SIGINT', shutdown)