@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
@@ -0,0 +1,374 @@
1
+ // probe-rs debug session shared by the tools in this folder: a DAP client over `probe-rs dap-server` (stdio).
2
+ //
3
+ import { spawn } from 'node:child_process';
4
+ import { existsSync } from 'node:fs';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { isAbsolute, join, relative, resolve } from 'node:path';
7
+ import { claimProbe, releaseProbe } from './utils/utils_mutex.js';
8
+ import { DebugActionServer } from './actions/DebugActionServer.js';
9
+ export class DebugSession {
10
+ opts;
11
+ proc;
12
+ breakpoints = new Map(); // project-relative file (forward slashes) -> breakpoints
13
+ capabilities = {};
14
+ state = 'running';
15
+ stopReason = '';
16
+ threadId = 1;
17
+ seq = 1;
18
+ buf = Buffer.alloc(0);
19
+ pending = new Map();
20
+ waiters = [];
21
+ log = []; // probe-rs output and stderr, for error messages
22
+ elfData;
23
+ constructor(opts, proc) {
24
+ this.opts = opts;
25
+ this.proc = proc;
26
+ proc.stdin.on('error', () => undefined); // writes after probe-rs exited; onExit reports it
27
+ proc.stdout.on('data', (chunk) => this.onData(chunk));
28
+ proc.stderr.on('data', (chunk) => this.addLog(chunk.toString()));
29
+ proc.on('exit', (code) => this.onExit(`probe-rs dap-server exited (code ${code})`));
30
+ proc.on('error', (e) => this.onExit(`probe-rs dap-server failed: ${e.message}`));
31
+ }
32
+ /**
33
+ * Sends a DAP request and waits for its response.
34
+ * @param command DAP command (e.g. stackTrace)
35
+ * @param args request arguments
36
+ * @param timeout milliseconds before the request fails
37
+ * @returns the response body
38
+ */
39
+ request(command, args = {}, timeout = 10_000) {
40
+ if (session !== this)
41
+ return Promise.reject(new Error('The debug session has ended: run `turingcode debug start`'));
42
+ const seq = this.seq++;
43
+ const json = JSON.stringify({ seq, type: 'request', command, arguments: args });
44
+ return new Promise((resolve, reject) => {
45
+ const timer = setTimeout(() => {
46
+ this.pending.delete(seq);
47
+ reject(new Error(`${command} timed out${this.logTail()}`));
48
+ }, timeout);
49
+ this.pending.set(seq, { resolve, reject, timer });
50
+ this.proc.stdin.write(`Content-Length: ${Buffer.byteLength(json)}\r\n\r\n${json}`);
51
+ });
52
+ }
53
+ /**
54
+ * Waits for a DAP event.
55
+ * @param name event name (e.g. stopped)
56
+ * @param timeout milliseconds to wait
57
+ * @returns the event body, or undefined on timeout or when the session ends
58
+ */
59
+ waitEvent(name, timeout) {
60
+ return new Promise((resolve) => {
61
+ const waiter = {
62
+ name,
63
+ done: (body) => {
64
+ clearTimeout(timer);
65
+ this.waiters = this.waiters.filter((w) => w !== waiter);
66
+ resolve(body);
67
+ },
68
+ };
69
+ const timer = setTimeout(() => waiter.done(undefined), timeout);
70
+ this.waiters.push(waiter);
71
+ });
72
+ }
73
+ /**
74
+ * Throws unless the target is halted.
75
+ */
76
+ requireHalted() {
77
+ if (this.state !== 'halted')
78
+ throw new Error('The target is running: halt it first (or continue with wait until a breakpoint hits)');
79
+ }
80
+ /**
81
+ * Converts a project-relative file to the path the ELF's debug info uses. The firmware is built on the
82
+ * TuringCode server, so the ELF holds the server's folder; its prefix is found from the path strings in the ELF.
83
+ * @param rel project-relative path with forward slashes
84
+ * @returns the path to send in setBreakpoints
85
+ */
86
+ async sourcePath(rel) {
87
+ this.elfData ??= await readFile(this.opts.elf);
88
+ const dir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
89
+ for (const tail of dir ? [rel, dir] : [rel]) {
90
+ for (const sep of ['/', '\\']) {
91
+ const t = tail.replace(/\//g, sep);
92
+ const end = this.elfData.indexOf(Buffer.from(`${sep}${t}\0`));
93
+ if (end < 0)
94
+ continue;
95
+ const start = this.elfData.lastIndexOf(0, end) + 1;
96
+ const prefix = this.elfData.subarray(start, end + 1).toString('utf8'); // ends with sep
97
+ return prefix + rel.replace(/\//g, sep);
98
+ }
99
+ }
100
+ return join(this.opts.root, rel); // built locally or with relative paths
101
+ }
102
+ /**
103
+ * Converts a path from the debug info to a project-relative one, by finding the longest tail of it that exists in the project.
104
+ * @param path source path from a stack frame
105
+ * @returns the project-relative path, or the path itself when no tail exists locally
106
+ */
107
+ projectPath(path) {
108
+ if (!path)
109
+ return '?';
110
+ const parts = path.split(/[\\/]/).filter(Boolean);
111
+ for (let i = 0; i < parts.length; i++) {
112
+ const rel = parts.slice(i).join('/');
113
+ if (existsSync(join(this.opts.root, rel)))
114
+ return rel;
115
+ }
116
+ return path;
117
+ }
118
+ /**
119
+ * Describes where the halted target is: function, file and line of the innermost frame.
120
+ * @returns e.g. "Halted (breakpoint) in main at Core/Src/main.c:42"
121
+ */
122
+ async location() {
123
+ if (this.state !== 'halted')
124
+ return 'Running';
125
+ const { stackFrames = [] } = await this.request('stackTrace', {
126
+ threadId: this.threadId,
127
+ levels: 1,
128
+ });
129
+ const f = stackFrames[0];
130
+ const where = f
131
+ ? ` in ${f.name} at ${this.projectPath(f.source?.path)}:${f.line}`
132
+ : '';
133
+ return `Halted${this.stopReason ? ` (${this.stopReason})` : ''}${where}`;
134
+ }
135
+ /**
136
+ * Ends the session: disconnects (the target keeps running) and stops probe-rs.
137
+ */
138
+ async stop() {
139
+ await this.request('disconnect', { terminateDebuggee: false }, 3000).catch(() => undefined);
140
+ // killing probe-rs while it still closes the probe can leave an ST-LINK in DEV_USB_COMM_ERR until replugged
141
+ if (this.proc.exitCode === null) {
142
+ const exited = new Promise((done) => this.proc.once('exit', done));
143
+ this.proc.stdin.end();
144
+ await Promise.race([exited, new Promise((done) => setTimeout(done, 2000))]);
145
+ }
146
+ if (this.proc.exitCode === null)
147
+ this.proc.kill();
148
+ this.onExit('Debug session stopped');
149
+ }
150
+ /**
151
+ * Returns the last lines of probe-rs output, for error messages.
152
+ * @returns the output prefixed with a newline, or an empty string
153
+ */
154
+ logTail() {
155
+ const tail = this.log.join('').slice(-1500).trim();
156
+ return tail ? `\n\nprobe-rs output:\n${tail}` : '';
157
+ }
158
+ /**
159
+ * Keeps the last probe-rs output lines.
160
+ * @param text output text
161
+ */
162
+ addLog(text) {
163
+ this.log.push(text);
164
+ if (this.log.length > 100)
165
+ this.log.shift();
166
+ }
167
+ /**
168
+ * Splits the stdout stream into DAP messages (Content-Length framed JSON).
169
+ * @param chunk data read from probe-rs stdout
170
+ */
171
+ onData(chunk) {
172
+ this.buf = Buffer.concat([this.buf, chunk]);
173
+ for (;;) {
174
+ const head = this.buf.indexOf('\r\n\r\n');
175
+ if (head < 0)
176
+ return;
177
+ const m = /Content-Length:\s*(\d+)/i.exec(this.buf.subarray(0, head).toString());
178
+ if (!m) {
179
+ this.buf = this.buf.subarray(head + 4);
180
+ continue;
181
+ }
182
+ const end = head + 4 + Number(m[1]);
183
+ if (this.buf.length < end)
184
+ return;
185
+ const msg = JSON.parse(this.buf.subarray(head + 4, end).toString('utf8'));
186
+ this.buf = this.buf.subarray(end);
187
+ this.onMessage(msg);
188
+ }
189
+ }
190
+ /**
191
+ * Handles one DAP message: resolves its request, or tracks the target state from events.
192
+ * @param msg response or event
193
+ */
194
+ onMessage(msg) {
195
+ if (msg.type === 'response') {
196
+ const p = this.pending.get(msg.request_seq);
197
+ if (!p)
198
+ return;
199
+ this.pending.delete(msg.request_seq);
200
+ clearTimeout(p.timer);
201
+ if (msg.success)
202
+ p.resolve(msg.body ?? {});
203
+ else
204
+ p.reject(new Error(`${msg.command} failed: ${errorText(msg)}`));
205
+ return;
206
+ }
207
+ if (msg.type !== 'event')
208
+ return;
209
+ if (msg.event === 'stopped') {
210
+ this.state = 'halted';
211
+ this.stopReason = msg.body?.description ?? msg.body?.reason ?? '';
212
+ this.threadId = msg.body?.threadId ?? this.threadId;
213
+ }
214
+ else if (msg.event === 'continued')
215
+ this.state = 'running';
216
+ else if (msg.event === 'output')
217
+ this.addLog(msg.body?.output ?? '');
218
+ else if (msg.event === 'terminated' || msg.event === 'exited')
219
+ this.onExit('The debug session ended');
220
+ for (const w of this.waiters.filter((w) => w.name === msg.event))
221
+ w.done(msg.body ?? {});
222
+ }
223
+ /**
224
+ * Fails every open request and frees the probe once probe-rs is gone.
225
+ * @param reason message for the open requests
226
+ */
227
+ onExit(reason) {
228
+ if (session !== this)
229
+ return;
230
+ session = undefined;
231
+ releaseProbe();
232
+ for (const p of this.pending.values()) {
233
+ clearTimeout(p.timer);
234
+ p.reject(new Error(`${reason}${this.logTail()}`));
235
+ }
236
+ this.pending.clear();
237
+ for (const w of [...this.waiters])
238
+ w.done(undefined);
239
+ if (this.proc.exitCode === null)
240
+ this.proc.kill();
241
+ }
242
+ }
243
+ let session;
244
+ /**
245
+ * Returns the message of a failed DAP response; probe-rs sends it as a format string with variables.
246
+ * @param msg DAP error response
247
+ * @returns the message with its {variables} filled in
248
+ */
249
+ function errorText(msg) {
250
+ const err = msg.body?.error;
251
+ if (!err?.format)
252
+ return msg.message ?? 'unknown error';
253
+ return err.format.replace(/\{(\w+)\}/g, (all, key) => err.variables?.[key] ?? msg.message ?? all);
254
+ }
255
+ /**
256
+ * Tells whether a probe-rs debug session holds the probe.
257
+ * @returns true while a session is running
258
+ */
259
+ export function debugSessionActive() {
260
+ return !!session;
261
+ }
262
+ /**
263
+ * Returns the running debug session.
264
+ * @returns the session
265
+ */
266
+ export function getSession() {
267
+ if (!session)
268
+ throw new Error('No debug session: run `turingcode debug start`');
269
+ return session;
270
+ }
271
+ /**
272
+ * Starts `probe-rs dap-server`, then attaches to the target (or flashes it and halts after reset).
273
+ * @param opts chip, ELF and project of the session
274
+ * @returns the started session
275
+ */
276
+ export async function startSession(opts) {
277
+ if (session)
278
+ throw new Error('A debug session is already running: run `turingcode debug stop` first');
279
+ const cmd = await DebugActionServer.build_command({});
280
+ claimProbe('Debug session');
281
+ const s = new DebugSession(opts, spawn(cmd.tool.path, cmd.args, { cwd: opts.root, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }));
282
+ session = s;
283
+ try {
284
+ s.capabilities = await s.request('initialize', {
285
+ clientID: 'turingcode',
286
+ adapterID: 'probe-rs-debug',
287
+ linesStartAt1: true,
288
+ columnsStartAt1: true,
289
+ pathFormat: 'path',
290
+ supportsVariableType: true,
291
+ });
292
+ const config = {
293
+ chip: opts.chip,
294
+ cwd: opts.root,
295
+ wireProtocol: 'Swd',
296
+ connectUnderReset: false,
297
+ consoleLogLevel: 'Console',
298
+ ...(opts.flash && {
299
+ flashingConfig: { flashingEnabled: true, haltAfterReset: true },
300
+ }),
301
+ coreConfigs: [{ coreIndex: 0, programBinary: opts.elf }],
302
+ };
303
+ // DAP order: launch/attach, wait for "initialized", then configurationDone; the launch reply may come before or after it
304
+ const initialized = s.waitEvent('initialized', 60_000);
305
+ const launched = s.request(opts.flash ? 'launch' : 'attach', config, 180_000);
306
+ await Promise.race([initialized, launched]);
307
+ await s.request('configurationDone');
308
+ await launched;
309
+ // Let the first stop (halt after reset) arrive before reporting the state
310
+ if (s.state !== 'halted')
311
+ await s.waitEvent('stopped', opts.flash ? 5000 : 1000);
312
+ return s;
313
+ }
314
+ catch (e) {
315
+ const log = s.logTail();
316
+ await s.stop();
317
+ throw new Error(`Debug start failed: ${e.message}${e.message.includes('probe-rs output') ? '' : log}`);
318
+ }
319
+ }
320
+ /**
321
+ * Stops the debug session if one is running.
322
+ */
323
+ export async function stopSession() {
324
+ await session?.stop();
325
+ }
326
+ /**
327
+ * Resolves a project-relative path the agent passed and checks it stays inside the project.
328
+ * @param root project root
329
+ * @param file project-relative path
330
+ * @returns the path relative to the root, with forward slashes
331
+ */
332
+ export function projectFile(root, file) {
333
+ const abs = resolve(root, file);
334
+ const rel = relative(root, abs);
335
+ if (!rel || rel.startsWith('..') || isAbsolute(rel))
336
+ throw new Error(`${file} is outside the project`);
337
+ if (!existsSync(abs))
338
+ throw new Error(`${file} does not exist in the project`);
339
+ return rel.replace(/\\/g, '/');
340
+ }
341
+ /**
342
+ * Sends the breakpoints of one file to probe-rs (DAP replaces the whole list of a file on each call).
343
+ * @param s debug session
344
+ * @param rel project-relative file
345
+ * @returns the breakpoints as probe-rs placed them
346
+ */
347
+ export async function syncBreakpoints(s, rel) {
348
+ const list = s.breakpoints.get(rel) ?? [];
349
+ const path = await s.sourcePath(rel);
350
+ const { breakpoints = [] } = await s.request('setBreakpoints', {
351
+ source: { path },
352
+ breakpoints: list.map((b) => ({
353
+ line: b.line,
354
+ ...(b.condition && { condition: b.condition }),
355
+ })),
356
+ });
357
+ return breakpoints;
358
+ }
359
+ /**
360
+ * Returns the DAP id of a stack frame of the halted target.
361
+ * @param s debug session
362
+ * @param frame frame index, 0 = innermost
363
+ * @returns the frame id
364
+ */
365
+ export async function frameId(s, frame) {
366
+ s.requireHalted();
367
+ const { stackFrames = [] } = await s.request('stackTrace', {
368
+ threadId: s.threadId,
369
+ levels: frame + 1,
370
+ });
371
+ if (!stackFrames[frame])
372
+ throw new Error(`No frame ${frame}: the stack has ${stackFrames.length} frames`);
373
+ return stackFrames[frame].id;
374
+ }
@@ -0,0 +1,24 @@
1
+ import { Project } from './tool.js';
2
+ export type ServerCall = (name: string, args: object, timeoutMs?: number) => Promise<string>;
3
+ /**
4
+ * Syncs the project's files to projects/<name> on the server through the signed link of the sync_project tool:
5
+ * POSTs their sha256sum manifest (the server deletes its files not in it, except build/ and dot folders, and
6
+ * replies the files it needs), then PUTs a zip of only those files.
7
+ * @param call server tool caller
8
+ * @param project project root and name
9
+ * @param forceFullSync skip the manifest check and upload every file (server-side deletions are skipped too)
10
+ * @returns the server's upload summary
11
+ * @throws when the server does not confirm the upload
12
+ */
13
+ export declare function syncProjectToServer(call: ServerCall, project: Project, forceFullSync?: boolean): Promise<string>;
14
+ /**
15
+ * Pulls the server's changes into the local project through the signed link of the sync_project_from_server tool:
16
+ * POSTs the sha256sum manifest of the local files (as listed for syncProjectToServer) and extracts the returned zip
17
+ * of the server files missing locally or different. Local files are overwritten; local files absent on the server are kept.
18
+ * @param call server tool caller
19
+ * @param project project root and name
20
+ * @param confirmOverwrite asked with the local files that would be overwritten and the downloaded zip (to inspect
21
+ * the new versions); false cancels. Default: overwrite
22
+ * @returns a summary of the pulled files
23
+ */
24
+ export declare function syncProjectFromServer(call: ServerCall, project: Project, confirmOverwrite?: (files: string[], zip: Buffer) => Promise<boolean>): Promise<string>;
@@ -0,0 +1,72 @@
1
+ // Project sync with the TuringCode server through the signed links of its sync tools. Used by the project commands
2
+ // and, as a library, by the VS Code extension (which adds progress and confirmation UI around it).
3
+ import { readFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { extractZip, fetchOrThrow, syncLink, zipEntryNames, zipFiles } from './utils/downloadzip_utils.js';
6
+ import { listSyncFiles } from './utils/listSyncFiles.js';
7
+ import { truncate } from './utils/truncate.js';
8
+ import { sha256, sha256Files, toSha256sum } from './utils/hash_utils.js';
9
+ /**
10
+ * Syncs the project's files to projects/<name> on the server through the signed link of the sync_project tool:
11
+ * POSTs their sha256sum manifest (the server deletes its files not in it, except build/ and dot folders, and
12
+ * replies the files it needs), then PUTs a zip of only those files.
13
+ * @param call server tool caller
14
+ * @param project project root and name
15
+ * @param forceFullSync skip the manifest check and upload every file (server-side deletions are skipped too)
16
+ * @returns the server's upload summary
17
+ * @throws when the server does not confirm the upload
18
+ */
19
+ export async function syncProjectToServer(call, project, forceFullSync = false) {
20
+ const files_to_sync = await listSyncFiles(project.root);
21
+ const link = syncLink(await call('sync_project', { project_name: project.name }, 125_000));
22
+ const data = new Map(await Promise.all(files_to_sync.map(async (name) => [name, await readFile(join(project.root, name))])));
23
+ const upload = async (names) => {
24
+ const zip = await zipFiles(names.map((name) => ({ name, data: data.get(name) })));
25
+ return (await (await fetchOrThrow(link, { method: 'PUT', body: new Uint8Array(zip) })).text()).trim();
26
+ };
27
+ let msg;
28
+ if (forceFullSync)
29
+ msg = await upload([...data.keys()]);
30
+ else {
31
+ // send the manifest, the server replies what it needs
32
+ const manifest = Object.fromEntries([...data].map(([name, buf]) => [name, sha256(buf)]));
33
+ const reply = await (await fetchOrThrow(link, { method: 'POST', body: toSha256sum(manifest) })).text();
34
+ const lines = reply.split('\n');
35
+ const missing = lines.filter((l) => l.startsWith('need ')).map((l) => l.slice(5));
36
+ const deleted = lines.filter((l) => l.startsWith('deleted ')).map((l) => l.slice(8));
37
+ const deletedNote = deleted.length
38
+ ? `\nDeleted ${deleted.length} files on the server that no longer exist locally: ${deleted.join(', ')}`
39
+ : '';
40
+ msg = missing.length
41
+ ? (await upload(missing.filter((name) => data.has(name)))) + deletedNote
42
+ : `Uploaded 0 files: all ${files_to_sync.length} files already match the server.${deletedNote}`;
43
+ }
44
+ if (!msg.startsWith('Uploaded '))
45
+ throw new Error(msg);
46
+ return msg;
47
+ }
48
+ /**
49
+ * Pulls the server's changes into the local project through the signed link of the sync_project_from_server tool:
50
+ * POSTs the sha256sum manifest of the local files (as listed for syncProjectToServer) and extracts the returned zip
51
+ * of the server files missing locally or different. Local files are overwritten; local files absent on the server are kept.
52
+ * @param call server tool caller
53
+ * @param project project root and name
54
+ * @param confirmOverwrite asked with the local files that would be overwritten and the downloaded zip (to inspect
55
+ * the new versions); false cancels. Default: overwrite
56
+ * @returns a summary of the pulled files
57
+ */
58
+ export async function syncProjectFromServer(call, project, confirmOverwrite) {
59
+ const files = await listSyncFiles(project.root);
60
+ const link = syncLink(await call('sync_project_from_server', { project_name: project.name }, 125_000));
61
+ const manifest = await sha256Files(project.root, files);
62
+ const res = await fetchOrThrow(link, { method: 'POST', body: toSha256sum(manifest) });
63
+ if (res.status === 204)
64
+ return `Downloaded 0 files: all ${files.length} local files already match the server.`;
65
+ const zip = Buffer.from(await res.arrayBuffer());
66
+ const changed = zipEntryNames(zip);
67
+ const overwritten = changed.filter((name) => name in manifest);
68
+ if (confirmOverwrite && overwritten.length && !(await confirmOverwrite(overwritten, zip)))
69
+ return 'Sync from server cancelled.';
70
+ await extractZip(zip, project.root);
71
+ return `Downloaded ${changed.length} files from the server: ${truncate(changed.join(', '), 512)}`;
72
+ }
@@ -0,0 +1,43 @@
1
+ export type Prop = {
2
+ type: 'string' | 'integer' | 'number' | 'boolean';
3
+ description?: string;
4
+ enum?: string[];
5
+ pattern?: string;
6
+ minimum?: number;
7
+ maximum?: number;
8
+ maxLength?: number;
9
+ };
10
+ export interface Project {
11
+ root: string;
12
+ name: string;
13
+ }
14
+ export interface ToolContext {
15
+ cwd: string;
16
+ socketPath: string;
17
+ debugActive(): boolean;
18
+ }
19
+ export interface ToolDef {
20
+ name: string;
21
+ description: string;
22
+ inputSchema: {
23
+ type: 'object';
24
+ properties: Record<string, Prop>;
25
+ required?: string[];
26
+ additionalProperties: boolean;
27
+ };
28
+ needsProbe: boolean;
29
+ run: (args: any, ctx: ToolContext) => Promise<string>;
30
+ }
31
+ /**
32
+ * Builds a tool definition.
33
+ * @param def name, description, arguments and handler
34
+ * @returns the tool definition
35
+ */
36
+ export declare function _defineTool(def: {
37
+ name: string;
38
+ description: string;
39
+ properties?: Record<string, Prop>;
40
+ required?: string[];
41
+ needsProbe?: boolean;
42
+ run: ToolDef['run'];
43
+ }): ToolDef;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Builds a tool definition.
3
+ * @param def name, description, arguments and handler
4
+ * @returns the tool definition
5
+ */
6
+ export function _defineTool(def) {
7
+ const { name, description, properties = {}, required, needsProbe = false, run } = def;
8
+ return {
9
+ name,
10
+ description,
11
+ inputSchema: {
12
+ type: 'object',
13
+ properties,
14
+ ...(required && { required }),
15
+ additionalProperties: false,
16
+ },
17
+ needsProbe,
18
+ run,
19
+ };
20
+ }
@@ -0,0 +1,50 @@
1
+ import { CommandModule } from "yargs";
2
+ import { ToolDef } from "./tool.js";
3
+ /**
4
+ * Where a tool runs:
5
+ * - `local`: in this process (project and server commands);
6
+ * - `probe`: in the debug daemon when one runs for the project (it owns the probe), else in this process with the probe lock file;
7
+ * - `session`: in the debug daemon; fails when none runs;
8
+ * - `start`: in the debug daemon, launched first when none runs.
9
+ */
10
+ export type RunMode = "local" | "probe" | "session" | "start";
11
+ export interface ToolCommandSpec {
12
+ command: string;
13
+ tool: ToolDef;
14
+ mode: RunMode;
15
+ server?: boolean;
16
+ examples: [string, string][];
17
+ aliases?: Record<string, string>;
18
+ }
19
+ /**
20
+ * Converts a tool argument name to its flag: `force_full_sync` -> `force-full-sync`.
21
+ *
22
+ * @param {string} name - Argument name from the tool's schema.
23
+ * @returns {string} The flag name, without dashes.
24
+ */
25
+ export declare const flagName: (name: string) => string;
26
+ /**
27
+ * Picks the tool arguments from parsed flags, leaving out flags that were not given.
28
+ *
29
+ * @param {ToolDef} tool - The tool.
30
+ * @param {Record<string, unknown>} argv - Parsed yargs arguments.
31
+ * @returns {Record<string, unknown>} Tool arguments by schema name.
32
+ */
33
+ export declare function toolArgs(tool: ToolDef, argv: Record<string, unknown>): Record<string, unknown>;
34
+ /**
35
+ * Runs a tool where its mode says and returns its text.
36
+ *
37
+ * @param {ToolDef} tool - The tool.
38
+ * @param {Record<string, unknown>} args - Validated tool arguments.
39
+ * @param {RunMode} mode - Where it runs.
40
+ * @returns {Promise<string>} The tool's text output.
41
+ * @throws {Error} With the tool's or the daemon's error message.
42
+ */
43
+ export declare function runToolCommand(tool: ToolDef, args: Record<string, unknown>, mode: RunMode): Promise<string>;
44
+ /**
45
+ * Builds the yargs subcommand of one tool: a flag per argument, the tool's description as help, and its examples.
46
+ *
47
+ * @param {ToolCommandSpec} spec - Subcommand name, tool, run mode and examples.
48
+ * @returns {CommandModule} The subcommand.
49
+ */
50
+ export declare function toolCommand(spec: ToolCommandSpec): CommandModule;