@turingcode/cli 0.2.13 → 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 (177) 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 -1
  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/mcp.d.ts +92 -0
  14. package/dist/core/mcp.js +56 -15
  15. package/dist/core/query.d.ts +69 -0
  16. package/dist/core/report.d.ts +11 -0
  17. package/dist/core/tables/csv.d.ts +18 -0
  18. package/dist/core/tables/markdown.d.ts +22 -0
  19. package/dist/core/tables/types.d.ts +25 -0
  20. package/dist/features/contract/check.d.ts +30 -0
  21. package/dist/features/contract/command.d.ts +12 -0
  22. package/dist/features/contract/command.js +64 -64
  23. package/dist/features/contract/describe.d.ts +22 -0
  24. package/dist/features/contract/diagnostics.d.ts +108 -0
  25. package/dist/features/contract/load.d.ts +58 -0
  26. package/dist/features/contract/model.d.ts +67 -0
  27. package/dist/features/contract/rules.d.ts +137 -0
  28. package/dist/features/debug/clear_breakpoint.d.ts +2 -0
  29. package/dist/features/debug/clear_breakpoint.js +24 -0
  30. package/dist/features/debug/command.d.ts +5 -0
  31. package/dist/features/debug/command.js +66 -0
  32. package/dist/features/debug/continue.d.ts +2 -0
  33. package/dist/features/debug/continue.js +22 -0
  34. package/dist/features/debug/debug_start.d.ts +2 -0
  35. package/dist/features/debug/debug_start.js +22 -0
  36. package/dist/features/debug/debug_stop.d.ts +2 -0
  37. package/dist/features/debug/debug_stop.js +11 -0
  38. package/dist/features/debug/evaluate.d.ts +2 -0
  39. package/dist/features/debug/evaluate.js +48 -0
  40. package/dist/features/debug/get_stack.d.ts +2 -0
  41. package/dist/features/debug/get_stack.js +14 -0
  42. package/dist/features/debug/get_variables.d.ts +2 -0
  43. package/dist/features/debug/get_variables.js +26 -0
  44. package/dist/features/debug/halt.d.ts +2 -0
  45. package/dist/features/debug/halt.js +16 -0
  46. package/dist/features/debug/set_breakpoint.d.ts +2 -0
  47. package/dist/features/debug/set_breakpoint.js +30 -0
  48. package/dist/features/debug/step.d.ts +2 -0
  49. package/dist/features/debug/step.js +23 -0
  50. package/dist/features/install-mods/command.d.ts +6 -0
  51. package/dist/features/install-mods/command.js +18 -0
  52. package/dist/features/install-mods/install.d.ts +23 -0
  53. package/dist/features/install-mods/install.js +48 -0
  54. package/dist/features/install-skills/command.d.ts +7 -0
  55. package/dist/features/install-skills/command.js +22 -0
  56. package/dist/features/install-skills/install.d.ts +13 -0
  57. package/dist/features/install-skills/install.js +29 -0
  58. package/dist/features/probe/command.d.ts +5 -0
  59. package/dist/features/probe/command.js +44 -0
  60. package/dist/features/probe/kill_all_debuggers.d.ts +2 -0
  61. package/dist/features/probe/kill_all_debuggers.js +50 -0
  62. package/dist/features/probe/list_probes.d.ts +2 -0
  63. package/dist/features/probe/list_probes.js +8 -0
  64. package/dist/features/probe/program_project.d.ts +2 -0
  65. package/dist/features/probe/program_project.js +29 -0
  66. package/dist/features/probe/read_fault_status.d.ts +2 -0
  67. package/dist/features/probe/read_fault_status.js +19 -0
  68. package/dist/features/probe/read_memory.d.ts +2 -0
  69. package/dist/features/probe/read_memory.js +36 -0
  70. package/dist/features/probe/read_peripheral.d.ts +2 -0
  71. package/dist/features/probe/read_peripheral.js +58 -0
  72. package/dist/features/probe/reset_probe_usb.d.ts +2 -0
  73. package/dist/features/probe/reset_probe_usb.js +17 -0
  74. package/dist/features/probe/reset_target.d.ts +2 -0
  75. package/dist/features/probe/reset_target.js +16 -0
  76. package/dist/features/probe/target_info.d.ts +2 -0
  77. package/dist/features/probe/target_info.js +34 -0
  78. package/dist/features/project/analysis_static.d.ts +2 -0
  79. package/dist/features/project/analysis_static.js +19 -0
  80. package/dist/features/project/analysis_syntax_check.d.ts +2 -0
  81. package/dist/features/project/analysis_syntax_check.js +21 -0
  82. package/dist/features/project/command.d.ts +5 -0
  83. package/dist/features/project/command.js +64 -0
  84. package/dist/features/project/project_build.d.ts +2 -0
  85. package/dist/features/project/project_build.js +22 -0
  86. package/dist/features/project/project_download_template.d.ts +2 -0
  87. package/dist/features/project/project_download_template.js +34 -0
  88. package/dist/features/project/project_regenerate.d.ts +2 -0
  89. package/dist/features/project/project_regenerate.js +20 -0
  90. package/dist/features/project/project_sync_from_server.d.ts +2 -0
  91. package/dist/features/project/project_sync_from_server.js +13 -0
  92. package/dist/features/project/project_sync_to_server.d.ts +2 -0
  93. package/dist/features/project/project_sync_to_server.js +51 -0
  94. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +2 -0
  95. package/dist/features/project/stm32_cubetools_download_drivers.js +19 -0
  96. package/dist/features/status/command.d.ts +2 -0
  97. package/dist/features/status/command.js +6 -0
  98. package/dist/features/status/get_status.d.ts +2 -0
  99. package/dist/features/status/get_status.js +44 -0
  100. package/dist/features/table/check.d.ts +38 -0
  101. package/dist/features/table/command.d.ts +3 -0
  102. package/dist/features/table/read.d.ts +28 -0
  103. package/dist/features/tool/command.d.ts +35 -0
  104. package/dist/lib.d.ts +11 -0
  105. package/dist/lib.js +9 -0
  106. package/dist/stm32/actions/DebugAction.d.ts +63 -0
  107. package/dist/stm32/actions/DebugAction.js +105 -0
  108. package/dist/stm32/actions/DebugActionInfo.d.ts +7 -0
  109. package/dist/stm32/actions/DebugActionInfo.js +9 -0
  110. package/dist/stm32/actions/DebugActionListProbes.d.ts +9 -0
  111. package/dist/stm32/actions/DebugActionListProbes.js +10 -0
  112. package/dist/stm32/actions/DebugActionProgram.d.ts +28 -0
  113. package/dist/stm32/actions/DebugActionProgram.js +79 -0
  114. package/dist/stm32/actions/DebugActionRead.d.ts +38 -0
  115. package/dist/stm32/actions/DebugActionRead.js +59 -0
  116. package/dist/stm32/actions/DebugActionReset.d.ts +11 -0
  117. package/dist/stm32/actions/DebugActionReset.js +9 -0
  118. package/dist/stm32/actions/DebugActionServer.d.ts +7 -0
  119. package/dist/stm32/actions/DebugActionServer.js +9 -0
  120. package/dist/stm32/analysis.d.ts +19 -0
  121. package/dist/stm32/analysis.js +21 -0
  122. package/dist/stm32/build.d.ts +34 -0
  123. package/dist/stm32/build.js +79 -0
  124. package/dist/stm32/context.d.ts +23 -0
  125. package/dist/stm32/context.js +42 -0
  126. package/dist/stm32/daemon.d.ts +63 -0
  127. package/dist/stm32/daemon.js +202 -0
  128. package/dist/stm32/regen.d.ts +68 -0
  129. package/dist/stm32/regen.js +225 -0
  130. package/dist/stm32/session.d.ts +134 -0
  131. package/dist/stm32/session.js +374 -0
  132. package/dist/stm32/sync.d.ts +24 -0
  133. package/dist/stm32/sync.js +72 -0
  134. package/dist/stm32/tool.d.ts +43 -0
  135. package/dist/stm32/tool.js +20 -0
  136. package/dist/stm32/toolCommand.d.ts +50 -0
  137. package/dist/stm32/toolCommand.js +102 -0
  138. package/dist/stm32/utils/discover_tools.d.ts +24 -0
  139. package/dist/stm32/utils/discover_tools.js +121 -0
  140. package/dist/stm32/utils/downloadzip_utils.d.ts +57 -0
  141. package/dist/stm32/utils/downloadzip_utils.js +180 -0
  142. package/dist/stm32/utils/faultUtils.d.ts +14 -0
  143. package/dist/stm32/utils/faultUtils.js +69 -0
  144. package/dist/stm32/utils/findElf.d.ts +9 -0
  145. package/dist/stm32/utils/findElf.js +19 -0
  146. package/dist/stm32/utils/hash_utils.d.ts +19 -0
  147. package/dist/stm32/utils/hash_utils.js +28 -0
  148. package/dist/stm32/utils/listSyncFiles.d.ts +9 -0
  149. package/dist/stm32/utils/listSyncFiles.js +98 -0
  150. package/dist/stm32/utils/mcu_utils.d.ts +59 -0
  151. package/dist/stm32/utils/mcu_utils.js +99 -0
  152. package/dist/stm32/utils/project_utils.d.ts +54 -0
  153. package/dist/stm32/utils/project_utils.js +102 -0
  154. package/dist/stm32/utils/svdUtils.d.ts +31 -0
  155. package/dist/stm32/utils/svdUtils.js +30 -0
  156. package/dist/stm32/utils/truncate.d.ts +7 -0
  157. package/dist/stm32/utils/truncate.js +9 -0
  158. package/dist/stm32/utils/usb_utils.d.ts +5 -0
  159. package/dist/stm32/utils/usb_utils.js +23 -0
  160. package/dist/stm32/utils/user_code.d.ts +14 -0
  161. package/dist/stm32/utils/user_code.js +43 -0
  162. package/dist/stm32/utils/utils_mutex.d.ts +15 -0
  163. package/dist/stm32/utils/utils_mutex.js +93 -0
  164. package/dist/stm32/validate.d.ts +16 -0
  165. package/dist/stm32/validate.js +46 -0
  166. package/mods/claude/.claude-plugin/marketplace.json +8 -0
  167. package/mods/claude/turingcode-skills/.claude-plugin/plugin.json +5 -0
  168. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +50 -0
  169. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/board-and-debug.md +22 -0
  170. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/build-and-check.md +19 -0
  171. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/new-project.md +9 -0
  172. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +43 -0
  173. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +42 -0
  174. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +35 -0
  175. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +34 -0
  176. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +35 -0
  177. package/package.json +11 -3
