@huaqiu/hardware-artifacts 0.0.0-stage → 0.7.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.
package/src/service.ts ADDED
@@ -0,0 +1,423 @@
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 and verified installation facts, never a
7
+ * shadow project database.
8
+ */
9
+ import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
10
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
11
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
12
+
13
+ export type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'mechanical-3d'
14
+ export type NativeApplication = 'kicad' | 'solidcraft'
15
+
16
+ export interface HardwareArtifact {
17
+ readonly id: string
18
+ readonly kind: ArtifactKind
19
+ readonly path: string
20
+ readonly projectPath?: string
21
+ /** BOM keeps its schematic; PCB 3D keeps its board; sheets keep their root. */
22
+ readonly sourcePath?: string
23
+ readonly title: string
24
+ readonly format: string
25
+ }
26
+
27
+ export interface HardwareProject {
28
+ readonly path: string
29
+ readonly name: string
30
+ readonly schematic?: HardwareArtifact
31
+ /** Semantic views; both keep the identity of their source artifact. */
32
+ readonly bom?: HardwareArtifact
33
+ readonly pcb3d?: HardwareArtifact
34
+ readonly sheets: readonly HardwareArtifact[]
35
+ readonly boards: readonly HardwareArtifact[]
36
+ readonly mechanical: readonly HardwareArtifact[]
37
+ readonly selectionRequired: boolean
38
+ }
39
+
40
+ export interface DiscoveryResult {
41
+ readonly cwd: string
42
+ readonly manifestPath?: string
43
+ readonly projects: readonly HardwareProject[]
44
+ readonly selected?: HardwareProject
45
+ readonly issue?: { readonly code: string; readonly message: string }
46
+ }
47
+
48
+ export interface InstallationInfo {
49
+ readonly configured: boolean
50
+ readonly root?: string
51
+ readonly cli?: string
52
+ readonly projectManager?: string
53
+ readonly pcbEditor?: string
54
+ readonly schematicEditor?: string
55
+ readonly executable?: string
56
+ readonly version?: string
57
+ readonly error?: string
58
+ }
59
+
60
+ export interface Installations {
61
+ readonly kicad: InstallationInfo
62
+ readonly solidcraft: InstallationInfo
63
+ }
64
+
65
+ export interface OpenArtifactRequest {
66
+ readonly application: NativeApplication
67
+ readonly artifactPath: string
68
+ readonly kind: ArtifactKind
69
+ readonly projectPath?: string
70
+ }
71
+
72
+ export interface OpenArtifactResult {
73
+ readonly launched: true
74
+ readonly command: string
75
+ readonly args: readonly string[]
76
+ readonly cwd: string
77
+ readonly pid?: number
78
+ }
79
+
80
+ export interface HardwareArtifactsOptions {
81
+ readonly kicadRoot?: string
82
+ readonly solidcraftRoot?: string
83
+ readonly probeVersion?: (executable: string) => string | undefined
84
+ readonly spawnProcess?: (
85
+ command: string,
86
+ args: readonly string[],
87
+ options: { cwd: string; detached: boolean; stdio: 'ignore'; windowsHide: boolean; shell: false },
88
+ ) => Pick<ChildProcess, 'pid'>
89
+ }
90
+
91
+ interface ProjectManifest {
92
+ project?: string
93
+ schematic?: string
94
+ boards?: readonly { id?: string; path: string }[]
95
+ mechanical?: readonly { id?: string; path: string }[]
96
+ }
97
+
98
+ const EXCLUDED_DIRS = new Set([
99
+ '.git', '.cache', 'node_modules', 'dist', 'build', 'out', 'tmp', 'temp',
100
+ 'archive', 'archives', 'backup', 'backups', 'export', 'exports',
101
+ ])
102
+ const MECHANICAL_EXTENSIONS = new Set(['.step', '.stp', '.glb'])
103
+ const MAX_DEPTH = 5
104
+
105
+ function canonical(path: string): string {
106
+ return resolve(path)
107
+ }
108
+
109
+ function isInside(child: string, parent: string): boolean {
110
+ const rel = relative(parent, child)
111
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
112
+ }
113
+
114
+ function isExcluded(name: string): boolean {
115
+ return EXCLUDED_DIRS.has(name.toLowerCase())
116
+ }
117
+
118
+ function walkFiles(root: string, predicate: (name: string) => boolean): string[] {
119
+ const found: string[] = []
120
+ const visit = (dir: string, depth: number): void => {
121
+ if (depth > MAX_DEPTH || !existsSync(dir)) return
122
+ let entries
123
+ try {
124
+ entries = readdirSync(dir, { withFileTypes: true })
125
+ } catch {
126
+ return
127
+ }
128
+ for (const entry of entries) {
129
+ const full = join(dir, entry.name)
130
+ if (entry.isDirectory()) {
131
+ if (!isExcluded(entry.name)) visit(full, depth + 1)
132
+ } else if (entry.isFile() && predicate(entry.name)) {
133
+ found.push(canonical(full))
134
+ }
135
+ }
136
+ }
137
+ visit(root, 0)
138
+ return found.sort()
139
+ }
140
+
141
+ function artifact(kind: ArtifactKind, path: string, projectPath?: string, sourcePath?: string): HardwareArtifact {
142
+ const full = canonical(path)
143
+ return {
144
+ id: `${kind}:${full}`,
145
+ kind,
146
+ path: full,
147
+ ...(projectPath === undefined ? {} : { projectPath: canonical(projectPath) }),
148
+ ...(sourcePath === undefined ? {} : { sourcePath: canonical(sourcePath) }),
149
+ title: basename(full),
150
+ format: extname(full).toLowerCase().replace(/^\./, '') || kind,
151
+ }
152
+ }
153
+
154
+ function defaultVersionProbe(executable: string): string | undefined {
155
+ if (!existsSync(executable)) return undefined
156
+ try {
157
+ return execFileSync(executable, ['version'], {
158
+ encoding: 'utf8',
159
+ timeout: 5_000,
160
+ stdio: ['ignore', 'pipe', 'ignore'],
161
+ }).trim().split('\n')[0] || undefined
162
+ } catch {
163
+ return undefined
164
+ }
165
+ }
166
+
167
+ function existing(paths: readonly string[]): string | undefined {
168
+ return paths.find((candidate) => {
169
+ try {
170
+ return existsSync(candidate) && statSync(candidate).isFile()
171
+ } catch {
172
+ return false
173
+ }
174
+ })
175
+ }
176
+
177
+ function kicadCandidates(root: string): { cli: string[]; kicad: string[]; eeschema: string[]; pcbnew: string[] } {
178
+ const app = basename(root).toLowerCase().endsWith('.app')
179
+ if (app || process.platform === 'darwin') {
180
+ const base = app ? root : join(root, 'KiCad.app')
181
+ return {
182
+ cli: [join(base, 'Contents/MacOS/kicad-cli')],
183
+ kicad: [join(base, 'Contents/MacOS/kicad')],
184
+ eeschema: [join(base, 'Contents/Applications/eeschema.app/Contents/MacOS/eeschema')],
185
+ pcbnew: [join(base, 'Contents/Applications/pcbnew.app/Contents/MacOS/pcbnew')],
186
+ }
187
+ }
188
+ const exe = process.platform === 'win32' ? '.exe' : ''
189
+ const bin = app ? root : basename(root).toLowerCase() === 'bin' ? root : join(root, 'bin')
190
+ return {
191
+ cli: [join(bin, `kicad-cli${exe}`), join(root, `kicad-cli${exe}`)],
192
+ kicad: [join(bin, `kicad${exe}`)],
193
+ eeschema: [join(bin, `eeschema${exe}`)],
194
+ pcbnew: [join(bin, `pcbnew${exe}`)],
195
+ }
196
+ }
197
+
198
+ function solidcraftCandidates(root: string): string[] {
199
+ const exe = process.platform === 'win32' ? '.exe' : ''
200
+ const app = basename(root).toLowerCase().endsWith('.app')
201
+ if (app || process.platform === 'darwin') {
202
+ const base = app ? root : join(root, 'SolidCraft.app')
203
+ return [
204
+ join(base, `Contents/MacOS/SolidCraft`),
205
+ join(base, `Contents/MacOS/solidcraft`),
206
+ ]
207
+ }
208
+ return [
209
+ root,
210
+ join(root, `SolidCraft${exe}`),
211
+ join(root, `solidcraft${exe}`),
212
+ join(root, 'bin', `SolidCraft${exe}`),
213
+ join(root, 'bin', `solidcraft${exe}`),
214
+ ]
215
+ }
216
+
217
+ /** Small, immutable host capability implementation. */
218
+ export class HardwareArtifactService {
219
+ private readonly options: Required<Pick<HardwareArtifactsOptions, 'spawnProcess' | 'probeVersion'>>
220
+
221
+ constructor(private readonly config: HardwareArtifactsOptions = {}) {
222
+ this.options = {
223
+ probeVersion: config.probeVersion ?? defaultVersionProbe,
224
+ spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
225
+ }
226
+ }
227
+
228
+ /** Resolve configured installations from validated absolute paths only. */
229
+ installations(): Installations {
230
+ const kicadRoot = this.config.kicadRoot ? canonical(this.config.kicadRoot) : undefined
231
+ let kicadCli: string | undefined
232
+ if (kicadRoot !== undefined) {
233
+ const cliPaths = basename(kicadRoot).toLowerCase().startsWith('kicad-cli')
234
+ ? [kicadRoot]
235
+ : kicadCandidates(kicadRoot).cli
236
+ kicadCli = existing(cliPaths)
237
+ }
238
+ const candidates = kicadRoot === undefined
239
+ ? { cli: [], kicad: [], eeschema: [], pcbnew: [] }
240
+ : kicadCandidates(kicadCli && basename(kicadCli).toLowerCase().startsWith('kicad-cli') ? dirname(dirname(dirname(kicadCli))) : kicadRoot)
241
+ const pcbEditor = existing(candidates.pcbnew)
242
+ const schematicEditor = existing(candidates.eeschema)
243
+ const projectManager = existing(candidates.kicad)
244
+ const kicad: InstallationInfo = kicadCli === undefined
245
+ ? { configured: false, error: 'KiCad installation is not configured' }
246
+ : {
247
+ configured: true,
248
+ root: kicadRoot,
249
+ cli: kicadCli,
250
+ ...(projectManager === undefined ? {} : { projectManager }),
251
+ ...(pcbEditor === undefined ? {} : { pcbEditor }),
252
+ ...(schematicEditor === undefined ? {} : { schematicEditor }),
253
+ ...(this.options.probeVersion(kicadCli) === undefined ? {} : { version: this.options.probeVersion(kicadCli) }),
254
+ }
255
+
256
+ const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : undefined
257
+ const solidExecutable = solidRoot === undefined ? undefined : existing(solidcraftCandidates(solidRoot))
258
+ const solidcraft: InstallationInfo = solidExecutable === undefined
259
+ ? { configured: false, error: 'SolidCraft installation is not configured' }
260
+ : { configured: true, root: solidRoot, executable: solidExecutable }
261
+ return { kicad, solidcraft }
262
+ }
263
+
264
+ /** Paths passed to agent child processes. Never assign these globally. */
265
+ childEnvironment(): Record<string, string> {
266
+ const installed = this.installations()
267
+ const env: Record<string, string> = {}
268
+ if (installed.kicad.cli !== undefined) env.HUAQIU_KICAD_CLI = installed.kicad.cli
269
+ if (installed.kicad.pcbEditor !== undefined) env.HUAQIU_KICAD_PCBNEW = installed.kicad.pcbEditor
270
+ if (installed.kicad.schematicEditor !== undefined) env.HUAQIU_KICAD_EESCHEMA = installed.kicad.schematicEditor
271
+ if (installed.solidcraft.executable !== undefined) env.HUAQIU_SOLIDCRAFT = installed.solidcraft.executable
272
+ return env
273
+ }
274
+
275
+ /** Compact agent context: validated paths only, no project inventory dump. */
276
+ environmentText(current?: DiscoveryResult): string {
277
+ const installed = this.installations()
278
+ const lines = ['<hardware_environment>']
279
+ lines.push('KiCad:')
280
+ lines.push(` configured: ${String(installed.kicad.configured)}`)
281
+ for (const key of ['version', 'cli', 'pcbEditor', 'schematicEditor'] as const) {
282
+ const value = installed.kicad[key]
283
+ if (value !== undefined) lines.push(` ${key}: ${value}`)
284
+ }
285
+ if (installed.kicad.error !== undefined) lines.push(` error: ${installed.kicad.error}`)
286
+ lines.push('SolidCraft:')
287
+ lines.push(` configured: ${String(installed.solidcraft.configured)}`)
288
+ if (installed.solidcraft.executable !== undefined) lines.push(` executable: ${installed.solidcraft.executable}`)
289
+ if (installed.solidcraft.error !== undefined) lines.push(` error: ${installed.solidcraft.error}`)
290
+ if (current?.selected !== undefined) {
291
+ lines.push('Current project:')
292
+ lines.push(` root: ${current.cwd}`)
293
+ lines.push(` project: ${current.selected.path}`)
294
+ if (current.selected.schematic !== undefined) lines.push(` schematic: ${current.selected.schematic.path}`)
295
+ const board = current.selected.boards[0]
296
+ if (board !== undefined) lines.push(` selected_pcb: ${board.path}`)
297
+ }
298
+ lines.push('</hardware_environment>')
299
+ return lines.join('\n')
300
+ }
301
+
302
+ /**
303
+ * Deterministic discovery. An explicit project or manifest wins; otherwise
304
+ * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
305
+ * returned as a selection requirement, never resolved by taking the first.
306
+ */
307
+ discover(cwdInput: string, explicitProject?: string): DiscoveryResult {
308
+ const cwd = canonical(cwdInput)
309
+ const manifestPath = join(cwd, '.hardware-engineering.json')
310
+ let manifest: ProjectManifest | undefined
311
+ if (existsSync(manifestPath)) {
312
+ try {
313
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as ProjectManifest
314
+ } catch (error) {
315
+ return { cwd, manifestPath, projects: [], issue: { code: 'bad-manifest', message: `invalid .hardware-engineering.json: ${String(error)}` } }
316
+ }
317
+ }
318
+
319
+ const projectPaths = new Set<string>()
320
+ if (explicitProject !== undefined && explicitProject.trim() !== '') {
321
+ const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject)
322
+ if (!existsSync(requested)) {
323
+ return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects: [], issue: { code: 'missing-project', message: `${requested} does not exist` } }
324
+ }
325
+ projectPaths.add(requested)
326
+ } else if (manifest?.project !== undefined && manifest.project.trim() !== '') {
327
+ projectPaths.add(isAbsolute(manifest.project) ? canonical(manifest.project) : resolve(cwd, manifest.project))
328
+ } else {
329
+ for (const path of walkFiles(cwd, name => name.toLowerCase().endsWith('.kicad_pro'))) projectPaths.add(path)
330
+ }
331
+
332
+ const projects: HardwareProject[] = [...projectPaths].sort().map(path => this.projectFrom(path, cwd, manifest))
333
+ if (projects.length === 0) {
334
+ return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'no-project', message: `no .kicad_pro found under ${cwd}` } }
335
+ }
336
+ if (projects.length > 1) {
337
+ return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'selection-required', message: `${projects.length} projects found; select one explicitly` } }
338
+ }
339
+ const selected = projects[0] as HardwareProject
340
+ return {
341
+ cwd,
342
+ ...(manifest === undefined ? {} : { manifestPath }),
343
+ projects,
344
+ selected,
345
+ ...(selected.selectionRequired
346
+ ? { issue: { code: 'selection-required', message: 'select an artifact explicitly' } }
347
+ : {}),
348
+ }
349
+ }
350
+
351
+ private projectFrom(projectPath: string, cwd: string, manifest?: ProjectManifest): HardwareProject {
352
+ const dir = dirname(projectPath)
353
+ const name = basename(projectPath, extname(projectPath))
354
+ const resolvePath = (value: string): string =>
355
+ isAbsolute(value) ? canonical(value) : resolve(dir, value)
356
+
357
+ const schematicPath = manifest?.schematic !== undefined
358
+ ? resolvePath(manifest.schematic)
359
+ : existing([join(dir, `${name}.kicad_sch`), ...walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_sch'))])
360
+ const boards = manifest?.boards !== undefined
361
+ ? manifest.boards.map(board => artifact('pcb', resolvePath(board.path), projectPath))
362
+ : walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_pcb')).map(path => artifact('pcb', path, projectPath))
363
+ const mechanical = manifest?.mechanical !== undefined
364
+ ? manifest.mechanical.map(model => artifact('mechanical-3d', resolvePath(model.path), projectPath))
365
+ : walkFiles(dir, file => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase()))
366
+ .map(path => artifact('mechanical-3d', path, projectPath))
367
+ const sheets = schematicPath === undefined
368
+ ? []
369
+ : walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_sch'))
370
+ .filter(path => path !== schematicPath && isInside(path, dir))
371
+ .map(path => artifact('schematic', path, projectPath, schematicPath))
372
+
373
+ const sourceSchematic = schematicPath === undefined ? undefined : artifact('schematic', schematicPath, projectPath)
374
+ const sourceBoard = boards[0]
375
+ return {
376
+ path: projectPath,
377
+ name,
378
+ ...(sourceSchematic === undefined ? {} : { schematic: sourceSchematic }),
379
+ ...(sourceSchematic === undefined ? {} : {
380
+ bom: { ...artifact('bom', sourceSchematic.path, projectPath, sourceSchematic.path), title: `BOM — ${sourceSchematic.title}` },
381
+ }),
382
+ ...(sourceBoard === undefined ? {} : {
383
+ pcb3d: { ...artifact('pcb-3d', sourceBoard.path, projectPath, sourceBoard.path), title: `3D — ${sourceBoard.title}` },
384
+ }),
385
+ sheets,
386
+ boards,
387
+ mechanical,
388
+ selectionRequired: boards.length > 1 || sheets.length > 1,
389
+ }
390
+ }
391
+
392
+ /** Validate and launch a native application without a shell. */
393
+ open(request: OpenArtifactRequest): OpenArtifactResult {
394
+ const path = canonical(request.artifactPath)
395
+ if (!existsSync(path)) {
396
+ throw Object.assign(new Error(`artifact does not exist: ${path}`), { code: 'missing-artifact', status: 404 })
397
+ }
398
+ const installed = this.installations()
399
+ const isKicad = request.application === 'kicad'
400
+ let command: string | undefined
401
+ if (isKicad) {
402
+ const ext = extname(path).toLowerCase()
403
+ if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
404
+ else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
405
+ else if (ext === '.kicad_pro') command = installed.kicad.projectManager
406
+ else throw Object.assign(new Error(`unsupported KiCad artifact: ${ext}`), { code: 'unsupported-artifact', status: 415 })
407
+ if (command === undefined) {
408
+ throw Object.assign(new Error('the configured KiCad installation has no editor for this artifact'), { code: 'missing-executable', status: 412 })
409
+ }
410
+ } else {
411
+ command = installed.solidcraft.executable
412
+ if (command === undefined) {
413
+ throw Object.assign(new Error('SolidCraft is not configured'), { code: 'not-configured', status: 412 })
414
+ }
415
+ if (!MECHANICAL_EXTENSIONS.has(extname(path).toLowerCase())) {
416
+ throw Object.assign(new Error(`unsupported SolidCraft artifact: ${extname(path)}`), { code: 'unsupported-artifact', status: 415 })
417
+ }
418
+ }
419
+ const settings = { cwd: dirname(path), detached: true, stdio: 'ignore' as const, windowsHide: true, shell: false as const }
420
+ const child = this.options.spawnProcess(command, [path], settings)
421
+ return { launched: true, command, args: [path], cwd: settings.cwd, ...(child.pid === undefined ? {} : { pid: child.pid }) }
422
+ }
423
+ }