@huaqiu/hardware-artifacts 0.7.12 → 0.7.14

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/lib/service.d.mts CHANGED
@@ -1,99 +1,2 @@
1
- import { ChildProcess } from "node:child_process";
2
- //#region src/service.d.ts
3
- type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'mechanical-3d';
4
- type NativeApplication = 'kicad' | 'solidcraft';
5
- interface HardwareArtifact {
6
- readonly id: string;
7
- readonly kind: ArtifactKind;
8
- readonly path: string;
9
- readonly projectPath?: string;
10
- /** BOM keeps its schematic; PCB 3D keeps its board; sheets keep their root. */
11
- readonly sourcePath?: string;
12
- readonly title: string;
13
- readonly format: string;
14
- }
15
- interface HardwareProject {
16
- readonly path: string;
17
- readonly name: string;
18
- readonly schematic?: HardwareArtifact;
19
- /** Semantic views; both keep the identity of their source artifact. */
20
- readonly bom?: HardwareArtifact;
21
- readonly pcb3d?: HardwareArtifact;
22
- readonly sheets: readonly HardwareArtifact[];
23
- readonly boards: readonly HardwareArtifact[];
24
- readonly mechanical: readonly HardwareArtifact[];
25
- readonly selectionRequired: boolean;
26
- }
27
- interface DiscoveryResult {
28
- readonly cwd: string;
29
- readonly manifestPath?: string;
30
- readonly projects: readonly HardwareProject[];
31
- readonly selected?: HardwareProject;
32
- readonly issue?: {
33
- readonly code: string;
34
- readonly message: string;
35
- };
36
- }
37
- interface InstallationInfo {
38
- readonly configured: boolean;
39
- readonly root?: string;
40
- readonly cli?: string;
41
- readonly projectManager?: string;
42
- readonly pcbEditor?: string;
43
- readonly schematicEditor?: string;
44
- readonly executable?: string;
45
- readonly version?: string;
46
- readonly error?: string;
47
- }
48
- interface Installations {
49
- readonly kicad: InstallationInfo;
50
- readonly solidcraft: InstallationInfo;
51
- }
52
- interface OpenArtifactRequest {
53
- readonly application: NativeApplication;
54
- readonly artifactPath: string;
55
- readonly kind: ArtifactKind;
56
- readonly projectPath?: string;
57
- }
58
- interface OpenArtifactResult {
59
- readonly launched: true;
60
- readonly command: string;
61
- readonly args: readonly string[];
62
- readonly cwd: string;
63
- readonly pid?: number;
64
- }
65
- interface HardwareArtifactsOptions {
66
- readonly kicadRoot?: string;
67
- readonly solidcraftRoot?: string;
68
- readonly probeVersion?: (executable: string) => string | undefined;
69
- readonly spawnProcess?: (command: string, args: readonly string[], options: {
70
- cwd: string;
71
- detached: boolean;
72
- stdio: 'ignore';
73
- windowsHide: boolean;
74
- shell: false;
75
- }) => Pick<ChildProcess, 'pid'>;
76
- }
77
- /** Small, immutable host capability implementation. */
78
- declare class HardwareArtifactService {
79
- private readonly config;
80
- private readonly options;
81
- constructor(config?: HardwareArtifactsOptions);
82
- /** Resolve configured installations from validated absolute paths only. */
83
- installations(): Installations;
84
- /** Paths passed to agent child processes. Never assign these globally. */
85
- childEnvironment(): Record<string, string>;
86
- /** Compact agent context: validated paths only, no project inventory dump. */
87
- environmentText(current?: DiscoveryResult): string;
88
- /**
89
- * Deterministic discovery. An explicit project or manifest wins; otherwise
90
- * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
91
- * returned as a selection requirement, never resolved by taking the first.
92
- */
93
- discover(cwdInput: string, explicitProject?: string): DiscoveryResult;
94
- private projectFrom;
95
- /** Validate and launch a native application without a shell. */
96
- open(request: OpenArtifactRequest): OpenArtifactResult;
97
- }
98
- //#endregion
99
- export { ArtifactKind, DiscoveryResult, HardwareArtifact, HardwareArtifactService, HardwareArtifactsOptions, HardwareProject, InstallationInfo, Installations, NativeApplication, OpenArtifactRequest, OpenArtifactResult };
1
+ import { C as groupBomRows, S as SourceResult, _ as OrderConfigInfo, a as FabricationResult, b as PlaceOrderResult, c as HardwareArtifact, d as HardwareProject, f as InstallationInfo, g as OpenArtifactResult, h as OpenArtifactRequest, i as DiscoveryResult, l as HardwareArtifactService, m as NativeApplication, n as BomResult, o as GlbRequest, p as Installations, r as BomRow, s as GlbResult, t as ArtifactKind, u as HardwareArtifactsOptions, v as OrderPackageSummary, w as parseCsv, x as SourceRequest, y as PlaceOrderRequest } from "./service-CtVn7z8b.mjs";
2
+ export { ArtifactKind, BomResult, BomRow, DiscoveryResult, FabricationResult, GlbRequest, GlbResult, HardwareArtifact, HardwareArtifactService, HardwareArtifactsOptions, HardwareProject, InstallationInfo, Installations, NativeApplication, OpenArtifactRequest, OpenArtifactResult, OrderConfigInfo, OrderPackageSummary, PlaceOrderRequest, PlaceOrderResult, SourceRequest, SourceResult, groupBomRows, parseCsv };
package/lib/service.mjs CHANGED
@@ -1,377 +1,2 @@
1
- import { execFileSync, spawn } from "node:child_process";
2
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
- import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
4
- //#region src/service.ts
5
- /**
6
- * Hardware Engineering artifact model and host operations.
7
- *
8
- * This module deliberately has no Cordis dependency: it is the testable core
9
- * behind `hardwareArtifacts`. Native project files remain authoritative; the
10
- * objects here are path pointers and verified installation facts, never a
11
- * shadow project database.
12
- */
13
- const EXCLUDED_DIRS = /* @__PURE__ */ new Set([
14
- ".git",
15
- ".cache",
16
- "node_modules",
17
- "dist",
18
- "build",
19
- "out",
20
- "tmp",
21
- "temp",
22
- "archive",
23
- "archives",
24
- "backup",
25
- "backups",
26
- "export",
27
- "exports"
28
- ]);
29
- const MECHANICAL_EXTENSIONS = /* @__PURE__ */ new Set([
30
- ".step",
31
- ".stp",
32
- ".glb"
33
- ]);
34
- const MAX_DEPTH = 5;
35
- function canonical(path) {
36
- return resolve(path);
37
- }
38
- function isInside(child, parent) {
39
- const rel = relative(parent, child);
40
- return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
41
- }
42
- function isExcluded(name) {
43
- return EXCLUDED_DIRS.has(name.toLowerCase());
44
- }
45
- function walkFiles(root, predicate) {
46
- const found = [];
47
- const visit = (dir, depth) => {
48
- if (depth > MAX_DEPTH || !existsSync(dir)) return;
49
- let entries;
50
- try {
51
- entries = readdirSync(dir, { withFileTypes: true });
52
- } catch {
53
- return;
54
- }
55
- for (const entry of entries) {
56
- const full = join(dir, entry.name);
57
- if (entry.isDirectory()) {
58
- if (!isExcluded(entry.name)) visit(full, depth + 1);
59
- } else if (entry.isFile() && predicate(entry.name)) found.push(canonical(full));
60
- }
61
- };
62
- visit(root, 0);
63
- return found.sort();
64
- }
65
- function artifact(kind, path, projectPath, sourcePath) {
66
- const full = canonical(path);
67
- return {
68
- id: `${kind}:${full}`,
69
- kind,
70
- path: full,
71
- ...projectPath === void 0 ? {} : { projectPath: canonical(projectPath) },
72
- ...sourcePath === void 0 ? {} : { sourcePath: canonical(sourcePath) },
73
- title: basename(full),
74
- format: extname(full).toLowerCase().replace(/^\./, "") || kind
75
- };
76
- }
77
- function defaultVersionProbe(executable) {
78
- if (!existsSync(executable)) return void 0;
79
- try {
80
- return execFileSync(executable, ["version"], {
81
- encoding: "utf8",
82
- timeout: 5e3,
83
- stdio: [
84
- "ignore",
85
- "pipe",
86
- "ignore"
87
- ]
88
- }).trim().split("\n")[0] || void 0;
89
- } catch {
90
- return;
91
- }
92
- }
93
- function existing(paths) {
94
- return paths.find((candidate) => {
95
- try {
96
- return existsSync(candidate) && statSync(candidate).isFile();
97
- } catch {
98
- return false;
99
- }
100
- });
101
- }
102
- function kicadCandidates(root) {
103
- const app = basename(root).toLowerCase().endsWith(".app");
104
- if (app || process.platform === "darwin") {
105
- const base = app ? root : join(root, "KiCad.app");
106
- return {
107
- cli: [join(base, "Contents/MacOS/kicad-cli")],
108
- kicad: [join(base, "Contents/MacOS/kicad")],
109
- eeschema: [join(base, "Contents/Applications/eeschema.app/Contents/MacOS/eeschema")],
110
- pcbnew: [join(base, "Contents/Applications/pcbnew.app/Contents/MacOS/pcbnew")]
111
- };
112
- }
113
- const exe = process.platform === "win32" ? ".exe" : "";
114
- const bin = app ? root : basename(root).toLowerCase() === "bin" ? root : join(root, "bin");
115
- return {
116
- cli: [join(bin, `kicad-cli${exe}`), join(root, `kicad-cli${exe}`)],
117
- kicad: [join(bin, `kicad${exe}`)],
118
- eeschema: [join(bin, `eeschema${exe}`)],
119
- pcbnew: [join(bin, `pcbnew${exe}`)]
120
- };
121
- }
122
- function solidcraftCandidates(root) {
123
- const exe = process.platform === "win32" ? ".exe" : "";
124
- const app = basename(root).toLowerCase().endsWith(".app");
125
- if (app || process.platform === "darwin") {
126
- const base = app ? root : join(root, "SolidCraft.app");
127
- return [join(base, `Contents/MacOS/SolidCraft`), join(base, `Contents/MacOS/solidcraft`)];
128
- }
129
- return [
130
- root,
131
- join(root, `SolidCraft${exe}`),
132
- join(root, `solidcraft${exe}`),
133
- join(root, "bin", `SolidCraft${exe}`),
134
- join(root, "bin", `solidcraft${exe}`)
135
- ];
136
- }
137
- /** Small, immutable host capability implementation. */
138
- var HardwareArtifactService = class {
139
- config;
140
- options;
141
- constructor(config = {}) {
142
- this.config = config;
143
- this.options = {
144
- probeVersion: config.probeVersion ?? defaultVersionProbe,
145
- spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings))
146
- };
147
- }
148
- /** Resolve configured installations from validated absolute paths only. */
149
- installations() {
150
- const kicadRoot = this.config.kicadRoot ? canonical(this.config.kicadRoot) : void 0;
151
- let kicadCli;
152
- if (kicadRoot !== void 0) kicadCli = existing(basename(kicadRoot).toLowerCase().startsWith("kicad-cli") ? [kicadRoot] : kicadCandidates(kicadRoot).cli);
153
- const candidates = kicadRoot === void 0 ? {
154
- cli: [],
155
- kicad: [],
156
- eeschema: [],
157
- pcbnew: []
158
- } : kicadCandidates(kicadCli && basename(kicadCli).toLowerCase().startsWith("kicad-cli") ? dirname(dirname(dirname(kicadCli))) : kicadRoot);
159
- const pcbEditor = existing(candidates.pcbnew);
160
- const schematicEditor = existing(candidates.eeschema);
161
- const projectManager = existing(candidates.kicad);
162
- const kicad = kicadCli === void 0 ? {
163
- configured: false,
164
- error: "KiCad installation is not configured"
165
- } : {
166
- configured: true,
167
- root: kicadRoot,
168
- cli: kicadCli,
169
- ...projectManager === void 0 ? {} : { projectManager },
170
- ...pcbEditor === void 0 ? {} : { pcbEditor },
171
- ...schematicEditor === void 0 ? {} : { schematicEditor },
172
- ...this.options.probeVersion(kicadCli) === void 0 ? {} : { version: this.options.probeVersion(kicadCli) }
173
- };
174
- const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : void 0;
175
- const solidExecutable = solidRoot === void 0 ? void 0 : existing(solidcraftCandidates(solidRoot));
176
- return {
177
- kicad,
178
- solidcraft: solidExecutable === void 0 ? {
179
- configured: false,
180
- error: "SolidCraft installation is not configured"
181
- } : {
182
- configured: true,
183
- root: solidRoot,
184
- executable: solidExecutable
185
- }
186
- };
187
- }
188
- /** Paths passed to agent child processes. Never assign these globally. */
189
- childEnvironment() {
190
- const installed = this.installations();
191
- const env = {};
192
- if (installed.kicad.cli !== void 0) env.HUAQIU_KICAD_CLI = installed.kicad.cli;
193
- if (installed.kicad.pcbEditor !== void 0) env.HUAQIU_KICAD_PCBNEW = installed.kicad.pcbEditor;
194
- if (installed.kicad.schematicEditor !== void 0) env.HUAQIU_KICAD_EESCHEMA = installed.kicad.schematicEditor;
195
- if (installed.solidcraft.executable !== void 0) env.HUAQIU_SOLIDCRAFT = installed.solidcraft.executable;
196
- return env;
197
- }
198
- /** Compact agent context: validated paths only, no project inventory dump. */
199
- environmentText(current) {
200
- const installed = this.installations();
201
- const lines = ["<hardware_environment>"];
202
- lines.push("KiCad:");
203
- lines.push(` configured: ${String(installed.kicad.configured)}`);
204
- for (const key of [
205
- "version",
206
- "cli",
207
- "pcbEditor",
208
- "schematicEditor"
209
- ]) {
210
- const value = installed.kicad[key];
211
- if (value !== void 0) lines.push(` ${key}: ${value}`);
212
- }
213
- if (installed.kicad.error !== void 0) lines.push(` error: ${installed.kicad.error}`);
214
- lines.push("SolidCraft:");
215
- lines.push(` configured: ${String(installed.solidcraft.configured)}`);
216
- if (installed.solidcraft.executable !== void 0) lines.push(` executable: ${installed.solidcraft.executable}`);
217
- if (installed.solidcraft.error !== void 0) lines.push(` error: ${installed.solidcraft.error}`);
218
- if (current?.selected !== void 0) {
219
- lines.push("Current project:");
220
- lines.push(` root: ${current.cwd}`);
221
- lines.push(` project: ${current.selected.path}`);
222
- if (current.selected.schematic !== void 0) lines.push(` schematic: ${current.selected.schematic.path}`);
223
- const board = current.selected.boards[0];
224
- if (board !== void 0) lines.push(` selected_pcb: ${board.path}`);
225
- }
226
- lines.push("</hardware_environment>");
227
- return lines.join("\n");
228
- }
229
- /**
230
- * Deterministic discovery. An explicit project or manifest wins; otherwise
231
- * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
232
- * returned as a selection requirement, never resolved by taking the first.
233
- */
234
- discover(cwdInput, explicitProject) {
235
- const cwd = canonical(cwdInput);
236
- const manifestPath = join(cwd, ".hardware-engineering.json");
237
- let manifest;
238
- if (existsSync(manifestPath)) try {
239
- manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
240
- } catch (error) {
241
- return {
242
- cwd,
243
- manifestPath,
244
- projects: [],
245
- issue: {
246
- code: "bad-manifest",
247
- message: `invalid .hardware-engineering.json: ${String(error)}`
248
- }
249
- };
250
- }
251
- const projectPaths = /* @__PURE__ */ new Set();
252
- if (explicitProject !== void 0 && explicitProject.trim() !== "") {
253
- const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject);
254
- if (!existsSync(requested)) return {
255
- cwd,
256
- ...manifest === void 0 ? {} : { manifestPath },
257
- projects: [],
258
- issue: {
259
- code: "missing-project",
260
- message: `${requested} does not exist`
261
- }
262
- };
263
- projectPaths.add(requested);
264
- } else if (manifest?.project !== void 0 && manifest.project.trim() !== "") projectPaths.add(isAbsolute(manifest.project) ? canonical(manifest.project) : resolve(cwd, manifest.project));
265
- else for (const path of walkFiles(cwd, (name) => name.toLowerCase().endsWith(".kicad_pro"))) projectPaths.add(path);
266
- const projects = [...projectPaths].sort().map((path) => this.projectFrom(path, cwd, manifest));
267
- if (projects.length === 0) return {
268
- cwd,
269
- ...manifest === void 0 ? {} : { manifestPath },
270
- projects,
271
- issue: {
272
- code: "no-project",
273
- message: `no .kicad_pro found under ${cwd}`
274
- }
275
- };
276
- if (projects.length > 1) return {
277
- cwd,
278
- ...manifest === void 0 ? {} : { manifestPath },
279
- projects,
280
- issue: {
281
- code: "selection-required",
282
- message: `${projects.length} projects found; select one explicitly`
283
- }
284
- };
285
- const selected = projects[0];
286
- return {
287
- cwd,
288
- ...manifest === void 0 ? {} : { manifestPath },
289
- projects,
290
- selected,
291
- ...selected.selectionRequired ? { issue: {
292
- code: "selection-required",
293
- message: "select an artifact explicitly"
294
- } } : {}
295
- };
296
- }
297
- projectFrom(projectPath, cwd, manifest) {
298
- const dir = dirname(projectPath);
299
- const name = basename(projectPath, extname(projectPath));
300
- const resolvePath = (value) => isAbsolute(value) ? canonical(value) : resolve(dir, value);
301
- const schematicPath = manifest?.schematic !== void 0 ? resolvePath(manifest.schematic) : existing([join(dir, `${name}.kicad_sch`), ...walkFiles(dir, (file) => file.toLowerCase().endsWith(".kicad_sch"))]);
302
- const boards = manifest?.boards !== void 0 ? manifest.boards.map((board) => artifact("pcb", resolvePath(board.path), projectPath)) : walkFiles(dir, (file) => file.toLowerCase().endsWith(".kicad_pcb")).map((path) => artifact("pcb", path, projectPath));
303
- const mechanical = manifest?.mechanical !== void 0 ? manifest.mechanical.map((model) => artifact("mechanical-3d", resolvePath(model.path), projectPath)) : walkFiles(dir, (file) => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase())).map((path) => artifact("mechanical-3d", path, projectPath));
304
- const sheets = schematicPath === void 0 ? [] : walkFiles(dir, (file) => file.toLowerCase().endsWith(".kicad_sch")).filter((path) => path !== schematicPath && isInside(path, dir)).map((path) => artifact("schematic", path, projectPath, schematicPath));
305
- const sourceSchematic = schematicPath === void 0 ? void 0 : artifact("schematic", schematicPath, projectPath);
306
- const sourceBoard = boards[0];
307
- return {
308
- path: projectPath,
309
- name,
310
- ...sourceSchematic === void 0 ? {} : { schematic: sourceSchematic },
311
- ...sourceSchematic === void 0 ? {} : { bom: {
312
- ...artifact("bom", sourceSchematic.path, projectPath, sourceSchematic.path),
313
- title: `BOM — ${sourceSchematic.title}`
314
- } },
315
- ...sourceBoard === void 0 ? {} : { pcb3d: {
316
- ...artifact("pcb-3d", sourceBoard.path, projectPath, sourceBoard.path),
317
- title: `3D — ${sourceBoard.title}`
318
- } },
319
- sheets,
320
- boards,
321
- mechanical,
322
- selectionRequired: boards.length > 1 || sheets.length > 1
323
- };
324
- }
325
- /** Validate and launch a native application without a shell. */
326
- open(request) {
327
- const path = canonical(request.artifactPath);
328
- if (!existsSync(path)) throw Object.assign(/* @__PURE__ */ new Error(`artifact does not exist: ${path}`), {
329
- code: "missing-artifact",
330
- status: 404
331
- });
332
- const installed = this.installations();
333
- const isKicad = request.application === "kicad";
334
- let command;
335
- if (isKicad) {
336
- const ext = extname(path).toLowerCase();
337
- if (ext === ".kicad_sch") command = installed.kicad.schematicEditor;
338
- else if (ext === ".kicad_pcb") command = installed.kicad.pcbEditor;
339
- else if (ext === ".kicad_pro") command = installed.kicad.projectManager;
340
- else throw Object.assign(/* @__PURE__ */ new Error(`unsupported KiCad artifact: ${ext}`), {
341
- code: "unsupported-artifact",
342
- status: 415
343
- });
344
- if (command === void 0) throw Object.assign(/* @__PURE__ */ new Error("the configured KiCad installation has no editor for this artifact"), {
345
- code: "missing-executable",
346
- status: 412
347
- });
348
- } else {
349
- command = installed.solidcraft.executable;
350
- if (command === void 0) throw Object.assign(/* @__PURE__ */ new Error("SolidCraft is not configured"), {
351
- code: "not-configured",
352
- status: 412
353
- });
354
- if (!MECHANICAL_EXTENSIONS.has(extname(path).toLowerCase())) throw Object.assign(/* @__PURE__ */ new Error(`unsupported SolidCraft artifact: ${extname(path)}`), {
355
- code: "unsupported-artifact",
356
- status: 415
357
- });
358
- }
359
- const settings = {
360
- cwd: dirname(path),
361
- detached: true,
362
- stdio: "ignore",
363
- windowsHide: true,
364
- shell: false
365
- };
366
- const child = this.options.spawnProcess(command, [path], settings);
367
- return {
368
- launched: true,
369
- command,
370
- args: [path],
371
- cwd: settings.cwd,
372
- ...child.pid === void 0 ? {} : { pid: child.pid }
373
- };
374
- }
375
- };
376
- //#endregion
377
- export { HardwareArtifactService };
1
+ import { n as groupBomRows, r as parseCsv, t as HardwareArtifactService } from "./service-Yrc2C_eo.mjs";
2
+ export { HardwareArtifactService, groupBomRows, parseCsv };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/hardware-artifacts",
3
- "version": "0.7.12",
3
+ "version": "0.7.14",
4
4
  "type": "module",
