@huaqiu/hardware-artifacts 0.0.0-stage → 0.7.13

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.
package/src/service.ts ADDED
@@ -0,0 +1,1008 @@
1
+ /**
2
+ * Hardware Engineering artifact model and host operations.
3
+ *
4
+ * This module deliberately has no Cordis dependency: it is the testable core
5
+ * behind `hardwareArtifacts`. Native project files remain authoritative; the
6
+ * objects here are path pointers, verified installation facts and disposable
7
+ * derived outputs, never a shadow project database.
8
+ */
9
+ import { execFile, execFileSync, spawn, type ChildProcess } from 'node:child_process'
10
+ import { createHash } from 'node:crypto'
11
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from 'node:fs'
12
+ import { readFile } from 'node:fs/promises'
13
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
14
+ import { tmpdir } from 'node:os'
15
+
16
+ export type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'mechanical-3d'
17
+ /** Native handoff is KiCad-only in this POC; SolidCraft stays agent context. */
18
+ export type NativeApplication = 'kicad'
19
+
20
+ export interface HardwareArtifact {
21
+ readonly id: string
22
+ readonly kind: ArtifactKind
23
+ readonly path: string
24
+ readonly projectPath?: string
25
+ /** BOM keeps its schematic; PCB 3D keeps its board; sheets keep their root. */
26
+ readonly sourcePath?: string
27
+ readonly title: string
28
+ readonly format: string
29
+ /** Content hash of the saved source, filled when the source is read. */
30
+ readonly revision?: string
31
+ }
32
+
33
+ export interface HardwareProject {
34
+ readonly path: string
35
+ readonly name: string
36
+ /** Root schematic: the authoritative project entry point. */
37
+ readonly rootSheet?: HardwareArtifact
38
+ readonly schematic?: HardwareArtifact
39
+ /** Semantic views; both keep the identity of their source artifact. */
40
+ readonly bom?: HardwareArtifact
41
+ readonly pcb3d?: HardwareArtifact
42
+ readonly sheets: readonly HardwareArtifact[]
43
+ /** Deterministic default board, only when ownership is unambiguous. */
44
+ readonly defaultBoard?: string
45
+ readonly boards: readonly HardwareArtifact[]
46
+ readonly mechanical: readonly HardwareArtifact[]
47
+ readonly selectionRequired: boolean
48
+ }
49
+
50
+ export interface DiscoveryResult {
51
+ readonly cwd: string
52
+ readonly manifestPath?: string
53
+ readonly projects: readonly HardwareProject[]
54
+ readonly selected?: HardwareProject
55
+ readonly issue?: { readonly code: string; readonly message: string }
56
+ }
57
+
58
+ export interface InstallationInfo {
59
+ readonly configured: boolean
60
+ readonly root?: string
61
+ readonly cli?: string
62
+ readonly projectManager?: string
63
+ readonly pcbEditor?: string
64
+ readonly schematicEditor?: string
65
+ readonly executable?: string
66
+ readonly version?: string
67
+ readonly error?: string
68
+ }
69
+
70
+ export interface Installations {
71
+ readonly kicad: InstallationInfo
72
+ readonly solidcraft: InstallationInfo
73
+ }
74
+
75
+ export interface OpenArtifactRequest {
76
+ readonly application: NativeApplication
77
+ readonly artifactPath: string
78
+ readonly kind: ArtifactKind
79
+ readonly projectPath?: string
80
+ }
81
+
82
+ export interface OpenArtifactResult {
83
+ readonly launched: true
84
+ readonly command: string
85
+ readonly args: readonly string[]
86
+ readonly cwd: string
87
+ readonly pid?: number
88
+ }
89
+
90
+ export interface SourceRequest {
91
+ readonly artifactPath: string
92
+ readonly expectedRevision?: string
93
+ /** Workspace roots the caller is currently authorized to read. */
94
+ readonly roots?: readonly string[]
95
+ }
96
+
97
+ export interface SourceResult {
98
+ readonly path: string
99
+ readonly kind: 'schematic' | 'pcb'
100
+ readonly revision: string
101
+ readonly bytes: number
102
+ readonly mtimeMs: number
103
+ readonly text: string
104
+ }
105
+
106
+ export interface GlbRequest {
107
+ readonly artifactPath: string
108
+ readonly roots?: readonly string[]
109
+ readonly signal?: AbortSignal
110
+ }
111
+
112
+ export interface GlbResult {
113
+ readonly path: string
114
+ readonly revision: string
115
+ readonly bytes: number
116
+ readonly generatedAt: string
117
+ readonly cached: boolean
118
+ readonly file: string
119
+ }
120
+
121
+ /** One grouped BOM line, as KiCad's own BOM export groups it. */
122
+ export interface BomRow {
123
+ readonly references: readonly string[]
124
+ readonly quantity: number
125
+ readonly value: string
126
+ readonly footprint: string
127
+ readonly dnp: boolean
128
+ readonly fields: Readonly<Record<string, string>>
129
+ }
130
+
131
+ export interface BomResult {
132
+ readonly path: string
133
+ readonly revision: string
134
+ readonly generatedAt: string
135
+ readonly cached: boolean
136
+ readonly rows: readonly BomRow[]
137
+ readonly source: 'kicad-cli-bom'
138
+ }
139
+
140
+ export interface HardwareArtifactsOptions {
141
+ readonly kicadRoot?: string
142
+ readonly solidcraftRoot?: string
143
+ readonly probeVersion?: (executable: string) => string | undefined
144
+ readonly spawnProcess?: (
145
+ command: string,
146
+ args: readonly string[],
147
+ options: { cwd: string; detached: boolean; stdio: 'ignore'; windowsHide: boolean; shell: false },
148
+ ) => Pick<ChildProcess, 'pid'>
149
+ /** Runs one short-lived CLI command and returns its exit facts. */
150
+ readonly runCommand?: (
151
+ command: string,
152
+ args: readonly string[],
153
+ options: { cwd: string; timeoutMs: number; signal?: AbortSignal },
154
+ ) => Promise<{ exitCode: number | null; stdout: string; stderr: string; timedOut: boolean }>
155
+ /** Cache directory for derived outputs; defaults to a temp subdirectory. */
156
+ readonly cacheRoot?: string
157
+ readonly glbTimeoutMs?: number
158
+ /** Source text limit; protects the host from pathological files. */
159
+ readonly maxSourceBytes?: number
160
+ }
161
+
162
+ interface ProjectManifest {
163
+ project?: string
164
+ schematic?: string
165
+ boards?: readonly { id?: string; path: string }[]
166
+ mechanical?: readonly { id?: string; path: string }[]
167
+ }
168
+
169
+ const EXCLUDED_DIRS = new Set([
170
+ '.git', '.cache', 'node_modules', 'dist', 'build', 'out', 'tmp', 'temp',
171
+ 'archive', 'archives', 'backup', 'backups', 'export', 'exports',
172
+ ])
173
+ const MECHANICAL_EXTENSIONS = new Set(['.step', '.stp', '.glb'])
174
+ const SOURCE_EXTENSIONS: Readonly<Record<string, 'schematic' | 'pcb'>> = {
175
+ '.kicad_sch': 'schematic',
176
+ '.kicad_pcb': 'pcb',
177
+ }
178
+ const MAX_DEPTH = 5
179
+ /** KiCad writes each child sheet as `(property "Sheetfile" "child.kicad_sch")`. */
180
+ const SHEET_FILE_PATTERN = /\(property\s+"Sheetfile"\s+"((?:[^"\\]|\\.)*)"/gu
181
+
182
+ function canonical(path: string): string {
183
+ return resolve(path)
184
+ }
185
+
186
+ function isInside(child: string, parent: string): boolean {
187
+ const rel = relative(parent, child)
188
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
189
+ }
190
+
191
+ function isExcluded(name: string): boolean {
192
+ return EXCLUDED_DIRS.has(name.toLowerCase())
193
+ }
194
+
195
+ function realOrUndefined(path: string): string | undefined {
196
+ try {
197
+ return realpathSync(path)
198
+ } catch {
199
+ return undefined
200
+ }
201
+ }
202
+
203
+ function errorWithCode(message: string, code: string, status: number): Error {
204
+ return Object.assign(new Error(message), { code, status })
205
+ }
206
+
207
+ function walkFiles(root: string, predicate: (name: string) => boolean): string[] {
208
+ const found: string[] = []
209
+ const visit = (dir: string, depth: number): void => {
210
+ if (depth > MAX_DEPTH || !existsSync(dir)) return
211
+ let entries
212
+ try {
213
+ entries = readdirSync(dir, { withFileTypes: true })
214
+ } catch {
215
+ return
216
+ }
217
+ for (const entry of entries) {
218
+ const full = join(dir, entry.name)
219
+ if (entry.isDirectory()) {
220
+ if (!isExcluded(entry.name)) visit(full, depth + 1)
221
+ } else if (entry.isFile() && predicate(entry.name)) {
222
+ found.push(canonical(full))
223
+ }
224
+ }
225
+ }
226
+ visit(root, 0)
227
+ return found.sort()
228
+ }
229
+
230
+ /** Child schematics declared by sheet references in one saved schematic. */
231
+ function childSheetFiles(path: string): string[] {
232
+ let text: string
233
+ try {
234
+ text = readFileSync(path, 'utf8')
235
+ } catch {
236
+ return []
237
+ }
238
+ const dir = dirname(path)
239
+ const children: string[] = []
240
+ for (const match of text.matchAll(SHEET_FILE_PATTERN)) {
241
+ const raw = match[1]
242
+ if (raw === undefined || raw === '') continue
243
+ const declared = raw.replace(/\\(["\\])/gu, '$1')
244
+ const target = isAbsolute(declared) ? canonical(declared) : resolve(dir, declared)
245
+ children.push(target)
246
+ }
247
+ return children.sort()
248
+ }
249
+
250
+ function artifact(kind: ArtifactKind, path: string, projectPath?: string, sourcePath?: string): HardwareArtifact {
251
+ const full = canonical(path)
252
+ return {
253
+ id: `${kind}:${full}`,
254
+ kind,
255
+ path: full,
256
+ ...(projectPath === undefined ? {} : { projectPath: canonical(projectPath) }),
257
+ ...(sourcePath === undefined ? {} : { sourcePath: canonical(sourcePath) }),
258
+ title: basename(full),
259
+ format: extname(full).toLowerCase().replace(/^\./, '') || kind,
260
+ }
261
+ }
262
+
263
+ function defaultVersionProbe(executable: string): string | undefined {
264
+ if (!existsSync(executable)) return undefined
265
+ try {
266
+ return execFileSync(executable, ['version'], {
267
+ encoding: 'utf8',
268
+ timeout: 5_000,
269
+ stdio: ['ignore', 'pipe', 'ignore'],
270
+ }).trim().split('\n')[0] || undefined
271
+ } catch {
272
+ return undefined
273
+ }
274
+ }
275
+
276
+ function defaultRunCommand(
277
+ command: string,
278
+ args: readonly string[],
279
+ options: { cwd: string; timeoutMs: number; signal?: AbortSignal },
280
+ ): Promise<{ exitCode: number | null; stdout: string; stderr: string; timedOut: boolean }> {
281
+ return new Promise((resolvePromise, reject) => {
282
+ execFile(command, [...args], {
283
+ cwd: options.cwd,
284
+ timeout: options.timeoutMs,
285
+ encoding: 'utf8',
286
+ windowsHide: true,
287
+ shell: false,
288
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
289
+ maxBuffer: 8 * 1024 * 1024,
290
+ }, (error, stdout, stderr) => {
291
+ if (error === null) {
292
+ resolvePromise({ exitCode: 0, stdout: String(stdout), stderr: String(stderr), timedOut: false })
293
+ return
294
+ }
295
+ const killed = (error as { killed?: boolean }).killed === true
296
+ const signal = (error as { signal?: string | null }).signal
297
+ if (killed || signal !== null && signal !== undefined) {
298
+ resolvePromise({ exitCode: null, stdout: String(stdout), stderr: String(stderr), timedOut: true })
299
+ return
300
+ }
301
+ const code = typeof (error as { code?: unknown }).code === 'number' ? Number((error as { code: number }).code) : null
302
+ if (code === null) {
303
+ reject(error)
304
+ return
305
+ }
306
+ resolvePromise({ exitCode: code, stdout: String(stdout), stderr: String(stderr), timedOut: false })
307
+ })
308
+ })
309
+ }
310
+
311
+ function existing(paths: readonly string[]): string | undefined {
312
+ return paths.find((candidate) => {
313
+ try {
314
+ return existsSync(candidate) && statSync(candidate).isFile()
315
+ } catch {
316
+ return false
317
+ }
318
+ })
319
+ }
320
+
321
+ function kicadCandidates(root: string): { cli: string[]; kicad: string[]; eeschema: string[]; pcbnew: string[] } {
322
+ const app = basename(root).toLowerCase().endsWith('.app')
323
+ if (app || process.platform === 'darwin') {
324
+ const base = app ? root : join(root, 'KiCad.app')
325
+ return {
326
+ cli: [join(base, 'Contents/MacOS/kicad-cli')],
327
+ kicad: [join(base, 'Contents/MacOS/kicad')],
328
+ eeschema: [join(base, 'Contents/Applications/eeschema.app/Contents/MacOS/eeschema')],
329
+ pcbnew: [join(base, 'Contents/Applications/pcbnew.app/Contents/MacOS/pcbnew')],
330
+ }
331
+ }
332
+ const exe = process.platform === 'win32' ? '.exe' : ''
333
+ const bin = app ? root : basename(root).toLowerCase() === 'bin' ? root : join(root, 'bin')
334
+ return {
335
+ cli: [join(bin, `kicad-cli${exe}`), join(root, `kicad-cli${exe}`)],
336
+ kicad: [join(bin, `kicad${exe}`)],
337
+ eeschema: [join(bin, `eeschema${exe}`)],
338
+ pcbnew: [join(bin, `pcbnew${exe}`)],
339
+ }
340
+ }
341
+
342
+ /** Install root that owns one resolved `kicad-cli`, per layout convention. */
343
+ function installRootFromCli(cli: string): string {
344
+ const segments = cli.split(sep)
345
+ const macIndex = segments.indexOf('Contents')
346
+ if (macIndex > 0) return segments.slice(0, macIndex).join(sep) || sep
347
+ if (segments[segments.length - 2]?.toLowerCase() === 'bin') return segments.slice(0, -2).join(sep) || sep
348
+ return dirname(cli)
349
+ }
350
+
351
+ function solidcraftCandidates(root: string): string[] {
352
+ const exe = process.platform === 'win32' ? '.exe' : ''
353
+ const app = basename(root).toLowerCase().endsWith('.app')
354
+ if (app || process.platform === 'darwin') {
355
+ const base = app ? root : join(root, 'SolidCraft.app')
356
+ return [
357
+ join(base, `Contents/MacOS/SolidCraft`),
358
+ join(base, `Contents/MacOS/solidcraft`),
359
+ ]
360
+ }
361
+ return [
362
+ root,
363
+ join(root, `SolidCraft${exe}`),
364
+ join(root, `solidcraft${exe}`),
365
+ join(root, 'bin', `SolidCraft${exe}`),
366
+ join(root, 'bin', `solidcraft${exe}`),
367
+ ]
368
+ }
369
+
370
+ /** Small, immutable host capability implementation. */
371
+ export class HardwareArtifactService {
372
+ private readonly options: Required<Pick<HardwareArtifactsOptions, 'spawnProcess' | 'probeVersion' | 'runCommand'>>
373
+ private readonly cacheRoot: string
374
+ private readonly glbTimeoutMs: number
375
+ private readonly maxSourceBytes: number
376
+ private lastDiscovery?: DiscoveryResult
377
+ /** Completed GLB exports keyed by `sourcePath:revision`. */
378
+ private readonly glbCache = new Map<string, GlbResult>()
379
+ /** In-flight GLB exports keyed by the same key, so concurrent callers share one run. */
380
+ private readonly glbPending = new Map<string, Promise<GlbResult>>()
381
+ /** BOM projections keyed by `sourcePath:revision`. */
382
+ private readonly bomCache = new Map<string, BomResult>()
383
+
384
+ constructor(private readonly config: HardwareArtifactsOptions = {}) {
385
+ this.options = {
386
+ probeVersion: config.probeVersion ?? defaultVersionProbe,
387
+ spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
388
+ runCommand: config.runCommand ?? defaultRunCommand,
389
+ }
390
+ this.cacheRoot = canonical(config.cacheRoot ?? join(tmpdir(), 'huaqiu-hardware-artifacts'))
391
+ this.glbTimeoutMs = config.glbTimeoutMs ?? 120_000
392
+ this.maxSourceBytes = config.maxSourceBytes ?? 32 * 1024 * 1024
393
+ }
394
+
395
+ /** Resolve configured installations from validated absolute paths only. */
396
+ installations(): Installations {
397
+ const kicadRoot = this.config.kicadRoot ? canonical(this.config.kicadRoot) : undefined
398
+ let kicadCli: string | undefined
399
+ if (kicadRoot !== undefined) {
400
+ const cliPaths = basename(kicadRoot).toLowerCase().startsWith('kicad-cli')
401
+ ? [kicadRoot]
402
+ : kicadCandidates(kicadRoot).cli
403
+ kicadCli = existing(cliPaths)
404
+ }
405
+ const candidates = kicadRoot === undefined
406
+ ? { cli: [], kicad: [], eeschema: [], pcbnew: [] }
407
+ : kicadCandidates(kicadCli === undefined ? kicadRoot : installRootFromCli(kicadCli))
408
+ const pcbEditor = existing(candidates.pcbnew)
409
+ const schematicEditor = existing(candidates.eeschema)
410
+ const projectManager = existing(candidates.kicad)
411
+ const version = kicadCli === undefined ? undefined : this.options.probeVersion(kicadCli)
412
+ const kicad: InstallationInfo = kicadCli === undefined
413
+ ? { configured: false, error: 'KiCad installation is not configured' }
414
+ : version === undefined
415
+ ? { configured: false, root: kicadRoot, cli: kicadCli, error: `${kicadCli} did not answer a version probe` }
416
+ : {
417
+ configured: true,
418
+ root: kicadRoot,
419
+ cli: kicadCli,
420
+ version,
421
+ ...(projectManager === undefined ? {} : { projectManager }),
422
+ ...(pcbEditor === undefined ? {} : { pcbEditor }),
423
+ ...(schematicEditor === undefined ? {} : { schematicEditor }),
424
+ }
425
+
426
+ const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : undefined
427
+ const solidExecutable = solidRoot === undefined ? undefined : existing(solidcraftCandidates(solidRoot))
428
+ const solidcraft: InstallationInfo = solidExecutable === undefined
429
+ ? { configured: false, error: 'SolidCraft installation is not configured' }
430
+ : { configured: true, root: solidRoot, executable: solidExecutable }
431
+ return { kicad, solidcraft }
432
+ }
433
+
434
+ /** Paths passed to agent child processes. Never assign these globally. */
435
+ childEnvironment(): Record<string, string> {
436
+ const installed = this.installations()
437
+ const env: Record<string, string> = {}
438
+ if (installed.kicad.cli !== undefined) env.HUAQIU_KICAD_CLI = installed.kicad.cli
439
+ if (installed.kicad.pcbEditor !== undefined) env.HUAQIU_KICAD_PCBNEW = installed.kicad.pcbEditor
440
+ if (installed.kicad.schematicEditor !== undefined) env.HUAQIU_KICAD_EESCHEMA = installed.kicad.schematicEditor
441
+ if (installed.solidcraft.executable !== undefined) env.HUAQIU_SOLIDCRAFT = installed.solidcraft.executable
442
+ return env
443
+ }
444
+
445
+ /** Compact agent context: validated paths only, no project inventory dump. */
446
+ environmentText(current?: DiscoveryResult): string {
447
+ const installed = this.installations()
448
+ const lines = ['<hardware_environment>']
449
+ lines.push('KiCad:')
450
+ lines.push(` configured: ${String(installed.kicad.configured)}`)
451
+ for (const key of ['version', 'cli', 'pcbEditor', 'schematicEditor'] as const) {
452
+ const value = installed.kicad[key]
453
+ if (value !== undefined) lines.push(` ${key}: ${value}`)
454
+ }
455
+ if (installed.kicad.error !== undefined) lines.push(` error: ${installed.kicad.error}`)
456
+ lines.push('SolidCraft:')
457
+ lines.push(` configured: ${String(installed.solidcraft.configured)}`)
458
+ if (installed.solidcraft.executable !== undefined) lines.push(` executable: ${installed.solidcraft.executable}`)
459
+ if (installed.solidcraft.error !== undefined) lines.push(` error: ${installed.solidcraft.error}`)
460
+ if (current?.selected !== undefined) {
461
+ lines.push('Current project:')
462
+ lines.push(` root: ${current.cwd}`)
463
+ lines.push(` project: ${current.selected.path}`)
464
+ if (current.selected.schematic !== undefined) lines.push(` schematic: ${current.selected.schematic.path}`)
465
+ const board = current.selected.boards[0]
466
+ if (board !== undefined) lines.push(` selected_pcb: ${board.path}`)
467
+ }
468
+ lines.push('</hardware_environment>')
469
+ return lines.join('\n')
470
+ }
471
+
472
+ /**
473
+ * Deterministic discovery. An explicit project or manifest wins; otherwise
474
+ * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
475
+ * returned as a selection requirement, never resolved by taking the first.
476
+ */
477
+ discover(cwdInput: string, explicitProject?: string): DiscoveryResult {
478
+ const cwd = canonical(cwdInput)
479
+ const manifestPath = join(cwd, '.hardware-engineering.json')
480
+ let manifest: ProjectManifest | undefined
481
+ if (existsSync(manifestPath)) {
482
+ try {
483
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as ProjectManifest
484
+ } catch (error) {
485
+ const result: DiscoveryResult = { cwd, manifestPath, projects: [], issue: { code: 'bad-manifest', message: `invalid .hardware-engineering.json: ${String(error)}` } }
486
+ this.lastDiscovery = result
487
+ return result
488
+ }
489
+ }
490
+
491
+ const projectPaths = new Set<string>()
492
+ if (explicitProject !== undefined && explicitProject.trim() !== '') {
493
+ const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject)
494
+ if (!existsSync(requested)) {
495
+ const result: DiscoveryResult = { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects: [], issue: { code: 'missing-project', message: `${requested} does not exist` } }
496
+ this.lastDiscovery = result
497
+ return result
498
+ }
499
+ projectPaths.add(requested)
500
+ } else if (manifest?.project !== undefined && manifest.project.trim() !== '') {
501
+ projectPaths.add(isAbsolute(manifest.project) ? canonical(manifest.project) : resolve(cwd, manifest.project))
502
+ } else {
503
+ for (const path of walkFiles(cwd, name => name.toLowerCase().endsWith('.kicad_pro'))) projectPaths.add(path)
504
+ }
505
+
506
+ const projects: HardwareProject[] = [...projectPaths].sort().map(path => this.projectFrom(path, cwd, manifest))
507
+ if (projects.length === 0) {
508
+ const result: DiscoveryResult = { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'no-project', message: `no .kicad_pro found under ${cwd}` } }
509
+ this.lastDiscovery = result
510
+ return result
511
+ }
512
+ if (projects.length > 1) {
513
+ const result: DiscoveryResult = { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'selection-required', message: `${projects.length} projects found; select one explicitly` } }
514
+ this.lastDiscovery = result
515
+ return result
516
+ }
517
+ const selected = projects[0] as HardwareProject
518
+ const result: DiscoveryResult = {
519
+ cwd,
520
+ ...(manifest === undefined ? {} : { manifestPath }),
521
+ projects,
522
+ selected,
523
+ ...(selected.selectionRequired
524
+ ? { issue: { code: 'selection-required', message: 'select an artifact explicitly' } }
525
+ : {}),
526
+ }
527
+ this.lastDiscovery = result
528
+ return result
529
+ }
530
+
531
+ /** The most recent discovery, used to authorize source reads. */
532
+ discovery(): DiscoveryResult | undefined {
533
+ return this.lastDiscovery
534
+ }
535
+
536
+ private projectFrom(projectPath: string, cwd: string, manifest?: ProjectManifest): HardwareProject {
537
+ const dir = dirname(projectPath)
538
+ const name = basename(projectPath, extname(projectPath))
539
+ const resolvePath = (value: string): string =>
540
+ isAbsolute(value) ? canonical(value) : resolve(dir, value)
541
+
542
+ // The root schematic is authoritative: an explicit manifest entry, then the
543
+ // project-named file, then a single unambiguous candidate. Unrelated
544
+ // sibling `.kicad_sch` files are never promoted to sheets.
545
+ const explicitSchematic = manifest?.schematic === undefined ? undefined : resolvePath(manifest.schematic)
546
+ let schematicPath = explicitSchematic !== undefined && existsSync(explicitSchematic) ? explicitSchematic : undefined
547
+ if (schematicPath === undefined) {
548
+ const named = join(dir, `${name}.kicad_sch`)
549
+ if (existsSync(named)) schematicPath = named
550
+ else {
551
+ const candidates = readdirSync(dir, { withFileTypes: true })
552
+ .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.kicad_sch'))
553
+ .map(entry => join(dir, entry.name))
554
+ .sort()
555
+ if (candidates.length === 1) schematicPath = candidates[0]
556
+ }
557
+ }
558
+
559
+ // Hierarchy comes from sheet references only, resolved recursively with a
560
+ // cycle guard: parsing the root must never advertise unrelated files.
561
+ const sheets: HardwareArtifact[] = []
562
+ if (schematicPath !== undefined) {
563
+ const visited = new Set<string>([canonical(schematicPath)])
564
+ const queue = childSheetFiles(canonical(schematicPath))
565
+ while (queue.length > 0) {
566
+ const next = queue.shift() as string
567
+ const canonicalNext = canonical(next)
568
+ if (visited.has(canonicalNext)) continue
569
+ visited.add(canonicalNext)
570
+ if (!existsSync(canonicalNext) || extname(canonicalNext).toLowerCase() !== '.kicad_sch') continue
571
+ sheets.push(artifact('schematic', canonicalNext, projectPath, canonical(schematicPath)))
572
+ queue.push(...childSheetFiles(canonicalNext))
573
+ }
574
+ }
575
+
576
+ // Board ranking: manifest ownership first, then the project-named board, then
577
+ // the only candidate. Multiple unowned boards stay ambiguous on purpose.
578
+ const manifestBoards = manifest?.boards === undefined
579
+ ? []
580
+ : manifest.boards
581
+ .filter(entry => existsSync(resolvePath(entry.path)))
582
+ .map(entry => artifact('pcb', resolvePath(entry.path), projectPath))
583
+ const scannedBoards = walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_pcb'))
584
+ .map(path => artifact('pcb', path, projectPath))
585
+ const boards = manifestBoards.length > 0
586
+ ? manifestBoards
587
+ : [...scannedBoards].sort((left, right) => boardRank(left, right, name))
588
+ const owned = boards.find(board => basename(board.path, '.kicad_pcb') === name) ?? boards[0]
589
+ const ownershipAmbiguous = manifestBoards.length === 0 && boards.length > 1
590
+ && basename(owned?.path ?? '', '.kicad_pcb') !== name
591
+
592
+ const mechanical = manifest?.mechanical !== undefined
593
+ ? manifest.mechanical.map(model => artifact('mechanical-3d', resolvePath(model.path), projectPath))
594
+ : walkFiles(dir, file => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase()))
595
+ .map(path => artifact('mechanical-3d', path, projectPath))
596
+
597
+ const sourceSchematic = schematicPath === undefined ? undefined : artifact('schematic', schematicPath, projectPath)
598
+ const sourceBoard = ownershipAmbiguous ? undefined : owned
599
+ return {
600
+ path: projectPath,
601
+ name,
602
+ ...(sourceSchematic === undefined ? {} : { rootSheet: sourceSchematic, schematic: sourceSchematic }),
603
+ ...(sourceSchematic === undefined ? {} : {
604
+ bom: { ...artifact('bom', sourceSchematic.path, projectPath, sourceSchematic.path), title: `BOM — ${sourceSchematic.title}` },
605
+ }),
606
+ ...(sourceBoard === undefined ? {} : {
607
+ pcb3d: { ...artifact('pcb-3d', sourceBoard.path, projectPath, sourceBoard.path), title: `3D — ${sourceBoard.title}` },
608
+ defaultBoard: sourceBoard.path,
609
+ }),
610
+ sheets,
611
+ boards,
612
+ mechanical,
613
+ selectionRequired: boards.length > 1 && ownershipAmbiguous,
614
+ }
615
+ }
616
+
617
+ /** Validate and launch a native application without a shell. */
618
+ open(request: OpenArtifactRequest): OpenArtifactResult {
619
+ const path = canonical(request.artifactPath)
620
+ if (!existsSync(path)) {
621
+ throw errorWithCode(`artifact does not exist: ${path}`, 'missing-artifact', 404)
622
+ }
623
+ const installed = this.installations()
624
+ const ext = extname(path).toLowerCase()
625
+ let command: string | undefined
626
+ if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
627
+ else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
628
+ else if (ext === '.kicad_pro') command = installed.kicad.projectManager
629
+ else throw errorWithCode(`unsupported KiCad artifact: ${ext}`, 'unsupported-artifact', 415)
630
+ if (command === undefined) {
631
+ throw errorWithCode('the configured KiCad installation has no editor for this artifact', 'missing-executable', 412)
632
+ }
633
+ const settings = { cwd: dirname(path), detached: true, stdio: 'ignore' as const, windowsHide: true, shell: false as const }
634
+ const child = this.options.spawnProcess(command, [path], settings)
635
+ return { launched: true, command, args: [path], cwd: settings.cwd, ...(child.pid === undefined ? {} : { pid: child.pid }) }
636
+ }
637
+
638
+ /** Workspace roots a read may target: explicit request, last discovery, config. */
639
+ private authorizedRoots(roots?: readonly string[]): string[] {
640
+ const candidates = new Set<string>()
641
+ for (const root of roots ?? []) {
642
+ if (root !== undefined && root.trim() !== '') candidates.add(canonical(root))
643
+ }
644
+ const discovered = this.lastDiscovery?.cwd
645
+ if (discovered !== undefined) candidates.add(canonical(discovered))
646
+ return [...candidates]
647
+ }
648
+
649
+ /**
650
+ * Authorize one artifact path: canonical, realpath-checked, inside a
651
+ * workspace root, and of an expected type. A browser request cannot turn
652
+ * this into an arbitrary filesystem read, even from loopback.
653
+ */
654
+ private authorize(artifactPath: string, roots: readonly string[] | undefined): { path: string; kind: 'schematic' | 'pcb' } {
655
+ if (!isAbsolute(artifactPath)) {
656
+ throw errorWithCode('artifact identity must be an absolute path', 'invalid-identity', 400)
657
+ }
658
+ const requested = canonical(artifactPath)
659
+ const kind = SOURCE_EXTENSIONS[extname(requested).toLowerCase()]
660
+ if (kind === undefined) {
661
+ throw errorWithCode(`unsupported artifact type: ${extname(requested)}`, 'unsupported-artifact', 415)
662
+ }
663
+ const authorized = this.authorizedRoots(roots)
664
+ if (authorized.length === 0) {
665
+ throw errorWithCode('no authorized workspace is known to the host', 'unauthorized', 403)
666
+ }
667
+ // Boundary check before existence: a path outside the workspace is refused
668
+ // whether or not it exists, so the route cannot probe the filesystem.
669
+ const permittedLexically = authorized.some((root) => isInside(requested, canonical(root)))
670
+ if (!permittedLexically) {
671
+ throw errorWithCode('artifact is outside the authorized workspace', 'unauthorized', 403)
672
+ }
673
+ if (!existsSync(requested)) {
674
+ throw errorWithCode(`artifact does not exist: ${requested}`, 'missing-artifact', 404)
675
+ }
676
+ const real = realOrUndefined(requested)
677
+ if (real === undefined) {
678
+ throw errorWithCode(`artifact cannot be resolved: ${requested}`, 'invalid-identity', 400)
679
+ }
680
+ const permitted = authorized.some((root) => {
681
+ const realRoot = realOrUndefined(root) ?? root
682
+ return isInside(real, realRoot)
683
+ })
684
+ if (!permitted) {
685
+ throw errorWithCode('artifact is outside the authorized workspace', 'unauthorized', 403)
686
+ }
687
+ const info = statSync(real)
688
+ if (!info.isFile()) {
689
+ throw errorWithCode(`artifact is not a regular file: ${requested}`, 'invalid-identity', 400)
690
+ }
691
+ if ((SOURCE_EXTENSIONS[extname(real).toLowerCase()]) === undefined) {
692
+ throw errorWithCode('artifact type changed during resolution', 'unsupported-artifact', 415)
693
+ }
694
+ return { path: real, kind: SOURCE_EXTENSIONS[extname(real).toLowerCase()] as 'schematic' | 'pcb' }
695
+ }
696
+
697
+ /** Saved source text plus a content-addressed revision. */
698
+ async readSource(request: SourceRequest): Promise<SourceResult> {
699
+ const { path, kind } = this.authorize(request.artifactPath, request.roots)
700
+ const info = statSync(path)
701
+ if (info.size > this.maxSourceBytes) {
702
+ throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, 'too-large', 413)
703
+ }
704
+ const body = await readFile(path)
705
+ const revision = createHash('sha256').update(body).digest('hex')
706
+ if (request.expectedRevision !== undefined && request.expectedRevision !== ''
707
+ && request.expectedRevision !== revision) {
708
+ throw errorWithCode(
709
+ `source changed since it was selected (expected ${request.expectedRevision}, found ${revision})`,
710
+ 'stale-revision',
711
+ 409,
712
+ )
713
+ }
714
+ return {
715
+ path,
716
+ kind,
717
+ revision,
718
+ bytes: body.byteLength,
719
+ mtimeMs: info.mtimeMs,
720
+ text: body.toString('utf8'),
721
+ }
722
+ }
723
+
724
+ private sourceRevision(path: string): string {
725
+ const info = statSync(path)
726
+ if (info.size > this.maxSourceBytes) {
727
+ throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, 'too-large', 413)
728
+ }
729
+ return createHash('sha256').update(readFileSync(path)).digest('hex')
730
+ }
731
+
732
+ /** Cache directory for one board's derived outputs. */
733
+ private glbDirectory(boardPath: string): string {
734
+ const digest = createHash('sha256').update(boardPath).digest('hex').slice(0, 16)
735
+ return join(this.cacheRoot, 'glb', digest)
736
+ }
737
+
738
+ /**
739
+ * Generate (or reuse) the GLB for one board.
740
+ *
741
+ * - cache key includes the source content hash, so same-size/same-mtime edits invalidate
742
+ * - one in-flight export is shared by concurrent callers for the same revision
743
+ * - output is written to a temp file and renamed only after it validates
744
+ * - a timeout or abort leaves no partial file behind
745
+ */
746
+ async exportGlb(request: GlbRequest): Promise<GlbResult> {
747
+ const { path } = this.authorize(request.artifactPath, request.roots)
748
+ if (extname(path).toLowerCase() !== '.kicad_pcb') {
749
+ throw errorWithCode('GLB export requires a .kicad_pcb artifact', 'unsupported-artifact', 415)
750
+ }
751
+ const installed = this.installations()
752
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
753
+ throw errorWithCode(
754
+ installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli',
755
+ 'not-configured',
756
+ 412,
757
+ )
758
+ }
759
+ const cli = installed.kicad.cli
760
+ const revision = this.sourceRevision(path)
761
+ const key = `${path}:${revision}`
762
+ const cached = this.glbCache.get(key)
763
+ if (cached !== undefined && existsSync(cached.file)) {
764
+ const info = statSync(cached.file)
765
+ return { ...cached, bytes: info.size, cached: true }
766
+ }
767
+ const pending = this.glbPending.get(key)
768
+ if (pending !== undefined) return pending
769
+
770
+ const directory = this.glbDirectory(path)
771
+ const target = join(directory, `board-${revision.slice(0, 16)}.glb`)
772
+ const running = (async (): Promise<GlbResult> => {
773
+ mkdirSync(directory, { recursive: true })
774
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
775
+ mkdirSync(tempDirectory, { recursive: true })
776
+ const tempFile = join(tempDirectory, 'board.glb')
777
+ try {
778
+ const result = await this.options.runCommand(
779
+ cli,
780
+ ['pcb', 'export', 'glb', '--output', tempFile, path],
781
+ { cwd: dirname(path), timeoutMs: this.glbTimeoutMs, ...(request.signal === undefined ? {} : { signal: request.signal }) },
782
+ )
783
+ if (result.timedOut) {
784
+ throw errorWithCode(`kicad-cli pcb export glb timed out after ${this.glbTimeoutMs} ms`, 'export-timeout', 504)
785
+ }
786
+ if (result.exitCode !== 0) {
787
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
788
+ throw errorWithCode(`kicad-cli pcb export glb failed: ${detail}`, 'export-failed', 502)
789
+ }
790
+ if (!existsSync(tempFile)) {
791
+ throw errorWithCode('kicad-cli pcb export glb produced no output', 'export-failed', 502)
792
+ }
793
+ const bytes = statSync(tempFile).size
794
+ if (bytes === 0 || readFileSync(tempFile).subarray(0, 4).toString('ascii') !== 'glTF') {
795
+ throw errorWithCode('kicad-cli wrote an invalid GLB', 'export-failed', 502)
796
+ }
797
+ renameSync(tempFile, target)
798
+ const generated = {
799
+ path,
800
+ revision,
801
+ bytes,
802
+ generatedAt: new Date().toISOString(),
803
+ cached: false,
804
+ file: target,
805
+ } satisfies GlbResult
806
+ this.glbCache.set(key, generated)
807
+ return generated
808
+ } finally {
809
+ rmSync(tempDirectory, { recursive: true, force: true })
810
+ }
811
+ })()
812
+
813
+ this.glbPending.set(key, running)
814
+ try {
815
+ return await running
816
+ } finally {
817
+ this.glbPending.delete(key)
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Grouped BOM for one saved root schematic.
823
+ *
824
+ * Reuses KiCad's own BOM extraction (`kicad-cli sch export bom`), the same
825
+ * authoritative source `analyze_kicad_module` consumes, rather than building a
826
+ * second component analyser. Grouping key is every non-reference column, so
827
+ * different MPNs never merge and DNP stays explicit.
828
+ */
829
+ async exportBom(request: {
830
+ readonly artifactPath: string
831
+ readonly roots?: readonly string[]
832
+ readonly signal?: AbortSignal
833
+ }): Promise<BomResult> {
834
+ const { path, kind } = this.authorize(request.artifactPath, request.roots)
835
+ if (kind !== 'schematic') {
836
+ throw errorWithCode('BOM export requires a .kicad_sch artifact', 'unsupported-artifact', 415)
837
+ }
838
+ const installed = this.installations()
839
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
840
+ throw errorWithCode(installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli', 'not-configured', 412)
841
+ }
842
+ const revision = this.sourceRevision(path)
843
+ const key = `${path}:${revision}`
844
+ const cached = this.bomCache.get(key)
845
+ if (cached !== undefined) return { ...cached, cached: true }
846
+
847
+ const directory = join(this.cacheRoot, 'bom', createHash('sha256').update(path).digest('hex').slice(0, 16))
848
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
849
+ mkdirSync(tempDirectory, { recursive: true })
850
+ const tempFile = join(tempDirectory, 'bom.csv')
851
+ try {
852
+ const result = await this.options.runCommand(
853
+ installed.kicad.cli,
854
+ ['sch', 'export', 'bom', '--output', tempFile, path],
855
+ { cwd: dirname(path), timeoutMs: 60_000, ...(request.signal === undefined ? {} : { signal: request.signal }) },
856
+ )
857
+ if (result.timedOut) throw errorWithCode('kicad-cli sch export bom timed out', 'export-timeout', 504)
858
+ if (result.exitCode !== 0) {
859
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
860
+ throw errorWithCode(`kicad-cli sch export bom failed: ${detail}`, 'export-failed', 502)
861
+ }
862
+ if (!existsSync(tempFile)) throw errorWithCode('kicad-cli produced no BOM output', 'export-failed', 502)
863
+ const rows = groupBomRows(parseCsv(readFileSync(tempFile, 'utf8')))
864
+ const generated: BomResult = {
865
+ path,
866
+ revision,
867
+ generatedAt: new Date().toISOString(),
868
+ cached: false,
869
+ rows,
870
+ source: 'kicad-cli-bom',
871
+ }
872
+ this.bomCache.set(key, generated)
873
+ return generated
874
+ } finally {
875
+ rmSync(tempDirectory, { recursive: true, force: true })
876
+ }
877
+ }
878
+
879
+ /** Serve a generated GLB file, re-validating the cache entry first. */ glbFile(boardPath: string, revision: string): string {
880
+ const key = `${canonical(boardPath)}:${revision}`
881
+ const entry = this.glbCache.get(key)
882
+ if (entry === undefined || !existsSync(entry.file)) {
883
+ throw errorWithCode('generated GLB is not available for this revision', 'stale-revision', 409)
884
+ }
885
+ return entry.file
886
+ }
887
+
888
+ /** Drop cached derived outputs for one board (or all of them). */
889
+ clearCache(boardPath?: string): void {
890
+ if (boardPath === undefined) {
891
+ this.glbCache.clear()
892
+ rmSync(this.cacheRoot, { recursive: true, force: true })
893
+ return
894
+ }
895
+ const prefix = `${canonical(boardPath)}:`
896
+ for (const key of [...this.glbCache.keys()]) {
897
+ if (key.startsWith(prefix)) this.glbCache.delete(key)
898
+ }
899
+ rmSync(this.glbDirectory(canonical(boardPath)), { recursive: true, force: true })
900
+ }
901
+ }
902
+
903
+ /** Ownership order: project-named board first, then shallower, then alphabetical. */
904
+ function boardRank(left: HardwareArtifact, right: HardwareArtifact, projectName: string): number { const leftNamed = basename(left.path, '.kicad_pcb') === projectName ? 0 : 1
905
+ const rightNamed = basename(right.path, '.kicad_pcb') === projectName ? 0 : 1
906
+ if (leftNamed !== rightNamed) return leftNamed - rightNamed
907
+ const leftDepth = left.path.split(sep).length
908
+ const rightDepth = right.path.split(sep).length
909
+ if (leftDepth !== rightDepth) return leftDepth - rightDepth
910
+ return left.path.localeCompare(right.path)
911
+ }
912
+
913
+ /** RFC4180-style CSV reader: quoted fields, doubled quotes, CRLF rows. */
914
+ export function parseCsv(text: string): string[][] {
915
+ const rows: string[][] = []
916
+ let row: string[] = []
917
+ let field = ''
918
+ let quoted = false
919
+ const source = text.replace(/^\uFEFF/u, '')
920
+ for (let index = 0; index < source.length; index += 1) {
921
+ const char = source[index]
922
+ if (quoted) {
923
+ if (char === '"') {
924
+ if (source[index + 1] === '"') {
925
+ field += '"'
926
+ index += 1
927
+ } else {
928
+ quoted = false
929
+ }
930
+ } else {
931
+ field += char
932
+ }
933
+ continue
934
+ }
935
+ if (char === '"') {
936
+ quoted = true
937
+ } else if (char === ',') {
938
+ row.push(field)
939
+ field = ''
940
+ } else if (char === '\r') {
941
+ continue
942
+ } else if (char === '\n') {
943
+ row.push(field)
944
+ rows.push(row)
945
+ row = []
946
+ field = ''
947
+ } else {
948
+ field += char
949
+ }
950
+ }
951
+ if (field !== '' || row.length > 0) {
952
+ row.push(field)
953
+ rows.push(row)
954
+ }
955
+ return rows.filter(cells => cells.some(cell => cell.trim() !== ''))
956
+ }
957
+
958
+ /**
959
+ * Group KiCad's per-reference BOM rows.
960
+ *
961
+ * Identity is every column except the reference and quantity columns, so a
962
+ * different MPN or a DNP flag always produces a separate line; ordering follows
963
+ * the first reference seen, which keeps the table stable between reads.
964
+ */
965
+ export function groupBomRows(table: readonly string[][]): BomRow[] {
966
+ const [header, ...body] = table
967
+ if (header === undefined) return []
968
+ const columns = header.map(cell => cell.trim())
969
+ const referenceIndex = columns.findIndex(cell => /^reference$/iu.test(cell))
970
+ const quantityIndex = columns.findIndex(cell => /^quantity$/iu.test(cell))
971
+ const valueIndex = columns.findIndex(cell => /^value$/iu.test(cell))
972
+ const footprintIndex = columns.findIndex(cell => /^footprint$/iu.test(cell))
973
+ const dnpIndex = columns.findIndex(cell => /^dnp$/iu.test(cell))
974
+ const groups = new Map<string, { references: string[]; fields: Record<string, string>; dnp: boolean }>()
975
+ for (const cells of body) {
976
+ const reference = referenceIndex === -1 ? '' : (cells[referenceIndex] ?? '').trim()
977
+ if (reference === '') continue
978
+ const fields: Record<string, string> = {}
979
+ columns.forEach((column, index) => {
980
+ if (index === referenceIndex || index === quantityIndex || index === valueIndex
981
+ || index === footprintIndex || index === dnpIndex) return
982
+ const text = (cells[index] ?? '').trim()
983
+ if (text !== '') fields[column] = text
984
+ })
985
+ const dnpText = dnpIndex === -1 ? '' : (cells[dnpIndex] ?? '').trim()
986
+ const dnp = /^(1|true|yes|dnp|x)$/iu.test(dnpText)
987
+ const identity = JSON.stringify([
988
+ valueIndex === -1 ? '' : (cells[valueIndex] ?? '').trim(),
989
+ footprintIndex === -1 ? '' : (cells[footprintIndex] ?? '').trim(),
990
+ dnp,
991
+ Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b))),
992
+ ])
993
+ const group = groups.get(identity) ?? { references: [], fields, dnp }
994
+ group.references.push(reference)
995
+ groups.set(identity, group)
996
+ }
997
+ return [...groups.entries()].map(([identity, group]) => {
998
+ const [value, footprint, dnp] = JSON.parse(identity) as [string, string, boolean]
999
+ return {
1000
+ references: group.references,
1001
+ quantity: group.references.length,
1002
+ value,
1003
+ footprint,
1004
+ dnp,
1005
+ fields: group.fields,
1006
+ } satisfies BomRow
1007
+ })
1008
+ }