@henols/c64-re-tools 2.5.1-rc.2 → 2.6.0-rc.10

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 (87) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +26 -12
  3. package/skills/c64-assembler/scripts/assembler.ts +25 -13
  4. package/skills/c64-development/SKILL.md +2 -2
  5. package/skills/c64-docs/SKILL.md +4 -4
  6. package/skills/c64-docs/scripts/docs.ts +7 -7
  7. package/skills/c64-docs/scripts/lib/reference.ts +3 -3
  8. package/skills/c64-docs/scripts/lib/source-map.ts +9 -4
  9. package/skills/c64-knowledge/SKILL.md +29 -20
  10. package/skills/c64-knowledge/scripts/knowledge.ts +33 -39
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +16 -10
  17. package/skills/c64-source/SKILL.md +60 -42
  18. package/skills/c64-source/scripts/lib/export.ts +76 -32
  19. package/skills/c64-source/scripts/lib/loader.ts +26 -7
  20. package/skills/c64-source/scripts/lib/source.ts +21 -24
  21. package/skills/c64-source/scripts/lib/stage.ts +6 -5
  22. package/skills/c64-source/scripts/source.ts +213 -106
  23. package/skills/c64-static-analysis/SKILL.md +7 -5
  24. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  25. package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
  26. package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -43
  27. package/skills/c64-testing/SKILL.md +5 -2
  28. package/skills/c64-testing/references/recording-format.md +18 -3
  29. package/skills/c64-testing/references/scenario-format.md +7 -6
  30. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  31. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  32. package/skills/c64-testing/scripts/lib/recording.ts +46 -37
  33. package/skills/c64-testing/scripts/lib/replay.ts +1 -1
  34. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  35. package/skills/c64-testing/scripts/lib/scenario.ts +17 -10
  36. package/skills/c64-unpacker/SKILL.md +4 -1
  37. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  38. package/skills/c64-unpacker/scripts/unpacker.ts +5 -3
  39. package/skills/emulator/SKILL.md +7 -12
  40. package/src/build-name.ts +50 -0
  41. package/src/c64-keys.ts +98 -0
  42. package/src/c64.ts +20 -0
  43. package/src/cli/main.ts +3 -29
  44. package/src/host/main.ts +1 -1
  45. package/src/host/tools/index.ts +1 -6
  46. package/src/host/vice/session.ts +88 -9
  47. package/src/host-client/steps.ts +17 -17
  48. package/src/host-client/tools.ts +2 -7
  49. package/src/host-client/vice-session.ts +7 -1
  50. package/src/knowledge/program.ts +44 -1
  51. package/src/knowledge/read.ts +28 -8
  52. package/src/knowledge/schema.ts +33 -9
  53. package/src/knowledge/start-screen.ts +4 -0
  54. package/src/knowledge/text.ts +4 -2
  55. package/src/knowledge/write.ts +59 -25
  56. package/src/mcp/inputs.ts +12 -0
  57. package/src/mcp/server.ts +1 -1
  58. package/src/mcp/tools/input.ts +38 -5
  59. package/src/mcp/tools/machine.ts +3 -42
  60. package/src/mcp/tools/media.ts +1 -1
  61. package/src/native/acme.ts +1 -1
  62. package/src/native/c64run.ts +1 -1
  63. package/src/native/discover.ts +3 -3
  64. package/src/native/dxa.ts +12 -1
  65. package/src/native/ghidra/analyze.ts +74 -63
  66. package/src/native/ghidra/c64rt-wasm.ts +4 -0
  67. package/src/native/ghidra/language/c64rt_6510.sla +0 -0
  68. package/src/native/ghidra/pcode.ts +222 -0
  69. package/src/native/ghidra/walk.ts +205 -0
  70. package/src/native/ghidra/wasm.ts +98 -0
  71. package/src/native/processes.ts +4 -4
  72. package/src/native/types.ts +2 -2
  73. package/src/platform.ts +30 -1
  74. package/src/project.ts +17 -4
  75. package/src/protocol/tools.ts +1 -45
  76. package/src/protocol/vice.ts +47 -0
  77. package/src/script.ts +1 -1
  78. package/src/vsf.ts +98 -0
  79. package/tools/c64run.c +9 -12
  80. package/tools/install-container.sh +1 -2
  81. package/src/cli/status.ts +0 -127
  82. package/src/host/tools/status.ts +0 -47
  83. package/src/native/ghidra/index.ts +0 -170
  84. package/src/native/ghidra/scripts/C64Export.java +0 -274
  85. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  86. package/src/native/status.ts +0 -135
  87. package/tools/install-ghidra.sh +0 -40
