@henols/c64-re-tools 2.6.0-rc.5 → 2.6.0-rc.7

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.6.0-rc.5",
3
+ "version": "2.6.0-rc.7",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -355,7 +355,7 @@ Errors of this group:
355
355
  - Each address has one module, and each file name has one module.
356
356
  - A file name has letters, digits, underscores or hyphens, and ends in `.asm`. It can have one folder, for example `music/driver.asm`. A folder name has lower-case letters, digits, underscores or hyphens.
357
357
  - Put the modules of one part of the program in one folder, for example `music/`, `irq/` or `graphics/`.
358
- - The generated source has the files `main.asm`, `loader.asm`, `switches.asm`, `config.asm`, `constants.asm`, `macros.asm` and `start_screen.asm` already. It also has the folders `leftovers/` and `segments/`. Thus a module cannot have one of these files or folders, in upper or lower case.
358
+ - The generated source has the files `main.asm`, `loader.asm`, `switches.asm`, `config.asm`, `constants.asm`, `macros.asm` and `start_screen.asm` already. It also has the folders `leftovers/` and `segments/`. Thus a module cannot have one of these files, also in a folder, or one of these folders, in upper or lower case.
359
359
  - Two modules cannot have file names that are different only in upper or lower case.
360
360
  - The title becomes the first line of the file.
361
361
  - `body.module` gives the module after the write.
@@ -548,7 +548,7 @@ A macro writes a run of instructions as one line of the source, for example `+in
548
548
  ### `apply <file>`
549
549
 
550
550
  - `<file>` is a JSON list of writes. Give `-` to read the list from standard input.
551
- - `body` holds `revision`, `writes` and `replaced`. Each item of `replaced` has the number of the `write`, its `op` and its `previous`.
551
+ - `body` holds `revision`, `writes` and `replaced`. `replaced` lists each write that replaced a row of a different origin, for example an `llm` write over a `user` row. Each item has the number of the `write`, its `op` and its `previous`. A write over a row of the same origin is not in `replaced`.
552
552
  - All writes become one revision. If the knowledge refuses one write, the script writes nothing, and the `error` names the write.
553
553
  - Each write has `op` and the fields of the command with the same name. Each write can also have `space`. For example:
554
554
 
@@ -72,7 +72,7 @@ Each flag applies only to the commands in the table. On another command, the scr
72
72
 
73
73
  | Flag | Command | Effect |
74
74
  |---|---|---|
75
- | `--out <dir>` | `generate` | The folder for the source files. It is necessary. The script writes over the files of an earlier run. It removes a generated `.asm` file that this run does not write. A run without `--loader` keeps `loader.asm`, the loader program, `start_screen.asm` and `start_screen_stage.asm` of an earlier run. `staleLoader` tells when they are of another knowledge revision. |
75
+ | `--out <dir>` | `generate` | The folder for the source files. It is necessary. The script writes over the files of an earlier run. It removes a generated `.asm` file that this run does not write, also in a folder of `--out`. A folder with a generated `main.asm` is the source of another space, and it stays. A run without `--loader` keeps `loader.asm`, the loader program, `start_screen.asm` and `start_screen_stage.asm` of an earlier run. `staleLoader` tells when they are of another knowledge revision. |
76
76
  | `--entry <address>` | `generate` | An address where code starts. Give the flag again for more addresses. There is no default. |
77
77
  | `--space <space>` | `generate` | The knowledge space: `c64`, `drive8`, `loading`, or `bank0` to `bank255`. The default is `c64`. `--loader` and the platform names apply only to `c64`. The coverage is the coverage of the space. |
78
78
  | `--loader` | `generate` | Also write `loader.asm` and the loader program, and `start_screen.asm` when the knowledge has a start screen. A start screen of a captured stage also gives `start_screen_stage.asm`. The script writes the loader program only after the check of the new loader ran. Else the loader program of an earlier run stays. It needs a capture in the knowledge. The default is no loader. |
@@ -767,7 +767,8 @@ function outside(ranges: readonly AddressRange[], others: readonly AddressRange[
767
767
  * not_executed.json). An earlier loader.asm stays unless this run has
768
768
  * --loader: a source of the user can include loader.asm. The files of a
769
769
  * module are in `out` or in one folder of it: a folder that the run leaves
770
- * empty goes too. Other files stay. Gives the paths it removed.
770
+ * empty goes too. A folder with a generated main.asm is the source of another
771
+ * space, and it stays. Other files stay. Gives the paths it removed.
771
772
  */
772
773
  function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
773
774
  const removed: string[] = [];
@@ -787,6 +788,8 @@ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boole
787
788
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
788
789
  const name = folder === "" ? entry.name : `${folder}/${entry.name}`;
789
790
  if (entry.isDirectory() && folder === "") {
791
+ const main = join(root, name, "main.asm");
792
+ if (existsSync(main) && readFileSync(main, "utf8").startsWith(GENERATED_MARK)) continue;
790
793
  // A folder of the user that held no generated file stays, also when it is empty.
791
794
  if (clean(name) > 0 && readdirSync(join(root, name)).length === 0) rmSync(join(root, name), { recursive: true, force: true });
792
795
  continue;
@@ -27,7 +27,6 @@ Use only the MCP tools. Each MCP session has its own machine. Nothing else can c
27
27
 
28
28
  | Need | C64 tool |
29
29
  |---|---|
30
- | Run state, warp mode, window | `c64_status` |
31
30
  | Reset, power cycle | `c64_reset` |
32
31
  | Fast emulation | `c64_warp` |
33
32
  | Show the machine to the user in a window, hide it again | `c64_window` |
@@ -64,12 +63,11 @@ To keep a coverage run:
64
63
  ## Workflow
65
64
 
66
65
  1. Read the project knowledge for the addresses in the question.
67
- 2. Get the machine state with `c64_status`.
68
- 3. Load the subject if it is not loaded. Use `c64_autostart` to start it as a user does. Use `c64_program_load` to put a program in memory with no start.
69
- 4. Set the stop condition. Use a breakpoint, a watchpoint or a `c64_run_until` target. Add a condition when the stop must occur only in one state.
70
- 5. Run, step or give input. Prefer `c64_run_until` and `advance-frames` to waits. They stop at the same emulated time on every run.
71
- 6. Read only the state that answers the question. To read several things from one moment, use `c64_observe`.
72
- 7. Interpret the evidence. Keep the observed facts apart from your conclusions.
66
+ 2. Load the subject if it is not loaded. Use `c64_autostart` to start it as a user does. Use `c64_program_load` to put a program in memory with no start.
67
+ 3. Set the stop condition. Use a breakpoint, a watchpoint or a `c64_run_until` target. Add a condition when the stop must occur only in one state.
68
+ 4. Run, step or give input. Prefer `c64_run_until` and `advance-frames` to waits. They stop at the same emulated time on every run.
69
+ 5. Read only the state that answers the question. To read several things from one moment, use `c64_observe`.
70
+ 6. Interpret the evidence. Keep the observed facts apart from your conclusions.
73
71
 
74
72
  Before a risky experiment, save the state with `c64_snapshot`. Restore it to try again from the same point.
75
73
 
package/src/cli/main.ts CHANGED
@@ -1,20 +1,16 @@
1
1
  #!/usr/bin/env tsx
2
2
  // The human CLI: installs the skills and the VICE MCP
3
- // declaration into agent harnesses through AP SDK, and reports status. It is
4
- // thin: AP SDK does the harness-specific work.
3
+ // declaration into agent harnesses through AP SDK. It is thin: AP SDK does
4
+ // the harness-specific work.
5
5
 
6
- import { dirname, join } from "node:path";
7
- import { fileURLToPath } from "node:url";
8
6
  import { parseArgs } from "node:util";
9
7
 
10
8
  import { oldNodeRefusal, PACKAGE } from "../package.ts";
11
9
  import { localToolContext } from "../native/local.ts";
12
- import { localToolStatus } from "../native/status.ts";
13
10
  import { isRefusal } from "../errors.ts";
14
11
  import { startTrace } from "../trace.ts";
15
12
  import { runApSdk } from "./ap-sdk.ts";
16
13
  import { installedItems, parseTargets, removeDroppedItems, tidyAfterUninstall, type Scope, undoWindsurfProjectMcp, windsurfBefore, withoutWindsurfMcp } from "./cleanup.ts";
17
- import { hostStatusLines, installedLines, toolLines } from "./status.ts";
18
14
 
19
15
  const HELP = `c64-re-tools: Commodore 64 reverse engineering and development
