dsh-stm32 0.1.7 → 0.1.9

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.
Files changed (153) hide show
  1. package/README.md +567 -516
  2. package/README_EN.md +544 -510
  3. package/client/client.js +7033 -682
  4. package/docs/reading-guide.md +921 -859
  5. package/lib/client.js +7033 -682
  6. package/lib/commands/register.js +2 -0
  7. package/lib/data/firmware-packages.js +35 -0
  8. package/lib/data/firmware-pins.js +7 -0
  9. package/lib/data/install-guides.js +110 -0
  10. package/lib/data/ioc-presets.js +118 -0
  11. package/lib/engine/artifacts.js +123 -0
  12. package/lib/engine/breakpoint-hits.js +73 -0
  13. package/lib/engine/build.js +161 -5
  14. package/lib/engine/channel-tap.js +227 -0
  15. package/lib/engine/channels.js +48 -0
  16. package/lib/engine/clocks.js +192 -0
  17. package/lib/engine/datasheet/auto.js +74 -0
  18. package/lib/engine/datasheet/digest.js +74 -0
  19. package/lib/engine/datasheet/lcsc.js +60 -0
  20. package/lib/engine/datasheet/pinout.js +119 -0
  21. package/lib/engine/datasheet/price.js +152 -0
  22. package/lib/engine/datasheet/search.js +147 -0
  23. package/lib/engine/datasheet/store.js +371 -0
  24. package/lib/engine/debug-session.js +48 -2
  25. package/lib/engine/ecad/autobuild.js +156 -0
  26. package/lib/engine/ecad/bom.js +238 -0
  27. package/lib/engine/ecad/brief.js +205 -0
  28. package/lib/engine/ecad/checks.js +239 -0
  29. package/lib/engine/ecad/design.js +177 -0
  30. package/lib/engine/ecad/dfm.js +314 -0
  31. package/lib/engine/ecad/easyeda.js +454 -0
  32. package/lib/engine/ecad/fabrication.js +104 -0
  33. package/lib/engine/ecad/gen/footprint.js +159 -0
  34. package/lib/engine/ecad/gen/symbol.js +103 -0
  35. package/lib/engine/ecad/import.js +372 -0
  36. package/lib/engine/ecad/jlcpcb.js +141 -0
  37. package/lib/engine/ecad/libs.js +316 -0
  38. package/lib/engine/ecad/models3d.js +89 -0
  39. package/lib/engine/ecad/netgate.js +286 -0
  40. package/lib/engine/ecad/normalize.js +182 -0
  41. package/lib/engine/ecad/package.js +126 -0
  42. package/lib/engine/ecad/padmerge.js +128 -0
  43. package/lib/engine/ecad/padprecheck.js +123 -0
  44. package/lib/engine/ecad/part-import.js +257 -0
  45. package/lib/engine/ecad/pcb/apply.js +53 -0
  46. package/lib/engine/ecad/pcb/emc-deep.js +396 -0
  47. package/lib/engine/ecad/pcb/emc.js +275 -0
  48. package/lib/engine/ecad/pcb/geometry.js +63 -0
  49. package/lib/engine/ecad/pcb/gerber.js +499 -0
  50. package/lib/engine/ecad/pcb/hand-sync.js +242 -0
  51. package/lib/engine/ecad/pcb/impedance.js +119 -0
  52. package/lib/engine/ecad/pcb/ipc-open.js +78 -0
  53. package/lib/engine/ecad/pcb/ipc-script.js +276 -0
  54. package/lib/engine/ecad/pcb/ipc.js +129 -0
  55. package/lib/engine/ecad/pcb/krt.js +182 -0
  56. package/lib/engine/ecad/pcb/links.js +393 -0
  57. package/lib/engine/ecad/pcb/mech.js +201 -0
  58. package/lib/engine/ecad/pcb/model-fix.js +178 -0
  59. package/lib/engine/ecad/pcb/netlist.js +146 -0
  60. package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
  61. package/lib/engine/ecad/pcb/placement.js +140 -0
  62. package/lib/engine/ecad/pcb/power.js +203 -0
  63. package/lib/engine/ecad/pcb/render3d.js +208 -0
  64. package/lib/engine/ecad/pcb/route.js +167 -0
  65. package/lib/engine/ecad/pcb/router.js +469 -0
  66. package/lib/engine/ecad/pcb/rules.js +122 -0
  67. package/lib/engine/ecad/pcb/scene.js +513 -0
  68. package/lib/engine/ecad/pcb/stackup.js +154 -0
  69. package/lib/engine/ecad/pcb/swap.js +222 -0
  70. package/lib/engine/ecad/pcb/tracks.js +70 -0
  71. package/lib/engine/ecad/runtime.js +227 -0
  72. package/lib/engine/ecad/toolchain.js +146 -0
  73. package/lib/engine/ecad/tsci.js +362 -0
  74. package/lib/engine/ecad/zip.js +98 -0
  75. package/lib/engine/event-bus.js +158 -0
  76. package/lib/engine/event-log.js +335 -0
  77. package/lib/engine/fault-hints.js +146 -0
  78. package/lib/engine/generate-script.js +4 -1
  79. package/lib/engine/generate.js +145 -5
  80. package/lib/engine/interrupts.js +247 -0
  81. package/lib/engine/ioc-diff.js +369 -0
  82. package/lib/engine/ioc-plan.js +12 -2
  83. package/lib/engine/ioc-sync.js +58 -0
  84. package/lib/engine/mcu-info.js +134 -0
  85. package/lib/engine/msys2-install.js +31 -6
  86. package/lib/engine/panel-actions.js +103 -0
  87. package/lib/engine/pdf/curve.js +321 -0
  88. package/lib/engine/pdf/png.js +83 -0
  89. package/lib/engine/pdf/reader.js +336 -0
  90. package/lib/engine/pdf/schematic.js +93 -0
  91. package/lib/engine/pdf/tables.js +249 -0
  92. package/lib/engine/pdf/toolchain.js +50 -0
  93. package/lib/engine/pinout.js +140 -0
  94. package/lib/engine/probe-info.js +95 -0
  95. package/lib/engine/probe.js +45 -0
  96. package/lib/engine/progress.js +99 -0
  97. package/lib/engine/project-conf.js +254 -0
  98. package/lib/engine/project-layout.js +198 -0
  99. package/lib/engine/project-repair.js +205 -0
  100. package/lib/engine/schematic/checks.js +153 -0
  101. package/lib/engine/schematic/draw.js +390 -0
  102. package/lib/engine/schematic/edit.js +229 -0
  103. package/lib/engine/schematic/kicad-sch.js +225 -0
  104. package/lib/engine/schematic/model.js +442 -0
  105. package/lib/engine/schematic/nets.js +219 -0
  106. package/lib/engine/schematic/pcb.js +144 -0
  107. package/lib/engine/schematic/review.js +134 -0
  108. package/lib/engine/schematic/sexpr.js +134 -0
  109. package/lib/engine/schematic/to-ioc.js +197 -0
  110. package/lib/engine/schematic/transform.js +25 -0
  111. package/lib/engine/session-context.js +106 -0
  112. package/lib/engine/source-slice.js +59 -0
  113. package/lib/engine/tool-events.js +119 -0
  114. package/lib/engine/toolchain-gate.js +8 -0
  115. package/lib/engine/watch-admin.js +101 -0
  116. package/lib/engine/watch-record.js +39 -0
  117. package/lib/engine/watch-recorder.js +116 -0
  118. package/lib/engine/web-api.js +1123 -4
  119. package/lib/engine/web-routes.js +18 -1
  120. package/lib/engine/workspace-memo.js +41 -0
  121. package/lib/index.js +118 -24
  122. package/lib/skill/stm32-workflow.js +1 -1
  123. package/lib/tools/build.js +10 -2
  124. package/lib/tools/code-patch.js +2 -2
  125. package/lib/tools/datasheet.js +447 -0
  126. package/lib/tools/debug-session.js +9 -4
  127. package/lib/tools/debug.js +2 -2
  128. package/lib/tools/doctor.js +2 -2
  129. package/lib/tools/ecad.js +903 -0
  130. package/lib/tools/flash.js +2 -2
  131. package/lib/tools/gen.js +166 -0
  132. package/lib/tools/generate.js +7 -5
  133. package/lib/tools/import-circuit.js +146 -0
  134. package/lib/tools/ioc-apply.js +11 -2
  135. package/lib/tools/ioc-inspect.js +2 -2
  136. package/lib/tools/ioc-plan.js +2 -2
  137. package/lib/tools/ioc-verify.js +2 -2
  138. package/lib/tools/layout.js +92 -0
  139. package/lib/tools/mcu-info.js +163 -0
  140. package/lib/tools/part-import.js +182 -0
  141. package/lib/tools/pcb.js +2316 -0
  142. package/lib/tools/pdf.js +423 -0
  143. package/lib/tools/project-create.js +28 -0
  144. package/lib/tools/project-dir.js +25 -1
  145. package/lib/tools/regs.js +2 -2
  146. package/lib/tools/route-plan.js +2 -2
  147. package/lib/tools/rtt.js +10 -2
  148. package/lib/tools/sch-draw.js +433 -0
  149. package/lib/tools/sch-edit.js +145 -0
  150. package/lib/tools/schematic.js +817 -0
  151. package/lib/tools/serial.js +22 -0
  152. package/lib/tools/watch.js +24 -2
  153. package/package.json +1 -1
