@henols/c64-re-tools 2.6.0-rc.8 → 2.6.0-rc.9

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 (35) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-docs/SKILL.md +1 -1
  3. package/skills/c64-docs/scripts/docs.ts +6 -6
  4. package/skills/c64-knowledge/SKILL.md +2 -2
  5. package/skills/c64-source/SKILL.md +2 -2
  6. package/skills/c64-source/scripts/lib/source.ts +10 -0
  7. package/skills/c64-source/scripts/source.ts +15 -12
  8. package/skills/c64-static-analysis/SKILL.md +4 -2
  9. package/skills/c64-static-analysis/scripts/static-analysis.ts +15 -8
  10. package/skills/c64-testing/SKILL.md +1 -1
  11. package/skills/c64-testing/references/recording-format.md +11 -5
  12. package/skills/c64-testing/references/scenario-format.md +2 -3
  13. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  14. package/skills/c64-testing/scripts/lib/play.ts +39 -37
  15. package/skills/c64-testing/scripts/lib/recording.ts +21 -38
  16. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  17. package/skills/c64-testing/scripts/lib/scenario.ts +3 -5
  18. package/skills/c64-unpacker/SKILL.md +2 -1
  19. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  20. package/skills/emulator/SKILL.md +2 -5
  21. package/src/c64-keys.ts +98 -0
  22. package/src/host/vice/session.ts +82 -8
  23. package/src/host-client/steps.ts +17 -17
  24. package/src/host-client/vice-session.ts +7 -1
  25. package/src/knowledge/read.ts +9 -0
  26. package/src/mcp/inputs.ts +12 -0
  27. package/src/mcp/server.ts +1 -0
  28. package/src/mcp/tools/input.ts +38 -5
  29. package/src/native/c64run.ts +1 -1
  30. package/src/native/discover.ts +3 -3
  31. package/src/native/processes.ts +3 -3
  32. package/src/protocol/vice.ts +47 -0
  33. package/src/vsf.ts +98 -0
  34. package/tools/c64run.c +9 -12
  35. package/skills/c64-testing/scripts/lib/keys.ts +0 -36
@@ -13,13 +13,13 @@ import { readFileSync, writeFileSync } from "node:fs";
13
13
 
14
14
  import { isRefusal, Refusal } from "#src/errors.ts";
15
15
  import { c64AddressOf, formatC64Address, parseC64Address } from "#src/c64.ts";
16
+ import { keyTaps, type KeyTap } from "#src/c64-keys.ts";
16
17
  import { READY_FRAMES } from "#src/host-client/entry-state.ts";
17
18
  import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
18
19
  import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
19
20
  import { START_SCREEN_CONTINUE, START_SCREEN_WAIT } from "#src/knowledge/start-screen.ts";
20
21
  import { PAL_FRAME_CYCLES, type C64RunSession, type CoreStatus } from "#src/native/c64run.ts";
21
22
  import type { Workspace } from "#src/native/staging.ts";
22
- import { NAMED_KEYS } from "./keys.ts";
23
23
  import { namesOf, type Outcome } from "./scenario.ts";
24
24
 
25
25
  export const RECORDING_FORMAT = 1;
@@ -139,28 +139,8 @@ const QUEUE_SIZE = 10;
139
139
 
140
140
  const hex = (address: number) => address.toString(16).padStart(4, "0");
141
141
 
142
- /** The keys of the replay core for the characters that a press step can have. */
143
- const KEY_CODES = new Map<string, number>([
144
- ...[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 +-.:@,*;=/!\"#$%&'()[]<>?"].map((character) => [character, character.charCodeAt(0)] as [string, number]),
145
- ["\n", 0x0d],
146
- ]);
147
-
148
- /**
149
- * The key codes of a text; a-z type as A-Z, as the C64 shows them after
150
- * power-on. A key without a character has its name in braces, for example {F1}.
151
- */
152
- export function keyCodes(text: string): number[] {
153
- return (text.replace(/\r\n?/g, "\n").match(/\{[^{}]*\}|[^]/g) ?? []).map((part) => {
154
- if (part.length > 1) {
155
- const named = NAMED_KEYS[part.slice(1, -1).toUpperCase()];
156
- if (named === undefined) throw new Refusal("invalid-input", `press has no key ${part}. The keys in braces are ${Object.keys(NAMED_KEYS).map((name) => `{${name}}`).join(", ")}`);
157
- return named;
158
- }
159
- const code = KEY_CODES.get(part.toUpperCase());
160
- if (code === undefined) throw new Refusal("invalid-input", `press cannot press ${JSON.stringify(part)} on the C64 keyboard`);
161
- return code;
162
- });
163
- }
142
+ /** The key code of the replay core for a matrix place: 80 + the place. RESTORE is ff. */
143
+ const coreKey = (place: number) => (0x80 + place).toString(16);
164
144
 