20
16
 
@@ -22,7 +18,6 @@ Usage:
22
18
  c64-re-tools install [--target <harnesses>] [--global] install the skills and the VICE MCP
23
19
  c64-re-tools update [--target <harnesses>] [--global] install this version over an earlier one
24
20
  c64-re-tools uninstall [--target <harnesses>] [--global] remove them
25
- c64-re-tools status version, package, tools and the Host Runtime
26
21
  c64-re-tools --help
27
22
 
28
23
  Harnesses: claude, codex, pi, opencode, gemini, copilot, cursor, windsurf
@@ -38,7 +33,6 @@ with npx -y --package=${PACKAGE.name}@${PACKAGE.tag} c64-re-tools-host.
38
33
  It runs VICE and the tools that come with it (c1541, petcat). The skill
39
34
  scripts run ACME, DXA, Exomizer, Ghidra and c64run in the dev container.`;
40
35
 
41
- const here = dirname(fileURLToPath(import.meta.url));
42
36
 
43
37
  /** Runs the AP SDK CLI. Writes its error output to stderr and returns its exit status and its report. */
44
38
  async function apSdk(command: "install" | "uninstall", flags: readonly string[]): Promise<{ code: number; output: string }> {
@@ -48,20 +42,6 @@ async function apSdk(command: "install" | "uninstall", flags: readonly string[])
48
42
  return { code: run.code, output: run.stdout };
49
43
  }
50
44
 
51
- async function status(): Promise<number> {
52
- console.log(`c64-re-tools ${PACKAGE.version}`);
53
- console.log(`Package: ${join(here, "..", "..")}`);
54
- console.log(`Node: ${process.version} (${process.execPath})`);
55
- for (const line of installedLines()) console.log(line);
56
- // The skill scripts run these tools here, on this machine.
57
- const local = await localToolStatus(localToolContext());
58
- for (const line of toolLines("Tools here:", local)) console.log(line);
59
- const host = await hostStatusLines();
60
- for (const line of host.lines) console.log(line);
61
- // A script or a CI check can tell a ready setup from a broken one.
62
- return host.ready && local.every((tool) => tool.runs) ? 0 : 1;
63
- }
64
-
65
45
  async function main(argv: string[]): Promise<number> {
66
46
  startTrace("cli", { warn: (line) => console.error(line) });
67
47
  const { values, positionals } = parseArgs({
@@ -106,12 +86,6 @@ async function main(argv: string[]): Promise<number> {
106
86
  if (code === 0) tidyAfterUninstall(items, scope);
107
87
  return code;
108
88
  }
109
- case "status":
110
- if (flags.length > 0) {
111
- console.error(`status takes no --target or --global.\n\n${HELP}`);
112
- return 2;
113
- }
114
- return status();
115
89
  default:
116
90
  console.error(`Unknown command ${command}.\n\n${HELP}`);
117
91
  return 2;
package/src/host/main.ts CHANGED
@@ -126,7 +126,7 @@ async function main(): Promise<number> {
126
126
  return result.action === "directory" ? result.entries : [];
127
127
  },
128
128
  }),
129
- tools: createToolDispatcher({ supervisor, log, vice }),
129
+ tools: createToolDispatcher({ supervisor, log }),
130
130
  });
131
131
  } catch (error) {
132
132
  if (error instanceof ListenError && error.code === "EADDRINUSE") {
@@ -3,14 +3,12 @@
3
3
  // ACME, DXA and Ghidra themselves. One entry per operation, never a
4
4
  // generic executable route.
5
5
 
6
- import type { ViceVersion } from "../../native/discover.ts";
7
6
  import type { ProcessSupervisor } from "../../native/processes.ts";
8
7
  import type { ToolContext } from "../../native/run.ts";
9
8
  import type { ToolOperation, ToolOperations } from "../../protocol/tools.ts";
10
9
  import type { ToolDispatcher } from "../server.ts";
11
10
  import { inspect } from "./c1541.ts";
12
11
  import { decode } from "./petcat.ts";
13
- import { hostStatus } from "./status.ts";
14
12
 
15
13
  /** Runs one operation with its validated parameters and attachments. */
16
14
  type Adapter<O extends ToolOperation> = (
@@ -20,16 +18,13 @@ type Adapter<O extends ToolOperation> = (
20
18
  ) => Promise<{ result: ToolOperations[O]["result"]; attachments?: Buffer[] }>;
21
19
 
22
20
  const ADAPTERS: { [O in ToolOperation]: Adapter<O> } = {
23
- "host.status": (_params, _attachments, context) => hostStatus(context),
24
21
  "c1541.inspect": (params, attachments, context) => inspect(params, attachments[0]!, context),
25
22
  "petcat.decode": (_params, attachments, context) => decode(attachments[0]!, context),
26
23
  };
27
24
 
28
- /** `vice`: the version that the host read from the emulator at start, for host.status. */
29
- export function createToolDispatcher(options: { supervisor: ProcessSupervisor; env?: NodeJS.ProcessEnv; log?: (line: string) => void; vice?: ViceVersion }): ToolDispatcher {
25
+ export function createToolDispatcher(options: { supervisor: ProcessSupervisor; env?: NodeJS.ProcessEnv; log?: (line: string) => void }): ToolDispatcher {
30
26
  return (op, params, attachments, signal) => {
31
27
  const context = { supervisor: options.supervisor, signal, env: options.env, log: options.log };
32
- if (op === "host.status") return hostStatus(context, options.vice) as ReturnType<ToolDispatcher>;
33
28
  return ADAPTERS[op](params, attachments, context);
34
29
  };
35
30
  }
@@ -476,7 +476,7 @@ export class ViceSession implements ViceSessionHandle {
476
476
  if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
477
477
  throw new WireFailure(
478
478
  "operation-failed",
479
- "The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames until c64_status gives warp false, then type.",
479
+ "The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames, then type again.",
480
480
  );
481
481
  }
482
482
  await this.#observe(() => this.#machine.feedKeyboard(bytes));
@@ -4,7 +4,7 @@
4
4
  // ACME, DXA and Ghidra themselves through src/native.
5
5
 
6
6
  import { ProtocolError, WireFailure } from "../protocol/messages.ts";
7
- import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations, type HostInfo, type ToolStatus } from "../protocol/tools.ts";
7
+ import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
8
8
  import { HostConnection } from "./connect.ts";
9
9
  import { readPrg } from "./image.ts";
10
10
  import { readProjectFile } from "./transfer.ts";
@@ -84,11 +84,6 @@ export async function decodeBasic(request: { program: string }, options: ToolCal
84
84
  return (await callTool("petcat.decode", {}, [bytes], options)).result;
85
85
  }
86
86
 
87
- /** host.status: the Host Runtime, and each native tool on the host, found and run once. */
88
- export async function hostTools(options: ToolCallOptions = {}): Promise<{ host: HostInfo; tools: ToolStatus[] }> {
89
- return (await callTool("host.status", {}, [], options)).result;
90
- }
91
-
92
87
  /** Skill scripts see failures and wire limits through the host-client, never the private protocol module. */
93
88
  export { WireFailure } from "../protocol/messages.ts";
94
89
  export { DISK_ACTIONS, DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, MAX_DISK_SECTORS } from "../protocol/tools.ts";
@@ -111,10 +111,15 @@ export const SEGMENT_FOLDER = "segments";
111
111
  /** The folders that c64-source writes itself: no module file is in them. */
112
112
  export const GENERATED_FOLDERS = [LEFTOVER_FOLDER, SEGMENT_FOLDER] as const;
113
113
 
114
- /** True for a generated file name in any letter case: the file systems of macOS and Windows ignore case. */
114
+ /**
115
+ * True for a generated file name in any letter case (the file systems of macOS
116
+ * and Windows ignore case), also in a folder: a folder with a generated
117
+ * main.asm is the source of another space, not a folder of modules.
118
+ */
115
119
  export function isGeneratedFile(file: string): boolean {
116
120
  const lower = file.toLowerCase();
117
- return (GENERATED_FILES as readonly string[]).includes(lower) || GENERATED_FOLDERS.some((folder) => lower.startsWith(`${folder}/`));
121
+ const name = lower.slice(lower.lastIndexOf("/") + 1);
122
+ return (GENERATED_FILES as readonly string[]).includes(name) || GENERATED_FOLDERS.some((folder) => lower.startsWith(`${folder}/`));
118
123
  }
119
124
 
120
125
  /**
@@ -762,7 +762,7 @@ function checkModule(request: ModuleRequest): void {
762
762
  throw new Refusal("invalid-input", "A module file is a name of letters, digits, underscores or hyphens (at most 60) that ends in .asm. It can have one folder of lower-case letters, digits, underscores or hyphens (at most 30), for example music/driver.asm.");
763
763
  }
764
764
  if (isGeneratedFile(request.file)) {
765
- throw new Refusal("invalid-input", `A module cannot have the file ${request.file}, because the generated source writes ${GENERATED_FILES.join(", ")} and the folders ${GENERATED_FOLDERS.map((folder) => `${folder}/`).join(", ")} itself, in any letter case. Give the module another file.`);
765
+ throw new Refusal("invalid-input", `A module cannot have the file ${request.file}, because the generated source writes ${GENERATED_FILES.join(", ")} in any folder, and the folders ${GENERATED_FOLDERS.map((folder) => `${folder}/`).join(", ")} itself, in any letter case. Give the module another file.`);
766
766
  }
767
767
  if (request.title !== undefined && (request.title.trim().length === 0 || request.title.length > MAX_COMMENT)) throw new Refusal("invalid-input", `A module title has 1 to ${MAX_COMMENT} characters.`);
768
768
  }
package/src/mcp/server.ts CHANGED
@@ -19,7 +19,6 @@ import { elapsedMs, trace, type TraceFields } from "../trace.ts";
19
19
  /** The session operations tools may call. */
20
20
  export type ViceSessionApi = Pick<
21
21
  ViceSessionClient,
22
- | "status"
23
22
  | "memoryRead"
24
23
  | "registersGet"
25
24
  | "memoryWrite"
@@ -1,50 +1,11 @@
1
- // Machine tools: c64_status, c64_reset, c64_warp and c64_window.
1
+ // Machine tools: c64_reset, c64_warp and c64_window.
2
2
 
3
3
  import { z } from "zod";
4
4
 
5
5
  import { formatC64Address } from "../../c64.ts";
6
- import { VIDEO_STANDARDS } from "../../protocol/messages.ts";
7
- import { POINT_STOP_REASONS, RESET_MODES, RUN_STATES, SPACES, WINDOW_ACTIONS } from "../../protocol/vice.ts";
6
+ import { RESET_MODES, RUN_STATES, WINDOW_ACTIONS } from "../../protocol/vice.ts";
8
7
  import { AddressOutput, defineTool } from "../server.ts";
9
8
 
10
- export const c64Status = defineTool({
11
- name: "c64_status",
12
- title: "C64 status",
13
- description:
14
- "Get the state of the C64. The result tells if the CPU runs or has stopped, the video standard (pal or ntsc), " +
15
- "and if warp mode is on. It also tells if the emulator window is open (window). " +
16
- "When the CPU has stopped, the result also gives the program counter (pc). " +
17
- "When a breakpoint, a watchpoint or a JAM opcode stopped the CPU, stopReason tells which, and pointId gives the id of the breakpoint or watchpoint. " +
18
- "cartridge is true while a cartridge from c64_autostart is attached: a reset keeps it, and an autostart of another file detaches it.",
19
- inputSchema: z.object({}).strict(),
20
- outputSchema: z.object({
21
- state: z.enum(RUN_STATES),
22
- videoStandard: z.enum(VIDEO_STANDARDS),
23
- warp: z.boolean(),
24
- window: z.boolean().describe("true when the emulator window is open (c64_window)"),
25
- pc: AddressOutput.optional().describe("program counter. Only when the CPU is stopped"),
26
- stopReason: z.enum(POINT_STOP_REASONS).optional().describe("what stopped the CPU. Only when a breakpoint, a watchpoint or a JAM opcode stopped it"),
27
- pointId: z.number().int().min(1).optional().describe("the id of the breakpoint or watchpoint that stopped the CPU"),
28
- space: z.enum(SPACES).optional().describe("with pc: c64, or drive8 when a breakpoint or watchpoint in the disk drive stopped the CPU. pc is the address in that space"),
29
- cartridge: z.boolean().describe("true while a cartridge from c64_autostart is attached"),
30
- }),
31
- readOnly: true,
32
- async run(_input, session) {
33
- const status = await session.status();
34
- return {
35
- state: status.state,
36
- videoStandard: status.videoStandard,
37
- warp: status.warp,
38
- window: status.window,
39
- cartridge: status.cartridge,
40
- ...(status.pc === undefined ? {} : { pc: formatC64Address(status.pc) }),
41
- ...(status.stopReason === undefined ? {} : { stopReason: status.stopReason }),
42
- ...(status.pointId === undefined ? {} : { pointId: status.pointId }),
43
- ...(status.space === undefined ? {} : { space: status.space }),
44
- };
45
- },
46
- });
47
-
48
9
  export const c64Window = defineTool({
49
10
  name: "c64_window",
50
11
  title: "Emulator window",
@@ -104,4 +65,4 @@ export const c64Warp = defineTool({
104
65
  },
105
66
  });
106
67
 
107
- export const machineTools = [c64Status, c64Reset, c64Warp, c64Window];
68
+ export const machineTools = [c64Reset, c64Warp, c64Window];
@@ -30,7 +30,7 @@ export const c64Autostart = defineTool({
30
30
  "Without index, a disk image loads like LOAD\"*\",8,1. index selects one directory entry by its number in the directory list of the disk (0 is the first entry). " +
31
31
  "The tool refuses an index of a DEL entry, or an index after the last entry. " +
32
32
  "The machine runs when this tool returns, and the load continues. The emulator keeps warp mode on until it types RUN. " +
33
- "A key in that time stops the autostart, so c64_keyboard refuses keys until then. Run frames with c64_execution advance-frames until c64_status gives warp false. " +
33
+ "A key in that time stops the autostart, so c64_keyboard refuses keys until then. Run frames with c64_execution advance-frames, then type again. " +
34
34
  "The c64_timing stopwatch starts again from zero.",
35
35
  inputSchema: z
36
36
  .object({
package/src/native/dxa.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  // changed listing is refused instead of half imported.
7
7
 
8
8
  import { writeFileSync } from "node:fs";
9
+ import { stripVTControlCharacters } from "node:util";
9
10
 
10
11
  import { Refusal } from "../errors.ts";
11
12
  import { SYMBOL_NAME } from "../c64.ts";
@@ -14,7 +15,17 @@ import { checkDxaResult, checkRequestBounds, imageRange, seedsInside, type DxaPa
14
15
  import { Workspace } from "./staging.ts";
15
16
  import { DXA, findTool } from "./discover.ts";
16
17
  import { outputTail, runTool, runToolOrFail, type ToolContext } from "./run.ts";
17
- import { DXA_VERSION, versionLine } from "./status.ts";
18
+
19
+ /** dxa's version line, also as "D:\\tools\\dxa.exe v0.1.5 -- symbolic 65xx disassembler" on Windows. */
20
+ export const DXA_VERSION = /^(?:.*[\\/])?dxa(?:\.exe)? v\d/i;
21
+
22
+ /** The first output line that matches, without terminal color codes. */
23
+ export function versionLine(output: string, pattern: RegExp): string | undefined {
24
+ return stripVTControlCharacters(output)
25
+ .split(/\r?\n/)
26
+ .map((line) => line.trim())
27
+ .find((line) => pattern.test(line));
28
+ }
18
29
 
19
30
  const TIMEOUT_MS = 120_000;
20
31
  /** The listing is returned as an attachment; larger output is refused. */
@@ -79,38 +79,12 @@ export type PetcatResult =
79
79
  handoffs: BasicHandoff[];
80
80
  };
81
81
 
82
- /** One native tool on the host, as host.status found and ran it. */
83
- export interface ToolStatus {
84
- name: string;
85
- found: boolean;
86
- /** Where it is, when found. */
87
- path?: string;
88
- /** Its version text, when it ran. */
89
- version?: string;
90
- runs: boolean;
91
- /** What is wrong and what to do, when it is missing or does not run. */
92
- problem?: string;
93
- /** Known flaws of this version, each with the version that fixes it. The tool still runs. */
94
- flaws?: string[];
95
- }
96
-
97
- /** The Host Runtime itself: its package version and the system it runs on. */
98
- export interface HostInfo {
99
- version: string;
100
- /** Node's name of the operating system: linux, darwin or win32. */
101
- platform: string;
102
- /** The release of the operating system. */
103
- release: string;
104
- arch: string;
105
- }
106
-
107
82
  export interface ToolOperations {
108
- "host.status": { params: Record<string, never>; result: { host: HostInfo; tools: ToolStatus[] } };
109
83
  "c1541.inspect": { params: C1541Params; result: C1541Result };
110
84
  "petcat.decode": { params: PetcatParams; result: PetcatResult };
111
85
  }
112
86
  export type ToolOperation = keyof ToolOperations;
113
- export const TOOL_OPERATIONS = ["host.status", "c1541.inspect", "petcat.decode"] as const satisfies readonly ToolOperation[];
87
+ export const TOOL_OPERATIONS = ["c1541.inspect", "petcat.decode"] as const satisfies readonly ToolOperation[];
114
88
 
115
89
  const RELATIVE_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[^\0\\]+$/;
116
90
 
@@ -166,10 +140,6 @@ export function validateToolParams<O extends ToolOperation>(op: O, params: unkno
166
140
  oneFile(attachments, "the program");
167
141
  return {} as ToolOperations[O]["params"];
168
142
  }
169
- case "host.status":
170
- onlyFields(params, []);
171
- if (attachments.length !== 0) invalid("host.status takes no attachment");
172
- return {} as ToolOperations[O]["params"];
173
143
  }
174
144
  return invalid(`unknown tool operation: ${String(op)}`);
175
145
  }
@@ -186,20 +156,6 @@ export function validateToolResult<O extends ToolOperation>(op: O, value: unknow
186
156
  if (!isPetcatResult(value) || attachments.length !== 0) throw new ProtocolError("petcat.decode result is malformed");
187
157
  return value as unknown as ToolOperations[O]["result"];
188
158
  }
189
- case "host.status": {
190
- const tools = value.tools;
191
- const isStatus = (tool: unknown) =>
192
- isObject(tool) &&
193
- typeof tool.name === "string" &&
194
- typeof tool.found === "boolean" &&
195
- typeof tool.runs === "boolean" &&
196
- [tool.path, tool.version, tool.problem].every((field) => field === undefined || typeof field === "string") &&
197
- (tool.flaws === undefined || (Array.isArray(tool.flaws) && tool.flaws.every((flaw: unknown) => typeof flaw === "string")));
198
- const host = value.host;
199
- const isHost = isObject(host) && [host.version, host.platform, host.release, host.arch].every((field) => typeof field === "string");
200
- if (!isHost || !Array.isArray(tools) || !tools.every(isStatus) || attachments.length !== 0) throw new ProtocolError("host.status result is malformed");
201
- return value as unknown as ToolOperations[O]["result"];
202
- }
203
159
  }
204
160
  throw new ProtocolError(`unknown tool operation: ${String(op)}`);
205
161
  }
package/src/cli/status.ts DELETED
@@ -1,127 +0,0 @@
1
- // The status report of the CLI: the installed skills and MCP declarations,
2
- // the tools on this machine and the Host Runtime with its tools.
3
-
4
- import { readFileSync } from "node:fs";
5
- import { isAbsolute, join } from "node:path";
6
-
7
- import { installedItems, scopeRoot, type InstallItem, type Scope } from "./cleanup.ts";
8
- import { hostTools, type ToolCallOptions } from "../host-client/tools.ts";
9
- import { viceVersionOf } from "../native/discover.ts";
10
- import { PACKAGE } from "../package.ts";
11
- import { STOP_AND_ASK } from "../protocol/messages.ts";
12
- import type { HostInfo, ToolStatus } from "../protocol/tools.ts";
13
-
14
- /** One line per tool under `heading`: its version, or why it does not run; then each known flaw of it. */
15
- export function toolLines(heading: string, tools: readonly ToolStatus[]): string[] {
16
- return [
17
- heading,
18
- ...tools.flatMap((tool) => [
19
- tool.runs
20
- ? ` ${tool.name}: ${tool.version} (${tool.path})`
21
- : tool.found
22
- ? ` ${tool.name}: found at ${tool.path} but it does not run. ${tool.problem}`
23
- : ` ${tool.name}: missing. ${tool.problem}`,
24
- ...(tool.flaws ?? []).map((flaw) => ` Known flaw: ${flaw}`),
25
- ]),
26
- ];
27
- }
28
-
29
- /**
30
- * Whether the Host Runtime answers, and the tools it has. VICE and its tools
31
- * live on the host; it finds and runs each one. One request shows both that
32
- * the host answers and what it has. `ready` is true when the host answers and
33
- * every tool on it runs.
34
- */
35
- export async function hostStatusLines(options: ToolCallOptions = {}): Promise<{ lines: string[]; ready: boolean }> {
36
- let host: HostInfo;
37
- let tools: ToolStatus[];
38
- try {
39
- ({ host, tools } = await hostTools(options));
40
- } catch (error) {
41
- // status is read by a person: the instruction for an agent stays out.
42
- return { lines: [`Host Runtime: not reachable. ${(error as Error).message.replace(` ${STOP_AND_ASK}`, "")}`], ready: false };
43
- }
44
- const mixed = mixedViceBuilds(tools);
45
- return {
46
- lines: [
47
- `Host Runtime: reachable, c64-re-tools ${host.version} on ${host.platform} ${host.release} (${host.arch})`,
48
- ...(host.version === PACKAGE.version ? [] : [` Warning: the Host Runtime is c64-re-tools ${host.version} and this is ${PACKAGE.version}. Start the host again so that both are the same version.`]),
49
- ...toolLines("Tools on the host:", tools),
50
- ...(mixed === undefined ? [] : [` Warning: ${mixed}`]),
51
- ],
52
- ready: tools.every((tool) => tool.runs),
53
- };
54
- }
55
-
56
- /** A warning when x64sc, c1541 and petcat that run come from different VICE versions or builds. */
57
- export function mixedViceBuilds(tools: readonly ToolStatus[]): string | undefined {
58
- const running = tools.filter((tool) => tool.runs && tool.version !== undefined);
59
- const builds = running.map((tool) => {
60
- const version = viceVersionOf(tool.version!);
61
- return version === undefined ? tool.version! : `VICE ${version.major}.${version.minor}${version.revision === undefined ? "" : ` SVN r${version.revision}`}`;
62
- });
63
- if (new Set(builds).size <= 1) return undefined;
64
- return `the VICE tools come from different VICE builds: ${running.map((tool) => `${tool.version} (${tool.path})`).join(", ")}. Put x64sc, c1541 and petcat of one VICE first on PATH, or set C64RT_VICE, C64RT_C1541 and C64RT_PETCAT.`;
65
- }
66
-
67
- /**
68
- * The skills and MCP declarations that install wrote for this project and
69
- * globally: the c64-re-tools version of each harness's skills,
70
- * from their package.json, and the command that starts the MCP server. A
71
- * warning names skills of another version than this one.
72
- */
73
- export function installedLines(cwd = process.cwd()): string[] {
74
- const lines: string[] = [];
75
- for (const scope of ["project", "global"] as const satisfies readonly Scope[]) {
76
- const items = installedItems(scope, undefined, cwd);
77
- if (items.length === 0) continue;
78
- const root = scopeRoot(scope, cwd);
79
- lines.push(`Installed ${scope === "project" ? `in this project (${root})` : "globally"}:`);
80
- for (const harness of [...new Set(items.map((item) => item.harness))]) {
81
- const skills = items.filter((item) => item.harness === harness && item.kind === "skill");
82
- const versions = [...new Set(skills.map((item) => skillVersion(item, root)).filter((version) => version !== undefined))];
83
- if (skills.length > 0) {
84
- lines.push(` ${harness}: ${skills.length} skills, c64-re-tools ${versions.length === 0 ? "of an unknown version" : versions.join(" and ")}`);
85
- const other = versions.filter((version) => version !== PACKAGE.version);
86
- if (other.length > 0) lines.push(` Warning: the ${harness} skills are c64-re-tools ${other.join(" and ")} and this is ${PACKAGE.version}. Run npx -y ${PACKAGE.name}@${PACKAGE.tag} update${scope === "global" ? " --global" : ""} to install this version.`);
87
- }
88
- for (const item of items.filter((candidate) => candidate.harness === harness && candidate.kind === "mcp")) {
89
- lines.push(` ${harness} MCP server: ${mcpCommand(item, root) ?? `declared in ${item.files.join(", ")}`}`);
90
- }
91
- }
92
- }
93
- if (lines.length === 0) return ["Installed: nothing in this project or globally."];
94
- return lines;
95
- }
96
-
97
- function itemPath(file: string, root: string): string {
98
- return isAbsolute(file) ? file : join(root, file);
99
- }
100
-
101
- /** The version in the package.json of an installed skill; a skill without scripts has none. */
102
- function skillVersion(item: InstallItem, root: string): string | undefined {
103
- const file = item.files.find((candidate) => candidate.endsWith("/package.json") || candidate.endsWith("\\package.json"));
104
- if (file === undefined) return undefined;
105
- try {
106
- const { version } = JSON.parse(readFileSync(itemPath(file, root), "utf8")) as { version?: unknown };
107
- return typeof version === "string" ? version : undefined;
108
- } catch {
109
- return undefined;
110
- }
111
- }
112
-
113
- /** The command of the MCP server in a JSON configuration file, or undefined for another format. */
114
- function mcpCommand(item: InstallItem, root: string): string | undefined {
115
- const key = item.detail?.mergeKey;
116
- const [file] = item.files;
117
- if (key === undefined || file === undefined) return undefined;
118
- try {
119
- const servers = (JSON.parse(readFileSync(itemPath(file, root), "utf8")) as Record<string, unknown>)[key] as Record<string, { command?: unknown; args?: unknown }> | undefined;
120
- const server = servers?.[item.name];
121
- if (typeof server?.command !== "string") return undefined;
122
- const args = Array.isArray(server.args) ? server.args.filter((arg): arg is string => typeof arg === "string") : [];
123
- return [server.command, ...args].join(" ");
124
- } catch {
125
- return undefined;
126
- }
127
- }
@@ -1,47 +0,0 @@
1
- // host.status: VICE and the tools that come with it, each found the way its
2
- // operations find it and run once with a version option. A tool from a
3
- // VICE older than MIN_VICE is reported as not working, as its operations refuse it.
4
- // VICE itself is reported with the version that the host read from the
5
- // running emulator at start: the Homebrew x64sc of VICE 3.10 on macOS stops
6
- // on -version ("argv[0] is NULL") although the emulator runs.
7
-
8
- import { arch, platform, release } from "node:os";
9
-
10
- import { PACKAGE } from "../../package.ts";
11
- import type { HostInfo, ToolStatus } from "../../protocol/tools.ts";
12
- import { C1541, findTool, isOlderThanMinimum, MIN_VICE, PETCAT, VICE, viceFlaws, viceVersionOf, type ToolSpec, type ViceVersion } from "../../native/discover.ts";
13
- import type { ToolContext } from "../../native/run.ts";
14
- import { probeTools } from "../../native/status.ts";
15
- import { findVice } from "../vice/process.ts";
16
-
17
- function requireMinimum(status: ToolStatus, tool: ToolSpec): ToolStatus {
18
- if (!status.runs) return status;
19
- const version = viceVersionOf(status.version ?? "");
20
- if (version !== undefined && !isOlderThanMinimum(version)) return status;
21
- const found = version === undefined ? "It does not tell its VICE version" : `It comes from VICE ${version.major}.${version.minor}`;
22
- return { ...status, runs: false, problem: `${found}, and c64-re-tools needs VICE ${MIN_VICE.major}.${MIN_VICE.minor} or later. ${tool.remedy}` };
23
- }
24
-
25
- /** The version text of a VICE version, as x64sc -version prints it. */
26
- const versionText = (version: ViceVersion) => `x64sc (VICE ${version.major}.${version.minor}${version.revision === undefined ? "" : ` SVN r${version.revision}`})`;
27
-
28
- /** `started`: the version that the host read from the emulator at start; without it, VICE is probed with -version too. */
29
- export async function hostStatus(context: ToolContext, started?: ViceVersion): Promise<{ result: { host: HostInfo; tools: ToolStatus[] } }> {
30
- const specs = [VICE, C1541, PETCAT];
31
- const probed = await probeTools(
32
- [
33
- ...(started === undefined ? [{ name: VICE.name, find: findVice, args: ["-version"], pattern: /^x64sc \(VICE \d/ }] : []),
34
- { name: C1541.name, find: (env) => findTool(C1541, env), args: ["-version"], pattern: /^c1541 \(VICE \d/ },
35
- { name: PETCAT.name, find: (env) => findTool(PETCAT, env), args: ["-version"], pattern: /^petcat \(VICE \d/ },
36
- ],
37
- context,
38
- );
39
- const tools = started === undefined ? probed : [{ name: VICE.name, found: true, path: findVice(context.env ?? process.env), version: versionText(started), runs: true }, ...probed];
40
- const checked = tools.map((status, index) => requireMinimum(status, specs[index]!));
41
- // VICE runs with its known flaws; status names them.
42
- const vice = checked[0]!;
43
- const version = vice.runs ? viceVersionOf(vice.version ?? "") : undefined;
44
- const flaws = version === undefined ? [] : viceFlaws(version).map((flaw) => flaw.text);
45
- if (flaws.length > 0) checked[0] = { ...vice, flaws };
46
- return { result: { host: { version: PACKAGE.version, platform: platform(), release: release(), arch: arch() }, tools: checked } };
47
- }
@@ -1,135 +0,0 @@
1
- // Tool status: finds each native tool the way its operations do and runs it
2
- // once with a version option, so a user can see in advance which tools work.
3
- // The Host Runtime reports VICE and its tools (host.status); the CLI reports
4
- // the tools that skill scripts run themselves (ACME, DXA, Exomizer, Ghidra).
5
-
6
- import { tmpdir } from "node:os";
7
- import { stripVTControlCharacters } from "node:util";
8
-
9
- import { isRefusal } from "../errors.ts";
10
- import { type ToolStatus } from "../protocol/tools.ts";
11
- import { ACME, C64RUN, DXA, EXOMIZER, findTool, INSTALL_STEPS } from "./discover.ts";
12
- import { findGhidra, ghidraVersion, NO_USABLE_JDK, noJdk } from "./ghidra/index.ts";
13
- import { runTool, type ToolContext } from "./run.ts";
14
- import { Workspace } from "./staging.ts";
15
-
16
- const PROBE_TIMEOUT_MS = 20_000;
17
-
18
- export interface Probe {
19
- name: string;
20
- /** The executable; throws WireFailure(installation-incomplete) when missing. */
21
- find: (env: NodeJS.ProcessEnv) => string;
22
- args: string[];
23
- /** The version line; no such line means the tool did not run correctly. */
24
- pattern: RegExp;
25
- }
26
-
27
- /** dxa's version line, also as "D:\\tools\\dxa.exe v0.1.5 -- symbolic 65xx disassembler" on Windows. */
28
- export const DXA_VERSION = /^(?:.*[\\/])?dxa(?:\.exe)? v\d/i;
29
-
30
- /** The first output line that matches, without terminal color codes (c1541 colors an OpenCBM notice). */
31
- export function versionLine(output: string, pattern: RegExp): string | undefined {
32
- return stripVTControlCharacters(output)
33
- .split(/\r?\n/)
34
- .map((line) => line.trim())
35
- .find((line) => pattern.test(line));
36
- }
37
-
38
- async function run(
39
- name: string,
40
- path: string,
41
- args: string[],
42
- version: (output: string) => string | undefined,
43
- context: ToolContext,
44
- /** A known cause in the output, said in place of the exit status. */
45
- cause?: (output: string) => string | undefined,
46
- ): Promise<ToolStatus> {
47
- const result = await runTool({ argv: [path, ...args], cwd: tmpdir(), supervisor: context.supervisor, signal: context.signal, timeoutMs: PROBE_TIMEOUT_MS, env: context.env });
48
- const output = `${result.stdout}\n${result.stderr}`;
49
- const found = version(output);
50
- if (found !== undefined) return { name, found: true, path, version: found, runs: true };
51
- const known = cause?.(output);
52
- if (known !== undefined) return { name, found: true, path, runs: false, problem: known };
53
- const problem = result.timedOut ? "It did not answer in time." : result.spawnError !== undefined ? `It did not start (${result.spawnError}).` : `It did not run correctly (exit ${result.code ?? result.signal}).`;
54
- return { name, found: true, path, runs: false, problem };
55
- }
56
-
57
- function missing(name: string, error: unknown): ToolStatus {
58
- if (!isRefusal(error)) throw error;
59
- return { name, found: false, runs: false, problem: error.message };
60
- }
61
-
62
- /** Finds and runs each probed tool once. */
63
- export function probeTools(probes: Probe[], context: ToolContext): Promise<ToolStatus[]> {
64
- const env = context.env ?? process.env;
65
- return Promise.all(
66
- probes.map(async (probe) => {
67
- let path: string;
68
- try {
69
- path = probe.find(env);
70
- } catch (error) {
71
- return missing(probe.name, error);
72
- }
73
- return run(probe.name, path, probe.args, (output) => versionLine(output, probe.pattern), context);
74
- }),
75
- );
76
- }
77
-
78
- /** Ghidra: without arguments analyzeHeadless starts Java and prints its usage, which proves that it runs. */
79
- export async function probeGhidra(context: ToolContext): Promise<ToolStatus> {
80
- const env = context.env ?? process.env;
81
- try {
82
- const ghidra = findGhidra(env);
83
- // Its own settings directory keeps the user's Ghidra settings and logs untouched.
84
- const workspace = Workspace.create(context.supervisor, "c64-re-tools-ghidra-status-");
85
- const settings = workspace.root;
86
- try {
87
- const status = await run(
88
- "Ghidra",
89
- ghidra.analyzeHeadless,
90
- [],
91
- (output) => (/Headless Analyzer Usage/.test(output) ? ghidraVersion(ghidra) : undefined),
92
- { ...context, env: { ...env, XDG_CONFIG_HOME: settings, XDG_CACHE_HOME: settings } },
93
- (output) => (NO_USABLE_JDK.test(output) ? noJdk(ghidra).message : undefined),
94
- );
95
- return { ...status, path: ghidra.root };
96
- } finally {
97
- workspace.remove();
98
- }
99
- } catch (error) {
100
- return missing("Ghidra", error);
101
- }
102
- }
103
-
104
- /** c64run: --version prints its version and whether its ROM folder has the three C64 ROMs. */
105
- export async function probeC64run(context: ToolContext): Promise<ToolStatus> {
106
- const env = context.env ?? process.env;
107
- try {
108
- const path = findTool(C64RUN, env);
109
- return await run(
110
- "c64run",
111
- path,
112
- ["--version"],
113
- (output) => (/^roms=ok /m.test(output) ? versionLine(output, /^c64run protocol=/) : undefined),
114
- context,
115
- (output) => {
116
- const missing = /^roms=missing (.*)$/m.exec(output)?.[1];
117
- return missing === undefined ? undefined : `It has no C64 ROMs: ${missing}. ${INSTALL_STEPS}`;
118
- },
119
- );
120
- } catch (error) {
121
- return missing("c64run", error);
122
- }
123
- }
124
-
125
- /** The tools that skill scripts run themselves, on this machine. */
126
- export async function localToolStatus(context: ToolContext): Promise<ToolStatus[]> {
127
- const probes: Probe[] = [
128
- { name: "ACME", find: (env) => findTool(ACME, env), args: ["--version"], pattern: /^This is ACME, release / },
129
- // dxa -V prints its version and exits with status 1. It names itself by argv[0], without the
130
- // directory only where that uses "/": on Windows the line starts with the full path.
131
- { name: "dxa", find: (env) => findTool(DXA, env), args: ["-V"], pattern: DXA_VERSION },
132
- { name: "Exomizer", find: (env) => findTool(EXOMIZER, env), args: ["-v"], pattern: /^Exomizer v\d/ },
133
- ];
134
- return [...(await probeTools(probes, context)), await probeGhidra(context), await probeC64run(context)];
135
- }