@turingcode/cli 0.2.12 → 0.3.4

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 (186) hide show
  1. package/README.md +2 -0
  2. package/dist/cli/create-cli.d.ts +10 -0
  3. package/dist/cli/create-cli.js +12 -2
  4. package/dist/cli/index.d.ts +9 -0
  5. package/dist/cli/index.js +5 -1
  6. package/dist/core/bound-error.d.ts +10 -0
  7. package/dist/core/date.d.ts +12 -0
  8. package/dist/core/exact/expression.d.ts +49 -0
  9. package/dist/core/exact/fraction.d.ts +85 -0
  10. package/dist/core/files.d.ts +44 -0
  11. package/dist/core/files.js +46 -1
  12. package/dist/core/json-shape.d.ts +45 -0
  13. package/dist/core/json-shape.js +0 -43
  14. package/dist/core/mcp.d.ts +92 -0
  15. package/dist/core/mcp.js +57 -30
  16. package/dist/core/query.d.ts +69 -0
  17. package/dist/core/query.js +11 -0
  18. package/dist/core/report.d.ts +11 -0
  19. package/dist/core/tables/csv.d.ts +18 -0
  20. package/dist/core/tables/markdown.d.ts +22 -0
  21. package/dist/core/tables/types.d.ts +25 -0
  22. package/dist/features/contract/check.d.ts +30 -0
  23. package/dist/features/contract/check.js +2 -3
  24. package/dist/features/contract/command.d.ts +12 -0
  25. package/dist/features/contract/command.js +64 -64
  26. package/dist/features/contract/describe.d.ts +22 -0
  27. package/dist/features/contract/diagnostics.d.ts +108 -0
  28. package/dist/features/contract/load.d.ts +58 -0
  29. package/dist/features/contract/load.js +24 -17
  30. package/dist/features/contract/model.d.ts +67 -0
  31. package/dist/features/contract/rules.d.ts +137 -0
  32. package/dist/features/contract/rules.js +11 -12
  33. package/dist/features/debug/clear_breakpoint.d.ts +2 -0
  34. package/dist/features/debug/clear_breakpoint.js +24 -0
  35. package/dist/features/debug/command.d.ts +5 -0
  36. package/dist/features/debug/command.js +66 -0
  37. package/dist/features/debug/continue.d.ts +2 -0
  38. package/dist/features/debug/continue.js +22 -0
  39. package/dist/features/debug/debug_start.d.ts +2 -0
  40. package/dist/features/debug/debug_start.js +22 -0
  41. package/dist/features/debug/debug_stop.d.ts +2 -0
  42. package/dist/features/debug/debug_stop.js +11 -0
  43. package/dist/features/debug/evaluate.d.ts +2 -0
  44. package/dist/features/debug/evaluate.js +48 -0
  45. package/dist/features/debug/get_stack.d.ts +2 -0
  46. package/dist/features/debug/get_stack.js +14 -0
  47. package/dist/features/debug/get_variables.d.ts +2 -0
  48. package/dist/features/debug/get_variables.js +26 -0
  49. package/dist/features/debug/halt.d.ts +2 -0
  50. package/dist/features/debug/halt.js +16 -0
  51. package/dist/features/debug/set_breakpoint.d.ts +2 -0
  52. package/dist/features/debug/set_breakpoint.js +30 -0
  53. package/dist/features/debug/step.d.ts +2 -0
  54. package/dist/features/debug/step.js +23 -0
  55. package/dist/features/install-mods/command.d.ts +6 -0
  56. package/dist/features/install-mods/command.js +18 -0
  57. package/dist/features/install-mods/install.d.ts +23 -0
  58. package/dist/features/install-mods/install.js +48 -0
  59. package/dist/features/install-skills/command.d.ts +7 -0
  60. package/dist/features/install-skills/command.js +22 -0
  61. package/dist/features/install-skills/install.d.ts +13 -0
  62. package/dist/features/install-skills/install.js +29 -0
  63. package/dist/features/probe/command.d.ts +5 -0
  64. package/dist/features/probe/command.js +44 -0
  65. package/dist/features/probe/kill_all_debuggers.d.ts +2 -0
  66. package/dist/features/probe/kill_all_debuggers.js +50 -0
  67. package/dist/features/probe/list_probes.d.ts +2 -0
  68. package/dist/features/probe/list_probes.js +8 -0
  69. package/dist/features/probe/program_project.d.ts +2 -0
  70. package/dist/features/probe/program_project.js +29 -0
  71. package/dist/features/probe/read_fault_status.d.ts +2 -0
  72. package/dist/features/probe/read_fault_status.js +19 -0
  73. package/dist/features/probe/read_memory.d.ts +2 -0
  74. package/dist/features/probe/read_memory.js +36 -0
  75. package/dist/features/probe/read_peripheral.d.ts +2 -0
  76. package/dist/features/probe/read_peripheral.js +58 -0
  77. package/dist/features/probe/reset_probe_usb.d.ts +2 -0
  78. package/dist/features/probe/reset_probe_usb.js +17 -0
  79. package/dist/features/probe/reset_target.d.ts +2 -0
  80. package/dist/features/probe/reset_target.js +16 -0
  81. package/dist/features/probe/target_info.d.ts +2 -0
  82. package/dist/features/probe/target_info.js +34 -0
  83. package/dist/features/project/analysis_static.d.ts +2 -0
  84. package/dist/features/project/analysis_static.js +19 -0
  85. package/dist/features/project/analysis_syntax_check.d.ts +2 -0
  86. package/dist/features/project/analysis_syntax_check.js +21 -0
  87. package/dist/features/project/command.d.ts +5 -0
  88. package/dist/features/project/command.js +64 -0
  89. package/dist/features/project/project_build.d.ts +2 -0
  90. package/dist/features/project/project_build.js +22 -0
  91. package/dist/features/project/project_download_template.d.ts +2 -0
  92. package/dist/features/project/project_download_template.js +34 -0
  93. package/dist/features/project/project_regenerate.d.ts +2 -0
  94. package/dist/features/project/project_regenerate.js +20 -0
  95. package/dist/features/project/project_sync_from_server.d.ts +2 -0
  96. package/dist/features/project/project_sync_from_server.js +13 -0
  97. package/dist/features/project/project_sync_to_server.d.ts +2 -0
  98. package/dist/features/project/project_sync_to_server.js +51 -0
  99. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +2 -0
  100. package/dist/features/project/stm32_cubetools_download_drivers.js +19 -0
  101. package/dist/features/status/command.d.ts +2 -0
  102. package/dist/features/status/command.js +6 -0
  103. package/dist/features/status/get_status.d.ts +2 -0
  104. package/dist/features/status/get_status.js +44 -0
  105. package/dist/features/table/check.d.ts +38 -0
  106. package/dist/features/table/check.js +16 -23
  107. package/dist/features/table/command.d.ts +3 -0
  108. package/dist/features/table/command.js +4 -5
  109. package/dist/features/table/read.d.ts +28 -0
  110. package/dist/features/table/read.js +23 -3
  111. package/dist/features/tool/command.d.ts +35 -0
  112. package/dist/lib.d.ts +11 -0
  113. package/dist/lib.js +9 -0
  114. package/dist/stm32/actions/DebugAction.d.ts +63 -0
  115. package/dist/stm32/actions/DebugAction.js +105 -0
  116. package/dist/stm32/actions/DebugActionInfo.d.ts +7 -0
  117. package/dist/stm32/actions/DebugActionInfo.js +9 -0
  118. package/dist/stm32/actions/DebugActionListProbes.d.ts +9 -0
  119. package/dist/stm32/actions/DebugActionListProbes.js +10 -0
  120. package/dist/stm32/actions/DebugActionProgram.d.ts +28 -0
  121. package/dist/stm32/actions/DebugActionProgram.js +79 -0
  122. package/dist/stm32/actions/DebugActionRead.d.ts +38 -0
  123. package/dist/stm32/actions/DebugActionRead.js +59 -0
  124. package/dist/stm32/actions/DebugActionReset.d.ts +11 -0
  125. package/dist/stm32/actions/DebugActionReset.js +9 -0
  126. package/dist/stm32/actions/DebugActionServer.d.ts +7 -0
  127. package/dist/stm32/actions/DebugActionServer.js +9 -0
  128. package/dist/stm32/analysis.d.ts +19 -0
  129. package/dist/stm32/analysis.js +21 -0
  130. package/dist/stm32/build.d.ts +34 -0
  131. package/dist/stm32/build.js +79 -0
  132. package/dist/stm32/context.d.ts +23 -0
  133. package/dist/stm32/context.js +42 -0
  134. package/dist/stm32/daemon.d.ts +63 -0
  135. package/dist/stm32/daemon.js +202 -0
  136. package/dist/stm32/regen.d.ts +68 -0
  137. package/dist/stm32/regen.js +225 -0
  138. package/dist/stm32/session.d.ts +134 -0
  139. package/dist/stm32/session.js +374 -0
  140. package/dist/stm32/sync.d.ts +24 -0
  141. package/dist/stm32/sync.js +72 -0
  142. package/dist/stm32/tool.d.ts +43 -0
  143. package/dist/stm32/tool.js +20 -0
  144. package/dist/stm32/toolCommand.d.ts +50 -0
  145. package/dist/stm32/toolCommand.js +102 -0
  146. package/dist/stm32/utils/discover_tools.d.ts +24 -0
  147. package/dist/stm32/utils/discover_tools.js +121 -0
  148. package/dist/stm32/utils/downloadzip_utils.d.ts +57 -0
  149. package/dist/stm32/utils/downloadzip_utils.js +180 -0
  150. package/dist/stm32/utils/faultUtils.d.ts +14 -0
  151. package/dist/stm32/utils/faultUtils.js +69 -0
  152. package/dist/stm32/utils/findElf.d.ts +9 -0
  153. package/dist/stm32/utils/findElf.js +19 -0
  154. package/dist/stm32/utils/hash_utils.d.ts +19 -0
  155. package/dist/stm32/utils/hash_utils.js +28 -0
  156. package/dist/stm32/utils/listSyncFiles.d.ts +9 -0
  157. package/dist/stm32/utils/listSyncFiles.js +98 -0
  158. package/dist/stm32/utils/mcu_utils.d.ts +59 -0
  159. package/dist/stm32/utils/mcu_utils.js +99 -0
  160. package/dist/stm32/utils/project_utils.d.ts +54 -0
  161. package/dist/stm32/utils/project_utils.js +102 -0
  162. package/dist/stm32/utils/svdUtils.d.ts +31 -0
  163. package/dist/stm32/utils/svdUtils.js +30 -0
  164. package/dist/stm32/utils/truncate.d.ts +7 -0
  165. package/dist/stm32/utils/truncate.js +9 -0
  166. package/dist/stm32/utils/usb_utils.d.ts +5 -0
  167. package/dist/stm32/utils/usb_utils.js +23 -0
  168. package/dist/stm32/utils/user_code.d.ts +14 -0
  169. package/dist/stm32/utils/user_code.js +43 -0
  170. package/dist/stm32/utils/utils_mutex.d.ts +15 -0
  171. package/dist/stm32/utils/utils_mutex.js +93 -0
  172. package/dist/stm32/validate.d.ts +16 -0
  173. package/dist/stm32/validate.js +46 -0
  174. package/mods/claude/.claude-plugin/marketplace.json +8 -0
  175. package/mods/claude/turingcode-skills/.claude-plugin/plugin.json +5 -0
  176. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +50 -0
  177. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/board-and-debug.md +22 -0
  178. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/build-and-check.md +19 -0
  179. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/new-project.md +9 -0
  180. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +43 -0
  181. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +42 -0
  182. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +35 -0
  183. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +34 -0
  184. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +35 -0
  185. package/package.json +11 -3
  186. package/dist/features/clock/command.js +0 -63