165
145
  /** The joystick mask of the replay core: 1 up, 2 down, 4 left, 8 right, $10 fire. */
166
146
  export function joystickMask(direction: Extract<ActionStep, { joystick: unknown }>["joystick"]["direction"], fire: boolean): number {
@@ -235,7 +215,7 @@ export function readRecordFile(path: string): RecordFile {
235
215
  if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
236
216
  const steps = (value.steps as unknown[]).map((raw, index) => {
237
217
  const at = `step ${index + 1}`;
238
- const step = checkActionStep(stepKind(raw, ACTION_STEP_KINDS, at, fail), raw as Record<string, unknown>, at, fail, { press: true });
218
+ const step = checkActionStep(stepKind(raw, ACTION_STEP_KINDS, at, fail), raw as Record<string, unknown>, at, fail);
239
219
  checkCoreStep(step, at, fail);
240
220
  return step;
241
221
  });
@@ -254,14 +234,6 @@ export function readRecordFile(path: string): RecordFile {
254
234
  /** What the replay core cannot do of a step that is right for VICE: it has the C64 alone, no raster wait and no conditions. */
255
235
  function checkCoreStep(step: ActionStep, at: string, fail: (message: string) => never): void {
256
236
  if ("write" in step && step.write.space !== "c64") fail(`${at}: a recording has the C64 alone, not ${step.write.space}`);
257
- if ("press" in step) {
258
- try {
259
- keyCodes(step.press);
260
- } catch (error) {
261
- if (isRefusal(error)) fail(`${at}: ${error.message}`);
262
- throw error;
263
- }
264
- }
265
237
  if ("type" in step) {
266
238
  const keys = keyboardBytes(step.type);
267
239
  if (typeof keys !== "string" && keys.length > QUEUE_SIZE) fail(`${at}: the KERNAL keyboard queue holds ${QUEUE_SIZE} keys; give more type steps, or press for keys of the keyboard matrix`);
@@ -307,7 +279,7 @@ export function readRecording(folder: string): Recording {
307
279
  const named = typeof event.step === "number" ? `${at} (step ${event.step})` : at;
308
280
  if (event.action.restore === true && Object.keys(event.action).length === 1) return;
309
281
  // The action with the defaults filled in, as the record file gave it.
310
- event.action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where, { press: true });
282
+ event.action = checkActionStep(stepKind(event.action, ACTION_STEP_KINDS, named, where), event.action, named, where);
311
283
  });
312
284
  return value as unknown as Recording;
313
285
  }
@@ -532,11 +504,22 @@ export async function record(
532
504
  masks[step.joystick.port - 1] = joystickMask(step.joystick.direction, step.joystick.fire ?? false);
533
505
  await core.command(`joy ${masks[0]!.toString(16)} ${masks[1]!.toString(16)}`);
534
506
  } else if ("press" in step) {
535
- for (const code of keyCodes(step.press)) {
536
- await core.command(`key ${code.toString(16)} down`);
537
- await core.status(`run ${(tick += KEY_FRAMES * PAL_FRAME_CYCLES)}`);
538
- await core.command(`key ${code.toString(16)} up`);
539
- await core.status(`run ${(tick += KEY_FRAMES * PAL_FRAME_CYCLES)}`);
507
+ const hold = step.press.frames * PAL_FRAME_CYCLES;
508
+ for (const tap of keyTaps(step.press.keys) as KeyTap[]) {
509
+ for (const place of tap.keys) await core.command(`key ${coreKey(place)} down`);
510
+ // RESTORE is no read: an event at the next read of the program, with the keys of the tap down.
511
+ if (tap.restore) reason = await runEvent({ restore: true }, index + 1);
512
+ if (reason !== undefined) break;
513
+ tick = (await core.status("status")).tick;
514
+ await core.status(`run ${(tick += hold)}`);
515
+ for (const place of tap.keys) await core.command(`key ${coreKey(place)} up`);
516
+ await core.status(`run ${(tick += hold)}`);
517
+ // Frames ran: the next RESTORE is no event right after an event.
518
+ afterEvent = false;
519
+ }
520
+ if (reason !== undefined) {
521
+ reason = `step ${index + 1}: RESTORE: ${reason}`;
522
+ break;
540
523
  }
541
524
  } else {
542
525
  reason = await runEvent(step, index + 1);
@@ -9,7 +9,7 @@ import { screenText } from "#src/graphics.ts";
9
9
  import { runProgram } from "#src/host-client/autostart.ts";
10
10
  import { isRefusal, Refusal } from "#src/errors.ts";
11
11
  import { readCoverage } from "#src/host-client/coverage.ts";
12
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
12
+ import { ACTION_STEP_KINDS, checkActionStep, checkLocation, checkStepNames, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
13
  import { readPrg } from "#src/host-client/image.ts";
14
14
  import { MAX_MEMORY_READ, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, WireFailure, type TraceHit, type TraceKind } from "#src/host-client/tools.ts";
15
15
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -131,7 +131,7 @@ function readRun(path: string): Run {
131
131
  if (!isObject(step)) return fail(`${at} must be an object`);
132
132
  const kinds = "observe" in step ? ["observe"] : "expect" in step ? ["expect"] : "trace" in step ? ["trace"] : Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key) || (OWN_KINDS as readonly string[]).includes(key));
133
133
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
134
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
134
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...ACTION_STEP_KINDS, ...OWN_KINDS].join(", ")}`);
135
135
  const kind = kinds[0]!;
136
136
  refuseOldStep(kind, step, at, fail);
137
137
  const allowed = kind === "observe" ? OBSERVE_KEYS : kind === "expect" ? EXPECT_KEYS : kind === "trace" ? TRACE_KEYS : [kind];
@@ -7,7 +7,7 @@ import { isRefusal, Refusal } from "#src/errors.ts";
7
7
  import { c64AddressOf, formatC64Address, formatSprite, formatVicii, parseC64Address } from "#src/c64.ts";
8
8
  import { MAX_BASELINES, MAX_MASK_RECTANGLES, maskCoversFrame, WireFailure } from "#src/host-client/tools.ts";
9
9
  import { LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, runProgram } from "#src/host-client/autostart.ts";
10
- import { ACTION_STEP_KINDS, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
10
+ import { ACTION_STEP_KINDS, checkActionStep, checkLocation, isInteger, isObject, refuseOldStep, renamedField, runActionStep, type ActionStep, type ActionStepKind, type Location } from "#src/host-client/steps.ts";
11
11
  import { applyEntryState, parseEntryState } from "#src/host-client/entry-state.ts";
12
12
  import { readPrg } from "#src/host-client/image.ts";
13
13
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -52,7 +52,7 @@ type StepBody =
52
52
  | { autostart: true }
53
53
  | { snapshot: string }
54
54
  | { normalize: true }
55
- | Exclude<ActionStep, { press: string }>
55
+ | ActionStep
56
56
  | { observe: string; memory?: Array<Location | MemoryObservation>; registers?: ObservedRegister[]; screen?: ScreenPolicy; vicii?: boolean; sprites?: number[] };
57
57
 
58
58
  /** A step; with side, only that side does it. An observe step has no side: it compares both. */
@@ -108,8 +108,6 @@ export interface ScenarioResult {
108
108
  }
109
109
 
110
110
  const STEP_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...ACTION_STEP_KINDS, "observe"];
111
- /** The step kinds that a scenario runs: press is for the replay core only. */
112
- const SHOWN_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...VICE_STEP_KINDS, "observe"];
113
111
 
114
112
  /** The keys of a scenario file: all but videoStandard are required. */
115
113
  const SCENARIO_KEYS = ["name", "original", "rebuild", "steps", "videoStandard"];
@@ -156,7 +154,7 @@ export function readScenario(path: string): Scenario {
156
154
  // An observe step names what it observes with "memory" and "registers" too.
157
155
  const kinds = "observe" in step ? ["observe"] : Object.keys(step).filter((key) => STEP_KINDS.includes(key));
158
156
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
159
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${SHOWN_KINDS.join(", ")}`);
157
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${STEP_KINDS.join(", ")}`);
160
158
  const kind = kinds[0]!;
161
159
  refuseOldStep(kind, step, at, fail);
162
160
  const allowed = [...(STEP_KEYS[kind] ?? [kind]), ...(kind === "observe" ? [] : ["side"])];
@@ -58,6 +58,7 @@ Each step has one of these kinds:
58
58
  - `{ "registers": { "pc": "start", "a": 1 } }` sets registers. Only `pc` takes a name.
59
59
  - `{ "joystick": { "port": 2, "direction": "up", "fire": false } }` sets a joystick.
60
60
  - `{ "type": { "mode": "text", "text": "RUN\n" } }` or `{ "type": { "mode": "petscii", "bytes": [147] } }` puts keys in the keyboard queue of the KERNAL.
61
+ - `{ "press": { "keys": "{F1}" } }` presses keys of the keyboard matrix. Each character is one tap. A name in braces is a key without a character, for example `{STOP}` or `{RESTORE}`. `+` in braces holds keys together, for example `{LSHIFT+CBM}`. `frames` is 1 to 3000, and 3 by default.
61
62
  - `{ "frames": 50 }` runs 1 to 30000 frames.
62
63
  - `{ "runUntil": { "target": { "kind": "address", "address": "main_loop" }, "timeoutFrames": 300 } }` runs until the target. The target kinds are `address`, `memory` and `raster`. `timeoutFrames` is 1 to 30000. The default is 3000.
63
64
  - `{ "capture": "level1" }` captures a part. Only `loads` takes this step. Give each capture step a different name of 1 to 64 letters, digits, dots, underscores or hyphens.
@@ -65,7 +66,7 @@ Each step has one of these kinds:
65
66
 
66
67
  An address in a step can be a name. The script refuses an unknown name before the program runs. The message gives the file and the step.
67
68
 
68
- The script refuses a `press` step. A program that reads the keyboard matrix does not see the keys of a `type` step. A wait for any key that reads all keyboard columns can end without a key.
69
+ A program that reads the keyboard matrix does not see the keys of a `type` step. Use a `press` step for that program. A wait for any key that reads all keyboard columns can end without a key.
69
70
 
70
71
  The script refuses a step in an old form. The message gives the step to write.
71
72
 
@@ -10,7 +10,7 @@ import { type AddressRange, COVERAGE, formatC64Address } from "#src/c64.ts";
10
10
  import { Refusal } from "#src/errors.ts";
11
11
  import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
12
12
  import { IO_RAM, markIoRamWrites, readCoverage } from "#src/host-client/coverage.ts";
13
- import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
13
+ import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
14
14
  import { knowledgeAt } from "#src/knowledge/names.ts";
15
15
  import { WireFailure } from "#src/host-client/tools.ts";
16
16
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
@@ -64,7 +64,7 @@ export function readLoadSteps(path: string): LoadStep[] {
64
64
  }
65
65
  const kinds = Object.keys(step).filter((key) => (ACTION_STEP_KINDS as readonly string[]).includes(key));
66
66
  if (kinds.length > 1) return fail(`${at} has ${kinds.length} step kinds: ${kinds.join(", ")}. Give each one its own step`);
67
- if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...VICE_STEP_KINDS, "capture", "save"].join(", ")}`);
67
+ if (kinds.length !== 1) return fail(`${at} must have exactly one of ${[...ACTION_STEP_KINDS, "capture", "save"].join(", ")}`);
68
68
  // The step with its defaults filled in, as the shared schema of the action steps gives it.