@@ -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` |
@@ -44,7 +43,7 @@ Use only the MCP tools. Each MCP session has its own machine. Nothing else can c
44
43
  | Chips of the machine | `c64_vicii`, `c64_sprite`, `c64_cia`, `c64_sid` |
45
44
  | Screen image, screen compare | `c64_screen` |
46
45
  | Several of these from one moment | `c64_observe` |
47
- | Keyboard, joystick | `c64_keyboard`, `c64_joystick` |
46
+ | Keyboard, joystick | `c64_keyboard`, `c64_press`, `c64_joystick` |
48
47
  | Program and disk media | `c64_autostart`, `c64_program_load`, `c64_disk_attach` |
49
48
  | Machine state to go back to, also in a later session | `c64_snapshot` |
50
49
 
@@ -64,21 +63,17 @@ 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
 
76
74
  ### Input that the tools cannot give
77
75
 
78
- Some programs read input in a way that the input tools cannot give. The tool description tells when. Then use one of these ways:
79
-
80
- - Open the window and ask the user to give the input.
81
- - Record a test session with a `press` step.
76
+ Some programs read input in a way that the input tools cannot give. The tool description tells when. Then open the window and ask the user to give the input.
82
77
 
83
78
  Do not change the program to make it accept the input.
84
79
 
@@ -0,0 +1,50 @@
1
+ // The name of a build: the file name tells what kind of build a program is.
2
+ // A release build is release_<label>. A build of config.asm is clean when each
3
+ // switch has its default, else custom_ with each switch that differs: its
4
+ // name when it is on, no_<name> when it is off. A build of an entry other
5
+ // than main.asm adds the entry, for example clean_loader. A source without
6
+ // config.asm and without a release keeps the name of its entry. The symbols
7
+ // of a build go into symbols/ next to the program, so the program folder
8
+ // holds only programs.
9
+
10
+ import { basename, dirname, extname, join } from "node:path";
11
+
12
+ /** The folder of the builds, relative to the project folder. Git does not keep it. */
13
+ export const BUILD_DIRECTORY = "build";
14
+
15
+ /** The file with the value of each switch. The user edits it, and generate keeps the values. */
16
+ export const CONFIG_FILE = "config.asm";
17
+
18
+ /** A value line of config.asm: NAME = 0 or NAME = 1. */
19
+ const CONFIG_VALUE = /^\s*([A-Z][A-Z0-9_]*)\s*=\s*([01])\s*(?:;.*)?$/;
20
+
21
+ /** The values of the switches in a config.asm text, by name. Lines that are not a value line are not read. */
22
+ export function configValues(text: string): Map<string, 0 | 1> {
23
+ const values = new Map<string, 0 | 1>();
24
+ for (const line of text.split(/\r?\n/)) {
25
+ const match = CONFIG_VALUE.exec(line);
26
+ if (match !== null) values.set(match[1]!, match[2] === "1" ? 1 : 0);
27
+ }
28
+ return values;
29
+ }
30
+
31
+ /** What a build is made of: a release, or the values of config.asm with the default of each switch (0 when the defaults do not have it). */
32
+ export type BuildKind = { release: string } | { values: ReadonlyMap<string, number>; defaults: ReadonlyMap<string, number> };
33
+
34
+ /** The name of a build of `entry`, without an extension. */
35
+ export function buildName(entry: string, kind: BuildKind | undefined): string {
36
+ const base = basename(entry, extname(entry));
37
+ if (kind === undefined) return base;
38
+ let type: string;
39
+ if ("release" in kind) type = `release_${kind.release}`;
40
+ else {
41
+ const changed = [...kind.values].filter(([name, value]) => value !== (kind.defaults.get(name) ?? 0)).map(([name, value]) => (value === 0 ? `no_${name}` : name).toLowerCase());
42
+ type = changed.length === 0 ? "clean" : `custom_${changed.join("_")}`;
43
+ }
44
+ return base === "main" ? type : `${type}_${base}`;
45
+ }
46
+
47
+ /** The symbols file of a program: symbols/<name>.json in the folder of the program. */
48
+ export function symbolsPath(program: string): string {
49
+ return join(dirname(program), "symbols", `${basename(program, extname(program))}.json`).split("\\").join("/");
50
+ }
@@ -0,0 +1,98 @@
1
+ // The keys of the C64 keyboard matrix and RESTORE. A key is its place in the
2
+ // matrix: row * 8 + column, where the row is the line of CIA 1 port A that
3
+ // the scan drives low and the column the bit of port B that reads low. The
4
+ // press of VICE and of the replay core, and the play page, use these numbers.
5
+
6
+ /** A press of keys that go down together and up together. `keys` are matrix places, without repeats, in rising order. */
7
+ export interface KeyTap {
8
+ keys: number[];
9
+ restore: boolean;
10
+ }
11
+
12
+ /** The keys that a tap holds at most, RESTORE included: the replay core has no more. */
13
+ export const MAX_TAP_KEYS = 4;
14
+ /** The taps of one press at most. */
15
+ export const MAX_PRESS_TAPS = 64;
16
+ /** The frames that a tap holds its keys, and then waits with all keys up, when the press gives no frames. */
17
+ export const PRESS_FRAMES = 3;
18
+ /** The frames of a tap at most: one minute of PAL frames. */
19
+ export const MAX_PRESS_FRAMES = 3000;
20
+
21
+ /** The matrix, row by row (port A line 0 to 7), column 0 to 7 in each row. A name has more than one character. */
22
+ const MATRIX = [
23
+ ["DEL", "RETURN", "RIGHT", "F7", "F1", "F3", "F5", "DOWN"],
24
+ ["3", "W", "A", "4", "Z", "S", "E", "LSHIFT"],
25
+ ["5", "R", "D", "6", "C", "F", "T", "X"],
26
+ ["7", "Y", "G", "8", "B", "H", "U", "V"],
27
+ ["9", "I", "J", "0", "M", "K", "O", "N"],
28
+ ["+", "P", "L", "-", ".", ":", "@", ","],
29
+ ["POUND", "*", ";", "HOME", "RSHIFT", "=", "UPARROW", "/"],
30
+ ["1", "LEFTARROW", "CTRL", "2", "SPACE", "CBM", "Q", "STOP"],
31
+ ];
32
+
33
+ /** The matrix place of each key. */
34
+ export const MATRIX_KEYS: Readonly<Record<string, number>> = Object.fromEntries(MATRIX.flatMap((row, line) => row.map((key, column) => [key, line * 8 + column])));
35
+
36
+ const LSHIFT = MATRIX_KEYS.LSHIFT!;
37
+
38
+ /** The names that press a key with the left SHIFT: the second function of the key. */
39
+ const SHIFTED_NAMES: Readonly<Record<string, string>> = { F2: "F1", F4: "F3", F6: "F5", F8: "F7", UP: "DOWN", LEFT: "RIGHT", INST: "DEL", CLR: "HOME", RUN: "STOP" };
40
+ /** The characters that a key gives with SHIFT. */
41
+ const SHIFTED_CHARACTERS: Readonly<Record<string, string>> = { "!": "1", '"': "2", "#": "3", $: "4", "%": "5", "&": "6", "'": "7", "(": "8", ")": "9", "[": ":", "]": ";", "<": ",", ">": ".", "?": "/" };
42
+
43
+ /** The names in braces, in the order that a refusal lists them. */
44
+ export const KEY_NAMES = [
45
+ ...["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8"],
46
+ ...["RETURN", "SPACE", "DEL", "INST", "HOME", "CLR", "STOP", "RUN", "RESTORE", "CTRL", "CBM", "LSHIFT", "RSHIFT"],
47
+ ...["UP", "DOWN", "LEFT", "RIGHT", "POUND", "UPARROW", "LEFTARROW"],
48
+ ];
49
+
50
+ /** The matrix places of one key: a name, or one character. Undefined when the C64 has no such key. RESTORE has no place: it gives []. */
51
+ function placesOf(key: string): number[] | undefined {
52
+ const upper = key.toUpperCase();
53
+ if (upper === "RESTORE") return [];
54
+ if (key === "\n") return [MATRIX_KEYS.RETURN!];
55
+ if (key === " ") return [MATRIX_KEYS.SPACE!];
56
+ const shifted = SHIFTED_NAMES[upper] ?? SHIFTED_CHARACTERS[key];
57
+ if (shifted !== undefined) return [LSHIFT, MATRIX_KEYS[shifted]!];
58
+ // A character is its own key; a name has more than one character.
59
+ const place = key.length === 1 || KEY_NAMES.includes(upper) ? MATRIX_KEYS[upper] : undefined;
60
+ return place === undefined ? undefined : [place];
61
+ }
62
+
63
+ /**
64
+ * The taps of a text, or why it has no taps. Each character is one tap, and
65
+ * a-z press the same keys as A-Z. A key without a character has its name in
66
+ * braces, for example {F1}. Names joined with + in braces are one tap that
67
+ * holds the keys together, for example {LSHIFT+CBM} or {STOP+RESTORE}.
68
+ */
69
+ export function keyTaps(text: string): KeyTap[] | string {
70
+ const taps: KeyTap[] = [];
71
+ for (const part of text.replace(/\r\n?/g, "\n").match(/\{[^{}]*\}|[^]/g) ?? []) {
72
+ const keys = part.length > 1 ? part.slice(1, -1).split("+") : [part];
73
+ const places = new Set<number>();
74
+ let restore = false;
75
+ for (const key of keys) {
76
+ const found = key === "" ? undefined : placesOf(key);
77
+ if (found === undefined) {
78
+ if (part.length === 1) return `the C64 keyboard has no key ${JSON.stringify(part)}`;
79
+ return `there is no key ${key === "" ? part : `{${key}}`}. The keys in braces are ${KEY_NAMES.map((name) => `{${name}}`).join(", ")}, and each character key, for example {CTRL+3}. + joins the keys of one tap, for example {LSHIFT+CBM}`;
80
+ }
81
+ if (key.toUpperCase() === "RESTORE") restore = true;
82
+ for (const place of found) places.add(place);
83
+ }
84
+ const count = places.size + (restore ? 1 : 0);
85
+ if (count > MAX_TAP_KEYS) return `${part} holds ${count} keys, and one tap holds at most ${MAX_TAP_KEYS} keys, RESTORE included`;
86
+ taps.push({ keys: [...places].sort((a, b) => a - b), restore });
87
+ }
88
+ if (taps.length === 0) return "give at least one key";
89
+ if (taps.length > MAX_PRESS_TAPS) return `one press has at most ${MAX_PRESS_TAPS} taps. This text has ${taps.length}`;
90
+ return taps;
91
+ }
92
+
93
+ /** The 8 rows of the matrix with `keys` down: bit n of row r is the key at column n. */
94
+ export function matrixRows(keys: readonly number[]): number[] {
95
+ const rows = [0, 0, 0, 0, 0, 0, 0, 0];
96
+ for (const key of keys) rows[key >> 3]! |= 1 << (key & 7);
97
+ return rows;
98
+ }
package/src/c64.ts CHANGED
@@ -478,6 +478,26 @@ export function coverageEntries(map: Uint8Array, image: (address: number) => num
478
478
  return entries;
479
479
  }
480
480
 
481
+ const ROM_ACCESS = COVERAGE.romRead | COVERAGE.romExecute;
482
+ const RAM_USE = COVERAGE.ramRead | COVERAGE.ramExecute;
483
+
484
+ /**
485
+ * The image bytes under ROM that the runs never used: the CPU read or ran the
486
+ * ROM there, and never read or ran the RAM. A JSR $FFE4 or an IRQ
487
+ * vector at $FFFE then leads into ROM, not into the leftover RAM bytes of a
488
+ * flat image, so the ranges are data for an analysis run.
489
+ */
490
+ export function romOnlyRanges(map: Uint8Array, image: (address: number) => number | undefined): AddressRange[] {
491
+ const ranges: AddressRange[] = [];
492
+ for (let address = 0; address < 0x10000; address++) {
493
+ if ((map[address]! & ROM_ACCESS) === 0 || (map[address]! & RAM_USE) !== 0 || image(address) === undefined) continue;
494
+ const last = ranges.at(-1);
495
+ if (last !== undefined && last.end === address - 1) last.end = address;
496
+ else ranges.push({ start: address, end: address });
497
+ }
498
+ return ranges;
499
+ }
500
+
481
501
  /** Every executed instruction start in RAM inside the image: VICE marks the opcode byte of an instruction as executed, not its operand. */
482
502
  export function executedStarts(map: Uint8Array, image: (address: number) => number | undefined): number[] {
483
503
  const starts: number[] = [];
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
@@ -36,9 +31,8 @@ project folder below the root uses that install; a project is a folder with
36
31
  through npx. The Host Runtime runs on the machine with VICE: start it there
37
32
  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
- scripts run ACME, DXA, Exomizer, Ghidra and c64run in the dev container.`;
34
+ scripts run ACME, DXA, Exomizer 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
  }
