@turingcode/cli 0.2.13 → 0.3.5

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 (185) 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 +17 -4
  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/exact/fraction.js +2 -0
  11. package/dist/core/files.d.ts +44 -0
  12. package/dist/core/files.js +48 -3
  13. package/dist/core/json-shape.d.ts +45 -0
  14. package/dist/core/json-shape.js +1 -0
  15. package/dist/core/mcp.d.ts +92 -0
  16. package/dist/core/mcp.js +56 -15
  17. package/dist/core/query.d.ts +69 -0
  18. package/dist/core/query.js +2 -2
  19. package/dist/core/report.d.ts +11 -0
  20. package/dist/core/tables/csv.d.ts +29 -0
  21. package/dist/core/tables/csv.js +54 -25
  22. package/dist/core/tables/markdown.d.ts +22 -0
  23. package/dist/core/tables/markdown.js +8 -2
  24. package/dist/core/tables/types.d.ts +25 -0
  25. package/dist/features/contract/check.d.ts +30 -0
  26. package/dist/features/contract/command.d.ts +12 -0
  27. package/dist/features/contract/command.js +64 -64
  28. package/dist/features/contract/describe.d.ts +22 -0
  29. package/dist/features/contract/diagnostics.d.ts +111 -0
  30. package/dist/features/contract/diagnostics.js +7 -4
  31. package/dist/features/contract/load.d.ts +58 -0
  32. package/dist/features/contract/load.js +4 -4
  33. package/dist/features/contract/model.d.ts +67 -0
  34. package/dist/features/contract/rules.d.ts +149 -0
  35. package/dist/features/contract/rules.js +31 -4
  36. package/dist/features/debug/clear_breakpoint.d.ts +3 -0
  37. package/dist/features/debug/clear_breakpoint.js +24 -0
  38. package/dist/features/debug/command.d.ts +5 -0
  39. package/dist/features/debug/command.js +66 -0
  40. package/dist/features/debug/continue.d.ts +3 -0
  41. package/dist/features/debug/continue.js +22 -0
  42. package/dist/features/debug/debug_start.d.ts +3 -0
  43. package/dist/features/debug/debug_start.js +22 -0
  44. package/dist/features/debug/debug_stop.d.ts +3 -0
  45. package/dist/features/debug/debug_stop.js +11 -0
  46. package/dist/features/debug/evaluate.d.ts +3 -0
  47. package/dist/features/debug/evaluate.js +48 -0
  48. package/dist/features/debug/get_stack.d.ts +3 -0
  49. package/dist/features/debug/get_stack.js +14 -0
  50. package/dist/features/debug/get_variables.d.ts +3 -0
  51. package/dist/features/debug/get_variables.js +26 -0
  52. package/dist/features/debug/halt.d.ts +3 -0
  53. package/dist/features/debug/halt.js +16 -0
  54. package/dist/features/debug/set_breakpoint.d.ts +3 -0
  55. package/dist/features/debug/set_breakpoint.js +30 -0
  56. package/dist/features/debug/step.d.ts +3 -0
  57. package/dist/features/debug/step.js +23 -0
  58. package/dist/features/install-mods/command.d.ts +6 -0
  59. package/dist/features/install-mods/command.js +18 -0
  60. package/dist/features/install-mods/install.d.ts +23 -0
  61. package/dist/features/install-mods/install.js +49 -0
  62. package/dist/features/install-skills/command.d.ts +7 -0
  63. package/dist/features/install-skills/command.js +22 -0
  64. package/dist/features/install-skills/install.d.ts +14 -0
  65. package/dist/features/install-skills/install.js +29 -0
  66. package/dist/features/probe/command.d.ts +5 -0
  67. package/dist/features/probe/command.js +112 -0
  68. package/dist/features/probe/kill_all_debuggers.d.ts +3 -0
  69. package/dist/features/probe/kill_all_debuggers.js +50 -0
  70. package/dist/features/probe/list_probes.d.ts +3 -0
  71. package/dist/features/probe/list_probes.js +8 -0
  72. package/dist/features/probe/program_project.d.ts +3 -0
  73. package/dist/features/probe/program_project.js +29 -0
  74. package/dist/features/probe/read_fault_status.d.ts +3 -0
  75. package/dist/features/probe/read_fault_status.js +19 -0
  76. package/dist/features/probe/read_memory.d.ts +3 -0
  77. package/dist/features/probe/read_memory.js +36 -0
  78. package/dist/features/probe/read_peripheral.d.ts +3 -0
  79. package/dist/features/probe/read_peripheral.js +60 -0
  80. package/dist/features/probe/reset_probe_usb.d.ts +3 -0
  81. package/dist/features/probe/reset_probe_usb.js +17 -0
  82. package/dist/features/probe/reset_target.d.ts +3 -0
  83. package/dist/features/probe/reset_target.js +16 -0
  84. package/dist/features/probe/target_info.d.ts +3 -0
  85. package/dist/features/probe/target_info.js +34 -0
  86. package/dist/features/project/analysis_static.d.ts +3 -0
  87. package/dist/features/project/analysis_static.js +19 -0
  88. package/dist/features/project/analysis_syntax_check.d.ts +3 -0
  89. package/dist/features/project/analysis_syntax_check.js +21 -0
  90. package/dist/features/project/command.d.ts +5 -0
  91. package/dist/features/project/command.js +64 -0
  92. package/dist/features/project/project_build.d.ts +3 -0
  93. package/dist/features/project/project_build.js +22 -0
  94. package/dist/features/project/project_download_template.d.ts +3 -0
  95. package/dist/features/project/project_download_template.js +34 -0
  96. package/dist/features/project/project_regenerate.d.ts +2 -0
  97. package/dist/features/project/project_regenerate.js +20 -0
  98. package/dist/features/project/project_sync_from_server.d.ts +2 -0
  99. package/dist/features/project/project_sync_from_server.js +13 -0
  100. package/dist/features/project/project_sync_to_server.d.ts +2 -0
  101. package/dist/features/project/project_sync_to_server.js +51 -0
  102. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +3 -0
  103. package/dist/features/project/stm32_cubetools_download_drivers.js +19 -0
  104. package/dist/features/status/command.d.ts +2 -0
  105. package/dist/features/status/command.js +6 -0
  106. package/dist/features/status/get_status.d.ts +3 -0
  107. package/dist/features/status/get_status.js +44 -0
  108. package/dist/features/table/check.d.ts +38 -0
  109. package/dist/features/table/check.js +5 -5
  110. package/dist/features/table/command.d.ts +3 -0
  111. package/dist/features/table/read.d.ts +28 -0
  112. package/dist/features/table/read.js +9 -9
  113. package/dist/features/tool/command.d.ts +35 -0
  114. package/dist/features/tool/command.js +95 -66
  115. package/dist/lib.d.ts +15 -0
  116. package/dist/lib.js +11 -0
  117. package/dist/stm32/actions/DebugAction.d.ts +65 -0
  118. package/dist/stm32/actions/DebugAction.js +106 -0
  119. package/dist/stm32/actions/DebugActionInfo.d.ts +11 -0
  120. package/dist/stm32/actions/DebugActionInfo.js +11 -0
  121. package/dist/stm32/actions/DebugActionListProbes.d.ts +10 -0
  122. package/dist/stm32/actions/DebugActionListProbes.js +10 -0
  123. package/dist/stm32/actions/DebugActionProgram.d.ts +34 -0
  124. package/dist/stm32/actions/DebugActionProgram.js +81 -0
  125. package/dist/stm32/actions/DebugActionRead.d.ts +39 -0
  126. package/dist/stm32/actions/DebugActionRead.js +61 -0
  127. package/dist/stm32/actions/DebugActionReset.d.ts +12 -0
  128. package/dist/stm32/actions/DebugActionReset.js +9 -0
  129. package/dist/stm32/actions/DebugActionServer.d.ts +11 -0
  130. package/dist/stm32/actions/DebugActionServer.js +11 -0
  131. package/dist/stm32/analysis.d.ts +20 -0
  132. package/dist/stm32/analysis.js +21 -0
  133. package/dist/stm32/build.d.ts +34 -0
  134. package/dist/stm32/build.js +79 -0
  135. package/dist/stm32/context.d.ts +23 -0
  136. package/dist/stm32/context.js +42 -0
  137. package/dist/stm32/daemon.d.ts +65 -0
  138. package/dist/stm32/daemon.js +209 -0
  139. package/dist/stm32/regen.d.ts +68 -0
  140. package/dist/stm32/regen.js +231 -0
  141. package/dist/stm32/session.d.ts +137 -0
  142. package/dist/stm32/session.js +375 -0
  143. package/dist/stm32/sync.d.ts +25 -0
  144. package/dist/stm32/sync.js +74 -0
  145. package/dist/stm32/tool.d.ts +45 -0
  146. package/dist/stm32/tool.js +20 -0
  147. package/dist/stm32/toolCommand.d.ts +50 -0
  148. package/dist/stm32/toolCommand.js +100 -0
  149. package/dist/stm32/utils/discover_tools.d.ts +25 -0
  150. package/dist/stm32/utils/discover_tools.js +121 -0
  151. package/dist/stm32/utils/downloadzip_utils.d.ts +57 -0
  152. package/dist/stm32/utils/downloadzip_utils.js +180 -0
  153. package/dist/stm32/utils/faultUtils.d.ts +15 -0
  154. package/dist/stm32/utils/faultUtils.js +69 -0
  155. package/dist/stm32/utils/findElf.d.ts +9 -0
  156. package/dist/stm32/utils/findElf.js +19 -0
  157. package/dist/stm32/utils/hash_utils.d.ts +19 -0
  158. package/dist/stm32/utils/hash_utils.js +28 -0
  159. package/dist/stm32/utils/listSyncFiles.d.ts +9 -0
  160. package/dist/stm32/utils/listSyncFiles.js +100 -0
  161. package/dist/stm32/utils/mcu_utils.d.ts +58 -0
  162. package/dist/stm32/utils/mcu_utils.js +100 -0
  163. package/dist/stm32/utils/project_utils.d.ts +54 -0
  164. package/dist/stm32/utils/project_utils.js +104 -0
  165. package/dist/stm32/utils/svdUtils.d.ts +31 -0
  166. package/dist/stm32/utils/svdUtils.js +30 -0
  167. package/dist/stm32/utils/truncate.d.ts +7 -0
  168. package/dist/stm32/utils/truncate.js +9 -0
  169. package/dist/stm32/utils/usb_utils.d.ts +5 -0
  170. package/dist/stm32/utils/usb_utils.js +23 -0
  171. package/dist/stm32/utils/user_code.d.ts +17 -0
  172. package/dist/stm32/utils/user_code.js +45 -0
  173. package/dist/stm32/utils/utils_mutex.d.ts +15 -0
  174. package/dist/stm32/utils/utils_mutex.js +113 -0
  175. package/dist/stm32/validate.d.ts +17 -0
  176. package/dist/stm32/validate.js +46 -0
  177. package/mods/claude/.claude-plugin/marketplace.json +8 -0
  178. package/mods/claude/turingcode-skills/.claude-plugin/plugin.json +5 -0
  179. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +44 -0
  180. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +47 -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 +21 -0
  184. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +35 -0
  185. package/package.json +11 -3