@@ -1,14 +1,12 @@
1
- import { existsSync, statSync } from "node:fs";
2
1
  import { BoundError } from "../../core/bound-error.js";
3
2
  import { isDate } from "../../core/date.js";
4
3
  import { Fraction } from "../../core/exact/fraction.js";
5
- import { compileQuery, prepareQuery } from "../../core/query.js";
4
+ import { queryTester } from "../../core/query.js";
6
5
  import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
7
- import { loadContract, parseRef, parseTableRef } from "../contract/load.js";
6
+ import { failedLoadStatus, loadContract, parseRef, parseTableRef } from "../contract/load.js";
8
7
  import { keyColumns } from "../contract/model.js";
9
8
  import { evaluateCalc, explain, listItems, mentions, numberColumns, parseCalc, renderCondition, splitQuery, } from "../contract/rules.js";
10
- import { readTables } from "./read.js";
11
- const plain = (v) => String(v);
9
+ import { FORMAT_FILES, formatMismatch, readTables } from "./read.js";
12
10
  /**
13
11
  * Why a value does not fit its column's type, or null when it fits.
14
12
  *
@@ -55,9 +53,9 @@ function rowsOf(t, table, name, missing) {
55
53
  const parsed = t.tables.get(name);
56
54
  const key = table ? keyColumns(table) : [];
57
55
  const columns = new Map((table?.columns ?? []).map(c => [c.name, c]));
56
+ const names = new Set([...parsed.header, ...columns.keys()]);
58
57
  return parsed.rows.map((r, k) => {
59
58
  const cells = Object.fromEntries(parsed.header.flatMap((h, i) => (r[i] === undefined ? [] : [[h, r[i]]])));
60
- const names = new Set([...parsed.header, ...columns.keys()]);
61
59
  const doc = Object.fromEntries([...names].map(n => [n, valueOf(cells[n], columns.get(n), missing)]));
62
60
  const keyValues = key.map(c => cells[c] ?? "");
63
61
  const label = key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`;
@@ -90,9 +88,8 @@ export function tableCheck(input) {
90
88
  };
91
89
  const loaded = loadContract(input.contract, diags);
92
90
  label = loaded.label;
93
- if (!loaded.contract) {
94
- return finish(diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT");
95
- }
91
+ if (!loaded.contract)
92
+ return finish(failedLoadStatus(diags));
96
93
  const contract = loaded.contract;
97
94
  const extra = Object.keys(input.deps ?? {}).filter(a => !contract.depends_on?.[a]);
98
95
  if (extra.length) {
@@ -100,21 +97,17 @@ export function tableCheck(input) {
100
97
  }
101
98
  /** Reads one tables file; failures become a status. */