5
5
  "description": "Hardware Engineering host capability: deterministic artifact discovery, installation resolution, native application launch and compact agent context.",
6
6
  "license": "MIT",
@@ -23,7 +23,8 @@
23
23
  "dsh": "^0.2.2-rc.1"
24
24
  },
25
25
  "dependencies": {
26
- "@deepseek-ai/schemastery": "^3.18.1"
26
+ "@deepseek-ai/schemastery": "^3.18.1",
27
+ "fflate": "^0.8.2"
27
28
  },
28
29
  "peerDependencies": {
29
30
  "@deepseek-ai/cordis": "^4.0.1",
package/src/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `@huaqiu/hardware-artifacts` — Hardware Engineering host capability.
3
3
  *
4
- * Provides `hardwareArtifacts`, mounts same-origin read/launch routes, and
4
+ * Provides `hardwareArtifacts`, mounts same-origin read/export/launch routes, and
5
5
  * contributes a compact validated installation block to the agent prompt.
6
6
  * Nothing here injects hqEdge, opens a shell, or mutates global process env.
7
7
  */
@@ -14,6 +14,7 @@ import { HardwareArtifactService } from './service.js'
14
14
  export type {
15
15
  ArtifactKind,
16
16
  DiscoveryResult,
17
+ FabricationResult,
17
18
  HardwareArtifact,
18
19
  HardwareProject,
19
20
  HardwareArtifactsOptions,
@@ -22,22 +23,71 @@ export type {
22
23
  NativeApplication,
23
24
  OpenArtifactRequest,
24
25
  OpenArtifactResult,
26
+ OrderConfigInfo,
27
+ PlaceOrderRequest,
28
+ PlaceOrderResult,
25
29
  } from './service.js'
26
30
  export { HardwareArtifactService } from './service.js'
31
+ export {
32
+ DEFAULT_ORDER_BASE_URL, DEFAULT_ORDER_PAGE_BASE, ORDER_PATHS, ORDER_SOURCE_TID, orderBomCsv,
33
+ orderBomRows, orderIdsFromUrl, parsePositions, pcbOrderForm, pcbOrderUrl, positionsCsv,
34
+ readBoardFacts, smtOrderForm, smtOrderUrl, smtOrderUrlFromBackend, snapHoleTier, snapThickness,
35
+ snapTraceTier,
36
+ } from './order.js'
37
+ export type { BoardFacts, PositionRow } from './order.js'
27
38
  export { createHardwareHandler, HARDWARE_ROUTE_PREFIX } from './routes.js'
39
+ export type { HardwareHandlerOptions, WorkspaceResolver } from './routes.js'
28
40
 
29
41
  export const name = '@huaqiu/hardware-artifacts'
30
42
  export const inject = ['webServer', 'systemPrompt'] as const
31
43
 
32
- /** User-scoped installation settings persisted by DSH's host-backed config. */
44
+ /**
45
+ * User-scoped installation settings persisted by DSH's host-backed config.
46
+ *
47
+ * Every field is `.volatile()`: DSH's settings service only projects volatile
48
+ * fields into editable forms, and only volatile writes are persisted to the
49
+ * active profile patch. A non-volatile field here would make the Hardware
50
+ * Engineering settings page read-only by construction.
51
+ */
33
52
  export const Config = Schema.object({
34
- kicadRoot: Schema.string().default(''),
35
- solidcraftRoot: Schema.string().default(''),
53
+ kicadRoot: Schema.string().default('').volatile(),
54
+ solidcraftRoot: Schema.string().default('').volatile(),
55
+ /** Set by the first-run wizard once setup was completed or skipped. */
56
+ onboardingComplete: Schema.boolean().default(false).volatile(),
57
+ /**
58
+ * Place-order origin. Empty uses `HUAQIU_ORDER_BASE_URL`, then the Huaqiu
59
+ * host. It is only the transport target; it does not imply the endpoint
60
+ * supports the order contract.
61
+ */
62
+ orderBaseUrl: Schema.string().default('').volatile(),
63
+ /**
64
+ * Huaqiu access token for the assembly endpoint. Volatile so it stays in the
65
+ * profile patch and never reaches the client bundle.
66
+ */
67
+ accessToken: Schema.string().default('').volatile(),
36
68
  })
37
69
 
70
+ /**
71
+ * A schema field value: a plain value, or the stable reference a volatile
72
+ * field resolves to (`{ get(): T }`, see `@deepseek-ai/cosmokit`).
73
+ */
74
+ export type ConfigValue<T> = T | { get(): T }
75
+
38
76
  export interface HardwareArtifactsPluginConfig {
39
- readonly kicadRoot?: string
40
- readonly solidcraftRoot?: string
77
+ readonly kicadRoot?: ConfigValue<string>
78
+ readonly solidcraftRoot?: ConfigValue<string>
79
+ readonly onboardingComplete?: ConfigValue<boolean>
80
+ readonly orderBaseUrl?: ConfigValue<string>
81
+ readonly accessToken?: ConfigValue<string>
82
+ }
83
+
84
+ /** Read one config field, resolving a volatile reference at call time. */
85
+ function readConfig<T>(value: ConfigValue<T> | undefined): T | undefined {
86
+ if (value === undefined) return undefined
87
+ if (typeof value === 'object' && value !== null && typeof (value as { get?: unknown }).get === 'function') {
88
+ return (value as { get(): T }).get()
89
+ }
90
+ return value as T
41
91
  }
42
92
 
43
93
  declare module '@deepseek-ai/cordis' {
@@ -57,9 +107,68 @@ interface SystemPromptFace {
57
107
  }
58
108
 
59
109
  export function apply(ctx: Context, config: HardwareArtifactsPluginConfig = {}): void {
110
+ /**
111
+ * Read one optional host service without declaring it in `inject`.
112
+ *
113
+ * `hardwareArtifacts` must stay usable — and unit-testable — in a profile
114
+ * where auth, sessions or a sandbox policy are absent; each caller degrades
115
+ * on its own instead of the whole plugin refusing to mount.
116
+ */
117
+ const hostService = <T>(name: string): T | undefined => {
118
+ const get = (ctx as Context & { get?: (name: string) => unknown }).get
119
+ return typeof get === 'function' ? get.call(ctx, name) as T | undefined : undefined
120
+ }
121
+
122
+ /**
123
+ * The signed-in Huaqiu session, when the auth plugin is mounted.
124
+ *
125
+ * Read lazily rather than declared in `inject`: only the order path needs the
126
+ * token.
127
+ */
128
+ const huaqiuAuth = (): { auth?: { getAccessToken?: () => Promise<string | null> } } | undefined =>
129
+ hostService<{ auth?: { getAccessToken?: () => Promise<string | null> } }>('huaqiuAuth')
130
+
131
+ /**
132
+ * Workspace root of one DSH session, from the host's own session header.
133
+ *
134
+ * This is what makes authorization survive a workspace switch: the base for
135
+ * a read comes from the session the request names, so another session's
136
+ * discovery cannot revoke it. Falling back to the sandbox policy root keeps
137
+ * a session without a header usable instead of unauthorized.
138
+ */
139
+ const sessionWorkspace = async (sessionId: string): Promise<string | undefined> => {
140
+ const live = hostService<{ get?: (id: string) => { header?: { cwd?: string } } | undefined }>('sessions')
141
+ ?.get?.(sessionId)?.header?.cwd
142
+ if (live !== undefined) return live
143
+ try {
144
+ const stored = await hostService<{
145
+ stat?: (id: string) => Promise<{ header?: { cwd?: string } } | undefined>
146
+ }>('sessionPersistence')?.stat?.(sessionId)
147
+ if (stored?.header?.cwd !== undefined) return stored.header.cwd
148
+ } catch {
149
+ // A session the persistence layer cannot answer for is not an error here.
150
+ }
151
+ return hostService<{ workspaceRoot?: string }>('sandboxPolicy')?.workspaceRoot
152
+ }
153
+
60
154
  const service = new HardwareArtifactService({
61
- ...(config.kicadRoot ? { kicadRoot: config.kicadRoot } : {}),
62
- ...(config.solidcraftRoot ? { solidcraftRoot: config.solidcraftRoot } : {}),
155
+ // The accessor keeps the service on the live profile config reference:
156
+ // a settings write is visible to the next validation without a restart.
157
+ settings: () => ({
158
+ kicadRoot: readConfig(config.kicadRoot),
159
+ solidcraftRoot: readConfig(config.solidcraftRoot),
160
+ orderBaseUrl: readConfig(config.orderBaseUrl),
161
+ accessToken: readConfig(config.accessToken),
162
+ }),
163
+ // hqpcb is a Huaqiu business: the login that authenticates the eda.cn API
164
+ // is the token the order page expects. An explicit config token still wins.
165
+ authToken: async () => {
166
+ try {
167
+ return (await huaqiuAuth()?.auth?.getAccessToken?.()) ?? null
168
+ } catch {
169
+ return null
170
+ }
171
+ },
63
172
  })
64
173
  ctx.effect(() => ctx.provide('hardwareArtifacts', service))
65
174
 
@@ -67,7 +176,7 @@ export function apply(ctx: Context, config: HardwareArtifactsPluginConfig = {}):
67
176
  ctx.effect(() => ctx.webServer.register({
68
177
  kind: 'prefix',
69
178
  path: HARDWARE_ROUTE_PREFIX,
70
- handler: createHardwareHandler(service),
179
+ handler: createHardwareHandler(service, { resolveWorkspace: sessionWorkspace }),
71
180
  }), 'hardware-artifacts: local read/launch routes')
72
181
  }
73
182