69
69
  const checked = checkActionStep(kinds[0] as ActionStepKind, step, at, fail);
70
70
  // Its names resolve now: an unknown name stops the call before the emulator starts.
@@ -43,7 +43,7 @@ Use only the MCP tools. Each MCP session has its own machine. Nothing else can c
43
43
  | Chips of the machine | `c64_vicii`, `c64_sprite`, `c64_cia`, `c64_sid` |
44
44
  | Screen image, screen compare | `c64_screen` |
45
45
  | Several of these from one moment | `c64_observe` |
46
- | Keyboard, joystick | `c64_keyboard`, `c64_joystick` |
46
+ | Keyboard, joystick | `c64_keyboard`, `c64_press`, `c64_joystick` |
47
47
  | Program and disk media | `c64_autostart`, `c64_program_load`, `c64_disk_attach` |
48
48
  | Machine state to go back to, also in a later session | `c64_snapshot` |
49
49
 
@@ -73,10 +73,7 @@ Before a risky experiment, save the state with `c64_snapshot`. Restore it to try
73
73
 
74
74
  ### Input that the tools cannot give
75
75
 
76
- Some programs read input in a way that the input tools cannot give. The tool description tells when. Then use one of these ways:
77
-
78
- - Open the window and ask the user to give the input.
79
- - Record a test session with a `press` step. A `press` step presses one key of the keyboard matrix at a time, for example `{F1}` or `{STOP}`, in a session of a PRG file.
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.
80
77
 