@@ -0,0 +1,65 @@
1
+ import { ToolDef } from './tool.js';
2
+ export interface DaemonPaths {
3
+ dir: string; /** <project>/.turingcode */
4
+ token: string;
5
+ socket: string;
6
+ lock: string; /** probe lock file, see utils_mutex */
7
+ log: string; /** the daemon's stderr, for start failures */
8
+ }
9
+ /** One request and one response per line, newline-delimited JSON. */
10
+ export interface DaemonRequest {
11
+ id: number;
12
+ token: string;
13
+ cwd: string; /** the CLI's working directory */
14
+ tool: string;
15
+ args: Record<string, unknown>;
16
+ }
17
+ export type DaemonResponse = {
18
+ id: number;
19
+ ok: true;
20
+ text: string;
21
+ } | {
22
+ id: number;
23
+ ok: false;
24
+ error: string;
25
+ };
26
+ export declare const PING = "ping"; /** reserved tool: replies {"session": <true while a debug session runs>} */
27
+ /**
28
+ * Daemon files of one project, all inside <project>/.turingcode. Windows paths are lowercased so "c:" and "C:" give the same pipe.
29
+ * shortcut: Unix socket paths are limited to ~104 chars, so a very deep project folder fails to listen; move the socket to a short dir if that bites.
30
+ * @param root project root
31
+ * @returns the daemon's folder, token file, socket and probe lock file
32
+ */
33
+ export declare function daemonPaths(root: string): DaemonPaths;
34
+ /**
35
+ * Sends one tool call to the project's daemon.
36
+ * @param paths daemon files of the project
37
+ * @param tool tool name, or PING
38
+ * @param args tool arguments
39
+ * @param cwd the caller's working directory
40
+ * @returns the daemon's response, an error response when it closed the connection after the request was sent, or
41
+ * undefined when no daemon is running (the request was never sent)
42
+ */
43
+ export declare function forwardToDaemon(paths: DaemonPaths, tool: string, args: Record<string, unknown>, cwd: string): Promise<DaemonResponse | undefined>;
44
+ /**
45
+ * Asks the project's daemon whether it runs and holds a debug session.
46
+ * @param paths daemon files of the project
47
+ * @returns undefined when no daemon answers, else whether a debug session is active
48
+ */
49
+ export declare function pingDaemon(paths: DaemonPaths): Promise<{
50
+ session: boolean;
51
+ } | undefined>;
52
+ /**
53
+ * Launches the project's daemon in the background and waits until it answers.
54
+ * @param root project root; the daemon runs with it as its working directory
55
+ * @throws when the daemon does not answer within START_TIMEOUT_MS, with the end of its log
56
+ */
57
+ export declare function startDaemon(root: string): Promise<void>;
58
+ /**
59
+ * Runs the daemon for a project until it is idle without a debug session: serves the given tools over the socket,
60
+ * one request at a time per connection, with the probe lock file held while the probe is in use.
61
+ * @param root project root
62
+ * @param tools the tools the daemon may run
63
+ * @returns resolves once the daemon has stopped
64
+ */
65
+ export declare function runDaemon(root: string, tools: ToolDef[]): Promise<void>;
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Debug daemon: a background turingcode process per project that holds the probe-rs debug session between CLI runs.
3
+ * `debug start` launches it; probe and debug commands forward their tool call to it over a user-only local socket
4
+ * (Unix socket in <project>/.turingcode, a per-user, per-project named pipe on Windows; access is checked with the
5
+ * token file next to it). It exits on its own once no debug session is running.
6
+ */
7
+ import { spawn } from 'node:child_process';
8
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
9
+ import { closeSync, mkdirSync, openSync } from 'node:fs';
10
+ import { chmod, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
11
+ import { connect, createServer } from 'node:net';
12
+ import { userInfo } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { debugSessionActive, stopSession } from './session.js';
16
+ import { sha256 } from './utils/hash_utils.js';
17
+ import { setProbeLockFile } from './utils/utils_mutex.js';
18
+ import { safetyCheck, validateArgs } from './validate.js';
19
+ export const PING = 'ping'; /** reserved tool: replies {"session": <true while a debug session runs>} */
20
+ const IDLE_EXIT_MS = 5000; /** the daemon exits once no request ran for this long without a debug session */
21
+ const START_TIMEOUT_MS = 10_000;
22
+ /**
23
+ * Daemon files of one project, all inside <project>/.turingcode. Windows paths are lowercased so "c:" and "C:" give the same pipe.
24
+ * shortcut: Unix socket paths are limited to ~104 chars, so a very deep project folder fails to listen; move the socket to a short dir if that bites.
25
+ * @param root project root
26
+ * @returns the daemon's folder, token file, socket and probe lock file
27
+ */
28
+ export function daemonPaths(root) {
29
+ const dir = join(root, '.turingcode');
30
+ const id = sha256(process.platform === 'win32' ? dir.toLowerCase() : dir).slice(0, 16);
31
+ const socket = process.platform === 'win32' ? `\\\\.\\pipe\\turingcode-daemon-${userInfo().username}-${id}` : join(dir, 'daemon.sock');
32
+ return { dir, token: join(dir, 'daemon.token'), socket, lock: join(dir, 'probe.lock'), log: join(dir, 'daemon.log') };
33
+ }
34
+ /**
35
+ * Sends one tool call to the project's daemon.
36
+ * @param paths daemon files of the project
37
+ * @param tool tool name, or PING
38
+ * @param args tool arguments
39
+ * @param cwd the caller's working directory
40
+ * @returns the daemon's response, an error response when it closed the connection after the request was sent, or
41
+ * undefined when no daemon is running (the request was never sent)
42
+ */
43
+ export async function forwardToDaemon(paths, tool, args, cwd) {
44
+ const token = (await readFile(paths.token, 'utf8').catch(() => '')).trim();
45
+ if (!token)
46
+ return undefined;
47
+ const req = { id: 1, token, cwd, tool, args };
48
+ return new Promise((resolve) => {
49
+ const sock = connect(paths.socket);
50
+ let buf = '';
51
+ let sent = false; /** once sent, a close without reply is a daemon failure, not "no daemon": running locally would repeat the command */
52
+ sock.setEncoding('utf8');
53
+ sock.on('connect', () => {
54
+ sent = true;
55
+ sock.write(JSON.stringify(req) + '\n');
56
+ });
57
+ sock.on('data', (d) => {
58
+ buf += d;
59
+ const nl = buf.indexOf('\n');
60
+ if (nl < 0)
61
+ return;
62
+ sock.end();
63
+ try {
64
+ resolve(JSON.parse(buf.slice(0, nl)));
65
+ }
66
+ catch {
67
+ resolve({ id: 1, ok: false, error: 'Bad reply from the debug daemon' });
68
+ }
69
+ });
70
+ sock.on('error', () => { }); /** close follows */
71
+ sock.on('close', () => resolve(sent ? { id: 1, ok: false, error: 'The debug daemon closed the connection before replying' } : undefined));
72
+ });
73
+ }
74
+ /**
75
+ * Asks the project's daemon whether it runs and holds a debug session.
76
+ * @param paths daemon files of the project
77
+ * @returns undefined when no daemon answers, else whether a debug session is active
78
+ */
79
+ export async function pingDaemon(paths) {
80
+ const res = await forwardToDaemon(paths, PING, {}, process.cwd());
81
+ return res?.ok ? JSON.parse(res.text) : undefined;
82
+ }
83
+ /**
84
+ * Launches the project's daemon in the background and waits until it answers.
85
+ * @param root project root; the daemon runs with it as its working directory
86
+ * @throws when the daemon does not answer within START_TIMEOUT_MS, with the end of its log
87
+ */
88
+ export async function startDaemon(root) {
89
+ const cli = fileURLToPath(new URL('../cli/index.js', import.meta.url));
90
+ const paths = daemonPaths(root);
91
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
92
+ const log = openSync(paths.log, 'w');
93
+ try {
94
+ spawn(process.execPath, [cli, 'debug', 'daemon', '--root', root], { cwd: root, detached: true, stdio: ['ignore', 'ignore', log], windowsHide: true }).unref();
95
+ }
96
+ finally {
97
+ closeSync(log);
98
+ }
99
+ for (const end = Date.now() + START_TIMEOUT_MS; Date.now() < end; await new Promise((r) => setTimeout(r, 100)))
100
+ if (await pingDaemon(paths))
101
+ return;
102
+ const tail = (await readFile(paths.log, 'utf8').catch(() => '')).trim().slice(-1500);
103
+ throw new Error(`The debug daemon did not start within ${START_TIMEOUT_MS / 1000} s${tail ? `:
104
+ ${tail}` : ''}`);
105
+ }
106
+ /**
107
+ * Runs the daemon for a project until it is idle without a debug session: serves the given tools over the socket,
108
+ * one request at a time per connection, with the probe lock file held while the probe is in use.
109
+ * @param root project root
110
+ * @param tools the tools the daemon may run
111
+ * @returns resolves once the daemon has stopped
112
+ */
113
+ export async function runDaemon(root, tools) {
114
+ const paths = daemonPaths(root);
115
+ const byName = new Map(tools.map((t) => [t.name, t]));
116
+ await mkdir(paths.dir, { recursive: true, mode: 0o700 });
117
+ if (process.platform !== 'win32')
118
+ await chmod(paths.dir, 0o700);
119
+ if (await pingDaemon(paths))
120
+ return; /** another daemon serves this project */
121
+ if (process.platform !== 'win32')
122
+ await unlink(paths.socket).catch(() => { }); /** stale socket of a crashed daemon */
123
+ setProbeLockFile(paths.lock);
124
+ const token = randomBytes(32).toString('hex');
125
+ let running = 0;
126
+ let lastActivity = Date.now();
127
+ let stopping = false; /** set once idle: requests on still-open connections are dropped, so no session starts in a closing daemon */
128
+ /** Checks the token and arguments, then runs one tool call. */
129
+ const handle = async (req) => {
130
+ const given = Buffer.from(String(req.token));
131
+ if (given.length !== token.length || !timingSafeEqual(given, Buffer.from(token)))
132
+ return { id: req.id, ok: false, error: 'Bad token' };
133
+ if (req.tool === PING)
134
+ return { id: req.id, ok: true, text: JSON.stringify({ session: debugSessionActive() }) };
135
+ const def = byName.get(req.tool);
136
+ if (!def)
137
+ return { id: req.id, ok: false, error: `Unknown tool: ${req.tool}` };
138
+ const invalid = validateArgs(def, req.args) ?? safetyCheck(def, debugSessionActive());
139
+ if (invalid)
140
+ return { id: req.id, ok: false, error: invalid };
141
+ const ctx = { cwd: typeof req.cwd === 'string' ? req.cwd : root, socketPath: paths.socket, debugActive: debugSessionActive };
142
+ running++;
143
+ try {
144
+ return { id: req.id, ok: true, text: await def.run(req.args, ctx) };
145
+ }
146
+ catch (e) {
147
+ return { id: req.id, ok: false, error: e?.message ?? String(e) };
148
+ }
149
+ finally {
150
+ running--;
151
+ lastActivity = Date.now();
152
+ }
153
+ };
154
+ const server = createServer((sock) => {
155
+ let buf = '';
156
+ let queue = Promise.resolve(); /** replies go out in request order */
157
+ sock.setEncoding('utf8');
158
+ sock.on('error', () => { });
159
+ sock.on('data', (d) => {
160
+ if (stopping)
161
+ return sock.destroy();
162
+ buf += d;
163
+ if (buf.length > 1_000_000)
164
+ return sock.destroy();
165
+ let nl;
166
+ while ((nl = buf.indexOf('\n')) >= 0) {
167
+ const line = buf.slice(0, nl);
168
+ buf = buf.slice(nl + 1);
169
+ queue = queue.then(async () => {
170
+ let res;
171
+ try {
172
+ const req = JSON.parse(line);
173
+ res = req && typeof req === 'object' ? await handle(req) : { id: 0, ok: false, error: 'Bad request' };
174
+ }
175
+ catch {
176
+ res = { id: 0, ok: false, error: 'Bad request' };
177
+ }
178
+ if (!sock.destroyed)
179
+ sock.write(JSON.stringify(res) + '\n');
180
+ });
181
+ }
182
+ });
183
+ });
184
+ try {
185
+ await new Promise((resolve, reject) => (server.once('error', reject), server.listen(paths.socket, resolve)));
186
+ }
187
+ catch {
188
+ return; /** another daemon won the race to listen; its token file stays untouched */
189
+ }
190
+ if (process.platform !== 'win32')
191
+ await chmod(paths.socket, 0o600);
192
+ /** The token goes in only once listening, by rename, so clients never read a half-written or another daemon's token. */
193
+ const tmp = `${paths.token}.${process.pid}`;
194
+ await writeFile(tmp, token, { mode: 0o600 });
195
+ await rename(tmp, paths.token);
196
+ await new Promise((resolve) => {
197
+ const timer = setInterval(() => {
198
+ if (running || debugSessionActive() || Date.now() - lastActivity < IDLE_EXIT_MS)
199
+ return;
200
+ clearInterval(timer);
201
+ resolve();
202
+ }, 500);
203
+ });
204
+ stopping = true;
205
+ const closed = new Promise((resolve) => server.close(() => resolve())); /** stops accepting now, frees the socket name */
206
+ await unlink(paths.token).catch(() => { });
207
+ await stopSession();
208
+ await closed;
209
+ }
@@ -0,0 +1,68 @@
1
+ import { ServerCall } from './sync.js';
2
+ import { Project } from './tool.js';
3
+ /**
4
+ * Returns the folder holding the baseline: each generated file with its USER CODE section bodies emptied.
5
+ * @param root STM32 project root
6
+ * @returns the baseline folder
7
+ */
8
+ export declare function baselineDir(root: string): string;
9
+ /**
10
+ * Replaces the body of every well-formed USER CODE section of a file.
11
+ * @param text file contents
12
+ * @param body gets the section name and current body, returns the new body
13
+ * @returns the new contents
14
+ */
15
+ export declare function mapUserSections(text: string, body: (name: string, old: string) => string): string;
16
+ /**
17
+ * Saves the baseline: every file with USER CODE markers, with its section bodies emptied, and the .ioc as it is (to
18
+ * tell later which side changed it). Call it right after CubeMX output reached the project (template, create, regen).
19
+ * shortcut: user-written files with markers are saved too, so later edits outside their sections are reported
20
+ * even though CubeMX leaves those files alone; skip files CubeMX does not generate if that gets noisy.
21
+ * @param root STM32 project root
22
+ * @returns the number of files with markers saved
23
+ */
24
+ export declare function recordBaseline(root: string): Promise<number>;
25
+ /**
26
+ * Makes sure the regen uses the newest .ioc: the sync before it would otherwise overwrite an .ioc that a server
27
+ * tool (pins, clocks, set_params) changed. Takes the server's .ioc when only the server changed it since the baseline,
28
+ * keeps the local one (the sync sends it) when only it changed.
29
+ * @param call server tool caller
30
+ * @param project STM32 project root and name
31
+ * @returns a note per .ioc taken from the server
32
+ * @throws when both sides changed the .ioc, or it differs and there is no baseline to tell which side did
33
+ */
34
+ export declare function takeServerIoc(call: ServerCall, project: Project): Promise<string[]>;
35
+ /**
36
+ * Finds the code a regen would remove from the local files, before running it: broken USER CODE markers, and code
37
+ * outside the sections that differs from the baseline.
38
+ * @param root STM32 project root
39
+ * @returns one diff or message per affected file (broken markers first), the broken-marker messages alone, the local
40
+ * marked files, and those without a baseline
41
+ */
42
+ export declare function checkBeforeRegen(root: string): Promise<{
43
+ findings: string[];
44
+ broken: string[];
45
+ local: Map<string, string>;
46
+ unbaselined: Set<string>;
47
+ }>;
48
+ /**
49
+ * Finds the code a regen removed, comparing a local file with the regenerated one: USER CODE sections with code that
50
+ * no longer exist (e.g. a peripheral was removed), and, for files without a baseline, every change regen made.
51
+ * @param f posix relative path, for the headers
52
+ * @param local local contents
53
+ * @param regenerated contents after regen
54
+ * @param hasBaseline false: show the whole diff, since your code cannot be told apart from CubeMX's changes
55
+ * @returns the diff, or "" when nothing is removed
56
+ */
57
+ export declare function checkAfterRegen(f: string, local: string, regenerated: string, hasBaseline: boolean): string;
58
+ /**
59
+ * Regenerates the project's code from its .ioc on the server and pulls the result, refusing to remove local code:
60
+ * checks the local files, takes the server's .ioc if only it changed, syncs the files up, regenerates, checks the
61
+ * regenerated files before overwriting local ones, pulls them and saves a new baseline.
62
+ * @param call server tool caller
63
+ * @param project STM32 project root and name
64
+ * @param force regenerate and pull even when code would be removed (the removed code is still shown)
65
+ * @returns the removed code (with force), then the sync, regen and pull summaries
66
+ * @throws with the code that would be removed when force is not set; nothing local changes then
67
+ */
68
+ export declare function regenerateProject(call: ServerCall, project: Project, force?: boolean): Promise<string>;
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Safe CubeMX regeneration: CubeMX keeps only the code inside USER CODE sections, so before a regen this compares each
3
+ * file that has USER CODE markers with the version CubeMX generated last time (the baseline in .turingcode/generated/)
4
+ * and shows, as a diff, the code that regen would remove. Used by `turingcode project regen` and, as a library, by the
5
+ * VS Code extension.
6
+ */
7
+ import { copyFile, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
8
+ import { dirname, join } from 'node:path';
9
+ import { scanUserSections } from './utils/user_code.js';
10
+ import { syncProjectFromServer, syncProjectToServer } from './sync.js';
11
+ import { formatPatch, structuredPatch } from 'diff';
12
+ import { extractZip } from './utils/downloadzip_utils.js';
13
+ import { listSyncFiles } from './utils/listSyncFiles.js';
14
+ const MARKER = /\/\*\s*USER CODE BEGIN/;
15
+ /**
16
+ * Builds a unified diff of two texts with jsdiff.
17
+ * @param a old text
18
+ * @param b new text
19
+ * @param nameA header label of a
20
+ * @param nameB header label of b
21
+ * @returns the diff without jsdiff's ==== line, or "" when the texts are equal
22
+ */
23
+ function unifiedDiff(a, b, nameA, nameB) {
24
+ const patch = structuredPatch(nameA, nameB, a, b, undefined, undefined, { context: 3 });
25
+ return patch.hunks.length ? formatPatch(patch).replace(/^=+\n/, '').trimEnd() : '';
26
+ }
27
+ /**
28
+ * Returns the folder holding the baseline: each generated file with its USER CODE section bodies emptied.
29
+ * @param root STM32 project root
30
+ * @returns the baseline folder
31
+ */
32
+ export function baselineDir(root) {
33
+ return join(root, '.turingcode', 'generated');
34
+ }
35
+ /**
36
+ * Replaces the body of every well-formed USER CODE section of a file.
37
+ * @param text file contents
38
+ * @param body gets the section name and current body, returns the new body
39
+ * @returns the new contents
40
+ */
41
+ export function mapUserSections(text, body) {
42
+ let out = '';
43
+ let at = 0;
44
+ for (const s of scanUserSections(text).sections) {
45
+ out += text.slice(at, s.start) + body(s.name, text.slice(s.start, s.end));
46
+ at = s.end;
47
+ }
48
+ return out + text.slice(at);
49
+ }
50
+ /**
51
+ * Reads the project's source files that have USER CODE markers (Drivers/ is skipped: CubeMX does not regenerate it).
52
+ * @param root STM32 project root
53
+ * @returns posix relative path -> contents with \n line endings
54
+ */
55
+ async function readMarkedFiles(root) {
56
+ const names = (await listSyncFiles(root)).filter((f) => /\.(c|h|cpp|hpp)$/.test(f) && !f.startsWith('Drivers/'));
57
+ const files = new Map();
58
+ for (const f of names) {
59
+ const text = (await readFile(join(root, f), 'utf8')).replace(/\r\n/g, '\n');
60
+ if (MARKER.test(text))
61
+ files.set(f, text);
62
+ }
63
+ return files;
64
+ }
65
+ /**
66
+ * Saves the baseline: every file with USER CODE markers, with its section bodies emptied, and the .ioc as it is (to
67
+ * tell later which side changed it). Call it right after CubeMX output reached the project (template, create, regen).
68
+ * shortcut: user-written files with markers are saved too, so later edits outside their sections are reported
69
+ * even though CubeMX leaves those files alone; skip files CubeMX does not generate if that gets noisy.
70
+ * @param root STM32 project root
71
+ * @returns the number of files with markers saved
72
+ */
73
+ export async function recordBaseline(root) {
74
+ const dir = baselineDir(root);
75
+ await rm(dir, { recursive: true, force: true });
76
+ await mkdir(dir, { recursive: true });
77
+ const files = await readMarkedFiles(root);
78
+ for (const [f, text] of files) {
79
+ await mkdir(dirname(join(dir, f)), { recursive: true });
80
+ await writeFile(join(dir, f), mapUserSections(text, () => ''));
81
+ }
82
+ for (const f of (await readdir(root)).filter((f) => f.endsWith('.ioc')))
83
+ await copyFile(join(root, f), join(dir, f));
84
+ return files.size;
85
+ }
86
+ /**
87
+ * Makes sure the regen uses the newest .ioc: the sync before it would otherwise overwrite an .ioc that a server
88
+ * tool (pins, clocks, set_params) changed. Takes the server's .ioc when only the server changed it since the baseline,
89
+ * keeps the local one (the sync sends it) when only it changed.
90
+ * @param call server tool caller
91
+ * @param project STM32 project root and name
92
+ * @returns a note per .ioc taken from the server
93
+ * @throws when both sides changed the .ioc, or it differs and there is no baseline to tell which side did
94
+ */
95
+ export async function takeServerIoc(call, project) {
96
+ const { root } = project;
97
+ const notes = [];
98
+ const tmp = join(root, '.turingcode', `ioc-${process.pid}`);
99
+ /** A pull that is always cancelled: it only fetches the server's versions of the files that differ. */
100
+ await syncProjectFromServer(call, project, async (files, zip) => {
101
+ const iocs = files.filter((f) => f.endsWith('.ioc'));
102
+ if (!iocs.length)
103
+ return false;
104
+ await extractZip(zip, tmp);
105
+ try {
106
+ for (const f of iocs) {
107
+ const mine = await readFile(join(root, f));
108
+ const theirs = await readFile(join(tmp, f));
109
+ const base = await readFile(join(baselineDir(root), f)).catch(() => undefined);
110
+ if (base?.equals(theirs))
111
+ continue;
112
+ if (!base?.equals(mine))
113
+ throw new Error(`${f} differs from the server's, and ${base ? 'both were changed since the last regen' : 'there is no baseline to tell which side changed it'}. ` +
114
+ 'Run `turingcode project pull` to take the server\'s version or `turingcode project sync` to keep yours, then regen.');
115
+ await writeFile(join(root, f), theirs);
116
+ notes.push(`Took the server's ${f}: it was changed there (e.g. by a pin or clock tool), not here.`);
117
+ }
118
+ }
119
+ finally {
120
+ await rm(tmp, { recursive: true, force: true });
121
+ }
122
+ return false;
123
+ });
124
+ return notes;
125
+ }
126
+ /**
127
+ * Finds the code a regen would remove from the local files, before running it: broken USER CODE markers, and code
128
+ * outside the sections that differs from the baseline.
129
+ * @param root STM32 project root
130
+ * @returns one diff or message per affected file (broken markers first), the broken-marker messages alone, the local
131
+ * marked files, and those without a baseline
132
+ */
133
+ export async function checkBeforeRegen(root) {
134
+ const local = await readMarkedFiles(root);
135
+ const findings = [];
136
+ const broken = [];
137
+ const unbaselined = new Set();
138
+ for (const [f, text] of local) {
139
+ const errors = scanUserSections(text).errors;
140
+ if (errors.length)
141
+ broken.push(`${f}: broken USER CODE markers, CubeMX may drop the code around them:\n${errors.join('\n')}`);
142
+ const base = await readFile(join(baselineDir(root), f), 'utf8').catch(() => undefined);
143
+ if (base === undefined) {
144
+ unbaselined.add(f);
145
+ continue;
146
+ }
147
+ const bodies = new Map(scanUserSections(text).sections.map((s) => [s.name, text.slice(s.start, s.end)]));
148
+ const expected = mapUserSections(base, (name, old) => bodies.get(name) ?? old);
149
+ const diff = unifiedDiff(text, expected, `${f} (yours)`, `${f} (as CubeMX generates it)`);
150
+ if (diff)
151
+ findings.push(diff);
152
+ }
153
+ return { findings: [...broken, ...findings], broken, local, unbaselined };
154
+ }
155
+ /**
156
+ * Finds the code a regen removed, comparing a local file with the regenerated one: USER CODE sections with code that
157
+ * no longer exist (e.g. a peripheral was removed), and, for files without a baseline, every change regen made.
158
+ * @param f posix relative path, for the headers
159
+ * @param local local contents
160
+ * @param regenerated contents after regen
161
+ * @param hasBaseline false: show the whole diff, since your code cannot be told apart from CubeMX's changes
162
+ * @returns the diff, or "" when nothing is removed
163
+ */
164
+ export function checkAfterRegen(f, local, regenerated, hasBaseline) {
165
+ regenerated = regenerated.replace(/\r\n/g, '\n');
166
+ if (!hasBaseline) {
167
+ const diff = unifiedDiff(local, regenerated, `${f} (yours)`, `${f} (after regen)`);
168
+ return diff && `${f} has no baseline, so this is every change regen makes, yours and CubeMX's:\n${diff}`;
169
+ }
170
+ const kept = new Set(scanUserSections(regenerated).sections.map((s) => s.name));
171
+ const gone = (name, body) => !kept.has(name) && body.trim() !== '';
172
+ const diff = unifiedDiff(local, mapUserSections(local, (n, b) => (gone(n, b) ? '' : b)), `${f} (yours)`, `${f} (after regen)`);
173
+ return diff && `${f}: regen removes these USER CODE sections:\n${diff}`;
174
+ }
175
+ /**
176
+ * Regenerates the project's code from its .ioc on the server and pulls the result, refusing to remove local code:
177
+ * checks the local files, takes the server's .ioc if only it changed, syncs the files up, regenerates, checks the
178
+ * regenerated files before overwriting local ones, pulls them and saves a new baseline.
179
+ * @param call server tool caller
180
+ * @param project STM32 project root and name
181
+ * @param force regenerate and pull even when code would be removed (the removed code is still shown)
182
+ * @returns the removed code (with force), then the sync, regen and pull summaries
183
+ * @throws with the code that would be removed when force is not set; nothing local changes then
184
+ */
185
+ export async function regenerateProject(call, project, force = false) {
186
+ const { root, name } = project;
187
+ const { findings, local, unbaselined } = await checkBeforeRegen(root);
188
+ const head = '# Code outside USER CODE sections that regen removes (- lines are yours)';
189
+ if (findings.length && !force)
190
+ throw new Error([head, ...findings, 'Regen stopped, nothing changed. Move this code into USER CODE sections, or run `turingcode project regen --force` to regenerate anyway.'].join('\n\n'));
191
+ const iocNotes = await takeServerIoc(call, project);
192
+ const synced = [...iocNotes, await syncProjectToServer(call, project)].join('\n');
193
+ const regen = await call('project_regenerate', { project_name: name }, 125_000);
194
+ /** A failed regen comes back as plain text, not as a tool error; pulling then would save unregenerated files as the baseline. */
195
+ if (!/^# Regenerated project /m.test(regen))
196
+ throw new Error(`${regen.trim()}\n\nRegen failed on the server; your local files and the baseline are unchanged. Run it again.`);
197
+ const removed = [];
198
+ const tmp = join(root, '.turingcode', `regen-${process.pid}`);
199
+ const pulled = await syncProjectFromServer(call, project, async (files, zip) => {
200
+ await extractZip(zip, tmp);
201
+ try {
202
+ /** source files without markers too: their code would be overwritten without a USER CODE section to keep it */
203
+ for (const f of files.filter((x) => /\.(c|h|cpp|hpp)$/.test(x) && !x.startsWith('Drivers/'))) {
204
+ const mine = local.get(f) ?? (await readFile(join(root, f), 'utf8').catch(() => undefined))?.replace(/\r\n/g, '\n');
205
+ if (mine === undefined)
206
+ continue; /** new file from the server */
207
+ const diff = checkAfterRegen(f, mine, await readFile(join(tmp, f), 'utf8'), local.has(f) && !unbaselined.has(f));
208
+ if (diff)
209
+ removed.push(diff);
210
+ }
211
+ }
212
+ finally {
213
+ await rm(tmp, { recursive: true, force: true });
214
+ }
215
+ return force || !removed.length;
216
+ });
217
+ if (removed.length && !force)
218
+ throw new Error([
219
+ '# Code that regen removes (- lines are yours)',
220
+ ...removed,
221
+ 'Regen ran on the server, but your local files are unchanged. `turingcode project sync` puts your version back on the server; `turingcode project regen --force` regenerates and pulls anyway.',
222
+ ].join('\n\n'));
223
+ const saved = await recordBaseline(root);
224
+ const warning = [...findings, ...removed];
225
+ return [
226
+ ...(warning.length ? [`# Code that regen removed (- lines are yours)\n\nRegenerated anyway (--force); this code is gone from the local files.`, ...warning] : []),
227
+ `# Sync\n${synced}`,
228
+ `# Regen\n${regen.trim()}`,
229
+ `# Pull\n${pulled}\nSaved the generated code of ${saved} files as the baseline in .turingcode/generated/.`,
230
+ ].join('\n\n');
231
+ }