102
99
  const read = (path, c) => {
103
- // Markdown parsing of CSV text finds no tables, which would silently look like empty tables.
104
- if ((c.format ?? "markdown") === "markdown" && (/\.csv$/i.test(path) || (existsSync(path) && statSync(path).isDirectory()))) {
105
- return stop("INVALID_INPUT", "INVALID_INPUT", `${path} is CSV, but its contract reads Markdown: set "format": "csv" in that contract, or pass a Markdown file`, path, "a Markdown file");
106
- }
107
- if (c.format === "csv" && !/\.csv$/i.test(path) && existsSync(path) && !statSync(path).isDirectory()) {
108
- return stop("INVALID_INPUT", "INVALID_INPUT", `${path} is not CSV, but its contract reads CSV ("format": "csv"): pass a .csv file or a folder of them, `
109
- + `or remove "format" from that contract`, path, "a .csv file or a folder of them");
110
- }
100
+ const format = c.format ?? "markdown";
101
+ const mismatch = formatMismatch(path, format);
102
+ if (mismatch)
103
+ return stop("INVALID_INPUT", "INVALID_INPUT", mismatch, path, FORMAT_FILES[format]);
111
104
  try {
112
- return readTables(path, c.format ?? "markdown");
105
+ return readTables(path, format);
113
106
  }
114
107
  catch (e) {
115
108
  if (e instanceof BoundError)
116
109
  return stop("INVALID_INPUT", "TOO_LARGE", `${path}: ${e.message}`, path, `<= ${e.limit} rows`);
117
- return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path, c.format === "csv" ? "a .csv file or a folder of them" : "a Markdown file");
110
+ return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path, FORMAT_FILES[format]);
118
111
  }