81
78
  Do not change the program to make it accept the input.
82
79
 
@@ -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
+ }
@@ -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, then type again.",
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.
@@ -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
@@ -2,7 +2,8 @@
2
2
  // one VICE. Exposes C64-domain operations only.
3
3
 
4
4
  import { ProtocolError, WireFailure, type VideoStandard } from "../protocol/messages.ts";
5
- import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
5
+ import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type PressResult, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
6
+ import type { KeyTap } from "../c64-keys.ts";
6
7
  import { HostConnection } from "./connect.ts";
7
8
  import { readProjectFile } from "./transfer.ts";
8
9
 
@@ -158,6 +159,11 @@ export class ViceSessionClient {
158
159
  return this.#request("joystick", state);
159
160
  }
160
161
 
162
+ /** Presses keys of the keyboard matrix and RESTORE: each tap holds its keys `frames` frames, then waits `frames` frames with all keys up. */
163
+ press(taps: KeyTap[], frames: number): Promise<PressResult> {
164
+ return this.#request("press", { taps, frames });
165
+ }
166
+
161
167
  /** Action list gives all breakpoints, remove gives `{removed, id}`; add, enable and disable give the one breakpoint. */
162
168
  breakpoint(params: Extract<BreakpointParams, { action: "list" }>): Promise<{ breakpoints: Breakpoint[] }>;
