@turingcode/cli 0.3.23 → 0.3.24

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.
@@ -3,6 +3,7 @@ import contract from '../features/contract/command.js';
3
3
  import table from '../features/table/command.js';
4
4
  import tool from '../features/tool/command.js';
5
5
  import project from '../features/project/command.js';
6
+ import knowledge from '../features/knowledge/command.js';
6
7
  import probe from '../features/probe/command.js';
7
8
  import debug from '../features/debug/command.js';
8
9
  import status from '../features/status/command.js';
@@ -14,6 +15,7 @@ const commands = [
14
15
  table,
15
16
  tool,
16
17
  project,
18
+ knowledge,
17
19
  syntaxCheck,
18
20
  probe,
19
21
  debug,
@@ -51,14 +51,17 @@ function tableSection(t) {
51
51
  * @returns {string} The guide.
52
52
  */
53
53
  export function renderGuide(c) {
54
- const missing = (c.missing_values ?? [""]).map(v => (v === "" ? "an empty cell" : code(v))).join(" or ");
54
+ const missingValues = c.missing_values ?? [""];
55
+ const missing = missingValues.length
56
+ ? `A missing value is ${missingValues.map(v => (v === "" ? "an empty cell" : code(v))).join(" or ")}.`
57
+ : "No cell is a missing value.";
55
58
  const lines = [`# Contract ${c.name ? code(c.version ? `${c.name}@${c.version}` : c.name) : ""}`.trimEnd(), ""];
56
59
  if (c.description)
57
60
  lines.push(c.description, "");
58
61
  lines.push("## Format", "", c.format === "csv"
59
62
  ? "Write each table as `<table name>.csv` in one folder, header row first."
60
63
  : `Write each table under a heading with its name, e.g. ${code(`## ${c.tables[0].name}`)}, as a Markdown table: `
61
- + "a header row, a `|---|` separator row, then one row per item. Write `\\|` for a `|` inside a cell.", `A missing value is ${missing}. ${c.allow_extra_tables ? "Other tables are allowed." : "No other tables."}`, "", "## Tables", "");
64
+ + "a header row, a `|---|` separator row, then one row per item. Write `\\|` for a `|` inside a cell.", `${missing} ${c.allow_extra_tables ? "Other tables are allowed." : "No other tables."}`, "", "## Tables", "");
62
65
  for (const t of c.tables)
63
66
  lines.push(...tableSection(t));
64
67
  const deps = Object.entries(c.depends_on ?? {});
@@ -13,6 +13,7 @@ export default _defineTool({
13
13
  s.state = 'running';
14
14
  await s.request('continue', { threadId: s.threadId }).catch((e) => {
15
15
  s.state = 'halted';
16
+ stopped.cancel();
16
17
  throw e;
17
18
  });
18
19
  if (!args.wait)
@@ -9,7 +9,13 @@ export default _defineTool({
9
9
  if (s.state === 'halted')
10
10
  return `Already halted\n${await s.location()}`;
11
11
  const stopped = s.waitEvent('stopped', 5000);
12
- await s.request('pause', { threadId: s.threadId });
12
+ try {
13
+ await s.request('pause', { threadId: s.threadId });
14
+ }
15
+ catch (e) {
16
+ stopped.cancel();
17
+ throw e;
18
+ }
13
19
  await stopped;
14
20
  return s.location();
15
21
  },
@@ -14,6 +14,7 @@ export default _defineTool({
14
14
  s.state = 'running';
15
15
  await s.request(COMMANDS[args.kind ?? 'over'], { threadId: s.threadId }).catch((e) => {
16
16
  s.state = 'halted';
17
+ stopped.cancel();
17
18
  throw e;
18
19
  });
19
20
  if (!(await stopped))
@@ -0,0 +1,3 @@
1
+ import { CommandModule } from "yargs";
2
+ declare const command: CommandModule;
3
+ export default command;
@@ -0,0 +1,18 @@
1
+ import { TOKEN_HELP } from "../../core/mcp.js";
2
+ import { toolCommand } from "../../stm32/toolCommand.js";
3
+ import knowledgeDownload from "./knowledge_download.js";
4
+ const subcommands = [
5
+ toolCommand({ command: "download", tool: knowledgeDownload, mode: "local", server: true, positional: "filename", examples: [
6
+ ["$0 knowledge download ism330dhcx_reg", "download ism330dhcx_reg.c and ism330dhcx_reg.h into .turingcode/downloads/"],
7
+ ["$0 knowledge download ism330dhcx_reg.h --dir Drivers/BSP", "download only the header into Drivers/BSP/"],
8
+ ] }),
9
+ ];
10
+ const command = {
11
+ command: "knowledge",
12
+ describe: "Download .c and .h files from the Turing Code knowledge base",
13
+ builder: cli => subcommands.reduce((c, s) => c.command(s), cli)
14
+ .demandCommand(1, "knowledge needs a subcommand: download")
15
+ .epilogue(TOKEN_HELP),
16
+ handler: () => { },
17
+ };
18
+ export default command;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Parses the server's `<path> <link>` lines.
3
+ * @param text reply of the knowledge_base_download server tool
4
+ * @returns one { rel, url } per file
5
+ * @throws {Error} with the server reply when it holds no link (e.g. no .c/.h file matched)
6
+ */
7
+ export declare function parseDownloadLinks(text: string): {
8
+ rel: string;
9
+ url: string;
10
+ }[];
11
+ /** Downloads .c/.h files of the knowledge base into a local folder; existing files are kept. */
12
+ declare const _default: import("../../stm32/tool.js").ToolDef;
13
+ export default _default;
@@ -0,0 +1,54 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { basename, join, resolve } from 'node:path';
3
+ import { callServer } from '../../stm32/context.js';
4
+ import { downloadFile } from '../../stm32/utils/downloadzip_utils.js';
5
+ import { _defineTool } from '../../stm32/tool.js';
6
+ /**
7
+ * Parses the server's `<path> <link>` lines.
8
+ * @param text reply of the knowledge_base_download server tool
9
+ * @returns one { rel, url } per file
10
+ * @throws {Error} with the server reply when it holds no link (e.g. no .c/.h file matched)
11
+ */
12
+ export function parseDownloadLinks(text) {
13
+ const links = text.split('\n').map((line) => line.match(/^(.+) (https?:\/\/\S+)$/)).filter((m) => m !== null)
14
+ .map((m) => ({ rel: m[1], url: m[2] }));
15
+ if (!links.length)
16
+ throw new Error(text.trim());
17
+ return links;
18
+ }
19
+ /** Downloads .c/.h files of the knowledge base into a local folder; existing files are kept. */
20
+ export default _defineTool({
21
+ name: 'knowledge_download',
22
+ description: 'Download .c and .h files of the Turing Code knowledge base (e.g. sensor register drivers like ism330dhcx_reg.c/.h) ' +
23
+ 'into .turingcode/downloads/ of the working directory or --dir, by file name; existing files are not overwritten. Other file types are refused.',
24
+ properties: {
25
+ filename: {
26
+ type: 'string',
27
+ description: 'File names or parts of them, e.g. ism330dhcx_reg for both its .c and .h',
28
+ },
29
+ dir: {
30
+ type: 'string',
31
+ description: 'Folder to save into, relative to the working directory (default: .turingcode/downloads)',
32
+ },
33
+ },
34
+ required: ['filename'],
35
+ run: async (args, ctx) => {
36
+ const links = parseDownloadLinks(await callServer('knowledge_base_download', { filename: args.filename }, 125_000));
37
+ const names = links.map((l) => basename(l.rel));
38
+ const twice = names.find((n, i) => names.indexOf(n) !== i);
39
+ if (twice)
40
+ throw new Error(`Several files are named ${twice}:\n${links.map((l) => l.rel).join('\n')}\nGive a longer file name.`);
41
+ const dest = resolve(ctx.cwd, args.dir ?? '.turingcode/downloads');
42
+ const lines = [];
43
+ for (const [i, { rel, url }] of links.entries()) {
44
+ const file = join(dest, names[i]);
45
+ if (existsSync(file))
46
+ lines.push(`kept existing ${file}`);
47
+ else {
48
+ await downloadFile(url, file);
49
+ lines.push(`downloaded ${rel} to ${file}`);
50
+ }
51
+ }
52
+ return lines.join('\n');
53
+ },
54
+ });
@@ -99,6 +99,7 @@ export function pickTools(tools, names) {
99
99
  }
100
100
  /**
101
101
  * Saves a tool result as the next free `<project>/.turingcode/results/<tool>-<n>.txt`.
102
+ * The file is created exclusively, so two runs never overwrite each other's result.
102
103
  *
103
104
  * @param {string} tool - Tool name, used in the file name.
104
105
  * @param {string} text - The tool result.
@@ -107,11 +108,20 @@ export function pickTools(tools, names) {
107
108
  async function saveToolResult(tool, text) {
108
109
  const dir = join((await findProject()).root, '.turingcode', 'results');
109
110
  await mkdir(dir, { recursive: true });
110
- const pattern = new RegExp(`^${tool.replace(/[^\w-]/g, '_')}-(\\d+)\\.txt$`);
111
+ const base = tool.replace(/[^\w-]/g, '_');
112
+ const pattern = new RegExp(`^${base}-(\\d+)\\.txt$`);
111
113
  const taken = (await readdir(dir)).map((name) => Number(name.match(pattern)?.[1] ?? 0));
112
- const file = join(dir, `${tool.replace(/[^\w-]/g, '_')}-${Math.max(0, ...taken) + 1}.txt`);
113
- await writeFile(file, text);
114
- return file;
114
+ for (let n = Math.max(0, ...taken) + 1;; n++) {
115
+ const file = join(dir, `${base}-${n}.txt`);
116
+ try {
117
+ await writeFile(file, text, { flag: 'wx' });
118
+ return file;
119
+ }
120
+ catch (e) {
121
+ if (e.code !== 'EEXIST')
122
+ throw e;
123
+ }
124
+ }
115
125
  }
116
126
  /**
117
127
  * Calls one server tool and prints its result; unless `full`, one over SAVE_ABOVE_BYTES is saved to a file
@@ -26,6 +26,7 @@ export declare function downloadElf(call: ServerCall, project: Project, text: st
26
26
  export declare function compactBuildReply(text: string): string;
27
27
  /**
28
28
  * Builds the server copy of the project and, when the build succeeds, downloads its ELF into build/<preset>/.
29
+ * The server maps its project folder to project.root in the debug info, so a local debugger finds the sources.
29
30
  * @param call server tool caller
30
31
  * @param project project root and name
31
32
  * @param preset CMake preset, one of BUILD_PRESETS
@@ -58,13 +58,15 @@ export function compactBuildReply(text) {
58
58
  }
59
59
  /**
60
60
  * Builds the server copy of the project and, when the build succeeds, downloads its ELF into build/<preset>/.
61
+ * The server maps its project folder to project.root in the debug info, so a local debugger finds the sources.
61
62
  * @param call server tool caller
62
63
  * @param project project root and name
63
64
  * @param preset CMake preset, one of BUILD_PRESETS
64
65
  * @returns the build reply, its outcome and the ELF download note
65
66
  */
66
67
  export async function buildProject(call, project, preset) {
67
- const text = await call('project_build', { project_name: project.name, preset }, 125_000);
68
+ const local_source_dir = project.root.replace(/\\/g, '/');
69
+ const text = await call('project_build', { project_name: project.name, preset, local_source_dir }, 125_000);
68
70
  const ok = text.startsWith('Built ');
69
71
  if (!ok)
70
72
  return { text, ok, note: '' };
@@ -38,7 +38,8 @@ export declare function daemonPaths(root: string): DaemonPaths;
38
38
  * @param args tool arguments
39
39
  * @param cwd the caller's working directory
40
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)
41
+ * undefined when no daemon is running (the request was never sent). A missing token file still asks a live daemon,
42
+ * which answers "Bad token", so the caller does not run the command locally while the daemon holds the probe.
42
43
  */
43
44
  export declare function forwardToDaemon(paths: DaemonPaths, tool: string, args: Record<string, unknown>, cwd: string): Promise<DaemonResponse | undefined>;
44
45
  /**
@@ -38,12 +38,11 @@ export function daemonPaths(root) {
38
38
  * @param args tool arguments
39
39
  * @param cwd the caller's working directory
40
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)
41
+ * undefined when no daemon is running (the request was never sent). A missing token file still asks a live daemon,
42
+ * which answers "Bad token", so the caller does not run the command locally while the daemon holds the probe.
42
43
  */
43
44
  export async function forwardToDaemon(paths, tool, args, cwd) {
44
45
  const token = (await readFile(paths.token, 'utf8').catch(() => '')).trim();
45
- if (!token)
46
- return undefined;
47
46
  const req = { id: 1, token, cwd, tool, args };
48
47
  return new Promise((resolve) => {
49
48
  const sock = connect(paths.socket);
@@ -167,6 +166,10 @@ export async function runDaemon(root, tools) {
167
166
  const line = buf.slice(0, nl);
168
167
  buf = buf.slice(nl + 1);
169
168
  queue = queue.then(async () => {
169
+ if (stopping) {
170
+ sock.destroy();
171
+ return;
172
+ }
170
173
  let res;
171
174
  try {
172
175
  const req = JSON.parse(line);
@@ -40,9 +40,11 @@ export declare class DebugSession {
40
40
  * Waits for a DAP event.
41
41
  * @param name event name (e.g. stopped)
42
42
  * @param timeout milliseconds to wait
43
- * @returns the event body, or undefined on timeout or when the session ends
43
+ * @returns the event body, or undefined on timeout or when the session ends; call `cancel()` to stop waiting early
44
44
  */
45
- waitEvent(name: string, timeout: number): Promise<any | undefined>;
45
+ waitEvent(name: string, timeout: number): Promise<any | undefined> & {
46
+ cancel: () => void;
47
+ };
46
48
  /**
47
49
  * Throws unless the target is halted.
48
50
  */
@@ -56,10 +56,11 @@ export class DebugSession {
56
56
  * Waits for a DAP event.
57
57
  * @param name event name (e.g. stopped)
58
58
  * @param timeout milliseconds to wait
59
- * @returns the event body, or undefined on timeout or when the session ends
59
+ * @returns the event body, or undefined on timeout or when the session ends; call `cancel()` to stop waiting early
60
60
  */
61
61
  waitEvent(name, timeout) {
62
- return new Promise((resolve) => {
62
+ let cancel = () => { };
63
+ const promise = new Promise((resolve) => {
63
64
  const waiter = {
64
65
  name,
65
66
  done: (body) => {
@@ -70,7 +71,10 @@ export class DebugSession {
70
71
  };
71
72
  const timer = setTimeout(() => waiter.done(undefined), timeout);
72
73
  this.waiters.push(waiter);
74
+ cancel = () => waiter.done(undefined);
73
75
  });
76
+ promise.cancel = () => cancel();
77
+ return promise;
74
78
  }
75
79
  /**
76
80
  * Throws unless the target is halted.
@@ -66,7 +66,7 @@ export async function syncProjectFromServer(call, project, confirmOverwrite) {
66
66
  return `Downloaded 0 files: all ${files.length} local files already match the server.`;
67
67
  const zip = Buffer.from(await res.arrayBuffer());
68
68
  const changed = zipEntryNames(zip);
69
- const overwritten = changed.filter((name) => name in manifest);
69
+ const overwritten = changed.filter((name) => Object.hasOwn(manifest, name));
70
70
  if (confirmOverwrite && overwritten.length && !(await confirmOverwrite(overwritten, zip)))
71
71
  return 'Sync from server cancelled.';
72
72
  await extractZip(zip, project.root);
@@ -10,6 +10,7 @@ export declare function downloadAndUnzip(zipUrl: string, parentDir: string, over
10
10
  * @param data the zip bytes
11
11
  * @param parentDir folder to extract into
12
12
  * @param overwrite replace existing files; false only adds the missing ones
13
+ * @throws {Error} when an entry points outside parentDir
13
14
  */
14
15
  export declare function extractZip(data: Buffer, parentDir: string, overwrite?: boolean): Promise<void>;
15
16
  /**
@@ -17,13 +17,28 @@ export async function downloadAndUnzip(zipUrl, parentDir, overwrite = true) {
17
17
  const res = await fetchOrThrow(zipUrl, {});
18
18
  await extractZip(Buffer.from(await res.arrayBuffer()), parentDir, overwrite);
19
19
  }
20
+ /**
21
+ * Throws when a zip entry would be written outside the extraction folder.
22
+ * @param data the zip bytes
23
+ * @throws {Error} when an entry is absolute or contains a `..` segment
24
+ */
25
+ function assertSafeZipEntries(data) {
26
+ for (const name of zipEntryNames(data)) {
27
+ const parts = name.split(/[\\/]/);
28
+ if (name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name) || parts.includes("..")) {
29
+ throw new Error(`Refusing to extract ${name}: it points outside the project`);
30
+ }
31
+ }
32
+ }
20
33
  /**
21
34
  * Extracts zip bytes into parentDir with unzip, falling back to tar.
22
35
  * @param data the zip bytes
23
36
  * @param parentDir folder to extract into
24
37
  * @param overwrite replace existing files; false only adds the missing ones
38
+ * @throws {Error} when an entry points outside parentDir
25
39
  */
26
40
  export async function extractZip(data, parentDir, overwrite = true) {
41
+ assertSafeZipEntries(data);
27
42
  const zip = join(tmpdir(), `turingcode-${randomBytes(8).toString("hex")}.zip`);
28
43
  try {
29
44
  await writeFile(zip, data);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.3.23",
3
+ "version": "0.3.24",
4
4
  "description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,7 +18,7 @@
18
18
  "mods"
19
19
  ],
20
20
  "engines": {
21
- "node": ">=18"
21
+ "node": ">=20.12"
22
22
  },
23
23
  "scripts": {
24
24
  "build": "node scripts/build.cjs",
@@ -43,4 +43,4 @@
43
43
  "@types/yargs": "17.0.35",
44
44
  "typescript": "7.0.2"
45
45
  }
46
- }
46
+ }