119
112
  };
120
113
  const missingOf = (c) => {
@@ -215,7 +208,7 @@ export function tableCheck(input) {
215
208
  */
216
209
  const runParts = (q, tableRows, hooks, skip, report) => {
217
210
  for (const part of splitQuery(q)) {
218
- const test = compileQuery(prepareQuery(part).query, hooks);
211
+ const test = queryTester(part, hooks);
219
212
  for (const r of tableRows.filter(row => !skip(row) && !test(row.doc)))
220
213
  report(explain(part, r.doc, hooks), r);
221
214
  }
@@ -246,14 +239,14 @@ export function tableCheck(input) {
246
239
  if (!scope || !scopeRows)
247
240
  return; // the table is missing: reported as MISSING_TABLE
248
241
  const hooks = hooksFor(scope, !on.alias);
249
- const when = compileQuery(prepareQuery(rule.when ?? {}).query, hooks);
242
+ const when = queryTester(rule.when ?? {}, hooks);
250
243
  const matching = scopeRows.filter(r => when(r.doc));
251
244
  const where = { table: rule.on ?? owner.name, rule: rule.id ?? fallbackId };
252
245
  const severity = rule.severity === "warning" ? "WARN" : "FAIL";
253
246
  if (rule.count) {
254
- const test = compileQuery(prepareQuery({ _: rule.count }).query, hooks);
247
+ const test = queryTester({ _: rule.count }, hooks);
255
248
  if (!test({ _: String(matching.length) })) {
256
- diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count, plain), severity));
249
+ diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count, String), severity));
257
250
  }
258
251
  return;
259
252
  }
@@ -0,0 +1,3 @@
1
+ import { CommandModule } from "yargs";
2
+ declare const table: CommandModule;
3
+ export default table;
@@ -6,13 +6,13 @@ import { formatTableCheck, tableCheck } from "./check.js";
6
6
  *
7
7
  * @param {string[]} values - Raw flag values.
8
8
  * @returns {Record<string, string>} alias -> tables file.
9
- * @throws {Error} When a value has no `=`; its `exitCode` is 2 (bad input), as `table check` documents.
9
+ * @throws {Error} When a value has no `=` (an argument error: exit 2).
10
10
  */
11
11
  function parseDeps(values) {
12
12
  return Object.fromEntries(values.map(v => {
13
13
  const at = v.indexOf("=");
14
14
  if (at < 1)
15
- throw Object.assign(new Error(`--dep expects <alias>=<tables file>, got '${v}'`), { exitCode: 2 });
15
+ throw new Error(`--dep expects <alias>=<tables file>, got '${v}'`);
16
16
  return [v.slice(0, at), v.slice(at + 1)];
17
17
  }));
18
18
  }
@@ -26,7 +26,7 @@ const check = {
26
26
  describe: "Markdown file, or .csv file / folder of <Table>.csv when the contract has \"format\": \"csv\" (required)",
27
27
  },
28
28
  dep: {
29
- type: "string", array: true,
29
+ type: "string", array: true, coerce: parseDeps,
30
30
  describe: "<alias>=<tables file> for each alias in the contract's depends_on, in that dependency contract's format",
31
31
  },
32
32
  json: JSON_FLAG,
@@ -43,8 +43,7 @@ const check = {
43
43
  "Exit: 0 PASS, 1 FAIL or invalid contract, 2 bad input or missing file.",
44
44
  ].join("\n")),
45
45
  handler: args => {
46
- // Parsed here, not with yargs' coerce, which rewraps the error and loses its exit code.
47
- const result = tableCheck({ contract: args.contract, tables: args.tables, deps: args.dep && parseDeps(args.dep) });
46
+ const result = tableCheck({ contract: args.contract, tables: args.tables, deps: args.dep });
48
47
  report(result, formatTableCheck(result), args.json);
49
48
  },
50
49
  };