@@ -5,13 +5,14 @@
5
5
 
6
6
  import { isOneOf, WireFailure, type VideoStandard } from "../../protocol/messages.ts";
7
7
  import { DISK_IMAGE_TYPES, type DiskFile, type DiskImageType } from "../../protocol/tools.ts";
8
- import { MAX_BASELINES, MAX_SNAPSHOTS, MAX_COMPARE_DIFFERENCES, RASTER, type Breakpoint, type BreakpointParams, type PointRemoved, type Condition, type ExecutionParams, type HistoryEntry, type RunTarget, type RunUntilResult, type ScreenComparison, type CiaSelection, type CiaState, type ObserveParams, type ObserveResult, type SidState, type SpriteState, type ViciiState, type JoystickState, type Watchpoint, type WatchpointParams, type ExecutionResult, type MachineStatus, type TraceHit, type TraceKind, type TraceResult, type PointStopReason, type RunState, type ViceOperation, type ViceOperations, type WindowResult } from "../../protocol/vice.ts";
8
+ import { MAX_BASELINES, MAX_SNAPSHOTS, MAX_COMPARE_DIFFERENCES, RASTER, type Breakpoint, type BreakpointParams, type PointRemoved, type Condition, type ExecutionParams, type HistoryEntry, type RunTarget, type RunUntilResult, type ScreenComparison, type CiaSelection, type CiaState, type ObserveParams, type ObserveResult, type SidState, type SpriteState, type ViciiState, type JoystickState, type Watchpoint, type WatchpointParams, type ExecutionResult, type MachineStatus, type TraceHit, type TraceKind, type TraceResult, type PointStopReason, type PressResult, type RunState, type ViceOperation, type ViceOperations, type WindowResult } from "../../protocol/vice.ts";
9
9
  import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
