@huaqiu/hardware-artifacts 0.7.22 → 0.7.24

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/routes.ts CHANGED
@@ -438,8 +438,8 @@ export function createHardwareHandler(
438
438
  const application = asString(body.application)
439
439
  const artifactPath = asString(body.artifactPath)
440
440
  const kind = asString(body.kind)
441
- if (application !== 'kicad') {
442
- sendJson(res, 400, { error: { code: 'invalid-application', message: 'application must be kicad' }, ok: false })
441
+ if (application !== 'kicad' && application !== 'solidcraft') {
442
+ sendJson(res, 400, { error: { code: 'invalid-application', message: 'application must be kicad or solidcraft' }, ok: false })
443
443
  return
444
444
  }
445
445
  if (artifactPath === undefined || kind === undefined) {
@@ -447,7 +447,10 @@ export function createHardwareHandler(
447
447
  return
448
448
  }
449
449
  try {
450
- const opened = service.open({
450
+ // Which formats each application accepts is decided by the service,
451
+ // from the same configuration everything else reads: this route is a
452
+ // transport, never a second policy.
453
+ const opened = await service.open({
451
454
  application: application as NativeApplication,
452
455
  artifactPath,
453
456
  kind: kind as ArtifactKind,
package/src/service.ts CHANGED
@@ -19,12 +19,33 @@ import {
19
19
  smtOrderUrl, smtOrderUrlFromBackend, zipPackage,
20
20
  type BoardFacts,
21
21
  } from './order.js'
22
+ import { isKicadInput, KICAD_INPUT_FORMATS } from './kicad-inputs.js'
22
23
  import { validateFabricationPackage, validationSummary, type PackageValidation } from './package.js'
24
+ import {
25
+ DEFAULT_QUOTE_QUANTITY, parsePcbQuote, parseSmtQuote, pcbQuoteForm, smtQuoteForm,
26
+ QUOTE_PATHS, type PcbQuote, type PcbQuoteOverrides, type SmtQuote, type SmtQuoteOverrides,
27
+ } from './quote.js'
28
+ import { isSolidcraftInput, SOLIDCRAFT_INPUT_FORMATS } from './solidcraft-inputs.js'
23
29
  import { resolveToolchain } from './toolchain/resolve.js'
24
30
 
25
- export type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'mechanical-3d'
26
- /** Native handoff is KiCad-only in this POC; SolidCraft stays agent context. */
27
- export type NativeApplication = 'kicad'
31
+ /**
32
+ * What an artifact is, for the client that asked for it.
33
+ *
34
+ * `project` is a `.kicad_pro` handed to the project manager by a document
35
+ * action; it never appears in discovery, which lists the schematic, board and
36
+ * derived artifacts. The field is a label on the launch request — the editor is
37
+ * resolved from the suffix — so it is never a dispatch decision.
38
+ */
39
+ export type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'project' | 'mechanical-3d'
40
+ /**
41
+ * Applications this service can hand a file to.
42
+ *
43
+ * `kicad` opens a project artifact in the matching KiCad editor; `solidcraft`
44
+ * opens one of its verified inputs (§7 of the 3D/SolidCraft task) in the
45
+ * configured portable GUI. Both go through the same argument-array launch, so
46
+ * neither can be reached through a shell string or a PATH lookup.
47
+ */
48
+ export type NativeApplication = 'kicad' | 'solidcraft'
28
49
 
29
50
  export interface HardwareArtifact {
30
51
  readonly id: string
@@ -91,7 +112,20 @@ export interface InstallationInfo {
91
112
  readonly projectManager?: string
92
113
  readonly pcbEditor?: string
93
114
  readonly schematicEditor?: string
115
+ /** GUI executable (SolidCraft's `solidcraft.exe`); KiCad resolves editors instead. */
94
116
  readonly executable?: string
117
+ /** GUI half present; independent of {@link cliAvailable} (§6.2). */
118
+ readonly guiAvailable: boolean
119
+ /** CLI half present; independent of {@link guiAvailable} (§6.2). */
120
+ readonly cliAvailable: boolean
121
+ /**
122
+ * Formats the application opens natively, when that is a verified property of
123
+ * the application rather than of this installation — SolidCraft today.
124
+ *
125
+ * Read by the document action and by the agent context, so the header button
126
+ * and the prompt cannot disagree about what a hand-off can accept (§7.1).
127
+ */
128
+ readonly inputFormats?: readonly string[]
95
129
  readonly version?: string
96
130
  readonly error?: string
97
131
  }
@@ -101,6 +135,20 @@ export interface Installations {
101
135
  readonly solidcraft: InstallationInfo
102
136
  }
103
137
 
138
+ /**
139
+ * The slice of a spawned child the launch path uses.
140
+ *
141
+ * A real `child_process` handle satisfies it structurally; a test stub that only
142
+ * answers `{ pid }` satisfies it too, and is then treated as an issued launch
143
+ * whose fate the Host cannot observe — which is all a stub can honestly be.
144
+ */
145
+ export interface SpawnedProcess {
146
+ readonly pid?: number
147
+ once?(event: string, listener: (...args: any[]) => void): unknown
148
+ removeListener?(event: string, listener: (...args: any[]) => void): unknown
149
+ unref?(): void
150
+ }
151
+
104
152
  export interface OpenArtifactRequest {
105
153
  readonly application: NativeApplication
106
154
  readonly artifactPath: string
@@ -237,6 +285,36 @@ export interface PlaceOrderResult {
237
285
  readonly assembly?: FabricationResult['assembly']
238
286
  }
239
287
 
288
+ export interface QuotePcbRequest extends PcbQuoteOverrides {
289
+ /** Board (.kicad_pcb) to price. Absolute anywhere on this machine. */
290
+ readonly boardPath: string
291
+ readonly signal?: AbortSignal
292
+ }
293
+
294
+ export interface QuoteSmtRequest extends SmtQuoteOverrides {
295
+ readonly boardPath: string
296
+ readonly signal?: AbortSignal
297
+ }
298
+
299
+ /** A PCB price with the form and the board facts it was derived from. */
300
+ export interface QuotePcbResult extends PcbQuote {
301
+ readonly boardPath: string
302
+ readonly endpoint: string
303
+ /** The effective form sent to the endpoint — inspect, then override. */
304
+ readonly form: Readonly<Record<string, string>>
305
+ readonly facts: BoardFacts
306
+ readonly generatedAt: string
307
+ }
308
+
309
+ /** An assembly price with the form and the board facts it was derived from. */
310
+ export interface QuoteSmtResult extends SmtQuote {
311
+ readonly boardPath: string
312
+ readonly endpoint: string
313
+ readonly form: Readonly<Record<string, string | number>>
314
+ readonly facts: BoardFacts
315
+ readonly generatedAt: string
316
+ }
317
+
240
318
  export interface HardwareArtifactsOptions {
241
319
  readonly kicadRoot?: string
242
320
  readonly solidcraftRoot?: string
@@ -273,11 +351,19 @@ export interface HardwareArtifactsOptions {
273
351
  readonly accessToken?: string
274
352
  }
275
353
  readonly probeVersion?: (executable: string, tool?: 'kicad' | 'solidcraft') => string | undefined
354
+ /**
355
+ * Spawns one external process.
356
+ *
357
+ * The return value is the handle's pid plus, when the spawner is a real
358
+ * `child_process` one, the lifecycle events the launch path waits on. A test
359
+ * stub may answer `{ pid }` alone: that is a launch the Host cannot observe and
360
+ * counts as issued, which is exactly what such a stub wants to assert.
361
+ */
276
362
  readonly spawnProcess?: (
277
363
  command: string,
278
364
  args: readonly string[],
279
365
  options: { cwd: string; detached: boolean; stdio: 'ignore'; windowsHide: boolean; shell: false },
280
- ) => Pick<ChildProcess, 'pid'>
366
+ ) => SpawnedProcess
281
367
  /**
282
368
  * Command used to hand a URL to the OS. Defaults to `open` on macOS,
283
369
  * `rundll32 url.dll,FileProtocolHandler` on Windows and `xdg-open` elsewhere.
@@ -344,6 +430,37 @@ function errorWithCode(message: string, code: string, status: number): Error {
344
430
  return Object.assign(new Error(message), { code, status })
345
431
  }
346
432
 
433
+ /** Readable text of a thrown value, without the `Error: ` prefix. */
434
+ function messageOf(error: unknown): string {
435
+ if (error instanceof Error) return error.message
436
+ return typeof error === 'string' ? error : 'unknown error'
437
+ }
438
+
439
+ /**
440
+ * Replace the configured installation paths in a sentence with a placeholder.
441
+ *
442
+ * Used for the one text this plugin sends off the machine. §8.2 of the
443
+ * 3D/SolidCraft task forbids putting local installation paths in the agent
444
+ * prompt: the provider needs "no solidcraft executable under &lt;path&gt;", not
445
+ * the user's directory names.
446
+ *
447
+ * Replaced by identity rather than by a path-shaped regular expression: the
448
+ * roots are known here, they may contain spaces and non-ASCII characters, and a
449
+ * pattern loose enough to catch those would also eat prose like "step/stp".
450
+ * @param text - a validation message.
451
+ * @param installed - the installation report the message came from.
452
+ * @returns the message with every configured path replaced by `&lt;path&gt;`.
453
+ */
454
+ function redactPaths(text: string, installed: Installations): string {
455
+ let redacted = text
456
+ for (const info of [installed.kicad, installed.solidcraft]) {
457
+ for (const known of [info.root, info.executable, info.cli, info.pcbEditor, info.schematicEditor]) {
458
+ if (known !== undefined && known !== '') redacted = redacted.replaceAll(known, '<path>')
459
+ }
460
+ }
461
+ return redacted
462
+ }
463
+
347
464
  /**
348
465
  * POST one multipart order payload.
349
466
  *
@@ -623,22 +740,25 @@ export class HardwareArtifactService {
623
740
  exists: path => isFile(path),
624
741
  probeVersion: executable => this.options.probeVersion(executable, 'kicad'),
625
742
  })
626
- const kicad: InstallationInfo = kicadResolution.configured
627
- ? {
628
- configured: true,
629
- ...(roots.kicadRoot === undefined ? {} : { root: canonical(roots.kicadRoot) }),
630
- ...(kicadResolution.cli === undefined ? {} : { cli: kicadResolution.cli }),
631
- ...(kicadResolution.version === undefined ? {} : { version: kicadResolution.version }),
632
- ...(kicadResolution.projectManager === undefined ? {} : { projectManager: kicadResolution.projectManager }),
633
- ...(kicadResolution.pcbEditor === undefined ? {} : { pcbEditor: kicadResolution.pcbEditor }),
634
- ...(kicadResolution.schematicEditor === undefined ? {} : { schematicEditor: kicadResolution.schematicEditor }),
635
- }
636
- : {
637
- configured: false,
638
- ...(roots.kicadRoot === undefined ? {} : { root: canonical(roots.kicadRoot) }),
639
- ...(kicadResolution.cli === undefined ? {} : { cli: kicadResolution.cli }),
640
- ...(kicadResolution.error === undefined ? {} : { error: kicadResolution.error }),
641
- }
743
+ const kicad: InstallationInfo = {
744
+ configured: kicadResolution.configured,
745
+ guiAvailable: kicadResolution.guiAvailable,
746
+ cliAvailable: kicadResolution.cliAvailable,
747
+ // A property of KiCad, not of this installation: reported even when
748
+ // nothing is configured, so the document action and the agent prompt can
749
+ // state what a hand-off would accept before anything is set up (§2).
750
+ inputFormats: KICAD_INPUT_FORMATS,
751
+ ...(roots.kicadRoot === undefined ? {} : { root: canonical(roots.kicadRoot) }),
752
+ ...(kicadResolution.cli === undefined ? {} : { cli: kicadResolution.cli }),
753
+ ...(kicadResolution.version === undefined ? {} : { version: kicadResolution.version }),
754
+ // The editors are reported whether or not the installation validated:
755
+ // a GUI-only KiCad (no `kicad-cli`) has no CLI verdict but can still open
756
+ // a document, and the action decides on the editor, not on the verdict.
757
+ ...(kicadResolution.projectManager === undefined ? {} : { projectManager: kicadResolution.projectManager }),
758
+ ...(kicadResolution.pcbEditor === undefined ? {} : { pcbEditor: kicadResolution.pcbEditor }),
759
+ ...(kicadResolution.schematicEditor === undefined ? {} : { schematicEditor: kicadResolution.schematicEditor }),
760
+ ...(kicadResolution.error === undefined ? {} : { error: kicadResolution.error }),
761
+ }
642
762
 
643
763
  const solidResolution = resolveToolchain('solidcraft', roots.solidcraftRoot, {
644
764
  exists: path => isFile(path),
@@ -646,19 +766,23 @@ export class HardwareArtifactService {
646
766
  })
647
767
  // The GUI executable keeps its historical field name (`executable`) so the
648
768
  // launch path and the agent prompt are unchanged; the CLI is additive.
649
- const solidcraft: InstallationInfo = solidResolution.configured
650
- ? {
651
- configured: true,
652
- ...(roots.solidcraftRoot === undefined ? {} : { root: canonical(roots.solidcraftRoot) }),
653
- ...(solidResolution.app === undefined ? {} : { executable: solidResolution.app }),
654
- ...(solidResolution.cli === undefined ? {} : { cli: solidResolution.cli }),
655
- ...(solidResolution.version === undefined ? {} : { version: solidResolution.version }),
656
- }
657
- : {
658
- configured: false,
659
- ...(roots.solidcraftRoot === undefined ? {} : { root: canonical(roots.solidcraftRoot) }),
660
- ...(solidResolution.error === undefined ? {} : { error: solidResolution.error }),
661
- }
769
+ // Both halves are reported even when the installation is not configured:
770
+ // "the root exists but the archive lost one executable" is a real state the
771
+ // settings surface has to be able to show.
772
+ const solidcraft: InstallationInfo = {
773
+ configured: solidResolution.configured,
774
+ guiAvailable: solidResolution.guiAvailable,
775
+ cliAvailable: solidResolution.cliAvailable,
776
+ // A property of the application, not of this installation: it is reported
777
+ // even when nothing is configured, because the document action and the
778
+ // agent prompt must be able to state what a hand-off would accept.
779
+ inputFormats: SOLIDCRAFT_INPUT_FORMATS,
780
+ ...(roots.solidcraftRoot === undefined ? {} : { root: canonical(roots.solidcraftRoot) }),
781
+ ...(solidResolution.app === undefined ? {} : { executable: solidResolution.app }),
782
+ ...(solidResolution.cli === undefined ? {} : { cli: solidResolution.cli }),
783
+ ...(solidResolution.version === undefined ? {} : { version: solidResolution.version }),
784
+ ...(solidResolution.error === undefined ? {} : { error: solidResolution.error }),
785
+ }
662
786
  return { kicad, solidcraft }
663
787
  }
664
788
 
@@ -673,7 +797,18 @@ export class HardwareArtifactService {
673
797
  return env
674
798
  }
675
799
 
676
- /** Compact agent context: validated paths only, no project inventory dump. */
800
+ /**
801
+ * Compact agent context: validated facts only, no project inventory dump.
802
+ *
803
+ * Deliberately no executable paths: this text is sent to a model provider, and
804
+ * §8.2 of the 3D/SolidCraft task forbids leaking local installation paths for
805
+ * no benefit — the agent never launches anything itself, it asks the Host. What
806
+ * it does need is what it may claim: whether each half of SolidCraft exists,
807
+ * which formats each application verifiably opens, and where the user changes
808
+ * the setting.
809
+ * @param current - discovery scope to describe, when one applies.
810
+ * @returns the `<hardware_environment>` block for the system prompt.
811
+ */
677
812
  environmentText(current?: DiscoveryResult): string {
678
813
  const installed = this.installations()
679
814
  // The prompt has no session of its own; speaking for the only scope that
@@ -683,18 +818,23 @@ export class HardwareArtifactService {
683
818
  const lines = ['<hardware_environment>']
684
819
  lines.push('KiCad:')
685
820
  lines.push(` configured: ${String(installed.kicad.configured)}`)
686
- for (const key of ['version', 'cli', 'pcbEditor', 'schematicEditor'] as const) {
687
- const value = installed.kicad[key]
688
- if (value !== undefined) lines.push(` ${key}: ${value}`)
689
- }
690
- if (installed.kicad.error !== undefined) lines.push(` error: ${installed.kicad.error}`)
821
+ if (installed.kicad.version !== undefined) lines.push(` version: ${installed.kicad.version}`)
822
+ lines.push(` gui_launch: ${String(installed.kicad.guiAvailable)}`)
823
+ lines.push(` input_formats: ${KICAD_INPUT_FORMATS.join(', ')}`)
824
+ // §8.2: this text reaches a model provider, so a validation error is
825
+ // reported with its paths replaced rather than with the user's directories.
826
+ if (installed.kicad.error !== undefined) lines.push(` error: ${redactPaths(installed.kicad.error, installed)}`)
691
827
  lines.push('SolidCraft:')
692
- lines.push(` configured: ${String(installed.solidcraft.configured)}`)
693
- for (const key of ['version', 'executable', 'cli'] as const) {
694
- const value = installed.solidcraft[key]
695
- if (value !== undefined) lines.push(` ${key}: ${value}`)
696
- }
697
- if (installed.solidcraft.error !== undefined) lines.push(` error: ${installed.solidcraft.error}`)
828
+ lines.push(` installed: ${String(installed.solidcraft.configured)}`)
829
+ if (installed.solidcraft.version !== undefined) lines.push(` version: ${installed.solidcraft.version}`)
830
+ // The two halves answer different questions and must not be collapsed into
831
+ // one "available": the agent may tell the user a hand-off is possible while
832
+ // no command can run, and the reverse.
833
+ lines.push(` gui_launch: ${String(installed.solidcraft.guiAvailable)}`)
834
+ lines.push(` cli_available: ${String(installed.solidcraft.cliAvailable)}`)
835
+ lines.push(` input_formats: ${SOLIDCRAFT_INPUT_FORMATS.join(', ')}`)
836
+ if (installed.solidcraft.error !== undefined) lines.push(` error: ${redactPaths(installed.solidcraft.error, installed)}`)
837
+ lines.push(' note: input_formats is what SolidCraft opens natively; do not claim it can open other formats, and do not infer them from the document preview.')
698
838
  // §12.2: an agent must be able to tell the user *what to do* about a missing
699
839
  // toolchain without guessing at product navigation.
700
840
  const missing = [!installed.kicad.configured ? 'KiCad' : undefined, !installed.solidcraft.configured ? 'SolidCraft' : undefined]
@@ -899,8 +1039,20 @@ export class HardwareArtifactService {
899
1039
  }
900
1040
  }
901
1041
 
902
- /** Validate and launch a native application without a shell. */
903
- open(request: OpenArtifactRequest): OpenArtifactResult {
1042
+ /**
1043
+ * Validate and launch a native application without a shell.
1044
+ *
1045
+ * Two applications, one policy: the configured portable executable is used —
1046
+ * never a PATH lookup, never a shell string — the document path travels as one
1047
+ * argv entry, and the call resolves only after the child actually spawned.
1048
+ * A spawn that fails (missing file, permission, bad image) rejects with
1049
+ * `launch-failed` instead of reporting a launch that never happened, which is
1050
+ * what §7.4 of the 3D/SolidCraft task asks for and what `spawn` alone cannot
1051
+ * give: its `error` event arrives after the call returns.
1052
+ * @param request - application, absolute artifact path, and the originating kind.
1053
+ * @returns the command, argv and working directory that were handed to the OS.
1054
+ */
1055
+ async open(request: OpenArtifactRequest): Promise<OpenArtifactResult> {
904
1056
  const path = canonical(request.artifactPath)
905
1057
  if (!existsSync(path)) {
906
1058
  throw errorWithCode(`artifact does not exist: ${path}`, 'missing-artifact', 404)
@@ -908,16 +1060,118 @@ export class HardwareArtifactService {
908
1060
  const installed = this.installations()
909
1061
  const ext = extname(path).toLowerCase()
910
1062
  let command: string | undefined
911
- if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
912
- else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
913
- else if (ext === '.kicad_pro') command = installed.kicad.projectManager
914
- else throw errorWithCode(`unsupported KiCad artifact: ${ext}`, 'unsupported-artifact', 415)
915
- if (command === undefined) {
916
- throw errorWithCode('the configured KiCad installation has no editor for this artifact', 'missing-executable', 412)
917
- }
918
- const settings = { cwd: dirname(path), detached: true, stdio: 'ignore' as const, windowsHide: true, shell: false as const }
919
- const child = this.options.spawnProcess(command, [path], settings)
920
- return { launched: true, command, args: [path], cwd: settings.cwd, ...(child.pid === undefined ? {} : { pid: child.pid }) }
1063
+ if (request.application === 'solidcraft') {
1064
+ // The extension list is SolidCraft's own verified input support, not the
1065
+ // previewer's: §7.1 forbids inheriting the renderer's capability.
1066
+ if (!isSolidcraftInput(path)) {
1067
+ throw errorWithCode(`SolidCraft does not open ${ext} natively`, 'unsupported-artifact', 415)
1068
+ }
1069
+ if (!installed.solidcraft.configured) {
1070
+ throw errorWithCode(
1071
+ installed.solidcraft.error ?? 'the configured SolidCraft installation is not usable',
1072
+ 'not-configured',
1073
+ 412,
1074
+ )
1075
+ }
1076
+ command = installed.solidcraft.executable
1077
+ if (command === undefined || !installed.solidcraft.guiAvailable) {
1078
+ throw errorWithCode(
1079
+ 'the configured SolidCraft installation has no GUI executable to launch',
1080
+ 'missing-executable',
1081
+ 412,
1082
+ )
1083
+ }
1084
+ } else {
1085
+ // The routing table's KiCad half: a suffix with no editor resolution is
1086
+ // not a document KiCad can be handed, so it never reaches a spawn (§2).
1087
+ if (!isKicadInput(path)) {
1088
+ throw errorWithCode(`unsupported KiCad artifact: ${ext}`, 'unsupported-artifact', 415)
1089
+ }
1090
+ if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
1091
+ else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
1092
+ else command = installed.kicad.projectManager
1093
+ if (command === undefined) {
1094
+ throw errorWithCode('the configured KiCad installation has no editor for this artifact', 'missing-executable', 412)
1095
+ }
1096
+ }
1097
+ // `detached` + ignored stdio + `unref` is the launcher contract the Host's
1098
+ // own open-in-app path uses: the editor owns its lifetime, and a document tab
1099
+ // closing must never terminate it.
1100
+ //
1101
+ // The existence check at the top of this method is not the one that matters
1102
+ // here: resolving the installations above probes versions by running the
1103
+ // executables, which takes long enough for the file to be replaced or
1104
+ // removed underneath us. This second check is the one the launch depends on.
1105
+ if (!isFile(path)) {
1106
+ throw errorWithCode(`artifact disappeared before launch: ${path}`, 'missing-artifact', 404)
1107
+ }
1108
+ const settings = {
1109
+ cwd: dirname(path), detached: true as const, stdio: 'ignore' as const, windowsHide: true as const, shell: false as const,
1110
+ }
1111
+ const pid = await this.launch(command, [path], settings)
1112
+ return { launched: true, command, args: [path], cwd: settings.cwd, ...(pid === undefined ? {} : { pid }) }
1113
+ }
1114
+
1115
+ /**
1116
+ * Spawn one detached GUI process and report only a launch that happened.
1117
+ *
1118
+ * `spawn` reports its failures through an `error` event, so returning its
1119
+ * handle would claim success for a path that does not exist. Waiting for
1120
+ * `spawn` (Node emits it after the OS accepted the exec) is the smallest
1121
+ * contract that keeps that claim honest; the child is then unrefed so the
1122
+ * Host does not own the editor's lifetime and a running instance is never
1123
+ * killed when a document tab closes (§7.4).
1124
+ * @param command - absolute executable path from the validated configuration.
1125
+ * @param args - argv; the document path is one entry, never interpolated.
1126
+ * @param settings - working directory and process options.
1127
+ * @returns the child's pid, when the platform reports one.
1128
+ */
1129
+ private launch(
1130
+ command: string,
1131
+ args: readonly string[],
1132
+ settings: { cwd: string; detached: true; stdio: 'ignore'; windowsHide: true; shell: false },
1133
+ ): Promise<number | undefined> {
1134
+ return new Promise((resolvePromise, reject) => {
1135
+ let child: SpawnedProcess
1136
+ try {
1137
+ child = this.options.spawnProcess(command, args, settings)
1138
+ } catch (error) {
1139
+ reject(errorWithCode(`could not start ${command}: ${messageOf(error)}`, 'launch-failed', 500))
1140
+ return
1141
+ }
1142
+ // An injected spawner in a test (or a host wrapper) may hand back a plain
1143
+ // handle without event support; that is a launch we cannot observe, and
1144
+ // refusing it would break every such embedding.
1145
+ const { once, removeListener } = child
1146
+ if (once === undefined || removeListener === undefined) {
1147
+ resolvePromise(child.pid)
1148
+ return
1149
+ }
1150
+ let settled = false
1151
+ const finish = (settle: () => void): void => {
1152
+ if (settled) return
1153
+ settled = true
1154
+ clearTimeout(timer)
1155
+ removeListener.call(child, 'error', onError)
1156
+ settle()
1157
+ }
1158
+ const onError = (error: Error): void => {
1159
+ finish(() => { reject(errorWithCode(`could not start ${command}: ${messageOf(error)}`, 'launch-failed', 500)) })
1160
+ }
1161
+ // A guard, not a wait: `spawn` and `error` both arrive promptly, but a
1162
+ // stub that emits neither must not hold the request open.
1163
+ const timer = setTimeout(() => {
1164
+ finish(() => { resolvePromise(child.pid) })
1165
+ }, 5_000)
1166
+ timer.unref?.()
1167
+ once.call(child, 'error', onError)
1168
+ once.call(child, 'spawn', () => {
1169
+ finish(() => {
1170
+ child.unref?.()
1171
+ resolvePromise(child.pid)
1172
+ })
1173
+ })
1174
+ })
921
1175
  }
922
1176
 
923
1177
  /**
@@ -1509,6 +1763,137 @@ export class HardwareArtifactService {
1509
1763
  }
1510
1764
  }
1511
1765
 
1766
+ // -------------------------------------------------------------------------
1767
+ // Price quotes
1768
+ // -------------------------------------------------------------------------
1769
+
1770
+ /**
1771
+ * Read one board's facts for a price, refusing a board with no outline.
1772
+ *
1773
+ * A price is driven by geometry, so a board without an Edge.Cuts outline has
1774
+ * nothing to price: a clear refusal beats a quote for 0 × 0 mm. No KiCad
1775
+ * installation is required here — the facts come from the file itself.
1776
+ */
1777
+ private boardForQuote(boardPath: string): { path: string; facts: BoardFacts } {
1778
+ const { path } = this.authorize(boardPath)
1779
+ if (extname(path).toLowerCase() !== '.kicad_pcb') {
1780
+ throw errorWithCode('a price can only be quoted for a .kicad_pcb board', 'unsupported-artifact', 415)
1781
+ }
1782
+ const facts = readBoardFacts(readFileSync(path, 'utf8'))
1783
+ if (!(facts.widthMm > 0 && facts.heightMm > 0)) {
1784
+ throw errorWithCode(
1785
+ 'the board has no Edge.Cuts outline, so it has no size to price',
1786
+ 'quote-needs-outline',
1787
+ 422,
1788
+ )
1789
+ }
1790
+ return { path, facts }
1791
+ }
1792
+
1793
+ /**
1794
+ * POST one valuation request and decode its JSON.
1795
+ *
1796
+ * The same transport the order path uses, with the failure modes named: an
1797
+ * unreachable endpoint is not a rejected quote, and the Spring 400 the
1798
+ * endpoint answers a form missing a required field with is reported with that
1799
+ * hint instead of a bare status.
1800
+ */
1801
+ private async postQuote(
1802
+ endpoint: string,
1803
+ body: string,
1804
+ contentType: string,
1805
+ signal?: AbortSignal,
1806
+ ): Promise<unknown> {
1807
+ const post = this.config.postOrder ?? defaultPostOrder
1808
+ let response: { status: number; text: string }
1809
+ try {
1810
+ response = await post(endpoint, {
1811
+ body: Buffer.from(body, 'utf8'),
1812
+ contentType,
1813
+ ...(signal === undefined ? {} : { signal }),
1814
+ })
1815
+ } catch (error) {
1816
+ const detail = error instanceof Error ? error.message : String(error)
1817
+ throw errorWithCode(`the price endpoint could not be reached: ${detail}`, 'quote-unreachable', 502)
1818
+ }
1819
+ if (response.status < 200 || response.status >= 300) {
1820
+ const snippet = response.text.trim().slice(0, 300)
1821
+ const hint = snippet.includes('"timestamp"')
1822
+ ? ' — the endpoint rejected the form itself (a required field is missing or malformed)'
1823
+ : ''
1824
+ throw errorWithCode(
1825
+ `the price endpoint rejected the request (HTTP ${String(response.status)})${hint}: ${snippet}`,
1826
+ 'quote-rejected',
1827
+ 502,
1828
+ )
1829
+ }
1830
+ try {
1831
+ return JSON.parse(response.text) as unknown
1832
+ } catch {
1833
+ throw errorWithCode('the price endpoint returned an unreadable response', 'quote-unreadable', 502)
1834
+ }
1835
+ }
1836
+
1837
+ /**
1838
+ * Quote PCB fabrication for one board.
1839
+ *
1840
+ * Anonymous: no login, no order, no upload. The form is `pcbQuoteForm`'s —
1841
+ * this plugin's own order form plus the endpoint's transport block — so the
1842
+ * price is what the order page for this board would show.
1843
+ */
1844
+ async quotePcb(request: QuotePcbRequest): Promise<QuotePcbResult> {
1845
+ const { path, facts } = this.boardForQuote(request.boardPath)
1846
+ const form = pcbQuoteForm(facts, {
1847
+ ...(request.quantity === undefined ? {} : { quantity: request.quantity }),
1848
+ ...(request.layers === undefined ? {} : { layers: request.layers }),
1849
+ ...(request.thicknessMm === undefined ? {} : { thicknessMm: request.thicknessMm }),
1850
+ ...(request.color === undefined ? {} : { color: request.color }),
1851
+ ...(request.surfaceFinish === undefined ? {} : { surfaceFinish: request.surfaceFinish }),
1852
+ })
1853
+ const quantity = Math.max(1, Math.trunc(Number(form.bcount) || DEFAULT_QUOTE_QUANTITY))
1854
+ const endpoint = `${this.orderSettings().baseUrl}${QUOTE_PATHS.pcb}`
1855
+ const body = await this.postQuote(
1856
+ endpoint,
1857
+ new URLSearchParams(form).toString(),
1858
+ 'application/x-www-form-urlencoded',
1859
+ request.signal,
1860
+ )
1861
+ return {
1862
+ ...parsePcbQuote(body, quantity),
1863
+ boardPath: path,
1864
+ endpoint,
1865
+ form,
1866
+ facts,
1867
+ generatedAt: new Date().toISOString(),
1868
+ }
1869
+ }
1870
+
1871
+ /**
1872
+ * Quote SMT assembly for one board.
1873
+ *
1874
+ * Also anonymous, and also without a BOM export: the pad counts and the
1875
+ * distinct value/footprint pairs come from the board's own footprints, which
1876
+ * is the same material count the assembly form would carry.
1877
+ */
1878
+ async quoteSmt(request: QuoteSmtRequest): Promise<QuoteSmtResult> {
1879
+ const { path, facts } = this.boardForQuote(request.boardPath)
1880
+ const form = smtQuoteForm(facts, {
1881
+ ...(request.quantity === undefined ? {} : { quantity: request.quantity }),
1882
+ ...(request.sides === undefined ? {} : { sides: request.sides }),
1883
+ })
1884
+ const quantity = Math.max(1, Math.trunc(Number(form.number) || DEFAULT_QUOTE_QUANTITY))
1885
+ const endpoint = `${this.orderSettings().baseUrl}${QUOTE_PATHS.smt}`
1886
+ const body = await this.postQuote(endpoint, JSON.stringify(form), 'application/json', request.signal)
1887
+ return {
1888
+ ...parseSmtQuote(body, quantity),
1889
+ boardPath: path,
1890
+ endpoint,
1891
+ form,
1892
+ facts,
1893
+ generatedAt: new Date().toISOString(),
1894
+ }
1895
+ }
1896
+
1512
1897
  /**
1513
1898
  * Open one order page in the OS default browser.
1514
1899
  *
@@ -0,0 +1,44 @@
1
+ /**
2
+ * What SolidCraft verifiably opens, and what it only writes.
3
+ *
4
+ * This list is **evidence**, not preference. It was read from the installed
5
+ * distribution's own command surface (`solidcraft-cli.exe --help` and
6
+ * `solidcraft-cli.exe commands export`, SolidCraft 0.49.1, `7b2bd2be`):
7
+ *
8
+ * - Native *inputs* are the two the CLI takes positionally or after `--in`:
9
+ * `<design.sc|part.step>`. `.stp` is the same STEP family the reader accepts.
10
+ * - `.stl`, `.obj`, `.3mf`, `.glb` and friends are `file.export*` **outputs**,
11
+ * not inputs. Other formats reach a design only through an installed importer
12
+ * *plugin* (`file.import`, `plugin.list importers`), whose presence is per
13
+ * machine and therefore cannot be promised by a document action.
14
+ *
15
+ * Keeping this list here — one module, imported by the launch path, the
16
+ * capability report and the agent prompt — is what stops the product from
17
+ * inheriting the *previewer's* format list. §7.1 of the task says exactly that:
18
+ * a format Three.js can draw is not thereby a format SolidCraft can open.
19
+ *
20
+ * @module @huaqiu/hardware-artifacts/solidcraft-inputs
21
+ */
22
+
23
+ /** Suffixes SolidCraft 0.49.1 opens without an importer plugin, lower case, no dot. */
24
+ export const SOLIDCRAFT_INPUT_EXTENSIONS: readonly string[] = Object.freeze(['step', 'stp', 'sc'])
25
+
26
+ /** Display form of {@link SOLIDCRAFT_INPUT_EXTENSIONS}, for capability text and prompts. */
27
+ export const SOLIDCRAFT_INPUT_FORMATS: readonly string[] = Object.freeze(
28
+ SOLIDCRAFT_INPUT_EXTENSIONS.map(extension => `.${extension}`),
29
+ )
30
+
31
+ /**
32
+ * Is this path one SolidCraft opens natively?
33
+ * @param path - any filesystem path or bare file name; only its suffix is read.
34
+ * @returns true for a verified SolidCraft input, false for everything else.
35
+ */
36
+ export function isSolidcraftInput(path: string): boolean {
37
+ const lower = path.toLowerCase()
38
+ const dot = lower.lastIndexOf('.')
39
+ if (dot === -1) return false
40
+ // A path may carry a query or fragment when it came from an address; neither
41
+ // is part of the file name.
42
+ const suffix = lower.slice(dot + 1).replace(/[?#].*$/u, '')
43
+ return SOLIDCRAFT_INPUT_EXTENSIONS.includes(suffix)
44
+ }