package/README.md CHANGED
@@ -16,6 +16,8 @@ npm install -g @turingcode/cli
16
16
  | `turingcode tool list` | Lists the Turing Code server tools your token can call, one line each. |
17
17
  | `turingcode tool describe <name>... [--json]` | Shows the full description and arguments of the named tools (`--json`: raw schemas). |
18
18
  | `turingcode tool call <name> [--args json\|file]` | Calls a server tool and prints its text result, e.g. `> result.md` to save it. |
19
+ | `turingcode install-skills [names..] [--target dir]` | Copies the shipped agent skills into `~/.agents/skills` (Codex, OpenCode). |
20
+ | `turingcode install-mods [names..]` | Installs the shipped Claude Code plugins (`turingcode-skills`) via `claude plugin`. |
19
21
 
20
22
  Output is compact text: a status line, one line per finding (the same error on several rows is one
21
23
  line), and a fix hint per code. `--json` prints the full result. Exit codes: `0` PASS/VALID,
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Builds the yargs parser with every feature command registered.
3
+ *
4
+ * @param {string[]} args - Arguments after `turingcode`.
5
+ * @returns The parser; call `parseAsync()` to run it.
6
+ * @throws {Error} When the first word is not a command (yargs alone would print help and exit 0 for `<unknown> --help`).
7
+ * It and the argument errors yargs finds (missing option, unknown subcommand, bad flag value) carry
8
+ * `exitCode` 2, so they differ from a failed check or request (1).
9
+ */
10
+ export declare function createCli(args: string[]): import("yargs").Argv<{}>;
@@ -2,7 +2,13 @@ import yargs from "yargs/yargs";
2
2
  import contract from "../features/contract/command.js";
