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