@@ -12,9 +12,39 @@
12
12
  * HTTP 适配在 src/index.ts 里,保持极薄。
13
13
  */
14
14
  import { binDirsFromConfig, configReadingDisabled, cubeMxRootsFromConfig, readToolchainConfig, toolchainConfigPath, updateToolchainConfig, } from "../data/toolchain-config.js";
15
+ import { readFileSync, statSync } from "node:fs";
16
+ import { fileURLToPath } from "node:url";
15
17
  import { resolveSearchConfig } from "../data/search-roots.js";
16
18
  import { buildTargets, probeAll } from "./probe.js";
17
19
  import { planOrInstallMsys2 } from "./msys2-install.js";
20
+ import { EVENT_RING_LIMIT, eventSessionKey, eventSnapshot, subscribeEvents, } from "./event-bus.js";
21
+ import { evidencePolicy, evidenceRoot, pruneEvidence } from "./event-log.js";
22
+ import { readProjectConf, readWorkspaceIndex, scanWorkspaceProjects } from "./project-conf.js";
23
+ import { resolveProjectLayout } from "./project-layout.js";
24
+ import { applyLayoutFix, planLayoutFix } from "./project-repair.js";
25
+ import { abortAll, abortCall, listRunning } from "./progress.js";
26
+ import { channelTapStatus, setChannelTaps } from "./channel-tap.js";
27
+ import { watchRecorder } from "./watch-record.js";
28
+ import { agentOfSession } from "./session-context.js";
29
+ import { closeSerial, listPorts, openSerial, sendSerial, serialStatus } from "./serial.js";
30
+ import { readInterrupts, setInterruptPriorities, setInterruptPriority } from "./interrupts.js";
31
+ import { readIocSync } from "./ioc-sync.js";
32
+ import { addWatches, clearWatches, listWatches, removeWatches } from "./watch-admin.js";
33
+ import { buildFromPanel, flashFromPanel } from "./panel-actions.js";
34
+ import { readSourceSlice } from "./source-slice.js";
35
+ import { readProbeInfo } from "./probe-info.js";
36
+ import { debugSessions } from "./debug-session.js";
37
+ import { readClockTree } from "./clocks.js";
38
+ import { readArtifacts } from "./artifacts.js";
39
+ import { decodeFault, groupFaults } from "./fault-hints.js";
40
+ import { readIocDiff, readIocKeysForPin, restoreAllIocKeys, restoreIocKey, saveIocSnapshot } from "./ioc-diff.js";
41
+ import { readFile, readdir, stat } from "node:fs/promises";
42
+ import { dirname, join, resolve, sep } from "node:path";
43
+ import { readPinout } from "./pinout.js";
44
+ import { findRootSchematic, readSchematic } from "./schematic/model.js";
45
+ import { checkSchematic } from "./schematic/checks.js";
46
+ import { runSchematicReview } from "./schematic/review.js";
47
+ import { findIocFile } from "./generate.js";
18
48
  function envOf(deps) {
19
49
  return deps.env ?? process.env;
20
50
  }
@@ -281,6 +311,70 @@ export function installStart(payload, deps) {
281
311
  }
282
312
  /* ---------------------------- 分发 ---------------------------- */
283
313
  export const WEB_API_PREFIX = "/dsh-stm32/api";