3
3
  import table from "../features/table/command.js";
4
4
  import tool from "../features/tool/command.js";
5
- const commands = [contract, table, tool];
5
+ import project from "../features/project/command.js";
6
+ import probe from "../features/probe/command.js";
7
+ import debug from "../features/debug/command.js";
8
+ import status from "../features/status/command.js";
9
+ import installSkills from "../features/install-skills/command.js";
10
+ import installMods from "../features/install-mods/command.js";
11
+ const commands = [contract, table, tool, project, probe, debug, status, installSkills, installMods];
6
12
  const names = commands.map(c => String(c.command).split(" ")[0]);
7
13
  /** Exit code of every argument error, as each command's help documents. */
8
14
  const BAD_ARGUMENTS = 2;
@@ -30,6 +36,11 @@ export function createCli(args) {
30
36
  "- Tables: check Markdown or CSV tables against a contract (a JSON file of tables, columns and",
31
37
  " MongoDB-style checks): `contract describe` shows the tables to write; `table check` until PASS.",
32
38
  " Contract format: $0 contract --help.",
39
+ "- STM32 projects: `project sync`, `project build` on the server, `probe program` to flash the board,",
40
+ " `probe read` and `probe peripheral` to inspect it, `debug start` ... `debug stop` for a live debug",
41
+ " session; `status` shows the project and the installed debug tools.",
42
+ "- Agent skills: `install-skills` copies them into ~/.agents/skills (Codex, OpenCode);",
43
+ " `install-mods` installs them into Claude Code as the turingcode-skills plugin.",
33
44
  ].join("\n"))
34
45
  .command(commands)
35
46
  .demandCommand(1, `Name a command: ${names.slice(0, -1).join(", ")} or ${names.at(-1)}`)
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Runs the CLI. Errors propagate here, are printed, and exit with code 1, or with the error's
4
+ * own `exitCode` when it has one (e.g. 2 for bad input to a check command).
5
+ *
6
+ * @param {string[]} [args] - Arguments after `turingcode`.
7
+ * @returns {Promise<void>} Resolves when the command finished.
8
+ */
9
+ export declare function main(args?: string[]): Promise<void>;
package/dist/cli/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { hideBin } from "yargs/helpers";
3
+ import { loadDotEnv } from "../core/files.js";
3
4
  import { createCli } from "./create-cli.js";
4
5
  /**
5
6
  * Runs the CLI. Errors propagate here, are printed, and exit with code 1, or with the error's
@@ -10,11 +11,14 @@ import { createCli } from "./create-cli.js";
10
11
  */
11
12
  export async function main(args = hideBin(process.argv)) {
12
13
  try {
14
+ loadDotEnv(".env");
13
15
  await createCli(args).parseAsync();
14
16
  }
15
17
  catch (error) {
16
- process.stderr.write(`turingcode: ${error.message}\nRun "turingcode <command> --help" for usage.\n`);
17
18
  process.exitCode = error.exitCode ?? 1;
19
+ // the usage hint only helps with bad arguments, not after a failed request or a stopped regen
20
+ const hint = process.exitCode === 2 ? `Run "turingcode <command> --help" for usage.\n` : "";
21
+ process.stderr.write(`turingcode: ${error.message}\n${hint}`);
18
22
  }
19
23
  }
20
24
  void main();
