@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/LICENSE +21 -0
- package/README.md +10 -2
- package/cordis.patch.yml +10 -0
- package/lib/index.d.mts +27 -0
- package/lib/index.mjs +32 -0
- package/lib/routes.d.mts +7 -0
- package/lib/routes.mjs +139 -0
- package/lib/service.d.mts +99 -0
- package/lib/service.mjs +377 -0
- package/package.json +51 -3
- package/src/index.ts +83 -0
- package/src/routes.ts +96 -0
- package/src/service.ts +423 -0
package/lib/service.mjs
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@huaqiu/hardware-artifacts",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.7.12",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Hardware Engineering host capability: deterministic artifact discovery, installation resolution, native application launch and compact agent context.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "./lib/index.mjs",
|
|
8
|
+
"types": "./lib/index.d.mts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./lib/index.d.mts",
|
|
12
|
+
"default": "./lib/index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"dsh": {
|
|
18
|
+
"bundle": {
|
|
19
|
+
"patch": "./cordis.patch.yml"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"dsh": "^0.2.2-rc.1"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@deepseek-ai/schemastery": "^3.18.1"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@deepseek-ai/cordis": "^4.0.1",
|
|
30
|
+
"@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.2"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@deepseek-ai/cordis": "^4.0.2",
|
|
34
|
+
"@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.2",
|
|
35
|
+
"@types/node": "^24.0.0",
|
|
36
|
+
"tsdown": "^0.22.14",
|
|
37
|
+
"typescript": "^5.9.0",
|
|
38
|
+
"vitest": "^4.1.0"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"lib",
|
|
42
|
+
"src",
|
|
43
|
+
"cordis.patch.yml",
|
|
44
|
+
"README.md"
|
|
45
|
+
],
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"build": "tsdown",
|
|
52
|
+
"test": "vitest run"
|
|
53
|
+
}
|
|
6
54
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@huaqiu/hardware-artifacts` — Hardware Engineering host capability.
|
|
3
|
+
*
|
|
4
|
+
* Provides `hardwareArtifacts`, mounts same-origin read/launch routes, and
|
|
5
|
+
* contributes a compact validated installation block to the agent prompt.
|
|
6
|
+
* Nothing here injects hqEdge, opens a shell, or mutates global process env.
|
|
7
|
+
*/
|
|
8
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
9
|
+
import type {} from '@deepseek-ai/dsh-host-webserver'
|
|
10
|
+
import Schema from '@deepseek-ai/schemastery'
|
|
11
|
+
import { createHardwareHandler, HARDWARE_ROUTE_PREFIX } from './routes.js'
|
|
12
|
+
import { HardwareArtifactService } from './service.js'
|
|
13
|
+
|
|
14
|
+
export type {
|
|
15
|
+
ArtifactKind,
|
|
16
|
+
DiscoveryResult,
|
|
17
|
+
HardwareArtifact,
|
|
18
|
+
HardwareProject,
|
|
19
|
+
HardwareArtifactsOptions,
|
|
20
|
+
Installations,
|
|
21
|
+
InstallationInfo,
|
|
22
|
+
NativeApplication,
|
|
23
|
+
OpenArtifactRequest,
|
|
24
|
+
OpenArtifactResult,
|
|
25
|
+
} from './service.js'
|
|
26
|
+
export { HardwareArtifactService } from './service.js'
|
|
27
|
+
export { createHardwareHandler, HARDWARE_ROUTE_PREFIX } from './routes.js'
|
|
28
|
+
|
|
29
|
+
export const name = '@huaqiu/hardware-artifacts'
|
|
30
|
+
export const inject = ['webServer', 'systemPrompt'] as const
|
|
31
|
+
|
|
32
|
+
/** User-scoped installation settings persisted by DSH's host-backed config. */
|
|
33
|
+
export const Config = Schema.object({
|
|
34
|
+
kicadRoot: Schema.string().default(''),
|
|
35
|
+
solidcraftRoot: Schema.string().default(''),
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
export interface HardwareArtifactsPluginConfig {
|
|
39
|
+
readonly kicadRoot?: string
|
|
40
|
+
readonly solidcraftRoot?: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
declare module '@deepseek-ai/cordis' {
|
|
44
|
+
interface Context {
|
|
45
|
+
hardwareArtifacts: HardwareArtifactService
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface SystemPromptFace {
|
|
50
|
+
context(entry: {
|
|
51
|
+
name: string
|
|
52
|
+
order: number
|
|
53
|
+
text: string | (() => string)
|
|
54
|
+
interpolate?: boolean
|
|
55
|
+
required?: boolean
|
|
56
|
+
}): () => void
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function apply(ctx: Context, config: HardwareArtifactsPluginConfig = {}): void {
|
|
60
|
+
const service = new HardwareArtifactService({
|
|
61
|
+
...(config.kicadRoot ? { kicadRoot: config.kicadRoot } : {}),
|
|
62
|
+
...(config.solidcraftRoot ? { solidcraftRoot: config.solidcraftRoot } : {}),
|
|
63
|
+
})
|
|
64
|
+
ctx.effect(() => ctx.provide('hardwareArtifacts', service))
|
|
65
|
+
|
|
66
|
+
if (ctx.webServer !== undefined) {
|
|
67
|
+
ctx.effect(() => ctx.webServer.register({
|
|
68
|
+
kind: 'prefix',
|
|
69
|
+
path: HARDWARE_ROUTE_PREFIX,
|
|
70
|
+
handler: createHardwareHandler(service),
|
|
71
|
+
}), 'hardware-artifacts: local read/launch routes')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const prompt = (ctx as Context & { systemPrompt?: SystemPromptFace }).systemPrompt
|
|
75
|
+
if (prompt !== undefined && typeof prompt.context === 'function') {
|
|
76
|
+
ctx.effect(() => prompt.context({
|
|
77
|
+
name: 'hardware-environment',
|
|
78
|
+
order: 42,
|
|
79
|
+
interpolate: false,
|
|
80
|
+
text: () => service.environmentText(),
|
|
81
|
+
}), 'hardware-artifacts: compact agent environment')
|
|
82
|
+
}
|
|
83
|
+
}
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** Read-only HTTP surface for the Hardware Engineering client. */
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
3
|
+
import type { DiscoveryResult, HardwareArtifactService, NativeApplication, ArtifactKind } from './service.js'
|
|
4
|
+
|
|
5
|
+
export const HARDWARE_ROUTE_PREFIX = '/api/v1/hardware'
|
|
6
|
+
|
|
7
|
+
function sendJson(res: ServerResponse, status: number, body: unknown): void {
|
|
8
|
+
const text = JSON.stringify(body)
|
|
9
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(text) })
|
|
10
|
+
res.end(text)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function isTrustedRequest(req: IncomingMessage): boolean {
|
|
14
|
+
const host = String(req.headers.host ?? '')
|
|
15
|
+
if (!/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(host)) return false
|
|
16
|
+
const origin = req.headers.origin
|
|
17
|
+
return origin === undefined || /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(String(origin))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function readJson(req: IncomingMessage, maxBytes = 64 * 1024): Promise<unknown> {
|
|
21
|
+
const chunks: Buffer[] = []
|
|
22
|
+
let size = 0
|
|
23
|
+
for await (const chunk of req) {
|
|
24
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string)
|
|
25
|
+
size += buffer.byteLength
|
|
26
|
+
if (size > maxBytes) throw Object.assign(new Error('request body too large'), { status: 413 })
|
|
27
|
+
chunks.push(buffer)
|
|
28
|
+
}
|
|
29
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function asString(value: unknown): string | undefined {
|
|
33
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createHardwareHandler(service: HardwareArtifactService): (req: IncomingMessage, res: ServerResponse) => void {
|
|
37
|
+
let lastDiscovery: DiscoveryResult | undefined
|
|
38
|
+
return (req, res) => {
|
|
39
|
+
if (!isTrustedRequest(req)) {
|
|
40
|
+
sendJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } })
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
void (async () => {
|
|
44
|
+
try {
|
|
45
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
46
|
+
const p = url.pathname
|
|
47
|
+
if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/projects`) {
|
|
48
|
+
const result = service.discover(asString(url.searchParams.get('cwd') ?? undefined) ?? process.cwd(), asString(url.searchParams.get('project') ?? undefined))
|
|
49
|
+
lastDiscovery = result
|
|
50
|
+
sendJson(res, 200, { ok: true, ...result })
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/installations`) {
|
|
54
|
+
sendJson(res, 200, { ok: true, ...service.installations() })
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
if (req.method === 'GET' && p === `${HARDWARE_ROUTE_PREFIX}/environment`) {
|
|
58
|
+
sendJson(res, 200, { ok: true, text: service.environmentText(lastDiscovery), childEnv: service.childEnvironment() })
|
|
59
|
+
return
|
|
60
|
+
}
|
|
61
|
+
if (req.method === 'POST' && p === `${HARDWARE_ROUTE_PREFIX}/open`) {
|
|
62
|
+
const body = await readJson(req) as Record<string, unknown>
|
|
63
|
+
const application = asString(body.application)
|
|
64
|
+
const artifactPath = asString(body.artifactPath)
|
|
65
|
+
const kind = asString(body.kind)
|
|
66
|
+
if (application !== 'kicad' && application !== 'solidcraft') {
|
|
67
|
+
sendJson(res, 400, { ok: false, error: { code: 'invalid-application', message: 'application must be kicad or solidcraft' } })
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
if (artifactPath === undefined || kind === undefined) {
|
|
71
|
+
sendJson(res, 400, { ok: false, error: { code: 'invalid-request', message: 'artifactPath and kind are required' } })
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const opened = service.open({
|
|
76
|
+
application: application as NativeApplication,
|
|
77
|
+
artifactPath,
|
|
78
|
+
kind: kind as ArtifactKind,
|
|
79
|
+
...(asString(body.projectPath) === undefined ? {} : { projectPath: asString(body.projectPath) as string }),
|
|
80
|
+
})
|
|
81
|
+
sendJson(res, 200, { ok: true, ...opened })
|
|
82
|
+
} catch (error) {
|
|
83
|
+
const code = typeof (error as { code?: unknown }).code === 'string' ? String((error as { code: string }).code) : 'launch-failed'
|
|
84
|
+
const status = typeof (error as { status?: unknown }).status === 'number' ? Number((error as { status: number }).status) : 500
|
|
85
|
+
sendJson(res, status, { ok: false, error: { code, message: error instanceof Error ? error.message : String(error) } })
|
|
86
|
+
}
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
sendJson(res, 404, { ok: false, error: { code: 'not-found', message: 'unknown hardware route' } })
|
|
90
|
+
} catch (error) {
|
|
91
|
+
const status = typeof (error as { status?: unknown }).status === 'number' ? Number((error as { status: number }).status) : 500
|
|
92
|
+
sendJson(res, status, { ok: false, error: { code: 'internal', message: error instanceof Error ? error.message : String(error) } })
|
|
93
|
+
}
|
|
94
|
+
})()
|
|
95
|
+
}
|
|
96
|
+
}
|