314
+ /** 工程类接口缺 projectDir 时的统一提示:不再回落到进程工作目录(S84)。 */
315
+ const PROJECT_DIR_REQUIRED = "projectDir 不能为空:从工具栏「工程」下拉里选一个,或先打开调试会话";
316
+ /**
317
+ * 会话工作目录解析器(S84):宿主 `workingDirectory` 服务由 `src/index.ts` 注入。
318
+ * 面板没传 projectDir 时先问它,避免把插件进程的 profile 目录当成工程。
319
+ */
320
+ let sessionWorkspaceResolver = null;
321
+ export function setSessionWorkspaceResolver(resolver) {
322
+ sessionWorkspaceResolver = resolver;
323
+ }
324
+ /**
325
+ * 请求会话对应的 agent id(S91):调试会话记的是启动它的 agent id,
326
+ * 面板请求带的是会话 id,两者要对上才允许看/改这条调试会话。
327
+ */
328
+ function callerAgentIdOf(sessionId) {
329
+ if (sessionId === "")
330
+ return "";
331
+ const agent = agentOfSession(sessionId);
332
+ if (agent === undefined || agent === null)
333
+ return "";
334
+ return typeof agent.id === "string" ? agent.id : "";
335
+ }
336
+ /**
337
+ * 调试会话归属判定(S91):owner 是启动它的 agent id,请求里带的是会话 id。
338
+ * 两边都查得到且不相等才算「别人的」;查不到时不拦,保持老行为。
339
+ */
340
+ export function debugSessionForeign(sessionId, owner) {
341
+ if (sessionId === "" || owner === "")
342
+ return false;
343
+ const mine = callerAgentIdOf(sessionId);
344
+ if (mine === "")
345
+ return false;
346
+ return owner !== mine;
347
+ }
348
+ /** 当前调试会话是否属于另一条会话:是则面板不能把它当成自己的。 */
349
+ function isForeignDebugSession(sessionId) {
350
+ return debugSessionForeign(sessionId, debugSessions.status().owner);
351
+ }
352
+ /** 模块加载时刻:用来判断运行中的进程是不是本次构建后的实例。 */
353
+ const PLUGIN_STARTED_AT = Date.now();
354
+ /**
355
+ * 插件自检:版本、lib 构建时间、路由数。
356
+ *
357
+ * 面板拿到这三个值就能回答「页面功能是不是已经生效」——路由数是本次注册的数量,
358
+ * 旧进程加载的是旧 lib,路由数与构建时间都会停在重启之前。
359
+ */
360
+ function pluginSelfCheck() {
361
+ let version = "";
362
+ let libMtimeMs = 0;
363
+ try {
364
+ const text = readFileSync(new URL("../../package.json", import.meta.url), "utf8");
365
+ version = String(JSON.parse(text).version ?? "");
366
+ }
367
+ catch {
368
+ version = "";
369
+ }
370
+ try {
371
+ libMtimeMs = statSync(fileURLToPath(import.meta.url)).mtimeMs;
372
+ }
373
+ catch {
374
+ libMtimeMs = 0;
375
+ }
376
+ return { version, libMtimeMs, startedAt: PLUGIN_STARTED_AT, routeCount: WEB_API_PATHS.length };
377
+ }
284
378
  export const WEB_API_PATHS = [
285
379
  WEB_API_PREFIX + "/config",
286
380
  WEB_API_PREFIX + "/config/save",
@@ -288,7 +382,219 @@ export const WEB_API_PATHS = [
288
382
  WEB_API_PREFIX + "/install/plan",
289
383
  WEB_API_PREFIX + "/install/start",
290
384
  WEB_API_PREFIX + "/install/state",
385
+ WEB_API_PREFIX + "/events",
386
+ WEB_API_PREFIX + "/status",
387
+ WEB_API_PREFIX + "/debug",
388
+ WEB_API_PREFIX + "/debug/breakpoints",
389
+ WEB_API_PREFIX + "/pinout",
390
+ WEB_API_PREFIX + "/clocks",
391
+ WEB_API_PREFIX + "/faults",
392
+ WEB_API_PREFIX + "/artifacts",
393
+ WEB_API_PREFIX + "/evidence",
394
+ WEB_API_PREFIX + "/replay",
395
+ WEB_API_PREFIX + "/evidence/prune",
396
+ WEB_API_PREFIX + "/ioc-diff",
397
+ WEB_API_PREFIX + "/ioc-diff/save",
398
+ WEB_API_PREFIX + "/ioc-diff/restore",
399
+ WEB_API_PREFIX + "/ioc-diff/restore-all",
400
+ WEB_API_PREFIX + "/ioc-keys",
401
+ WEB_API_PREFIX + "/abort",
402
+ WEB_API_PREFIX + "/channels",
403
+ WEB_API_PREFIX + "/channels/start",
404
+ WEB_API_PREFIX + "/channels/stop",
405
+ WEB_API_PREFIX + "/watch-recording",
406
+ WEB_API_PREFIX + "/watch-recording/start",
407
+ WEB_API_PREFIX + "/watch-recording/stop",
408
+ WEB_API_PREFIX + "/serial/send",
409
+ WEB_API_PREFIX + "/debug/touch",
410
+ WEB_API_PREFIX + "/debug/stop",
411
+ WEB_API_PREFIX + "/interrupts",
412
+ WEB_API_PREFIX + "/interrupts/priority",
413
+ WEB_API_PREFIX + "/interrupts/priorities",
414
+ WEB_API_PREFIX + "/ioc-sync",
415
+ WEB_API_PREFIX + "/watch",
416
+ WEB_API_PREFIX + "/build",
417
+ WEB_API_PREFIX + "/projects",
418
+ WEB_API_PREFIX + "/flash",
419
+ WEB_API_PREFIX + "/source",
420
+ WEB_API_PREFIX + "/probe-info",
421
+ WEB_API_PREFIX + "/serial",
422
+ WEB_API_PREFIX + "/serial/ports",
423
+ WEB_API_PREFIX + "/serial/open",
424
+ WEB_API_PREFIX + "/serial/close",
425
+ WEB_API_PREFIX + "/schematic",
426
+ WEB_API_PREFIX + "/schematic/review",
427
+ // 板图要单独登记:host 只给 WEB_API_PATHS 里的路径注册 handler,没登记就是 404。
428
+ // 器件搜索也要单独登记(S163):GET /ecad/parts?q=… 直接查立创,不依赖工程。
429
+ WEB_API_PREFIX + "/layout",
291
430
  ];
431
+ /** 面板要看的库清单:封装按 .pretty 目录数封装,符号按 .kicad_sym 里的符号数。 */
432
+ async function scanEcadLibs(libsDir) {
433
+ const footprints = [];
434
+ const symbols = [];
435
+ try {
436
+ for (const name of await readdir(join(libsDir, "footprints"))) {
437
+ if (!name.endsWith(".pretty"))
438
+ continue;
439
+ const files = await readdir(join(libsDir, "footprints", name));
440
+ footprints.push({ lib: name.slice(0, -".pretty".length), count: files.filter((file) => file.endsWith(".kicad_mod")).length });
441
+ }
442
+ }
443
+ catch {
444
+ // 还没导出过库:空列表即正确状态。
445
+ }
446
+ try {
447
+ for (const name of await readdir(join(libsDir, "symbols"))) {
448
+ if (!name.endsWith(".kicad_sym"))
449
+ continue;
450
+ const text = await readFile(join(libsDir, "symbols", name), "utf8");
451
+ const count = (text.match(/\(symbol\s+"/gu) ?? []).length;
452
+ symbols.push({ lib: name.slice(0, -".kicad_sym".length), count: count });
453
+ }
454
+ }
455
+ catch {
456
+ // 同上。
457
+ }
458
+ return { footprints: footprints, symbols: symbols };
459
+ }
460
+ /** 面板要看的导出产物:out 根目录下的文件 + gerbers 目录里的文件数。 */
461
+ async function scanEcadArtifacts(outDir) {
462
+ const artifacts = [];
463
+ try {
464
+ for (const name of await readdir(outDir)) {
465
+ const info = await stat(join(outDir, name));
466
+ if (!info.isFile())
467
+ continue;
468
+ artifacts.push({ name: name, bytes: info.size });
469
+ }
470
+ }
471
+ catch {
472
+ // 还没导出过:空列表即正确状态。
473
+ }
474
+ try {
475
+ const gerbers = await readdir(join(outDir, "gerbers"));
476
+ artifacts.push({ name: "gerbers/(" + String(gerbers.length) + " 个文件)", bytes: 0 });
477
+ }
478
+ catch {
479
+ // 没有 gerbers 目录时不列。
480
+ }
481
+ return artifacts;
482
+ }
483
+ /** 证据文件最多列这么多条,面板只用来挑一个回放。 */
484
+ const EVIDENCE_FILE_LIMIT = 200;
485
+ /** 单个证据文件的读取上限:超出说明这个文件不该在面板里打开。 */
486
+ const REPLAY_MAX_BYTES = 8 * 1024 * 1024;
487
+ /** 一次回放最多载入多少条事件,与环形缓冲同量级。 */
488
+ const REPLAY_MAX_EVENTS = 5000;
489
+ /** 列证据目录下的 .jsonl,按修改时间倒序;最深到「日期 / 会话 / 文件」这一层。 */
490
+ /** 证据文件的分组键:`<日期>/<会话键>/events-….jsonl` 里的会话键。 */
491
+ export function evidenceSessionKey(filePath) {
492
+ const parts = filePath.split("/");
493
+ return parts.length >= 3 ? parts[1] ?? "" : "";
494
+ }
495
+ /**
496
+ * 按会话把证据文件分组(S48)。
497
+ *
498
+ * 目录结构已经是「日期/会话/文件」,列表却把 200 个文件平铺出来,找某个会话
499
+ * 要自己筛。分组只做展示,文件路径仍是唯一标识。
500
+ */
501
+ export function groupEvidenceFiles(files) {
502
+ const groups = new Map();
503
+ for (const file of files) {
504
+ const key = evidenceSessionKey(file.path);
505
+ const found = groups.get(key);
506
+ if (found === undefined) {
507
+ groups.set(key, { key, bytes: file.size, latestMs: file.mtimeMs, files: [file] });
508
+ continue;
509
+ }
510
+ found.bytes += file.size;
511
+ found.latestMs = Math.max(found.latestMs, file.mtimeMs);
512
+ found.files.push(file);
513
+ }
514
+ return Array.from(groups.values()).sort((left, right) => right.latestMs - left.latestMs || left.key.localeCompare(right.key));
515
+ }
516
+ async function listEvidenceFiles(root) {
517
+ const found = [];
518
+ const walk = async (dir, prefix, depth) => {
519
+ if (found.length >= EVIDENCE_FILE_LIMIT || depth > 3)
520
+ return;
521
+ let entries;
522
+ try {
523
+ entries = await readdir(dir, { withFileTypes: true });
524
+ }
525
+ catch {
526
+ return;
527
+ }
528
+ for (const entry of entries) {
529
+ if (found.length >= EVIDENCE_FILE_LIMIT)
530
+ return;
531
+ const relative = prefix === "" ? entry.name : prefix + "/" + entry.name;
532
+ if (entry.isDirectory()) {
533
+ await walk(join(dir, entry.name), relative, depth + 1);
534
+ continue;
535
+ }
536
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
537
+ continue;
538
+ try {
539
+ const info = await stat(join(dir, entry.name));
540
+ found.push({ path: relative, size: info.size, mtimeMs: info.mtimeMs });
541
+ }
542
+ catch {
543
+ // 单个文件读不到就跳过,不影响其余条目。
544
+ }
545
+ }
546
+ };
547
+ await walk(resolve(root), "", 1);
548
+ found.sort((left, right) => right.mtimeMs - left.mtimeMs);
549
+ return found.slice(0, EVIDENCE_FILE_LIMIT);
550
+ }
551
+ /** 把相对路径钉在证据目录内:绝对路径、`..` 与非 .jsonl 一律拒绝。 */
552
+ function evidenceTarget(root, relative) {
553
+ const trimmed = relative.trim();
554
+ if (trimmed === "" || !trimmed.endsWith(".jsonl"))
555
+ return null;
556
+ const base = resolve(root);
557
+ const target = resolve(base, trimmed);
558
+ if (target === base || !target.startsWith(base + sep))
559
+ return null;
560
+ return target;
561
+ }
562
+ /** 逐行解析 jsonl,只收形状完整的事件;坏行计入 skipped 不抛。 */
563
+ function parseEvidence(text) {
564
+ const events = [];
565
+ let skipped = 0;
566
+ for (const line of text.split(/\r?\n/u)) {
567
+ const trimmed = line.trim();
568
+ if (trimmed === "")
569
+ continue;
570
+ if (events.length >= REPLAY_MAX_EVENTS) {
571
+ skipped += 1;
572
+ continue;
573
+ }
574
+ try {
575
+ const parsed = JSON.parse(trimmed);
576
+ if (parsed === null || typeof parsed !== "object") {
577
+ skipped += 1;
578
+ continue;
579
+ }
580
+ const item = parsed;
581
+ if (typeof item["seq"] !== "number" ||
582
+ typeof item["time"] !== "string" ||
583
+ typeof item["kind"] !== "string" ||
584
+ typeof item["status"] !== "string" ||
585
+ typeof item["summary"] !== "string") {
586
+ skipped += 1;
587
+ continue;
588
+ }
589
+ events.push(item);
590
+ }
591
+ catch {
592
+ skipped += 1;
593
+ }
594
+ }
595
+ events.sort((left, right) => left.seq - right.seq);
596
+ return { events, skipped };
597
+ }
292
598
  function ok(body) {
293
599
  return { status: 200, body: { ok: true, ...body } };
294
600
  }
@@ -316,13 +622,94 @@ function parseJsonBody(text) {
316
622
  export async function handleWebApi(input) {
317
623
  const method = input.method.toUpperCase();
318
624
  const path = input.path.replace(/\/+$/u, "");
625
+ // 请求里的会话 id 决定用哪条会话的工作目录(S91)。缺省或查不到时解析为空串,
626
+ // 由路由回 400 说明缺什么——不回落到「最近一个 agent」或进程工作目录,
627
+ // 否则在别的工作区打开调试台会看到本工作区的工程。
628
+ const requestSession = typeof (input.query ?? {})["session"] === "string"
629
+ ? (input.query ?? {})["session"].trim()
630
+ : "";
631
+ let sessionDir = "";
632
+ if (sessionWorkspaceResolver !== null && requestSession !== "") {
633
+ try {
634
+ sessionDir = (await sessionWorkspaceResolver(requestSession)).trim();
635
+ }
636
+ catch {
637
+ sessionDir = "";
638
+ }
639
+ }
640
+ // 兜底顺序(S91):显式 projectDir → 本会话工作目录 → 空(由路由回 400)。
641
+ const withProject = (raw) => {
642
+ const trimmed = raw.trim();
643
+ if (trimmed !== "")
644
+ return trimmed;
645
+ return sessionDir;
646
+ };
647
+ /**
648
+ * 程序目录(S95):工程根可能把程序放在 `program/` 或 `firmware/` 下。
649
+ *
650
+ * 读 `.ioc`、跑构建、烧录都应以程序目录为准;工程根仍用于「选工程」与原理图。
651
+ */
652
+ const firmwareProject = (raw) => {
653
+ const root = withProject(raw);
654
+ if (root === "")
655
+ return "";
656
+ return resolveProjectLayout(root).firmwareDir;
657
+ };
319
658
  const query = input.query ?? {};
320
- const needsBody = path !== WEB_API_PREFIX + "/config" && path !== WEB_API_PREFIX + "/install/state";
321
- if (needsBody && method !== "POST")
659
+ const needsBody = path !== WEB_API_PREFIX + "/config" &&
660
+ path !== WEB_API_PREFIX + "/install/state" &&
661
+ path !== WEB_API_PREFIX + "/status" &&
662
+ path !== WEB_API_PREFIX + "/debug" &&
663
+ path !== WEB_API_PREFIX + "/channels" &&
664
+ path !== WEB_API_PREFIX + "/pinout" &&
665
+ path !== WEB_API_PREFIX + "/clocks" &&
666
+ path !== WEB_API_PREFIX + "/faults" &&
667
+ path !== WEB_API_PREFIX + "/artifacts" &&
668
+ path !== WEB_API_PREFIX + "/evidence" &&
669
+ path !== WEB_API_PREFIX + "/replay" &&
670
+ path !== WEB_API_PREFIX + "/ioc-diff" &&
671
+ path !== WEB_API_PREFIX + "/ioc-keys" &&
672
+ path !== WEB_API_PREFIX + "/watch-recording" &&
673
+ path !== WEB_API_PREFIX + "/interrupts" &&
674
+ path !== WEB_API_PREFIX + "/ioc-sync" &&
675
+ path !== WEB_API_PREFIX + "/source" &&
676
+ path !== WEB_API_PREFIX + "/probe-info" &&
677
+ path !== WEB_API_PREFIX + "/serial" &&
678
+ path !== WEB_API_PREFIX + "/serial/ports" &&
679
+ path !== WEB_API_PREFIX + "/schematic" &&
680
+ path !== WEB_API_PREFIX + "/ecad" &&
681
+ path !== WEB_API_PREFIX + "/ecad/pcb" &&
682
+ path !== WEB_API_PREFIX + "/ecad/bom" &&
683
+ path !== WEB_API_PREFIX + "/ecad/stackup" &&
684
+ path !== WEB_API_PREFIX + "/ecad/emc" &&
685
+ path !== WEB_API_PREFIX + "/ecad/links" &&
686
+ path !== WEB_API_PREFIX + "/ecad/gerber" &&
687
+ path !== WEB_API_PREFIX + "/ecad/render3d" &&
688
+ path !== WEB_API_PREFIX + "/ecad/swap" &&
689
+ path !== WEB_API_PREFIX + "/ecad/power" &&
690
+ path !== WEB_API_PREFIX + "/ecad/brief" &&
691
+ path !== WEB_API_PREFIX + "/ecad/impedance" &&
692
+ path !== WEB_API_PREFIX + "/ecad/netgate" &&
693
+ path !== WEB_API_PREFIX + "/ecad/mech" &&
694
+ path !== WEB_API_PREFIX + "/ecad/parts" &&
695
+ path !== WEB_API_PREFIX + "/ecad/ipc" &&
696
+ path !== WEB_API_PREFIX + "/projects";
697
+ // 一路径两动词的接口:GET 读、POST 改(S191:以前 /watch 的 GET 被 needsBody 挡成 405)。
698
+ const dualVerb = path === WEB_API_PREFIX + "/watch" ||
699
+ path === WEB_API_PREFIX + "/ecad/brief" ||
700
+ path === WEB_API_PREFIX + "/ecad/mech" ||
701
+ path === WEB_API_PREFIX + "/ecad/impedance" ||
702
+ path === WEB_API_PREFIX + "/schematic/edit" ||
703
+ path === WEB_API_PREFIX + "/schematic/sync" ||
704
+ path === WEB_API_PREFIX + "/ecad/swap";
705
+ if (!dualVerb && needsBody && method !== "POST") {
322
706
  return fail(405, "这个接口只接受 POST");
323
- if (!needsBody && method !== "GET")
707
+ }
708
+ else if (!dualVerb && !needsBody && method !== "GET") {
324
709
  return fail(405, "这个接口只接受 GET");
325
- const parsed = needsBody ? parseJsonBody(input.body ?? "") : { ok: true, value: {}, error: "" };
710
+ }
711
+ const twoVerb = dualVerb && method === "POST";
712
+ const parsed = needsBody || twoVerb ? parseJsonBody(input.body ?? "") : { ok: true, value: {}, error: "" };
326
713
  if (!parsed.ok)
327
714
  return fail(400, parsed.error);
328
715
  const env = envOf(input.deps);
@@ -367,9 +754,741 @@ export async function handleWebApi(input) {
367
754
  return fail(404, "没有这个安装任务:" + taskId);
368
755
  return ok({ state });
369
756
  }
757
+ if (path === WEB_API_PREFIX + "/debug") {
758
+ // 调试面板用:当前调试会话、断点与观察点预算、剩余租约。只读,不碰探针。
759
+ const report = debugSessions.status();
760
+ if (isForeignDebugSession(requestSession)) {
761
+ // 别的会话在调试:这条会话的面板看不到它的工程与输出,避免跨会话串信息(S91)。
762
+ return ok({
763
+ debug: {
764
+ active: false,
765
+ sessionId: "",
766
+ port: 0,
767
+ tclPort: 0,
768
+ projectDir: "",
769
+ elfPath: "",
770
+ remainingMs: 0,
771
+ idleTtlMs: 0,
772
+ hardTtlMs: 0,
773
+ breakpoints: [],
774
+ watchpoints: [],
775
+ hits: [],
776
+ outputs: [],
777
+ foreign: true,
778
+ message: "调试会话由另一条会话启动,这条会话看不到它的工程与输出",
779
+ },
780
+ });
781
+ }
782
+ return ok({
783
+ debug: {
784
+ active: report.active,
785
+ sessionId: report.sessionId,
786
+ port: report.port,
787
+ tclPort: report.tclPort,
788
+ projectDir: report.projectDir,
789
+ elfPath: report.elfPath,
790
+ remainingMs: report.remainingMs,
791
+ idleTtlMs: report.idleTtlMs,
792
+ hardTtlMs: report.hardTtlMs,
793
+ breakpoints: report.breakpoints,
794
+ watchpoints: report.watchpoints,
795
+ hits: debugSessions.hitHistory(),
796
+ outputs: debugSessions.recentTraces(),
797
+ message: report.message,
798
+ },
799
+ });
800
+ }
801
+ if (path === WEB_API_PREFIX + "/source") {
802
+ // 源码片段:只读工程目录内的文件,给「文件:行」补上下文。
803
+ // 源码在程序目录下(program/Core、fw/Core),不是工程根(S129)。
804
+ const projectDir = firmwareProject(typeof query["projectDir"] === "string" ? query["projectDir"] : "");
805
+ if (projectDir === "")
806
+ return fail(400, PROJECT_DIR_REQUIRED);
807
+ const file = typeof query["file"] === "string" ? query["file"] : "";
808
+ const line = Number.parseInt(typeof query["line"] === "string" ? query["line"] : "", 10);
809
+ const context = Number.parseInt(typeof query["context"] === "string" ? query["context"] : "3", 10);
810
+ const read = readSourceSlice(projectDir, file, Number.isFinite(line) ? line : Number.NaN, Number.isFinite(context) ? context : 3);
811
+ if (!read.ok)
812
+ return fail(400, read.error);
813
+ return ok({ source: read.slice });
814
+ }
815
+ if (path === WEB_API_PREFIX + "/watch") {
816
+ // 监视登记表:与 stm32_watch 共用同一份状态;硬件观察点要活动会话。
817
+ if (method === "GET")
818
+ return ok({ watch: listWatches() });
819
+ const action = typeof parsed.value.action === "string" ? parsed.value.action : "";
820
+ if (action === "add") {
821
+ const kind = typeof parsed.value.kind === "string" ? parsed.value.kind : "value";
822
+ const expressions = Array.isArray(parsed.value.expressions)
823
+ ? parsed.value.expressions.filter((item) => typeof item === "string")
824
+ : [];
825
+ const report = await addWatches({ kind, expressions });
826
+ if (!report.ok && report.added.length === 0)
827
+ return fail(409, report.message);
828
+ return ok({ watch: report });
829
+ }
830
+ if (action === "remove") {
831
+ const ids = Array.isArray(parsed.value.ids)
832
+ ? parsed.value.ids.filter((item) => typeof item === "number")
833
+ : [];
834
+ const report = await removeWatches(ids);
835
+ if (!report.ok && report.removed.length === 0)
836
+ return fail(404, report.message);
837
+ return ok({ watch: report });
838
+ }
839
+ if (action === "clear")
840
+ return ok({ watch: await clearWatches() });
841
+ return fail(400, "action 必须是 add / remove / clear 之一");
842
+ }
843
+ if (path === WEB_API_PREFIX + "/build") {
844
+ // 人在面板上点构建:不经过模型,但结果按同一种事件写进时间线。
845
+ // cmake 在程序目录里跑,工程根上没有 CMakeLists.txt(S129)。
846
+ const projectDir = firmwareProject(typeof parsed.value.projectDir === "string"
847
+ ? parsed.value.projectDir
848
+ : "");
849
+ if (projectDir === "")
850
+ return fail(400, PROJECT_DIR_REQUIRED);
851
+ const clean = parsed.value.clean === true;
852
+ const target = typeof parsed.value.target === "string" ? parsed.value.target : undefined;
853
+ const artifacts = Array.isArray(parsed.value.artifacts)
854
+ ? parsed.value.artifacts.filter((item) => item === "elf" || item === "hex" || item === "bin")
855
+ : undefined;
856
+ const report = await buildFromPanel({ subprocess: input.deps.subprocess, env: envOf(input.deps) }, {
857
+ projectDir,
858
+ ...(clean ? { clean: true } : {}),
859
+ ...(target === undefined ? {} : { target }),
860
+ ...(artifacts === undefined || artifacts.length === 0 ? {} : { artifacts }),
861
+ });
862
+ return ok({ build: report });
863
+ }
864
+ if (path === WEB_API_PREFIX + "/flash") {
865
+ const projectDir = firmwareProject(typeof parsed.value.projectDir === "string"
866
+ ? parsed.value.projectDir
867
+ : "");
868
+ if (projectDir === "")
869
+ return fail(400, PROJECT_DIR_REQUIRED);
870
+ const adapterSpeed = typeof parsed.value.adapterSpeed === "number" && Number.isFinite(parsed.value.adapterSpeed)
871
+ ? parsed.value.adapterSpeed
872
+ : undefined;
873
+ const report = await flashFromPanel({ subprocess: input.deps.subprocess, env: envOf(input.deps) }, {
874
+ projectDir,
875
+ ...(adapterSpeed === undefined ? {} : { adapterSpeed }),
876
+ ...(parsed.value.allowNoDebug === true ? { allowNoDebug: true } : {}),
877
+ });
878
+ return ok({ flash: report });
879
+ }
880
+ if (path === WEB_API_PREFIX + "/projects") {
881
+ // 工程选择器(S82):工作区索引 + 现场扫描合并,附当前工程描述。
882
+ const rootParam = typeof query["root"] === "string" ? query["root"].trim() : "";
883
+ const projectParam = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
884
+ const workspaceRoot = rootParam !== ""
885
+ ? rootParam
886
+ : (projectParam !== "" ? dirname(resolve(projectParam)) : sessionDir);
887
+ if (workspaceRoot === "") {
888
+ // 没有会话工作目录就没有可列的工作区:宁可空列表,也不猜一个别的工作区(S91)。
889
+ return ok({
890
+ projects: {
891
+ workspaceRoot: "",
892
+ confPath: "",
893
+ hasConf: false,
894
+ entries: [],
895
+ current: null,
896
+ note: "没有可用的会话工作目录:先在这条会话里调用一次 STM32 工具,或从工具栏「工程」下拉里选一个工程",
897
+ },
898
+ });
899
+ }
900
+ const index = readWorkspaceIndex(workspaceRoot);
901
+ const scanned = scanWorkspaceProjects(workspaceRoot);
902
+ const seen = new Set(index.projects.map((item) => item.dir));
903
+ const merged = [...index.projects];
904
+ for (const item of scanned) {
905
+ if (seen.has(item.dir))
906
+ continue;
907
+ seen.add(item.dir);
908
+ merged.push(item);
909
+ }
910
+ const current = projectParam !== "" ? readProjectConf(projectParam) : null;
911
+ return ok({
912
+ projects: {
913
+ workspaceRoot: index.workspaceRoot,
914
+ confPath: index.confPath,
915
+ hasConf: index.exists,
916
+ entries: merged.slice(0, 50),
917
+ current,
918
+ },
919
+ });
920
+ }
921
+ if (path === WEB_API_PREFIX + "/ioc-sync") {
922
+ // .ioc 与生成代码是否同步:只比修改时间,不读内容、不跑 CubeMX。
923
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
924
+ const projectDir = firmwareProject(requested);
925
+ if (projectDir === "")
926
+ return fail(400, PROJECT_DIR_REQUIRED);
927
+ const read = readIocSync(projectDir);
928
+ if (!read.ok)
929
+ return fail(409, read.error);
930
+ return ok({ iocSync: read.report });
931
+ }
932
+ if (path === WEB_API_PREFIX + "/probe-info") {
933
+ // 探针信息:只读 pnputil 的 USB 枚举,不连目标、不动探针。
934
+ const report = await readProbeInfo({
935
+ subprocess: input.deps.subprocess,
936
+ ...(input.deps.signal === undefined ? {} : { signal: input.deps.signal }),
937
+ });
938
+ return ok({ probeInfo: report });
939
+ }
940
+ if (path === WEB_API_PREFIX + "/interrupts/priorities") {
941
+ // 批量改优先级(S74):一次备份、一次写盘,逐路返回结果。
942
+ const requested = typeof parsed.value.projectDir === "string" ? parsed.value.projectDir.trim() : "";
943
+ const names = Array.isArray(parsed.value.names) ? parsed.value.names.filter((name) => typeof name === "string") : [];
944
+ if (names.length === 0)
945
+ return fail(400, "names 不能为空(要改的中断名数组)");
946
+ const preempt = typeof parsed.value.preempt === "number" ? parsed.value.preempt : Number.NaN;
947
+ const sub = typeof parsed.value.sub === "number" ? parsed.value.sub : Number.NaN;
948
+ const dir = firmwareProject(requested);
949
+ if (dir === "")
950
+ return fail(400, PROJECT_DIR_REQUIRED);
951
+ const written = setInterruptPriorities(dir, names, preempt, sub);
952
+ if (!written.ok)
953
+ return fail(409, written.error);
954
+ return ok({ interruptPriorities: written.report });
955
+ }
956
+ if (path === WEB_API_PREFIX + "/interrupts/priority") {
957
+ // 中断页改优先级:只改 NVIC.<name>_IRQn 那一条,写前备份。
958
+ const requested = typeof parsed.value.projectDir === "string" ? parsed.value.projectDir.trim() : "";
959
+ const name = typeof parsed.value.name === "string" ? parsed.value.name : "";
960
+ if (name.trim() === "")
961
+ return fail(400, "name 不能为空(例如 USART1)");
962
+ const preempt = typeof parsed.value.preempt === "number" ? parsed.value.preempt : Number.NaN;
963
+ const sub = typeof parsed.value.sub === "number" ? parsed.value.sub : Number.NaN;
964
+ const dir = firmwareProject(requested);
965
+ if (dir === "")
966
+ return fail(400, PROJECT_DIR_REQUIRED);
967
+ const written = setInterruptPriority(dir, name, preempt, sub);
968
+ if (!written.ok)
969
+ return fail(409, written.error);
970
+ return ok({ interruptPriority: written.report });
971
+ }
972
+ if (path === WEB_API_PREFIX + "/interrupts") {
973
+ // 中断页:只读 .ioc 的 NVIC.*,不启动 CubeMX、不改配置。
974
+ // 读的是 .ioc,所以要走程序目录而不是工程根——.ioc 常放在 fw/、program/ 之下(S129)。
975
+ const projectDir = firmwareProject(typeof query["projectDir"] === "string" ? query["projectDir"] : "");
976
+ if (projectDir === "")
977
+ return fail(400, PROJECT_DIR_REQUIRED);
978
+ const read = readInterrupts(projectDir);
979
+ if (!read.ok)
980
+ return fail(409, read.error);
981
+ return ok({ interrupts: read.report });
982
+ }
983
+ if (path === WEB_API_PREFIX + "/pinout") {
984
+ // 引脚面板:读工程 .ioc,按外设分组。只读文件,不跑 CubeMX、不碰探针。
985
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
986
+ const projectDir = firmwareProject(requested);
987
+ if (projectDir === "")
988
+ return fail(400, PROJECT_DIR_REQUIRED);
989
+ const read = readPinout(projectDir, env);
990
+ if (!read.ok)
991
+ return fail(409, read.error);
992
+ return ok({ pinout: read.report });
993
+ }
994
+ if (path === WEB_API_PREFIX + "/schematic/review") {
995
+ // 原理图一键评审:读图 → 规则检查 → 配置草案,只读不写盘(S135)。
996
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
997
+ const projectDir = withProject(requested);
998
+ if (projectDir === "")
999
+ return fail(400, PROJECT_DIR_REQUIRED);
1000
+ const rootFile = typeof query["rootFile"] === "string" ? query["rootFile"].trim() : "";
1001
+ return ok({ review: runSchematicReview({ projectDir, ...(rootFile === "" ? {} : { rootFile }) }) });
1002
+ }
1003
+ if (path === WEB_API_PREFIX + "/schematic") {
1004
+ // 原理图页:读 KiCad 工程,给模块框图与检查结果;只读文件,不碰探针。
1005
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
1006
+ const projectDir = withProject(requested);
1007
+ if (projectDir === "")
1008
+ return fail(400, PROJECT_DIR_REQUIRED);
1009
+ const layout = resolveProjectLayout(projectDir);
1010
+ const hardwareDir = layout.hardwareDir;
1011
+ if (hardwareDir === "") {
1012
+ return fail(404, "工程里没有 KiCad 原理图:把 KiCad 工程放到 hardware/ 下,或在 dsh-stm32.conf 里写 hardware=目录名");
1013
+ }
1014
+ const rootFile = findRootSchematic(hardwareDir);
1015
+ if (rootFile === null || rootFile === "")
1016
+ return fail(404, `硬件目录里没有 .kicad_sch:${hardwareDir}`);
1017
+ let schematic;
1018
+ try {
1019
+ schematic = readSchematic(rootFile);
1020
+ }
1021
+ catch (error) {
1022
+ return fail(409, `原理图解析失败:${error instanceof Error ? error.message : String(error)}`);
1023
+ }
1024
+ const report = schematic.report;
1025
+ // PCB 对账跟着工程走:目录里有 .kicad_pcb 就一起对,没有就只查原理图本身。
1026
+ const pcbName = (await readdir(hardwareDir)).find((name) => name.endsWith(".kicad_pcb")) ?? "";
1027
+ const iocFile = findIocFile(layout.firmwareDir);
1028
+ const check = checkSchematic(report, {
1029
+ ...(pcbName === "" ? {} : { pcbFile: join(hardwareDir, pcbName) }),
1030
+ ...(iocFile === null ? {} : { iocFile }),
1031
+ });
1032
+ return ok({
1033
+ schematic: {
1034
+ rootFile: report.rootFile,
1035
+ version: report.version,
1036
+ generator: report.generator,
1037
+ sheets: report.sheets,
1038
+ components: report.components.length,
1039
+ nets: report.nets.length,
1040
+ mcu: report.mcu === null ? null : { ref: report.mcu.ref, value: report.mcu.value, pins: report.mcu.pins },
1041
+ pinIndex: report.components.flatMap((component) => component.pins.map((pin) => ({ ref: component.ref, pin: pin.number, name: pin.name, net: pin.net }))),
1042
+ diagram: report.diagram,
1043
+ warnings: report.warnings,
1044
+ findings: check.findings,
1045
+ summary: check.summary,
1046
+ pcb: check.pcb,
1047
+ layout: { projectDir: layout.projectDir, firmwareDir: layout.firmwareDir, hardwareDir: layout.hardwareDir, notes: layout.notes },
1048
+ },
1049
+ });
1050
+ }
1051
+ if (path === WEB_API_PREFIX + "/layout") {
1052
+ // 工程结构与配置文件归位(S128):GET 只规划,POST 才动文件。
1053
+ const requested = typeof parsed.value.workspaceRoot === "string" ? parsed.value.workspaceRoot.trim() : "";
1054
+ const workspaceRoot = requested === "" ? withProject("") : resolve(requested);
1055
+ if (workspaceRoot === "")
1056
+ return ok({ layoutFix: { ok: false, error: PROJECT_DIR_REQUIRED, workspaceRoot: "", actions: [], notes: [] } });
1057
+ if (input.method !== "POST") {
1058
+ const plan = planLayoutFix(workspaceRoot);
1059
+ return ok({ layoutFix: { ok: plan.ok, error: plan.error, workspaceRoot: plan.workspaceRoot, actions: plan.actions, notes: plan.notes } });
1060
+ }
1061
+ const fixed = applyLayoutFix(workspaceRoot);
1062
+ return ok({ layoutFix: { ok: fixed.ok, error: fixed.error, workspaceRoot: fixed.workspaceRoot, actions: fixed.actions, notes: fixed.notes } });
1063
+ }
1064
+ if (path === WEB_API_PREFIX + "/clocks") {
1065
+ // 时钟页:读工程 .ioc 里 CubeMX 已经写下的各路频率,只读不改。
1066
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
1067
+ const projectDir = firmwareProject(requested);
1068
+ if (projectDir === "")
1069
+ return fail(400, PROJECT_DIR_REQUIRED);
1070
+ const read = readClockTree(projectDir);
1071
+ if (!read.ok)
1072
+ return fail(409, read.error);
1073
+ return ok({ clocks: read.report });
1074
+ }
1075
+ if (path === WEB_API_PREFIX + "/faults") {
1076
+ // 故障页:把本会话最近的失败事件按规则翻成「先看哪里」。只读事件流,不碰探针。
1077
+ const wanted = (query["session"] ?? "").trim();
1078
+ const since = Number(query["since"] ?? "0");
1079
+ const limitRaw = Number(query["limit"] ?? "50");
1080
+ const limit = Number.isFinite(limitRaw) ? Math.min(200, Math.max(1, Math.trunc(limitRaw))) : 50;
1081
+ const failures = eventSnapshot(Number.isFinite(since) ? since : 0, wanted).filter((item) => item.status === "fail");
1082
+ const faults = failures.slice(-limit).map((item) => {
1083
+ const decoded = decodeFault(item.summary);
1084
+ return {
1085
+ seq: item.seq,
1086
+ time: item.time,
1087
+ kind: item.kind,
1088
+ summary: item.summary,
1089
+ category: decoded.category,
1090
+ hint: decoded.hint,
1091
+ rule: decoded.rule,
1092
+ };
1093
+ });
1094
+ return ok({ faults, total: failures.length, groups: groupFaults(faults) });
1095
+ }
1096
+ if (path === WEB_API_PREFIX + "/ioc-diff") {
1097
+ // 变更页:当前 .ioc 与上次基线逐键比较。只读工程文件。
1098
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
1099
+ const projectDir = firmwareProject(requested);
1100
+ if (projectDir === "")
1101
+ return fail(400, PROJECT_DIR_REQUIRED);
1102
+ const read = readIocDiff(projectDir, env);
1103
+ if (!read.ok)
1104
+ return fail(409, read.error);
1105
+ return ok({ diff: read.report });
1106
+ }
1107
+ if (path === WEB_API_PREFIX + "/ioc-diff/save") {
1108
+ // 记录基线:把当前 .ioc 复制到用户目录。只写自己的基线文件,不动工程。
1109
+ const requested = typeof parsed.value.projectDir === "string" ? parsed.value.projectDir.trim() : "";
1110
+ const projectDir = firmwareProject(requested);
1111
+ if (projectDir === "")
1112
+ return fail(400, PROJECT_DIR_REQUIRED);
1113
+ const saved = saveIocSnapshot(projectDir, env);
1114
+ if (!saved.ok)
1115
+ return fail(409, saved.error);
1116
+ return ok({ snapshot: saved.report });
1117
+ }
1118
+ if (path === WEB_API_PREFIX + "/ioc-diff/restore") {
1119
+ // 把 baseline 里的一个键写回 .ioc:只改这一行,写前备份。
1120
+ const requested = typeof parsed.value.projectDir === "string" ? parsed.value.projectDir.trim() : "";
1121
+ const key = typeof parsed.value.key === "string" ? parsed.value.key : "";
1122
+ if (key.trim() === "")
1123
+ return fail(400, "key 不能为空");
1124
+ const dir = firmwareProject(requested);
1125
+ if (dir === "")
1126
+ return fail(400, PROJECT_DIR_REQUIRED);
1127
+ const restored = restoreIocKey(dir, key, env);
1128
+ if (!restored.ok)
1129
+ return fail(409, restored.error);
1130
+ return ok({ restored: restored.report });
1131
+ }
1132
+ if (path === WEB_API_PREFIX + "/ioc-keys") {
1133
+ // 引脚页点「ioc」:读这个引脚在 .ioc 里占的键,只读。
1134
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
1135
+ const pin = typeof query["pin"] === "string" ? query["pin"] : "";
1136
+ if (pin.trim() === "")
1137
+ return fail(400, "pin 不能为空");
1138
+ const dir = firmwareProject(requested);
1139
+ if (dir === "")
1140
+ return fail(400, PROJECT_DIR_REQUIRED);
1141
+ const keys = readIocKeysForPin(dir, pin, env);
1142
+ if (!keys.ok)
1143
+ return fail(409, keys.error);
1144
+ return ok({ iocKeys: keys.report });
1145
+ }
1146
+ if (path === WEB_API_PREFIX + "/ioc-diff/restore-all") {
1147
+ // 一次性把改动/删除的键恢复成基线值,整批只备份一次。
1148
+ const requested = typeof parsed.value.projectDir === "string" ? parsed.value.projectDir.trim() : "";
1149
+ const dir = firmwareProject(requested);
1150
+ if (dir === "")
1151
+ return fail(400, PROJECT_DIR_REQUIRED);
1152
+ const restored = restoreAllIocKeys(dir, env);
1153
+ if (!restored.ok)
1154
+ return fail(409, restored.error);
1155
+ return ok({ restoredAll: restored.report });
1156
+ }
1157
+ if (path === WEB_API_PREFIX + "/evidence") {
1158
+ // 回放:列出证据目录里可载入的 jsonl 文件。只读目录,不读内容。
1159
+ const root = evidenceRoot(env);
1160
+ const files = await listEvidenceFiles(root);
1161
+ const bytes = files.reduce((sum, file) => sum + file.size, 0);
1162
+ return ok({
1163
+ evidence: { root, files, groups: groupEvidenceFiles(files), usage: { count: files.length, bytes }, policy: evidencePolicy(env) },
1164
+ });
1165
+ }
1166
+ if (path === WEB_API_PREFIX + "/evidence/prune") {
1167
+ // 保留策略:按配置的天数与会话数清最旧的;面板也给一个手动入口。
1168
+ const policy = evidencePolicy(env);
1169
+ const pruned = await pruneEvidence({ env, keepDays: policy.keepDays, keepSessions: policy.keepSessions });
1170
+ return ok({ pruned });
1171
+ }
1172
+ if (path === WEB_API_PREFIX + "/replay") {
1173
+ // 回放:把一份证据文件读成事件数组,面板把它铺到时间线上。路径必须落在证据目录内。
1174
+ const root = evidenceRoot(env);
1175
+ const requested = typeof query["path"] === "string" ? query["path"] : "";
1176
+ const target = evidenceTarget(root, requested);
1177
+ if (target === null)
1178
+ return fail(400, "path 必须是证据目录下的 .jsonl 相对路径");
1179
+ try {
1180
+ const info = await stat(target);
1181
+ if (info.size > REPLAY_MAX_BYTES) {
1182
+ return fail(413, "证据文件过大(" + String(Math.round(info.size / 1024)) + " KB),不在面板里打开");
1183
+ }
1184
+ const text = await readFile(target, "utf8");
1185
+ const replay = parseEvidence(text);
1186
+ return ok({ replay: { file: requested.trim(), events: replay.events, skipped: replay.skipped } });
1187
+ }
1188
+ catch (error) {
1189
+ return fail(409, "读取证据失败:" + describeError(error));
1190
+ }
1191
+ }
1192
+ if (path === WEB_API_PREFIX + "/artifacts") {
1193
+ // 产物页:elf / hex / bin 的文件信息与芯片容量。只读文件属性,不起子进程。
1194
+ const requested = typeof query["projectDir"] === "string" ? query["projectDir"].trim() : "";
1195
+ const projectDir = firmwareProject(requested);
1196
+ if (projectDir === "")
1197
+ return fail(400, PROJECT_DIR_REQUIRED);
1198
+ const read = readArtifacts(projectDir, env);
1199
+ if (!read.ok)
1200
+ return fail(409, read.error);
1201
+ return ok({ artifacts: read.report });
1202
+ }
1203
+ if (path === WEB_API_PREFIX + "/debug/breakpoints") {
1204
+ // 断点面板:只放行三种动作,位置与编号在这里先校验,避免把任意 gdb 命令搬上 HTTP。
1205
+ const action = typeof parsed.value.action === "string" ? parsed.value.action : "";
1206
+ if (action !== "add" && action !== "remove" && action !== "list") {
1207
+ return fail(400, "action 必须是 add / remove / list 之一");
1208
+ }
1209
+ let command = "info breakpoints";
1210
+ if (action === "add") {
1211
+ const location = typeof parsed.value.location === "string" ? parsed.value.location.trim() : "";
1212
+ if (location === "" || location.length > 120 || !/^[A-Za-z0-9_.:$*/+\-]+$/u.test(location)) {
1213
+ return fail(400, "location 只接受符号名或 文件:行(字母、数字与 . _ : $ * / + -),长度 1–120");
1214
+ }
1215
+ command = "break " + location;
1216
+ }
1217
+ if (action === "remove") {
1218
+ const raw = parsed.value.id;
1219
+ const id = typeof raw === "number" ? raw : Number(raw);
1220
+ if (!Number.isInteger(id) || id < 1 || id > 9999)
1221
+ return fail(400, "id 必须是 1–9999 的整数");
1222
+ command = "delete " + String(id);
1223
+ }
1224
+ // 参数先校验、再看会话:没有会话时,参数错误也应当得到 400 而不是一句笼统的 409。
1225
+ if (isForeignDebugSession(requestSession)) {
1226
+ return fail(409, "当前调试会话由另一条会话启动:断点要在启动它的会话里操作");
1227
+ }
1228
+ if (!debugSessions.isActive())
1229
+ return fail(409, "当前没有调试会话(先开 stm32_debug_session)");
1230
+ const report = await debugSessions.eval({ commands: [command], keepHalted: true });
1231
+ if (!report.ok) {
1232
+ return fail(409, report.message === "" ? report.errors.join(";") : report.message);
1233
+ }
1234
+ return ok({
1235
+ breakpoints: { action, command, output: report.output, message: report.message, durationMs: report.durationMs },
1236
+ });
1237
+ }
1238
+ if (path === WEB_API_PREFIX + "/status") {
1239
+ // 面板状态条用:事件计数、当前会话键、证据目录。都是只读的诊断信息。
1240
+ const wanted = (query["session"] ?? "").trim();
1241
+ const ring = eventSnapshot(0, wanted);
1242
+ return ok({
1243
+ status: {
1244
+ eventCount: ring.length,
1245
+ latestSeq: ring.length === 0 ? 0 : (ring[ring.length - 1]?.seq ?? 0),
1246
+ sessionKey: wanted === "" ? eventSessionKey() : wanted,
1247
+ evidenceRoot: evidenceRoot(env),
1248
+ ringLimit: EVENT_RING_LIMIT,
1249
+ evidenceOverride: typeof env.DSH_STM32_EVIDENCE === "string" && env.DSH_STM32_EVIDENCE.trim() !== "",
1250
+ running: listRunning(wanted),
1251
+ self: pluginSelfCheck(),
1252
+ },
1253
+ });
1254
+ }
1255
+ if (path === WEB_API_PREFIX + "/channels") {
1256
+ return ok({ channels: channelTapStatus() });
1257
+ }
1258
+ if (path === WEB_API_PREFIX + "/channels/start" || path === WEB_API_PREFIX + "/channels/stop") {
1259
+ // 只认 serial / rtt 两个开关;不传就是两个都动,免得面板为「全开」多发一次请求。
1260
+ const wantOn = path.endsWith("/start");
1261
+ const picked = {};
1262
+ for (const name of ["serial", "rtt"]) {
1263
+ const raw = parsed.value[name];
1264
+ if (raw === undefined)
1265
+ continue;
1266
+ if (typeof raw !== "boolean")
1267
+ return fail(400, name + " 必须是布尔值");
1268
+ picked[name] = wantOn ? raw : !raw;
1269
+ }
1270
+ if (Object.keys(picked).length === 0) {
1271
+ picked.serial = wantOn;
1272
+ picked.rtt = wantOn;
1273
+ }
1274
+ return ok({ channels: setChannelTaps(picked) });
1275
+ }
1276
+ if (path === WEB_API_PREFIX + "/debug/touch") {
1277
+ // 续租:只重置空闲计时,总时长上限不变(面板轮询不该无限延长一次调试)。
1278
+ if (!debugSessions.touch())
1279
+ return fail(409, "当前没有调试会话(先开 stm32_debug_session)");
1280
+ return ok({ debug: debugSessions.status() });
1281
+ }
1282
+ if (path === WEB_API_PREFIX + "/debug/stop") {
1283
+ // 人在面板上关会话:释放 gdb/openocd 与探针;没有会话时也返回 200(关闭是幂等的)。
1284
+ const stopped = await debugSessions.stop("面板关闭");
1285
+ return ok({ debug: { ...debugSessions.status(), stopped: stopped.stopped, message: stopped.message } });
1286
+ }
1287
+ if (path === WEB_API_PREFIX + "/serial") {
1288
+ // 面板上的串口卡片:人自己开会话,不必先让 AI 调 stm32_serial。
1289
+ const status = await serialStatus({ env });
1290
+ return ok({
1291
+ serial: {
1292
+ open: status.open,
1293
+ sessionId: status.session?.sessionId ?? "",
1294
+ port: status.session?.port ?? "",
1295
+ baudRate: status.session?.settings.baudRate ?? 0,
1296
+ bridgePid: status.bridge.pid,
1297
+ bridgeAlive: status.bridge.alive,
1298
+ message: status.message,
1299
+ notes: status.notes,
1300
+ },
1301
+ });
1302
+ }
1303
+ if (path === WEB_API_PREFIX + "/serial/ports") {
1304
+ const listed = await listPorts({ env });
1305
+ return ok({
1306
+ serialPorts: {
1307
+ ok: listed.ok,
1308
+ ports: listed.ports.map((port) => ({ port: port.port, description: port.description, vid: port.vid, pid: port.pid })),
1309
+ message: listed.message,
1310
+ },
1311
+ });
1312
+ }
1313
+ if (path === WEB_API_PREFIX + "/serial/open") {
1314
+ const port = parsed.value.port;
1315
+ if (port !== undefined && typeof port !== "string")
1316
+ return fail(400, "port 必须是字符串(例如 COM3)");
1317
+ const baudRate = parsed.value.baudRate;
1318
+ if (baudRate !== undefined && (typeof baudRate !== "number" || !Number.isFinite(baudRate))) {
1319
+ return fail(400, "baudRate 必须是数字(例如 115200)");
1320
+ }
1321
+ const opened = await openSerial({
1322
+ ...(typeof port === "string" && port.trim() !== "" ? { port: port.trim() } : {}),
1323
+ ...(typeof baudRate === "number" ? { baudRate } : {}),
1324
+ env,
1325
+ });
1326
+ return ok({
1327
+ serial: {
1328
+ ok: opened.ok,
1329
+ message: opened.message,
1330
+ notes: opened.notes,
1331
+ sessionId: opened.session?.sessionId ?? "",
1332
+ port: opened.session?.port ?? "",
1333
+ bridgePid: opened.bridge.pid,
1334
+ },
1335
+ });
1336
+ }
1337
+ if (path === WEB_API_PREFIX + "/serial/close") {
1338
+ const force = parsed.value.force;
1339
+ if (force !== undefined && typeof force !== "boolean")
1340
+ return fail(400, "force 必须是布尔值");
1341
+ const closed = await closeSerial({ ...(force === true ? { force: true } : {}), env });
1342
+ return ok({
1343
+ serial: {
1344
+ ok: closed.ok,
1345
+ closed: closed.closed,
1346
+ forced: closed.forced,
1347
+ message: closed.message,
1348
+ notes: closed.notes,
1349
+ },
1350
+ });
1351
+ }
1352
+ if (path === WEB_API_PREFIX + "/serial/send") {
1353
+ // 面板直接发一行:与 stm32_serial action=send 同一条桥命令,只是入口在人这边。
1354
+ const text = parsed.value.text;
1355
+ if (typeof text !== "string")
1356
+ return fail(400, "text 必须是字符串(空串表示只发换行)");
1357
+ const newline = parsed.value.newline;
1358
+ if (newline !== undefined && newline !== "crlf" && newline !== "lf" && newline !== "none") {
1359
+ return fail(400, "newline 只能是 crlf / lf / none");
1360
+ }
1361
+ const raw = parsed.value.raw;
1362
+ if (raw !== undefined && typeof raw !== "boolean")
1363
+ return fail(400, "raw 必须是布尔值");
1364
+ const sent = await sendSerial({
1365
+ text,
1366
+ ...(newline === undefined ? {} : { newline }),
1367
+ ...(raw === true ? { raw: true } : {}),
1368
+ env,
1369
+ });
1370
+ const payload = {
1371
+ ok: sent.ok,
1372
+ id: sent.id,
1373
+ bytes: sent.bytes,
1374
+ ackMs: sent.ackMs,
1375
+ message: sent.message,
1376
+ };
1377
+ if (!sent.ok && sent.session === null)
1378
+ return fail(409, sent.message);
1379
+ return ok({ serial: payload });
1380
+ }
1381
+ if (path === WEB_API_PREFIX + "/watch-recording") {
1382
+ return ok({ watchRecording: watchRecorder.status() });
1383
+ }
1384
+ if (path === WEB_API_PREFIX + "/watch-recording/start" || path === WEB_API_PREFIX + "/watch-recording/stop") {
1385
+ if (path.endsWith("/stop"))
1386
+ return ok({ watchRecording: watchRecorder.stop() });
1387
+ const raw = parsed.value.intervalMs;
1388
+ if (raw !== undefined) {
1389
+ // 夹紧放在录制器里,这里只拒掉明显不是「毫秒数」的输入。
1390
+ if (typeof raw !== "number" || !Number.isFinite(raw) || Math.trunc(raw) !== raw) {
1391
+ return fail(400, "intervalMs 必须是 500–60000 的整数(毫秒)");
1392
+ }
1393
+ if (raw < 500 || raw > 60_000) {
1394
+ return fail(400, "intervalMs 必须是 500–60000 的整数(毫秒)");
1395
+ }
1396
+ }
1397
+ const started = watchRecorder.start(raw === undefined ? {} : { intervalMs: raw });
1398
+ return ok({ watchRecording: started });
1399
+ }
1400
+ if (path === WEB_API_PREFIX + "/abort") {
1401
+ // 面板「中止」:只中止登记过的在途调用,不碰调试会话与后台 job。
1402
+ const callId = typeof parsed.value.callId === "string" ? parsed.value.callId.trim() : "";
1403
+ const all = parsed.value.all === true;
1404
+ const session = typeof parsed.value.session === "string" ? parsed.value.session.trim() : "";
1405
+ if (callId === "" && !all)
1406
+ return fail(400, "callId 不能为空(全部中止请传 all: true)");
1407
+ if (callId !== "") {
1408
+ const aborted = abortCall(callId);
1409
+ if (aborted === null)
1410
+ return fail(404, "没有这条在途调用:" + callId);
1411
+ return ok({ abort: { count: 1, calls: [aborted] } });
1412
+ }
1413
+ const count = abortAll(session);
1414
+ return ok({ abort: { count, calls: [] } });
1415
+ }
370
1416
  return fail(404, "没有这个接口:" + path);
371
1417
  }
372
1418
  /** 单测用:清空安装任务表。 */
373
1419
  export function resetInstallTasks() {
374
1420
  installTasks.clear();
375
1421
  }
1422
+ /* ------------------------------ 事件流 ------------------------------ */
1423
+ /** 事件流的路径(SSE,长连接,不用 JSON 分发器)。 */
1424
+ export const EVENT_STREAM_PATH = WEB_API_PREFIX + "/events";
1425
+ /** 心跳间隔:反代与浏览器都会掐掉长时间无数据的连接。 */
1426
+ const EVENT_HEARTBEAT_MS = 15_000;
1427
+ function writeEvent(response, event) {
1428
+ if (typeof response.write !== "function")
1429
+ return;
1430
+ response.write("id: " + String(event.seq) + "\n");
1431
+ response.write("data: " + JSON.stringify(event) + "\n\n");
1432
+ }
1433
+ /**
1434
+ * 打开一条事件流:先补发 since 之后的存量事件,再持续推送新事件。
1435
+ *
1436
+ * 返回停止函数;请求方断开时自动停止,调用方也可显式停止。
1437
+ * 这里直接写原始 response,交给 registerWebRoutes 注册,不走 handleWebApi 的 JSON 分发。
1438
+ */
1439
+ export function openEventStream(request, response, options = {}) {
1440
+ let closed = false;
1441
+ let unsubscribe = () => { };
1442
+ let heartbeat;
1443
+ const stop = () => {
1444
+ if (closed)
1445
+ return;
1446
+ closed = true;
1447
+ unsubscribe();
1448
+ if (heartbeat !== undefined)
1449
+ clearInterval(heartbeat);
1450
+ if (typeof response.end === "function") {
1451
+ try {
1452
+ response.end();
1453
+ }
1454
+ catch {
1455
+ // 对端已断开,忽略。
1456
+ }
1457
+ }
1458
+ };
1459
+ if (typeof response.writeHead === "function") {
1460
+ response.writeHead(200, {
1461
+ "content-type": "text/event-stream; charset=utf-8",
1462
+ "cache-control": "no-cache, no-transform",
1463
+ connection: "keep-alive",
1464
+ "x-accel-buffering": "no",
1465
+ });
1466
+ }
1467
+ if (typeof response.write === "function")
1468
+ response.write(": connected\n\n");
1469
+ const since = typeof options.since === "number" && Number.isFinite(options.since) ? options.since : 0;
1470
+ const wanted = (options.session ?? "").trim();
1471
+ for (const event of eventSnapshot(since, wanted))
1472
+ writeEvent(response, event);
1473
+ unsubscribe = subscribeEvents((event) => {
1474
+ if (closed)
1475
+ return;
1476
+ // 带 session 的订阅只推本会话事件:多标签页同时开着时各看各的。
1477
+ if (wanted !== "" && event.session !== wanted)
1478
+ return;
1479
+ writeEvent(response, event);
1480
+ });
1481
+ heartbeat = setInterval(() => {
1482
+ if (closed)
1483
+ return;
1484
+ if (typeof response.write === "function")
1485
+ response.write(": ping\n\n");
1486
+ }, options.heartbeatMs ?? EVENT_HEARTBEAT_MS);
1487
+ if (typeof heartbeat.unref === "function")
1488
+ heartbeat.unref();
1489
+ if (typeof request?.on === "function") {
1490
+ request.on("close", stop);
1491
+ request.on("error", stop);
1492
+ }
1493
+ return stop;
1494
+ }