163
169
  breakpoint(params: Extract<BreakpointParams, { action: "remove" }>): Promise<PointRemoved>;
@@ -367,6 +367,15 @@ export function spacesRevision(db: DatabaseSync | undefined, spaces: readonly Sp
367
367
  return newest;
368
368
  }
369
369
 
370
+ /**
371
+ * The revision of the source of a space: the newest revision of that space and
372
+ * of the stage of its start screen. A change in another space does not change it.
373
+ */
374
+ export function sourceRevision(db: DatabaseSync | undefined, space: Space = DEFAULT_SPACE): string {
375
+ const stage = space === DEFAULT_SPACE ? currentStartScreen(db, space)?.stage : undefined;
376
+ return spacesRevision(db, [space, ...(stage === undefined ? [] : [stage])]);
377
+ }
378
+
370
379
  /** One import of a coverage map: its project path, its SHA-256, the space it went into and the revision. */
371
380
  export interface CoverageRun {
372
381
  name: string;
package/src/mcp/inputs.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import { z } from "zod";
7
7
 
8
8
  import { c64AddressOf } from "../c64.ts";
9
+ import { keyTaps, MAX_PRESS_FRAMES, PRESS_FRAMES } from "../c64-keys.ts";
9
10
  import { DEFAULT_TIMEOUT_FRAMES, keyboardBytes, MAX_RASTER_LINE } from "../host-client/steps.ts";
10
11
  import { COMPARISONS, CONDITION_REGISTERS, JOYSTICK_DIRECTIONS, MAX_KEYBOARD_BYTES, MAX_MEMORY_WRITE, MAX_TIMEOUT_FRAMES, MEMORY_VIEWS, SPACES } from "../protocol/vice.ts";
11
12
 
@@ -91,6 +92,17 @@ export const TOOL_INPUTS = {
91
92
  })
92
93
  .strict(),
93
94
 
95
+ press: z
96
+ .object({
97
+ keys: z.string().min(1).describe("the keys: each character is one tap, a name in braces is one key, for example {F1}, and + in braces holds keys together, for example {LSHIFT+CBM}"),
98
+ frames: z.number().int().min(1).max(MAX_PRESS_FRAMES).default(PRESS_FRAMES).describe("the frames that each tap holds its keys, and then waits with all keys up"),
99
+ })
100
+ .strict()
101
+ .superRefine((value, context) => {
102
+ const taps = keyTaps(value.keys);
103
+ if (typeof taps === "string") context.addIssue({ code: "custom", message: taps, path: ["keys"] });
104
+ }),
105
+
94
106
  keyboard: z
95
107
  .object({
96
108
  mode: z.enum(["text", "petscii"]),