10
  import { tmpdir } from "node:os";
11
11
  import { join } from "node:path";
12
12
  import { setTimeout as sleep } from "node:timers/promises";
13
13
 
14
14
  import { formatC64Address, instructionLength } from "../../c64.ts";
15
+ import { matrixRows } from "../../c64-keys.ts";
15
16
  import { encodePng, type IndexedFrame } from "../../graphics.ts";
16
17
  import { accessedValue, instructionText, operandAddress } from "../../opcodes.ts";
17
18
  import type { ProcessSupervisor } from "../../native/processes.ts";
@@ -33,6 +34,7 @@ import { compareFrames, differenceImage } from "./screen.ts";
33
34
  import { isRefusal } from "../../errors.ts";
34
35
  import type { ViceFeature, ViceFlaw } from "../../native/discover.ts";
35
36
  import { checkMedia, hasSignature } from "../../media.ts";
37
+ import { pressSnapshotRestore, setSnapshotMatrix } from "../../vsf.ts";
36
38
  import { launchVice, startErrorLines, type ViceMode, type ViceProcess } from "./process.ts";
37
39
  import { TextMonitorError, TextMonitorTimeoutError } from "./text-monitor.ts";
38
40
 
@@ -136,6 +138,7 @@ export interface SessionOptions {
136
138
  const BROKEN_MESSAGES: Record<ViceFeature, string> = {
137
139
  joystick: "Joystick input is not implemented in this setup. Do not use the joystick in this task. Give this message to the user.",
138
140
  tape: "The load of a tape image is not implemented in this setup. Do not load tape images in this task. Give this message to the user.",
141
+ keyboard: "Keys of the keyboard matrix are not implemented in this setup. Do not press keys in this task. Give this message to the user.",
139
142
  };
140
143
 
141
144
  export type DiskDirectory = (type: DiskImageType, image: Buffer) => Promise<DiskFile[]>;
@@ -472,16 +475,12 @@ export class ViceSession implements ViceSessionHandle {
472
475
  return this.#reset(params as ViceOperations["reset"]["params"]);
473
476
  case "keyboard": {
474
477
  const bytes = Buffer.from((params as ViceOperations["keyboard"]["params"]).data, "hex");
475
- // VICE turns warp on for an autostart and off when it types RUN. A key in between ends the autostart with no message.
476
- if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
477
- throw new WireFailure(
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.",
480
- );
481
- }
478
+ await this.#refuseWhileAutostartLoads("type");
482
479
  await this.#observe(() => this.#machine.feedKeyboard(bytes));
483
480
  return { queuedBytes: bytes.length };
484
481
  }
482
+ case "press":
483
+ return this.#press(params as ViceOperations["press"]["params"]);
485
484
  case "breakpoint":
486
485
  return this.#breakpoint(params as BreakpointParams);
487
486
  case "watchpoint":
@@ -1185,6 +1184,81 @@ export class ViceSession implements ViceSessionHandle {
1185
1184
  return publicView(point);
1186
1185
  }
1187
1186
 
1187
+ /** VICE turns warp on for an autostart and off when it types RUN. A key in between ends the autostart with no message. */
1188
+ async #refuseWhileAutostartLoads(verb: string): Promise<void> {
1189
+ if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
1190
+ throw new WireFailure(
1191
+ "operation-failed",
1192
+ `The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames, then ${verb} again.`,
1193
+ );
1194
+ }
1195
+ }
1196
+
1197
+ /**
1198
+ * Presses keys of the keyboard matrix and RESTORE. VICE has no command for
1199
+ * that: a snapshot gets the keys in its keyboard module, and RESTORE as a
1200
+ * pending NMI, and is restored at the same cycle. Each tap holds its keys
1201
+ * for `frames` frames, then waits `frames` frames with all keys up. A
1202
+ * breakpoint, watchpoint or JAM ends the taps early, and the machine stays
1203
+ * stopped; else it runs again when it ran before. All keys are up at the end.
1204
+ */
1205
+ async #press(params: ViceOperations["press"]["params"]): Promise<PressResult> {
1206
+ this.#refuseBroken("keyboard", "c64_press");
1207
+ await this.#refuseWhileAutostartLoads("press the keys");
1208
+ if (this.#atResetStop) {
1209
+ throw new WireFailure(
1210
+ "operation-failed",
1211
+ "The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering when keys are pressed here while the disk drive is busy. " +
1212
+ "Step one instruction with c64_execution, then press the keys.",
1213
+ );
1214
+ }
1215
+ const running = this.#state === "running";
1216
+ await this.#stop();
1217
+ await this.#refuseJammed("press");
1218
+ let taps = 0;
1219
+ for (const tap of params.taps) {
1220
+ await this.#setKeys(matrixRows(tap.keys), tap.restore);
1221
+ const held = await this.#runFrames(params.frames);
1222
+ await this.#setKeys(matrixRows([]), false);
1223
+ const end = held.end === "frames" ? await this.#runFrames(params.frames) : held;
1224
+ if (end.end !== "frames") {
1225
+ this.#stopSpace = end.space;
1226
+ return {
1227
+ taps,
1228
+ state: "stopped",
1229
+ stopReason: end.end as PointStopReason,
1230
+ pc: end.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : end.pc,
1231
+ space: end.space,
1232
+ ...(end.pointId === undefined ? {} : { pointId: end.pointId }),
1233
+ };
1234
+ }
1235
+ taps++;
1236
+ }
1237
+ if (running) await this.#resume();
1238
+ return { taps, state: this.#state };
1239
+ }
1240
+
1241
+ /** Sets the keyboard matrix (`rows`, bit n of row r for column n), and presses RESTORE, in a snapshot restored at the same cycle. */
1242
+ async #setKeys(rows: number[], restore: boolean): Promise<void> {
1243
+ const file = join(this.#workDir, "press.vsf");
1244
+ try {
1245
+ await this.#machine.saveSnapshot(file);
1246
+ const bytes = readFileSync(file);
1247
+ const why = setSnapshotMatrix(bytes, rows) ?? (restore ? pressSnapshotRestore(bytes) : undefined);
1248
+ if (why !== undefined) {
1249
+ this.#log(`c64_press was used, and this VICE writes snapshots that c64-re-tools does not know: ${why}.`);
1250
+ throw new WireFailure("not-implemented", BROKEN_MESSAGES.keyboard);
1251
+ }
1252
+ writeFileSync(file, bytes);
1253
+ await this.#machine.restoreSnapshot(file);
1254
+ } finally {
1255
+ rmSync(file, { force: true });
1256
+ }
1257
+ // A restore starts the CPU history of VICE again.
1258
+ this.#historySince = await this.#machine.clock();
1259
+ if (this.#historyStopped) this.#historyOld = true;
1260
+ }
1261
+
1188
1262
  /**
1189
1263
  * Refuses a tool that a known flaw of this VICE breaks: not-implemented for
1190
1264
  * the caller, without the VICE version, and the flaw on the host console.
@@ -1402,7 +1476,12 @@ export class ViceSession implements ViceSessionHandle {
1402
1476
  () => true,
1403
1477
  () => false,
1404
1478
  );
1405
- if (!kept) throw new WireFailure("machine-state-lost", "The emulator did not restore this snapshot file, and the machine state from before the restore is lost. Load the program again.");
1479
+ if (!kept) {
1480
+ throw new WireFailure(
1481
+ "machine-state-lost",
1482
+ "The emulator did not restore this snapshot file, and the machine state from before the restore is lost. A snapshot file restores only in the emulator version and with the machine settings that saved it. Make the snapshot again in this emulator version, and load the program again.",
1483
+ );
1484
+ }
1406
1485
  if (error instanceof WireFailure) throw error;
1407
1486
  throw new WireFailure(
1408
1487
  "invalid-input",
@@ -7,13 +7,14 @@
7
7
  // type c64_keyboard { mode: "text", text } or { mode: "petscii", bytes }: the KERNAL keyboard queue
8
8
  // frames c64_execution the count of advance-frames
9
9
  // runUntil c64_run_until { target, timeoutFrames? }
10
- // press (no tool) keys of the keyboard matrix; only the replay core of c64-testing record and replay has them
10
+ // press c64_press { keys, frames? }: keys of the keyboard matrix and RESTORE
11
11
  //
12
12
  // An address in a step is $ and 1 to 4 hex digits, or a name that the script resolves.
13
13
  // The scripts install without packages, so this checker has no zod: the MCP
14
14
  // tools keep their zod schemas, and a test checks that both take the same inputs.
15
15
 
16
16
  import { c64AddressOf, SYMBOL_NAME, textToPetscii } from "../c64.ts";
17
+ import { keyTaps, MAX_PRESS_FRAMES, PRESS_FRAMES, type KeyTap } from "../c64-keys.ts";
17
18
  import { isRefusal, Refusal } from "../errors.ts";
18
19
  import {
19
20
  COMPARISONS,
@@ -57,14 +58,12 @@ export type ActionStep =
57
58
  | { registers: { pc?: Location; a?: number; x?: number; y?: number; sp?: number; flags?: Flags } }
58
59
  | { joystick: { port: 1 | 2; direction: (typeof JOYSTICK_DIRECTIONS)[number]; fire: boolean } }
59
60
  | { type: KeyboardInput }
60
- | { press: string }
61
+ | { press: { keys: string; frames: number } }
61
62
  | { frames: number }
62
63
  | { runUntil: { target: StepTarget; timeoutFrames: number } };
63
64
 
64
65
  export const ACTION_STEP_KINDS = ["write", "registers", "joystick", "type", "press", "frames", "runUntil"] as const;
65
66
  export type ActionStepKind = (typeof ACTION_STEP_KINDS)[number];
66
- /** The step kinds that VICE runs: all but press, which only the replay core has. */
67
- export const VICE_STEP_KINDS = ACTION_STEP_KINDS.filter((kind) => kind !== "press");
68
67
 
69
68
  /** The fields of each object of the steps: the same as the inputs of the MCP tools. */
70
69
  export const STEP_FIELDS = {
@@ -72,6 +71,7 @@ export const STEP_FIELDS = {
72
71
  registers: ["pc", "a", "x", "y", "sp", "flags"],
73
72
  joystick: ["port", "direction", "fire"],
74
73
  type: ["mode", "text", "bytes"],
74
+ press: ["keys", "frames"],
75
75
  runUntil: ["target", "timeoutFrames"],
76
76
  addressTarget: ["kind", "address", "space", "condition"],
77
77
  memoryTarget: ["kind", "address", "operator", "value", "space", "view"],
@@ -228,9 +228,6 @@ function checkTarget(value: unknown, where: string, fail: (message: string) => n
228
228
  return fail(`${where}.kind must be one of address, memory, raster`);
229
229
  }
230
230
 
231
- /** What a step of a script without the replay core gets for press: the scripts that read these steps run without a window. */
232
- const PRESS_REMEDY = "press pushes keys of the keyboard matrix, and only the replay of a record file has them. Use type for the KERNAL keyboard queue, or put the press step in a record file and play the record file";
233
-
234
231
  /** Checks the input of one step kind and returns it with the defaults of its MCP tool. */
235
232
  function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (message: string) => never): ActionStep {
236
233
  const where = `${at}: ${kind}`;
@@ -275,9 +272,14 @@ function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (mes
275
272
  else if (keys.length > MAX_KEYBOARD_BYTES) fail(`${where}: the keyboard queue takes at most ${MAX_KEYBOARD_BYTES} keys at once. This input has ${keys.length} keys`);
276
273
  return { type: input };
277
274
  }
278
- case "press":
279
- if (typeof value !== "string" || value === "") fail(`${where} needs the keys to press as text`);
280
- return { press: value as string };
275
+ case "press": {
276
+ const fields = new Fields(value, where, STEP_FIELDS.press, fail);
277
+ const keys = fields.get("keys");
278
+ if (typeof keys !== "string") fields.fail("keys", "must be the keys as text, for example {F1} or {LSHIFT+CBM}");
279
+ const taps = keyTaps(keys as string);
280
+ if (typeof taps === "string") fail(`${where}.keys: ${taps}`);
281
+ return { press: { keys: keys as string, frames: fields.integer("frames", 1, MAX_PRESS_FRAMES, PRESS_FRAMES) } };
282
+ }
281
283
  case "frames":
282
284
  if (!isInteger(value, 1, MAX_TIMEOUT_FRAMES)) fail(`${where} must be a frame count from 1 to ${MAX_TIMEOUT_FRAMES}`);
283
285
  return { frames: value as number };
@@ -352,14 +354,12 @@ export function refuseOldStep(kind: string, step: Record<string, unknown>, at: s
352
354
 
353
355
  /**
354
356
  * Checks one action step of the given kind and returns it with the defaults
355
- * filled in. The step has no other key. `press` is refused unless the caller
356
- * runs the steps on the replay core. A step in a form of the 2.0 files is
357
+ * filled in. The step has no other key. A step in a form of the 2.0 files is
357
358
  * refused with the step to write.
358
359
  */
359
- export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never, options: { press?: boolean } = {}): ActionStep {
360
+ export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never): ActionStep {
360
361
  refuseOldStep(kind, step, at, fail);
361
362
  for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which a ${kind} step does not have`);
362
- if (kind === "press" && options.press !== true) fail(`${at}: ${PRESS_REMEDY}`);
363
363
  return checkInput(kind, step[kind], at, fail);
364
364
  }
365
365
 
@@ -376,11 +376,11 @@ export function stepKind<K extends string>(step: unknown, kinds: readonly K[], a
376
376
  }
377
377
 
378
378
  /** Checks a list of action steps and returns them with the defaults filled in. */
379
- export function checkActionSteps(value: unknown, fail: (message: string) => never, options: { press?: boolean } = {}): ActionStep[] {
379
+ export function checkActionSteps(value: unknown, fail: (message: string) => never): ActionStep[] {
380
380
  if (!Array.isArray(value) || value.length === 0) return fail("the steps are a JSON list with at least one step");
381
381
  return value.map((step: unknown, index) => {
382
382
  const at = `step ${index + 1}`;
383
- return checkActionStep(stepKind(step, ACTION_STEP_KINDS, at, fail, options.press === true ? ACTION_STEP_KINDS : VICE_STEP_KINDS), step as Record<string, unknown>, at, fail, options);
383
+ return checkActionStep(stepKind(step, ACTION_STEP_KINDS, at, fail), step as Record<string, unknown>, at, fail);
384
384
  });
385
385
  }
386
386
 
@@ -471,7 +471,7 @@ export async function runActionStep(client: ViceSessionClient, step: ActionStep,
471
471
  } else if ("type" in step) {
472
472
  await client.keyboard(keyboardBytes(step.type) as Uint8Array);
473
473
  } else if ("press" in step) {
474
- throw new Refusal("invalid-input", PRESS_REMEDY);
474
+ await client.press(keyTaps(step.press.keys) as KeyTap[], step.press.frames);
475
475
  } else if ("frames" in step) {
476
476
  await stop(client);
477
477
  // One advance-frames runs at most MAX_EXECUTION_COUNT frames. Each part ends at the raster position
@@ -1,10 +1,10 @@
1
1
  // Short-lived typed requests to the Host Runtime for skill scripts:
2
2
  // VICE's own tools (c1541, petcat) and the host tool status. Each request
3
3
  // opens its own "tool" connection, sends bytes, and closes. Skill scripts run
4
- // ACME, DXA and Ghidra themselves through src/native.
4
+ // ACME, DXA and Ghidra themselves through src/native (Ghidra in process).
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";