@@ -0,0 +1,10 @@
1
+ /** Raised when a search or size bound is exceeded (maps to SEARCH_BOUND_EXCEEDED). */
2
+ export declare class BoundError extends Error {
3
+ readonly bound: string;
4
+ readonly limit: number;
5
+ /**
6
+ * @param {string} bound - Name of the bound that was exceeded, e.g. `max_table_rows`.
7
+ * @param {number} limit - Its value.
8
+ */
9
+ constructor(bound: string, limit: number);
10
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Whether a text is a real calendar date written `YYYY-MM-DD`. Such dates sort
3
+ * correctly as plain text, so they can be compared without parsing.
4
+ *
5
+ * @param {string} v - The text to test.
6
+ * @returns {boolean} True for a valid date, false otherwise (including `2026-02-30`).
7
+ *
8
+ * @example
9
+ * isDate("2026-02-28"); // true
10
+ * isDate("2026-02-30"); // false
11
+ */
12
+ export declare function isDate(v: string): boolean;
@@ -0,0 +1,49 @@
1
+ import { Fraction } from "./fraction.js";
2
+ /** Raised when an expression cannot be parsed or evaluated. */
3
+ export declare class AstError extends Error {
4
+ }
5
+ export type Node = {
6
+ k: "num";
7
+ v: Fraction;
8
+ } | {
9
+ k: "name";
10
+ name: string;
11
+ } | {
12
+ k: "neg";
13
+ a: Node;
14
+ } | {
15
+ k: "bin";
16
+ op: "+" | "-" | "*" | "/" | "**";
17
+ a: Node;
18
+ b: Node;
19
+ };
20
+ /**
21
+ * Parses an exact-arithmetic expression (spec §3.4): literals, names,
22
+ * unary +/-, + - * / and right-associative **, with parentheses.
23
+ *
24
+ * @param {string} text - The expression, e.g. `180/pi`.
25
+ * @param {number} maxNodes - `bounds.max_ast_nodes`.
26
+ * @param {ReadonlySet<string>} names - Names the expression may use.
27
+ * @returns {Node} The tree.
28
+ * @throws {AstError} On a syntax error or unknown name.
29
+ * @throws {BoundError} When the tree would exceed maxNodes.
30
+ */
31
+ export declare function parseExpression(text: string, maxNodes: number, names: ReadonlySet<string>): Node;
32
+ /**
33
+ * Evaluates a tree exactly. A name bound to null (an irrational constant
34
+ * such as `pi`) makes the result null; division by zero is still caught
35
+ * wherever both sides are exact.
36
+ *
37
+ * @param {Node} n - The tree.
38
+ * @param {Readonly<Record<string, Fraction | null>>} env - Values of the names.
39
+ * @returns {Fraction | null} The exact value, or null when it involves an irrational name.
40
+ * @throws {AstError} On division by zero or a bad exponent.
41
+ */
42
+ export declare function evaluate(n: Node, env: Readonly<Record<string, Fraction | null>>): Fraction | null;
43
+ /**
44
+ * The names an expression uses.
45
+ *
46
+ * @param {Node} n - The tree.
47
+ * @returns {Set<string>} Distinct names.
48
+ */
49
+ export declare function namesIn(n: Node): Set<string>;
@@ -0,0 +1,85 @@
1
+ /** Largest integer exponent magnitude allowed anywhere in exact arithmetic (spec §3.4). */
2
+ export declare const MAX_EXPONENT = 1000;
3
+ /** Raised for any arithmetic the exact engine refuses (bad literal, division by zero, bad exponent). */
4
+ export declare class ArithmeticError extends Error {
5
+ }
6
+ /** An exact rational number on BigInt; never touches a JS float. */
7
+ export declare class Fraction {
8
+ readonly n: bigint;
9
+ readonly d: bigint;
10
+ /**
11
+ * Builds a reduced fraction with a positive denominator.
12
+ *
13
+ * @param {bigint} n - Numerator.
14
+ * @param {bigint} [d=1n] - Denominator.
15
+ * @throws {ArithmeticError} When the denominator is zero.
16
+ */
17
+ constructor(n: bigint, d?: bigint);
18
+ /**
19
+ * Parses a number literal: integer, decimal (with optional exponent),
20
+ * `0x..` / `..h` hex, or `0b..` / `..b` binary.
21
+ *
22
+ * @param {string} text - The literal.
23
+ * @returns {Fraction} Its exact value.
24
+ * @throws {ArithmeticError} When the text is not a literal or its exponent exceeds MAX_EXPONENT.
25
+ *
26
+ * @example
27
+ * Fraction.parse("1e-3").toString(); // "1/1000"
28
+ */
29
+ static parse(text: string): Fraction;
30
+ /**
31
+ * Parses a signed decimal number as written in a table cell: `-3`, `+0.25`, `1.5e3`.
32
+ *
33
+ * @param {string} text - The cell text.
34
+ * @returns {Fraction | null} Its exact value, or null when it is not a decimal number.
35
+ *
36
+ * @example
37
+ * Fraction.parseDecimal("-0.5")?.toString(); // "-1/2"
38
+ */
39
+ static parseDecimal(text: string): Fraction | null;
40
+ /**
41
+ * Compares with another fraction.
42
+ *
43
+ * @param {Fraction} o - The other value.
44
+ * @returns {number} -1, 0 or 1.
45
+ */
46
+ cmp(o: Fraction): number;
47
+ /** @returns {Fraction} |this|. */
48
+ abs(): Fraction;
49
+ /** @returns {boolean} Whether the value is zero. */
50
+ isZero(): boolean;
51
+ /** @returns {boolean} Whether the value is a whole number. */
52
+ isInteger(): boolean;
53
+ /** @param {Fraction} o - Addend. @returns {Fraction} this + o. */
54
+ add(o: Fraction): Fraction;
55
+ /** @param {Fraction} o - Subtrahend. @returns {Fraction} this - o. */
56
+ sub(o: Fraction): Fraction;
57
+ /** @param {Fraction} o - Factor. @returns {Fraction} this * o. */
58
+ mul(o: Fraction): Fraction;
59
+ /**
60
+ * @param {Fraction} o - Divisor.
61
+ * @returns {Fraction} this / o.
62
+ * @throws {ArithmeticError} When o is zero.
63
+ */
64
+ div(o: Fraction): Fraction;
65
+ /** @returns {Fraction} -this. */
66
+ neg(): Fraction;
67
+ /**
68
+ * Raises to a whole exponent.
69
+ *
70
+ * @param {Fraction} e - Exponent; must be an integer with |e| <= MAX_EXPONENT.
71
+ * @returns {Fraction} this ** e.
72
+ * @throws {ArithmeticError} For a non-integer or too-large exponent, or 0 ** negative.
73
+ */
74
+ pow(e: Fraction): Fraction;
75
+ /**
76
+ * Decimal text: exact when the fraction terminates, else rounded to `places`
77
+ * decimals and prefixed with `~`.
78
+ *
79
+ * @param {number} [places=10] - Decimals for a non-terminating value.
80
+ * @returns {string} e.g. `12.5`, `~0.3333333333`.
81
+ */
82
+ toDecimal(places?: number): string;
83
+ /** @returns {string} `n` or `n/d`. */
84
+ toString(): string;
85
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Copies the TURINGCODE_* settings of a `.env` file (`KEY=value` lines, optional `export ` and quotes)
3
+ * into an environment, keeping variables that are already set.
4
+ *
5
+ * @param {string} file - The .env path; a missing or unreadable file is ignored.
6
+ * @param {NodeJS.ProcessEnv} [env=process.env] - Environment to fill.
7
+ * @returns {string[]} The keys it set.
8
+ */
9
+ export declare function loadDotEnv(file: string, env?: NodeJS.ProcessEnv): string[];
10
+ /**
11
+ * The CLI's package folder: the nearest folder above this module that holds a package.json
12
+ * (works from dist/ and from the test build).
13
+ *
14
+ * @returns {string} Its path.
15
+ * @throws {Error} When no package.json is found.
16
+ */
17
+ export declare function packageRoot(): string;
18
+ export type JsonFile = {
19
+ ok: true;
20
+ data: unknown;
21
+ } | {
22
+ ok: false;
23
+ error: "unreadable" | "bad_json";
24
+ message: string;
25
+ };
26
+ /**
27
+ * Reads and parses a UTF-8 JSON file (a leading BOM is ignored).
28
+ *
29
+ * @param {string} path - File path.
30
+ * @returns {JsonFile} The parsed value, or why it could not be read.
31
+ *
32
+ * @example
33
+ * const file = readJsonFile("contract.json");
34
+ * if (file.ok) use(file.data);
35
+ */
36
+ export declare function readJsonFile(path: string): JsonFile;
37
+ /**
38
+ * Reads a JSON flag: inline JSON when it starts with `{` or `[`, otherwise a path to a .json file.
39
+ *
40
+ * @param {string} value - Raw flag value.
41
+ * @returns {unknown} The parsed JSON.
42
+ * @throws {Error} When the value is neither inline JSON nor an existing file, the file cannot be read, or the JSON is invalid.
43
+ */
44
+ export declare function readJsonArg(value: string): unknown;
@@ -1,4 +1,49 @@
1
- import { readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ /**
5
+ * Copies the TURINGCODE_* settings of a `.env` file (`KEY=value` lines, optional `export ` and quotes)
6
+ * into an environment, keeping variables that are already set.
7
+ *
8
+ * @param {string} file - The .env path; a missing or unreadable file is ignored.
9
+ * @param {NodeJS.ProcessEnv} [env=process.env] - Environment to fill.
10
+ * @returns {string[]} The keys it set.
11
+ */
12
+ export function loadDotEnv(file, env = process.env) {
13
+ let text;
14
+ try {
15
+ text = readFileSync(file, "utf8").replace(/^/, "");
16
+ }
17
+ catch {
18
+ return [];
19
+ }
20
+ const set = [];
21
+ for (const line of text.split(/\r?\n/)) {
22
+ const m = line.match(/^\s*(?:export\s+)?(TURINGCODE_\w+)\s*=\s*(.*?)\s*$/);
23
+ if (!m || env[m[1]]?.trim())
24
+ continue;
25
+ env[m[1]] = m[2].replace(/^(["'])(.*)\1$/, "$2");
26
+ set.push(m[1]);
27
+ }
28
+ return set;
29
+ }
30
+ /**
31
+ * The CLI's package folder: the nearest folder above this module that holds a package.json
32
+ * (works from dist/ and from the test build).
33
+ *
34
+ * @returns {string} Its path.
35
+ * @throws {Error} When no package.json is found.
36
+ */
37
+ export function packageRoot() {
38
+ let dir = dirname(fileURLToPath(import.meta.url));
39
+ while (!existsSync(join(dir, "package.json"))) {
40
+ const parent = dirname(dir);
41
+ if (parent === dir)
42
+ throw new Error("turingcode package root not found");
43
+ dir = parent;
44
+ }
45
+ return dir;
46
+ }
2
47
  /**
3
48
  * Reads and parses a UTF-8 JSON file (a leading BOM is ignored).
4
49
  *
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A JSON shape. Object keys ending in `?` are optional; all other keys are
3
+ * required, and keys not listed are rejected.
4
+ */
5
+ export type Shape = "string" | "bool" | "any" | "string_or_list" | {
6
+ enum: readonly string[];
7
+ } | {
8
+ list: Shape;
9
+ min?: number;
10
+ } | {
11
+ obj: Record<string, Shape>;
12
+ } | {
13
+ map: Shape;
14
+ };
15
+ /**
16
+ * One mismatch: `type` (wrong JSON type), `value` (right type, value not
17
+ * allowed), `missing` (required key absent) or `unknown` (key not in the shape).
18
+ */
19
+ export interface ShapeIssue {
20
+ kind: "type" | "value" | "missing" | "unknown";
21
+ /** JSON path of the value, e.g. `$.tables[0].name`. */
22
+ path: string;
23
+ message: string;
24
+ found: string;
25
+ expected: string;
26
+ }
27
+ /**
28
+ * Short, single-line JSON rendering of any value.
29
+ *
30
+ * @param {unknown} v - Value.
31
+ * @returns {string} At most 80 characters.
32
+ */
33
+ export declare function show(v: unknown): string;
34
+ /**
35
+ * Checks a JSON value against a shape.
36
+ *
37
+ * @param {unknown} value - The value.
38
+ * @param {Shape} shape - Its shape.
39
+ * @param {string} path - JSON path for messages, e.g. `$.tables[0]`.
40
+ * @returns {ShapeIssue[]} Every mismatch; empty when the value matches.
41
+ *
42
+ * @example
43
+ * checkShape({ a: 1 }, { obj: { a: "string" } }, "$")[0].message; // "$.a: expected a non-empty string, got number"
44
+ */
45
+ export declare function checkShape(value: unknown, shape: Shape, path: string): ShapeIssue[];
@@ -0,0 +1,92 @@
1
+ /** Default public MCP gateway (public-mcp-tools in the turingcode repo). */
2
+ export declare const DEFAULT_URL = "https://mcp.turingcode.ai/mcp";
3
+ /** Where to put the gateway token; shown in the help of server commands and when the token is missing. */
4
+ export declare const TOKEN_HELP: string;
5
+ export interface ToolResult {
6
+ text: string;
7
+ isError: boolean;
8
+ }
9
+ export interface ToolInfo {
10
+ name: string;
11
+ description?: string;
12
+ inputSchema?: unknown;
13
+ }
14
+ /**
15
+ * Calls one tool on the Turing Code MCP gateway.
16
+ *
17
+ * @param {string} name - Tool name, e.g. `stm32_cubetools_clock_solve`.
18
+ * @param {Record<string, unknown>} args - Tool arguments.
19
+ * @param {string} token - Bearer token for the gateway.
20
+ * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
21
+ * @param {number} [timeoutMs=125000] - Time before the request fails.
22
+ * @returns {Promise<ToolResult>} The tool's text content and error flag.
23
+ * @throws {Error} On HTTP errors, a timeout or a JSON-RPC error reply.
24
+ */
25
+ export declare function callTool(name: string, args: Record<string, unknown>, token: string, url?: string, timeoutMs?: number): Promise<ToolResult>;
26
+ /**
27
+ * Calls one tool on the gateway and returns its text, throwing when the tool reports an error.
28
+ *
29
+ * @param {string} name - Tool name.
30
+ * @param {object} args - Tool arguments.
31
+ * @param {string} token - Bearer token for the gateway.
32
+ * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
33
+ * @param {number} [timeoutMs] - Time before the request fails.
34
+ * @returns {Promise<string>} The tool's text content.
35
+ * @throws {Error} With the tool's text when it reports an error, or on a failed request.
36
+ */
37
+ export declare function callToolText(name: string, args: object, token: string, url?: string, timeoutMs?: number): Promise<string>;
38
+ /**
39
+ * A tool reply without the server's trailing footer lines (`Credits: ...`), for replies that are parsed
40
+ * (a link, JSON) rather than shown.
41
+ *
42
+ * @param {string} text - Tool reply.
43
+ * @returns {string} The reply body, trimmed.
44
+ */
45
+ export declare function replyBody(text: string): string;
46
+ /**
47
+ * Lists the tools the gateway token can reach (the gateway applies its allow/deny policy).
48
+ *
49
+ * @param {string} token - Bearer token for the gateway.
50
+ * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
51
+ * @returns {Promise<ToolInfo[]>} Name, description and input schema of each tool.
52
+ * @throws {Error} On HTTP errors or a JSON-RPC error reply.
53
+ */
54
+ export declare function listTools(token: string, url?: string): Promise<ToolInfo[]>;
55
+ /**
56
+ * Extracts the JSON-RPC `result` from a gateway reply (plain JSON or an SSE stream).
57
+ *
58
+ * @param {string} body - Raw response body.
59
+ * @returns {any} The reply's `result`.
60
+ * @throws {Error} When the reply holds no JSON-RPC response or carries an error.
61
+ *
62
+ * @example
63
+ * parseRpcReply('data: {"jsonrpc":"2.0","id":1,"result":{"tools":[]}}'); // { tools: [] }
64
+ */
65
+ export declare function parseRpcReply(body: string): any;
66
+ /**
67
+ * Joins a `tools/call` result's text content.
68
+ *
69
+ * @param {any} result - The JSON-RPC result of `tools/call`.
70
+ * @returns {ToolResult} The joined text content and error flag.
71
+ */
72
+ export declare function toToolResult(result: any): ToolResult;
73
+ /**
74
+ * Reads the gateway token and endpoint from TURINGCODE_TOKEN and TURINGCODE_URL.
75
+ *
76
+ * @returns {{token: string, url: string}} The token and gateway URL.
77
+ * @throws {Error} When TURINGCODE_TOKEN is not set.
78
+ */
79
+ export declare function getGatewayConfig(): {
80
+ token: string;
81
+ url: string;
82
+ };
83
+ /**
84
+ * Runs a server command: calls the tool with the gateway token from
85
+ * TURINGCODE_TOKEN and prints its text; a tool error sets exit code 1.
86
+ *
87
+ * @param {string} name - Tool name.
88
+ * @param {Record<string, unknown>} args - Tool arguments; undefined entries are dropped.
89
+ * @returns {Promise<void>} Resolves once the reply is printed.
90
+ * @throws {Error} When TURINGCODE_TOKEN is not set, or the gateway call fails.
91
+ */
92
+ export declare function runServerTool(name: string, args: Record<string, unknown>): Promise<void>;
package/dist/core/mcp.js CHANGED
@@ -6,6 +6,7 @@ export const TOKEN_HELP = [
6
6
  "`export TURINGCODE_TOKEN=<token>` to ~/.bashrc or ~/.zshrc and open a new shell",
7
7
  "(Windows: `setx TURINGCODE_TOKEN <token>`, then a new terminal). For an AI agent, set it in the",
8
8
  "agent's environment settings (e.g. \"env\" in Claude Code's settings.json). Keep it out of repositories.",
9
+ "Or put `TURINGCODE_TOKEN=<token>` in a git-ignored .env in the working directory; a set variable wins.",
9
10
  `TURINGCODE_URL overrides the gateway (default ${DEFAULT_URL}).`,
10
11
  ].join("\n");
11
12
  /**
@@ -18,27 +19,38 @@ export const TOKEN_HELP = [
18
19
  * @param {Record<string, unknown>} params - Method params.
19
20
  * @param {string} token - Bearer token for the gateway.
20
21
  * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
22
+ * @param {number} [timeoutMs=125000] - Time before the request fails; one HTTP 429 reply is retried after 2 s.
21
23
  * @returns {Promise<any>} The reply's `result`.
22
- * @throws {Error} When the gateway cannot be reached, on HTTP errors, or on a JSON-RPC error reply.
24
+ * @throws {Error} When the gateway cannot be reached or times out, on HTTP errors, or on a JSON-RPC error reply.
23
25
  */
24
- async function postGateway(method, params, token, url = DEFAULT_URL) {
26
+ async function postGateway(method, params, token, url = DEFAULT_URL, timeoutMs = 125_000) {
27
+ const post = () => fetch(url, {
28
+ method: "POST",
29
+ headers: {
30
+ "Authorization": `Bearer ${token}`,
31
+ "Content-Type": "application/json",
32
+ "Accept": "application/json, text/event-stream",
33
+ },
34
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
35
+ signal: AbortSignal.timeout(timeoutMs),
36
+ });
25
37
  let response;
38
+ let body;
26
39
  try {
27
- response = await fetch(url, {
28
- method: "POST",
29
- headers: {
30
- "Authorization": `Bearer ${token}`,
31
- "Content-Type": "application/json",
32
- "Accept": "application/json, text/event-stream",
33
- },
34
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
35
- });
40
+ response = await post();
41
+ if (response.status === 429) {
42
+ await new Promise(resolve => setTimeout(resolve, 2000));
43
+ response = await post();
44
+ }
45
+ body = await response.text();
36
46
  }
37
47
  catch (e) {
48
+ if (e.name === "TimeoutError") {
49
+ throw new Error(`the gateway did not answer within ${timeoutMs / 1000} s (builds are incremental, so run it again)`);
50
+ }
38
51
  const cause = e.cause;
39
52
  throw new Error(`cannot reach the gateway at ${url}: ${cause?.code ?? cause?.message ?? e.message}`);
40
53
  }
41
- const body = await response.text();
42
54
  if (!response.ok) {
43
55
  throw new Error(`gateway HTTP ${response.status}: ${body.trim() || response.statusText}`);
44
56
  }
@@ -51,11 +63,40 @@ async function postGateway(method, params, token, url = DEFAULT_URL) {
51
63
  * @param {Record<string, unknown>} args - Tool arguments.
52
64
  * @param {string} token - Bearer token for the gateway.
53
65
  * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
66
+ * @param {number} [timeoutMs=125000] - Time before the request fails.
54
67
  * @returns {Promise<ToolResult>} The tool's text content and error flag.
55
- * @throws {Error} On HTTP errors or a JSON-RPC error reply.
68
+ * @throws {Error} On HTTP errors, a timeout or a JSON-RPC error reply.
69
+ */
70
+ export async function callTool(name, args, token, url = DEFAULT_URL, timeoutMs) {
71
+ return toToolResult(await postGateway("tools/call", { name, arguments: args }, token, url, timeoutMs));
72
+ }
73
+ /**
74
+ * Calls one tool on the gateway and returns its text, throwing when the tool reports an error.
75
+ *
76
+ * @param {string} name - Tool name.
77
+ * @param {object} args - Tool arguments.
78
+ * @param {string} token - Bearer token for the gateway.
79
+ * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
80
+ * @param {number} [timeoutMs] - Time before the request fails.
81
+ * @returns {Promise<string>} The tool's text content.
82
+ * @throws {Error} With the tool's text when it reports an error, or on a failed request.
83
+ */
84
+ export async function callToolText(name, args, token, url = DEFAULT_URL, timeoutMs) {
85
+ const result = await callTool(name, args, token, url, timeoutMs);
86
+ if (result.isError) {
87
+ throw new Error(result.text);
88
+ }
89
+ return result.text;
90
+ }
91
+ /**
92
+ * A tool reply without the server's trailing footer lines (`Credits: ...`), for replies that are parsed
93
+ * (a link, JSON) rather than shown.
94
+ *
95
+ * @param {string} text - Tool reply.
96
+ * @returns {string} The reply body, trimmed.
56
97
  */
57
- export async function callTool(name, args, token, url = DEFAULT_URL) {
58
- return toToolResult(await postGateway("tools/call", { name, arguments: args }, token, url));
98
+ export function replyBody(text) {
99
+ return text.trim().replace(/(\r?\n\s*Credits:[^\n]*)+$/, "").trim();
59
100
  }
60
101
  /**
61
102
  * Lists the tools the gateway token can reach (the gateway applies its allow/deny policy).
@@ -0,0 +1,69 @@
1
+ /** A MongoDB-style query. */
2
+ export type Query = Record<string, unknown>;
3
+ /** A cell as a query sees it: text, `true`/`false` for booleans, items for lists, null when missing. */
4
+ export type Value = string | boolean | string[] | null;
5
+ /** A row as a query sees it: column name -> value. */
6
+ export type Doc = Record<string, Value>;
7
+ /** Operators that need the caller's data (other tables, the document text, exact arithmetic over the row). */
8
+ export interface QueryHooks {
9
+ /** `$ref`: whether the value exists in the referenced column. */
10
+ ref(ref: string, value: string): boolean;
11
+ /** `$mentioned`: whether the value is mentioned in the targets. */
12
+ mentioned(targets: string[], value: string): boolean;
13
+ /** `$calc`: whether the comparison holds for the row (true when it cannot be evaluated). */
14
+ calc(param: unknown, doc: Doc): boolean;
15
+ }
16
+ /** A query rewritten for sift, with what it uses and what is wrong with it. */
17
+ export interface PreparedQuery {
18
+ query: Query;
19
+ /** Column names the query reads. */
20
+ fields: string[];
21
+ /** Every `$ref` value. */
22
+ refs: string[];
23
+ /** Every `$mentioned` target. */
24
+ mentions: string[];
25
+ /** Every `$calc` parameter. */
26
+ calcs: unknown[];
27
+ /** Readable problems; the query must not be run when there are any. */
28
+ problems: string[];
29
+ }
30
+ /** Operators on one column's value. */
31
+ export declare const FIELD_OPERATORS: string[];
32
+ /** Operators on a whole row (besides column names). */
33
+ export declare const ROW_OPERATORS: string[];
34
+ /**
35
+ * Checks a row query and rewrites it for sift: a column's `$or`/`$and`/`$nor`
36
+ * is lifted to the row (sift allows them only there), and `$every`/`$length`
37
+ * sub-queries are prepared too.
38
+ *
39
+ * @param {unknown} query - The query from the contract.
40
+ * @returns {PreparedQuery} The rewritten query, what it uses and its problems.
41
+ *
42
+ * @example
43
+ * prepareQuery({ Kind: { $in: ["a", "b"] }, Qty: { $gte: 1 } }).fields; // ["Kind", "Qty"]
44
+ */
45
+ export declare function prepareQuery(query: unknown): PreparedQuery;
46
+ /**
47
+ * Compiles a prepared query into a row tester. `$unique` remembers the values
48
+ * it has seen, so run one tester over the rows in order.
49
+ *
50
+ * @param {Query} query - `prepareQuery(...).query` with no problems.
51
+ * @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
52
+ * @returns {(doc: Doc) => boolean} Whether a row matches.
53
+ * @throws {Error} When sift rejects the query, e.g. an invalid `$regex`.
54
+ *
55
+ * @example
56
+ * compileQuery(prepareQuery({ Qty: { $gte: 1 } }).query, hooks)({ Qty: "2" }); // true
57
+ */
58
+ export declare function compileQuery(query: Query, hooks: QueryHooks): (doc: Doc) => boolean;
59
+ /**
60
+ * Prepares and compiles a query in one step (for queries `contract check` already validated).
61
+ *
62
+ * @param {unknown} query - The query from the contract.
63
+ * @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
64
+ * @returns {(doc: Doc) => boolean} Whether a row matches.
65
+ *
66
+ * @example
67
+ * queryTester({ Qty: { $gte: 1 } }, hooks)({ Qty: "2" }); // true
68
+ */
69
+ export declare const queryTester: (query: unknown, hooks: QueryHooks) => ((doc: Doc) => boolean);
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Prints a tool result, as compact text or (with json) as one-line JSON,
3
+ * and sets the process exit code from its status.
4
+ *
5
+ * @param {{status: string}} result - The tool result.
6
+ * @param {string} text - Its compact text form.
7
+ * @param {boolean} [json] - Print the full JSON object instead.
8
+ */
9
+ export declare function report(result: {
10
+ status: string;
11
+ }, text: string, json?: boolean): void;