@@ -0,0 +1,28 @@
1
+ import { TablesDoc } from "../../core/tables/types.js";
2
+ /** Most rows read from one table. */
3
+ export declare const MAX_TABLE_ROWS = 100000;
4
+ /** The files a format reads, for `expected`. */
5
+ export declare const FORMAT_FILES: {
6
+ readonly markdown: "a Markdown file";
7
+ readonly csv: "a .csv file or a folder of them";
8
+ };
9
+ /**
10
+ * Why a path is in the wrong format for its contract, or null when it fits (or does not exist,
11
+ * which reading reports). Markdown parsing of CSV text finds no tables, so this must be checked
12
+ * first or a CSV dependency would silently look empty.
13
+ *
14
+ * @param {string} path - The file or folder.
15
+ * @param {"markdown" | "csv"} format - The contract's format.
16
+ * @returns {string | null} The problem, or null.
17
+ */
18
+ export declare function formatMismatch(path: string, format: "markdown" | "csv"): string | null;
19
+ /**
20
+ * Reads tables in a contract's format: a Markdown file, a folder of
21
+ * `<Table>.csv` files, or one `<Table>.csv` file.
22
+ *
23
+ * @param {string} path - The file or folder.
24
+ * @param {"markdown" | "csv"} format - The contract's format.
25
+ * @returns {TablesDoc} The tables.
26
+ * @throws {Error} When the path cannot be read; BoundError when a table has too many rows.
27
+ */
28
+ export declare function readTables(path: string, format: "markdown" | "csv"): TablesDoc;
@@ -1,9 +1,31 @@
1
- import { readFileSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
2
  import { basename, dirname } from "node:path";
3
3
  import { parseCsvFolder } from "../../core/tables/csv.js";
4
4
  import { parseMarkdown } from "../../core/tables/markdown.js";
5
5
  /** Most rows read from one table. */
6
6
  export const MAX_TABLE_ROWS = 100_000;
7
+ /** The files a format reads, for `expected`. */
8
+ export const FORMAT_FILES = { markdown: "a Markdown file", csv: "a .csv file or a folder of them" };
9
+ /**
10
+ * Why a path is in the wrong format for its contract, or null when it fits (or does not exist,
11
+ * which reading reports). Markdown parsing of CSV text finds no tables, so this must be checked
12
+ * first or a CSV dependency would silently look empty.
13
+ *
14
+ * @param {string} path - The file or folder.
15
+ * @param {"markdown" | "csv"} format - The contract's format.
16
+ * @returns {string | null} The problem, or null.
17
+ */
18
+ export function formatMismatch(path, format) {
19
+ const csv = /\.csv$/i.test(path) || (existsSync(path) && statSync(path).isDirectory());
20
+ if (format === "markdown" && csv) {
21
+ return `${path} is CSV, but its contract reads Markdown: set "format": "csv" in that contract, or pass a Markdown file`;
22
+ }
23
+ if (format === "csv" && !csv && existsSync(path)) {
24
+ return `${path} is not CSV, but its contract reads CSV ("format": "csv"): pass a .csv file or a folder of them, `
25
+ + `or remove "format" from that contract`;
26
+ }
27
+ return null;
28
+ }
7
29
  /**
8
30
  * Reads tables in a contract's format: a Markdown file, a folder of
9
31
  * `<Table>.csv` files, or one `<Table>.csv` file.
@@ -21,8 +43,6 @@ export function readTables(path, format) {
21
43
  const doc = parseCsvFolder(dirname(path), MAX_TABLE_ROWS);
22
44
  const name = basename(path).replace(/\.csv$/i, "");
23
45
  const only = doc.tables.get(name);
24
- if (!only && !doc.malformed.some(([n]) => n === name))
25
- throw new Error(`${path} is not a .csv file`);
26
46
  return {
27
47
  ...doc,
28
48
  tables: only ? new Map([[name, only]]) : new Map(),
@@ -0,0 +1,35 @@
1
+ import { CommandModule } from "yargs";
2
+ import { ToolInfo } from "../../core/mcp.js";
3
+ /**
4
+ * Formats tools as one line each: name, then the first line of its description.
5
+ *
6
+ * @param {ToolInfo[]} tools - Tools from the gateway.
7
+ * @returns {string} The text, ending in a newline (empty for no tools).
8
+ *
9
+ * @example
10
+ * formatToolSummaries([{ name: "read_file", description: "Reads a file.\nMore." }]); // "read_file Reads a file.\n"
11
+ */
12
+ export declare function formatToolSummaries(tools: ToolInfo[]): string;
13
+ /**
14
+ * Formats tools with their full description and arguments, one `## <name>` section per tool.
15
+ *
16
+ * @param {ToolInfo[]} tools - Tools from the gateway.
17
+ * @returns {string} The text, ending in a newline (empty for no tools).
18
+ *
19
+ * @example
20
+ * formatToolDetails([{ name: "read_file", description: "Reads a file.",
21
+ * inputSchema: { properties: { path: { type: "string" } }, required: ["path"] } }]);
22
+ * // "## read_file\n\nReads a file.\n\nArguments:\n- path (string, required)\n"
23
+ */
24
+ export declare function formatToolDetails(tools: ToolInfo[]): string;
25
+ /**
26
+ * Picks the named tools, in the order given.
27
+ *
28
+ * @param {ToolInfo[]} tools - Tools from the gateway.
29
+ * @param {string[]} names - Tool names to pick.
30
+ * @returns {ToolInfo[]} The named tools.
31
+ * @throws {Error} When a name is not among the tools.
32
+ */
33
+ export declare function pickTools(tools: ToolInfo[], names: string[]): ToolInfo[];
34
+ declare const command: CommandModule;
35
+ export default command;
package/dist/lib.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export { callTool, callToolText, listTools, DEFAULT_URL } from "./core/mcp.js";
2
+ export type { ToolInfo, ToolResult } from "./core/mcp.js";
3
+ export { syncProjectFromServer, syncProjectToServer } from "./stm32/sync.js";
4
+ export { recordBaseline, regenerateProject } from "./stm32/regen.js";
5
+ export type { ServerCall } from "./stm32/sync.js";
6
+ export { buildProject, BUILD_PRESETS } from "./stm32/build.js";
7
+ export { analyzeProject, syntaxCheckProject } from "./stm32/analysis.js";
8
+ export type { BuildResult } from "./stm32/build.js";
9
+ export { downloadAndUnzip, zipLink } from "./stm32/utils/downloadzip_utils.js";
10
+ export { findStm32Project, findStm32ProjectIn } from "./stm32/utils/project_utils.js";
11
+ export type { Project } from "./stm32/tool.js";
package/dist/lib.js ADDED
@@ -0,0 +1,9 @@
1
+ // Library entry of @turingcode/cli, for the TuringCode VS Code extension: the server client and the STM32 project
2
+ // workflows the CLI commands run, without their command line parsing.
3
+ export { callTool, callToolText, listTools, DEFAULT_URL } from "./core/mcp.js";
4
+ export { syncProjectFromServer, syncProjectToServer } from "./stm32/sync.js";
5
+ export { recordBaseline, regenerateProject } from "./stm32/regen.js";
6
+ export { buildProject, BUILD_PRESETS } from "./stm32/build.js";
7
+ export { analyzeProject, syntaxCheckProject } from "./stm32/analysis.js";
8
+ export { downloadAndUnzip, zipLink } from "./stm32/utils/downloadzip_utils.js";
9
+ export { findStm32Project, findStm32ProjectIn } from "./stm32/utils/project_utils.js";
@@ -0,0 +1,63 @@
1
+ import { DiscoveredSystemTool, SystemToolId } from '../utils/discover_tools.js';
2
+ export type ActionParams = Record<string, string | number | boolean>;
3
+ export type CommandArg = string | {
4
+ if: string;
5
+ args: string[];
6
+ };
7
+ export interface ToolOutput {
8
+ tool: SystemToolId;
9
+ stdout: string;
10
+ stderr: string;
11
+ }
12
+ /**
13
+ * A debug operation (program, read memory, reset, ...) and the command line of each tool that can do it.
14
+ * The first installed tool in `commands` order runs it, with the placeholders filled from the action params.
15
+ * Everything is static: subclasses set the fields and are used without an instance (DebugActionRead.run_action(...)).
16
+ */
17
+ export declare abstract class DebugAction {
18
+ static readonly title: string;
19
+ static readonly commands: Partial<Record<SystemToolId, CommandArg[]>>;
20
+ static readonly timeout: number;
21
+ static readonly exclusive: boolean;
22
+ /**
23
+ * Converts the action params to the placeholder values; override to add derived or formatted values.
24
+ * @param params action params
25
+ * @returns the placeholder values
26
+ */
27
+ protected static values(params: ActionParams): ActionParams;
28
+ /**
29
+ * Picks the first installed tool that has a command line for this action.
30
+ * @returns the tool
31
+ */
32
+ static pickSystemTool(): Promise<DiscoveredSystemTool>;
33
+ /**
34
+ * Builds the command line of a tool for this action.
35
+ * @param params action params
36
+ * @param tool tool to use, default the one pickSystemTool returns
37
+ * @returns the tool and its arguments
38
+ */
39
+ static build_command(params: ActionParams, tool?: DiscoveredSystemTool): Promise<{
40
+ tool: DiscoveredSystemTool;
41
+ args: string[];
42
+ }>;
43
+ /**
44
+ * Runs the action's command line (no shell) and returns its full output.
45
+ * @param params action params
46
+ * @param tool tool to use, default the one pickSystemTool returns
47
+ * @returns the tool that ran and its stdout and stderr
48
+ */
49
+ static run_action(params: ActionParams, tool?: DiscoveredSystemTool): Promise<ToolOutput>;
50
+ /**
51
+ * Runs the action and returns the tail of its output, for tool replies.
52
+ * @param params action params
53
+ * @param tool tool to use, default the one pickSystemTool returns
54
+ * @returns the last 1500 characters of stdout and stderr
55
+ */
56
+ static run_action_get_tail(params: ActionParams, tool?: DiscoveredSystemTool): Promise<string>;
57
+ /**
58
+ * Returns the tail of a run's output, for tool replies.
59
+ * @param out output of exec
60
+ * @returns the last 1500 characters of stdout and stderr
61
+ */
62
+ static tail(out: ToolOutput): string;
63
+ }
@@ -0,0 +1,105 @@
1
+ // Base of the debug actions: each one knows the command line of every tool that can run it.
2
+ //
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { discover_system_tools, toolHint, } from '../utils/discover_tools.js';
6
+ import { claimProbe, releaseProbe } from '../utils/utils_mutex.js';
7
+ const run = promisify(execFile);
8
+ /**
9
+ * A debug operation (program, read memory, reset, ...) and the command line of each tool that can do it.
10
+ * The first installed tool in `commands` order runs it, with the placeholders filled from the action params.
11
+ * Everything is static: subclasses set the fields and are used without an instance (DebugActionRead.run_action(...)).
12
+ */
13
+ export class DebugAction {
14
+ static title; // e.g. "Reading memory", for error messages
15
+ static commands;
16
+ static timeout = 30_000;
17
+ static exclusive = true; // the run opens the probe, so only one such run happens at a time
18
+ /**
19
+ * Converts the action params to the placeholder values; override to add derived or formatted values.
20
+ * @param params action params
21
+ * @returns the placeholder values
22
+ */
23
+ static values(params) {
24
+ return params;
25
+ }
26
+ /**
27
+ * Picks the first installed tool that has a command line for this action.
28
+ * @returns the tool
29
+ */
30
+ static async pickSystemTool() {
31
+ const ids = Object.keys(this.commands);
32
+ const first = async (refresh) => {
33
+ const installed = await discover_system_tools(refresh);
34
+ return ids.map((id) => installed.find((t) => t.id === id)).find((t) => t);
35
+ };
36
+ // Look again before failing, in case a tool was installed after the cached discovery
37
+ const tool = (await first(false)) ?? (await first(true));
38
+ if (!tool)
39
+ throw new Error(`${this.title} needs ${ids.map((id) => `${id} (${toolHint(id)})`).join(' or ')}`);
40
+ return tool;
41
+ }
42
+ /**
43
+ * Builds the command line of a tool for this action.
44
+ * @param params action params
45
+ * @param tool tool to use, default the one pickSystemTool returns
46
+ * @returns the tool and its arguments
47
+ */
48
+ static async build_command(params, tool) {
49
+ tool ??= await this.pickSystemTool();
50
+ const template = this.commands[tool.id];
51
+ if (!template)
52
+ throw new Error(`${this.title} is not supported by ${tool.id}`);
53
+ const values = this.values(params);
54
+ const fill = (arg) => arg.replace(/\{(\w+)\}/g, (_all, name) => {
55
+ if (!(name in values))
56
+ throw new Error(`${this.title}: no value for {${name}} in the ${tool.id} command`);
57
+ return String(values[name]);
58
+ });
59
+ const args = template.flatMap((a) => typeof a === 'string' ? [fill(a)] : values[a.if] === true ? a.args.map(fill) : []);
60
+ return { tool, args };
61
+ }
62
+ /**
63
+ * Runs the action's command line (no shell) and returns its full output.
64
+ * @param params action params
65
+ * @param tool tool to use, default the one pickSystemTool returns
66
+ * @returns the tool that ran and its stdout and stderr
67
+ */
68
+ static async run_action(params, tool) {
69
+ const cmd = await this.build_command(params, tool);
70
+ if (this.exclusive)
71
+ claimProbe(this.title);
72
+ try {
73
+ const { stdout, stderr } = await run(cmd.tool.path, cmd.args, {
74
+ timeout: this.timeout,
75
+ windowsHide: true,
76
+ maxBuffer: 16 * 1024 * 1024,
77
+ });
78
+ return { tool: cmd.tool.id, stdout, stderr };
79
+ }
80
+ catch (e) {
81
+ throw new Error(`${this.title} failed (${cmd.tool.id}): ${(`${e.stdout ?? ''}${e.stderr ?? ''}` || e.message).slice(-1500)}`);
82
+ }
83
+ finally {
84
+ if (this.exclusive)
85
+ releaseProbe();
86
+ }
87
+ }
88
+ /**
89
+ * Runs the action and returns the tail of its output, for tool replies.
90
+ * @param params action params
91
+ * @param tool tool to use, default the one pickSystemTool returns
92
+ * @returns the last 1500 characters of stdout and stderr
93
+ */
94
+ static async run_action_get_tail(params, tool) {
95
+ return this.tail(await this.run_action(params, tool));
96
+ }
97
+ /**
98
+ * Returns the tail of a run's output, for tool replies.
99
+ * @param out output of exec
100
+ * @returns the last 1500 characters of stdout and stderr
101
+ */
102
+ static tail(out) {
103
+ return `${out.stdout}${out.stderr}`.slice(-1500);
104
+ }
105
+ }
@@ -0,0 +1,7 @@
1
+ import { DebugAction } from './DebugAction.js';
2
+ export declare class DebugActionInfo extends DebugAction {
3
+ static readonly title = "Identifying the target";
4
+ static readonly commands: {
5
+ STM32_Programmer_CLI: string[];
6
+ };
7
+ }
@@ -0,0 +1,9 @@
1
+ import { DebugAction } from './DebugAction.js';
2
+ // Connects to the target without resetting it and reports what STM32_Programmer_CLI identifies
3
+ // (device ID, name, flash size, core). probe-rs cannot name a chip it is not told, so it has no command here.
4
+ export class DebugActionInfo extends DebugAction {
5
+ static title = 'Identifying the target';
6
+ static commands = {
7
+ STM32_Programmer_CLI: ['-c', 'port=SWD', 'mode=HOTPLUG'],
8
+ };
9
+ }
@@ -0,0 +1,9 @@
1
+ import { DebugAction } from './DebugAction.js';
2
+ export declare class DebugActionListProbes extends DebugAction {
3
+ static readonly title = "Listing probes";
4
+ static readonly exclusive = false;
5
+ static readonly commands: {
6
+ 'probe-rs': string[];
7
+ STM32_Programmer_CLI: string[];
8
+ };
9
+ }
@@ -0,0 +1,10 @@
1
+ import { DebugAction } from './DebugAction.js';
2
+ // Lists the connected debug probes. Does not open a probe, so it skips the busy lock.
3
+ export class DebugActionListProbes extends DebugAction {
4
+ static title = 'Listing probes';
5
+ static exclusive = false;
6
+ static commands = {
7
+ 'probe-rs': ['list'],
8
+ STM32_Programmer_CLI: ['--list'],
9
+ };
10
+ }
@@ -0,0 +1,28 @@
1
+ import { DebugAction, ToolOutput } from './DebugAction.js';
2
+ import { DiscoveredSystemTool } from '../utils/discover_tools.js';
3
+ export type ProgramParams = {
4
+ chip: string;
5
+ elf: string;
6
+ };
7
+ export declare class DebugActionProgram extends DebugAction {
8
+ static readonly title = "Programming";
9
+ static readonly timeout = 180000;
10
+ static readonly commands: {
11
+ 'probe-rs': (string | {
12
+ if: string;
13
+ args: string[];
14
+ })[];
15
+ STM32_Programmer_CLI: (string | {
16
+ if: string;
17
+ args: string[];
18
+ })[];
19
+ };
20
+ /**
21
+ * Programs the ELF. If probe-rs fails on a dual-bank G47x/G48x part it has no algorithm for, retries once
22
+ * with the whole chip erased first, which also clears data kept in flash.
23
+ * @param p chip and ELF
24
+ * @param tool tool to use, default the one pickSystemTool returns
25
+ * @returns the tool output, with a note at the end when the whole chip was erased
26
+ */
27
+ static run_action(p: ProgramParams, tool?: DiscoveredSystemTool): Promise<ToolOutput>;
28
+ }
@@ -0,0 +1,79 @@
1
+ import { DebugAction } from './DebugAction.js';
2
+ import { DebugActionRead } from './DebugActionRead.js';
3
+ import { hasSingleBankFlashAlgo } from '../utils/mcu_utils.js';
4
+ // STM32G4 FLASH_OPTR and its DBANK bit (dual-bank mode, 2 KB pages, bank 2 at 0x08040000).
5
+ const G4_FLASH_OPTR = 0x40022020;
6
+ const G4_OPTR_DBANK = 1 << 22;
7
+ /**
8
+ * Tells whether the target runs in a flash mode that probe-rs's per-sector erase gets wrong:
9
+ * a 128/256 KB STM32G47x/G48x with DBANK set, where probe-rs assumes the single-bank page layout.
10
+ * @param chip probe-rs target name (e.g. STM32G474CCTx)
11
+ * @returns true when the whole chip must be erased before programming
12
+ */
13
+ async function needsChipErase(chip) {
14
+ if (!hasSingleBankFlashAlgo(chip))
15
+ return false;
16
+ const { words: [optr], } = await DebugActionRead.run_action({
17
+ chip,
18
+ address: G4_FLASH_OPTR,
19
+ width: 32,
20
+ count: 1,
21
+ });
22
+ return (optr & G4_OPTR_DBANK) !== 0;
23
+ }
24
+ // Writes an ELF over SWD, verifies it and resets the target.
25
+ // ponytail: uses the only connected probe
26
+ // (probe-rs --non-interactive fails if there are several);
27
+ // pin the probe once the sidebar has a probe picker
28
+ export class DebugActionProgram extends DebugAction {
29
+ static title = 'Programming';
30
+ static timeout = 180_000;
31
+ static commands = {
32
+ 'probe-rs': [
33
+ 'download',
34
+ '--chip',
35
+ '{chip}',
36
+ '--protocol',
37
+ 'swd',
38
+ '--non-interactive',
39
+ '--disable-progressbars',
40
+ { if: 'chipErase', args: ['--chip-erase'] },
41
+ '--verify',
42
+ '--reset',
43
+ '{elf}',
44
+ ],
45
+ STM32_Programmer_CLI: [
46
+ '-c',
47
+ 'port=SWD',
48
+ { if: 'chipErase', args: ['-e', 'all'] },
49
+ '-w',
50
+ '{elf}',
51
+ '-v',
52
+ '-rst',
53
+ ],
54
+ };
55
+ /**
56
+ * Programs the ELF. If probe-rs fails on a dual-bank G47x/G48x part it has no algorithm for, retries once
57
+ * with the whole chip erased first, which also clears data kept in flash.
58
+ * @param p chip and ELF
59
+ * @param tool tool to use, default the one pickSystemTool returns
60
+ * @returns the tool output, with a note at the end when the whole chip was erased
61
+ */
62
+ static async run_action(p, tool) {
63
+ tool ??= await this.pickSystemTool();
64
+ try {
65
+ return await super.run_action({ ...p, chipErase: false }, tool);
66
+ }
67
+ catch (e) {
68
+ // A failed OPTR read (e.g. probe unplugged) means no retry, and the programming error is the one to report
69
+ if (tool.id !== 'probe-rs' || !(await needsChipErase(p.chip).catch(() => false)))
70
+ throw e;
71
+ const out = await super.run_action({ ...p, chipErase: true }, tool);
72
+ // appended to stderr so tail() keeps it
73
+ return {
74
+ ...out,
75
+ stderr: `${out.stderr}\nDual-bank flash (DBANK=1): first attempt failed, erased the whole chip and programmed again. First error:\n${e.message.slice(-500)}`,
76
+ };
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,38 @@
1
+ import { DebugAction, ToolOutput } from './DebugAction.js';
2
+ import { DiscoveredSystemTool } from '../utils/discover_tools.js';
3
+ export type ReadParams = {
4
+ chip: string;
5
+ address: number;
6
+ width: 8 | 16 | 32;
7
+ count: number;
8
+ };
9
+ export declare class DebugActionRead extends DebugAction {
10
+ static readonly title = "Reading memory";
11
+ static readonly commands: {
12
+ 'probe-rs': string[];
13
+ STM32_Programmer_CLI: string[];
14
+ };
15
+ protected static values(p: ReadParams): {
16
+ chip: string;
17
+ width: 8 | 16 | 32;
18
+ count: number;
19
+ address: string;
20
+ bytes: number;
21
+ };
22
+ /**
23
+ * Reads target memory and parses the words from the tool output.
24
+ * @param p chip, address, width and word count
25
+ * @param tool tool to use, default the one pickSystemTool returns
26
+ * @returns the tool output and the words read, in address order
27
+ */
28
+ static run_action(p: ReadParams, tool?: DiscoveredSystemTool): Promise<ToolOutput & {
29
+ words: number[];
30
+ }>;
31
+ /**
32
+ * Reads target memory and returns the whole tool output, not trimmed.
33
+ * @param p chip, address, width and word count
34
+ * @param tool tool to use, default the one pickSystemTool returns
35
+ * @returns stdout and stderr
36
+ */
37
+ static run_action_get_tail(p: ReadParams, tool?: DiscoveredSystemTool): Promise<string>;
38
+ }