@henols/c64-re-tools 2.6.0-rc.7 → 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 (54) 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 +3 -3
  5. package/skills/c64-knowledge/scripts/knowledge.ts +2 -0
  6. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  7. package/skills/c64-reverse-engineering/SKILL.md +1 -1
  8. package/skills/c64-source/SKILL.md +7 -7
  9. package/skills/c64-source/scripts/lib/source.ts +10 -0
  10. package/skills/c64-source/scripts/source.ts +32 -27
  11. package/skills/c64-static-analysis/SKILL.md +5 -3
  12. package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
  13. package/skills/c64-static-analysis/scripts/static-analysis.ts +16 -16
  14. package/skills/c64-testing/SKILL.md +2 -1
  15. package/skills/c64-testing/references/recording-format.md +17 -3
  16. package/skills/c64-testing/references/scenario-format.md +2 -3
  17. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  18. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  19. package/skills/c64-testing/scripts/lib/recording.ts +21 -29
  20. package/skills/c64-testing/scripts/lib/runs.ts +2 -2
  21. package/skills/c64-testing/scripts/lib/scenario.ts +3 -5
  22. package/skills/c64-unpacker/SKILL.md +2 -1
  23. package/skills/c64-unpacker/scripts/lib/loads.ts +2 -2
  24. package/skills/emulator/SKILL.md +2 -5
  25. package/src/c64-keys.ts +98 -0
  26. package/src/cli/main.ts +1 -1
  27. package/src/host/vice/session.ts +82 -8
  28. package/src/host-client/steps.ts +17 -17
  29. package/src/host-client/tools.ts +1 -1
  30. package/src/host-client/vice-session.ts +7 -1
  31. package/src/knowledge/read.ts +25 -1
  32. package/src/mcp/inputs.ts +12 -0
  33. package/src/mcp/server.ts +1 -0
  34. package/src/mcp/tools/input.ts +38 -5
  35. package/src/native/c64run.ts +1 -1
  36. package/src/native/discover.ts +3 -3
  37. package/src/native/ghidra/analyze.ts +74 -63
  38. package/src/native/ghidra/c64rt-wasm.ts +4 -0
  39. package/src/native/ghidra/language/c64rt_6510.sla +0 -0
  40. package/src/native/ghidra/pcode.ts +222 -0
  41. package/src/native/ghidra/walk.ts +205 -0
  42. package/src/native/ghidra/wasm.ts +98 -0
  43. package/src/native/processes.ts +4 -4
  44. package/src/native/types.ts +2 -2
  45. package/src/project.ts +4 -3
  46. package/src/protocol/vice.ts +47 -0
  47. package/src/script.ts +1 -1
  48. package/src/vsf.ts +98 -0
  49. package/tools/c64run.c +9 -12
  50. package/tools/install-container.sh +1 -2
  51. package/src/native/ghidra/index.ts +0 -170
  52. package/src/native/ghidra/scripts/C64Export.java +0 -274
  53. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  54. package/tools/install-ghidra.sh +0 -40
@@ -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
@@ -1,7 +1,7 @@
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
7
  import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
@@ -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>;
@@ -7,7 +7,7 @@ import type { DatabaseSync } from "node:sqlite";
7
7
  import type { AddressRange } from "../c64.ts";
8
8
  import { Refusal } from "../errors.ts";
9
9
  import { DEFAULT_SPACE, type CommentPlacement, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type StartScreenMode, type SuppressionEntity, type SwitchKind, type SymbolKind } from "./schema.ts";
10
- import { NO_REVISION } from "./text.ts";
10
+ import { compareText, NO_REVISION, sqlName, TABLES } from "./text.ts";
11
11
 
12
12
  export interface SymbolRow {
13
13
  space: Space;
@@ -352,6 +352,30 @@ export function currentRevision(db: DatabaseSync | undefined): string {
352
352
  return (db.prepare("SELECT max(id) AS id FROM revisions").get() as { id: string | null }).id ?? "0";
353
353
  }
354
354
 
355
+ /**
356
+ * The newest revision that changed a row in one of `spaces`, or the revision
357
+ * of no knowledge when none did. A change in another space does not change it.
358
+ */
359
+ export function spacesRevision(db: DatabaseSync | undefined, spaces: readonly Space[]): string {
360
+ if (db === undefined || spaces.length === 0) return NO_REVISION;
361
+ const marks = spaces.map(() => "?").join(", ");
362
+ let newest = NO_REVISION;
363
+ for (const spec of TABLES) {
364
+ const row = db.prepare(`SELECT max(valid_from_revision) AS added, max(valid_to_revision) AS closed FROM ${sqlName(spec.table)} WHERE space IN (${marks})`).get(...spaces) as { added: string | null; closed: string | null };
365
+ for (const id of [row.added, row.closed]) if (id !== null && compareText(id, newest) > 0) newest = id;
366
+ }
367
+ return newest;
368
+ }
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
+
355
379
  /** One import of a coverage map: its project path, its SHA-256, the space it went into and the revision. */
356
380
  export interface CoverageRun {
357
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"]),
package/src/mcp/server.ts CHANGED
@@ -35,6 +35,7 @@ export type ViceSessionApi = Pick<
35
35
  | "diskAttach"
36
36
  | "keyboard"
37
37
  | "joystick"
38
+ | "press"
38
39
  | "screenCapture"
39
40
  | "screenCompare"
40
41
  | "screenBaselines"
@@ -1,11 +1,13 @@
1
- // Input tools: c64_keyboard and c64_joystick.
1
+ // Input tools: c64_keyboard, c64_press and c64_joystick.
2
2
 
3
3
  import { z } from "zod";
4
4
 
5
- import { JOYSTICK_DIRECTIONS, MAX_KEYBOARD_BYTES } from "../../protocol/vice.ts";
5
+ import { formatC64Address } from "../../c64.ts";
6
+ import { keyTaps, MAX_PRESS_TAPS, MAX_TAP_KEYS, PRESS_FRAMES, type KeyTap } from "../../c64-keys.ts";
7
+ import { JOYSTICK_DIRECTIONS, MAX_KEYBOARD_BYTES, POINT_STOP_REASONS, RUN_STATES, SPACES } from "../../protocol/vice.ts";
6
8
  import { keyboardBytes } from "../../host-client/steps.ts";
7
9
  import { TOOL_INPUTS } from "../inputs.ts";
8
- import { defineTool } from "../server.ts";
10
+ import { AddressOutput, defineTool } from "../server.ts";
9
11
 
10
12
 
11
13
  export const c64Keyboard = defineTool({
@@ -14,7 +16,7 @@ export const c64Keyboard = defineTool({
14
16
  description:
15
17
  `Type up to ${MAX_KEYBOARD_BYTES} keys into the C64 keyboard queue. The C64 reads them while it runs. ` +
16
18
  "Only a program that reads keys through the KERNAL sees them. A program that reads the keyboard hardware directly does not see them. Many games do that. " +
17
- "No tool presses one key of the keyboard matrix. For one specific key, ask the user to press it in the window, or play a record file with a press step. " +
19
+ "For keys that a program reads from the keyboard hardware, use c64_press. " +
18
20
  'Mode text types text, for example "RUN\\n". Letters of either case type the normal (unshifted) key. A line break types RETURN. ' +
19
21
  "Mode petscii types PETSCII codes 1 to 255 in bytes, for example [147] to clear the screen. " +
20
22
  "While c64_autostart loads a program, this tool refuses keys: see c64_autostart. " +
@@ -29,6 +31,37 @@ export const c64Keyboard = defineTool({
29
31
  },
30
32
  });
31
33
 
34
+ export const c64Press = defineTool({
35
+ name: "c64_press",
36
+ title: "Press keys of the C64 keyboard",
37
+ description:
38
+ "Press keys of the C64 keyboard matrix, and RESTORE. A program that reads the keyboard hardware directly sees these keys. Many games do that. " +
39
+ "Each character of keys is one tap: the key goes down, then up. Letters of either case press the same key. A line break presses RETURN. " +
40
+ "A key without a character has its name in braces: {F1} to {F8}, {RETURN}, {SPACE}, {DEL}, {INST}, {HOME}, {CLR}, {STOP}, {RUN} and {RESTORE}. " +
41
+ "The other names are {CTRL}, {CBM}, {LSHIFT}, {RSHIFT}, {UP}, {DOWN}, {LEFT}, {RIGHT}, {POUND}, {UPARROW} and {LEFTARROW}. " +
42
+ "{F2}, {RUN}, {CLR}, {INST}, {UP} and {LEFT} also press the left SHIFT. " +
43
+ `Join keys with + in braces to hold them together in one tap, for example {LSHIFT+CBM}, {CTRL+3} or {STOP+RESTORE}. One tap holds at most ${MAX_TAP_KEYS} keys, RESTORE included. One call has at most ${MAX_PRESS_TAPS} taps. ` +
44
+ `Each tap holds its keys for frames frames (default ${PRESS_FRAMES}). Then all keys are up for frames frames. The machine runs during the taps, and it runs again after them when it ran before. ` +
45
+ "A breakpoint, watchpoint or JAM stops the taps early. Then stopReason tells why, taps tells how many taps were complete, and the machine stays stopped. All keys are up at the end. " +
46
+ "The CPU history starts again at each tap. " +
47
+ "To type text through the KERNAL keyboard queue, use c64_keyboard.",
48
+ inputSchema: TOOL_INPUTS.press,
49
+ outputSchema: z.object({
50
+ taps: z.number().int().min(0).max(MAX_PRESS_TAPS).describe("the taps that were complete"),
51
+ state: z.enum(RUN_STATES),
52
+ stopReason: z.enum(POINT_STOP_REASONS).optional().describe("why the taps stopped early"),
53
+ pc: AddressOutput.optional(),
54
+ pointId: z.number().int().min(1).optional().describe("the id of the breakpoint or watchpoint that stopped the taps"),
55
+ space: z.enum(SPACES).optional().describe("the CPU that stopped, c64 or drive8. pc is the address in that space"),
56
+ }),
57
+ readOnly: false,
58
+ async run(input, session) {
59
+ // The schema checked the keys: keyTaps gives taps here.
60
+ const { pc, ...result } = await session.press(keyTaps(input.keys) as KeyTap[], input.frames);
61
+ return { ...result, ...(pc === undefined ? {} : { pc: formatC64Address(pc) }) };
62
+ },
63
+ });
64
+
32
65
  export const c64Joystick = defineTool({
33
66
  name: "c64_joystick",
34
67
  title: "Move a joystick",
@@ -44,4 +77,4 @@ export const c64Joystick = defineTool({
44
77
  },
45
78
  });
46
79
 
47
- export const inputTools = [c64Keyboard, c64Joystick];
80
+ export const inputTools = [c64Keyboard, c64Press, c64Joystick];
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
12
12
  import type { ToolContext } from "./run.ts";
13
13
 
14
14
  /** The command protocol that this module speaks; c64run --version and version name it. */
15
- export const C64RUN_PROTOCOL = 3;
15
+ export const C64RUN_PROTOCOL = 4;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
@@ -99,8 +99,8 @@ export function viceVersionOf(text: string): ViceVersion | undefined {
99
99
  return { major: Number(match[1]), minor: Number(match[2]), ...(match[3] === undefined ? {} : { revision: Number(match[3]) }) };
100
100
  }
101
101
 
102
- /** What a VICE flaw stops from working: joystick input, or the load of a tape image. */
103
- export type ViceFeature = "joystick" | "tape";
102
+ /** What a VICE flaw stops from working: joystick input, the load of a tape image, or keys of the keyboard matrix. */
103
+ export type ViceFeature = "joystick" | "tape" | "keyboard";
104
104
 
105
105
  /** A known VICE flaw: the text for the person at the host, and what it stops from working. */
106
106
  export interface ViceFlaw {
@@ -120,7 +120,7 @@ const VICE_FLAWS = [
120
120
  {
121
121
  upTo: { major: 3, minor: 10 },
122
122
  fixedRevision: 45971,
123
- breaks: ["joystick", "tape"],
123
+ breaks: ["joystick", "tape", "keyboard"],
124
124
  text:
125
125
  "VICE 3.10 and older hold bits 5-7 of CIA 1 ports A and B low with the joystick device that c64-re-tools uses (VICE bug #2202). " +
126
126
  "$DC00 and $DC01 read $1F with no input. A program that waits for one key of the keyboard matrix (for example LDA $DC01 / CMP #$EF for SPACE) waits forever. " +
@@ -1,19 +1,16 @@
1
- // The Ghidra analysis: one disposable headless run with the NMOS
2
- // 6510 language, knowledge seeds before analysis, and the structural export
3
- // after it. The result is checked completely before the script imports it.
1
+ // The Ghidra analysis: the Ghidra SLEIGH decoder and decompiler with the NMOS
2
+ // 6510 language, in this process as a WebAssembly module. Knowledge seeds go
3
+ // in, the structural result comes out, and the result is checked completely
4
+ // before the script imports it.
4
5
 
5
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
-
7
- import { Refusal } from "../../errors.ts";
8
- import { describeError, isObject, WireFailure } from "../../protocol/messages.ts";
6
+ import { describeError, WireFailure } from "../../protocol/messages.ts";
9
7
  import { checkGhidraResult, checkRequestBounds, GHIDRA_LIMITS, imageRange, seedsInside, type GhidraParams, type GhidraResult } from "../types.ts";
10
- import { outputTail, type ToolContext } from "../run.ts";
11
- import { Workspace } from "../staging.ts";
12
- import { findGhidra, ghidraVersion, runHeadless, SCRIPT_DIRECTORY } from "./index.ts";
8
+ import type { ToolContext } from "../run.ts";
9
+ import { walk } from "./walk.ts";
10
+ import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
13
11
 
14
- const TIMEOUT_MS = 600_000;
15
- /** The part of the run that the decompilations leave for the export, the project removal and the end of Ghidra. */
16
- const AFTER_DECOMPILE_MS = 30_000;
12
+ /** The longest reason that the result check accepts. */
13
+ const MAX_REASON = 1000;
17
14
 
18
15
  export async function analyze(
19
16
  params: GhidraParams,
@@ -21,67 +18,81 @@ export async function analyze(
21
18
  context: ToolContext,
22
19
  ): Promise<{ result: GhidraResult }> {
23
20
  checkRequestBounds(params);
24
- const ghidra = findGhidra(context.env);
25
21
  const { start, end, body } = imageRange(params.imageKind, image);
26
- const base = start;
27
22
 
28
- // Ghidra disassembles and defines data only in the loaded bytes; labels may name any address.
23
+ // The decoder sees only the loaded bytes; labels may name any address.
29
24
  const { entryPoints, codeStarts, dataRanges } = seedsInside(params, start, end);
30
25
  if (entryPoints.length === 0) {
31
26
  throw new WireFailure("invalid-input", "Give at least one entry point inside the program, for example the SYS address of its BASIC loader.");
32
27
  }
28
+ context.signal.throwIfAborted();
33
29
 
34
- const workspace = Workspace.create(context.supervisor);
30
+ let walked: ReturnType<typeof walk>;
35
31
  try {
36
- workspace.materialize("input", [{ path: "image.bin", size: body.length }], [body]);
37
- writeFileSync(workspace.path("seeds.json"), JSON.stringify({ start, end, entryPoints, codeStarts, dataRanges, labels: params.labels }));
38
- writeFileSync(
39
- workspace.path("request.json"),
40
- JSON.stringify({
41
- start,
42
- end,
43
- decompile: params.decompile,
44
- maxChars: GHIDRA_LIMITS.decompiledChars,
45
- maxTotalChars: GHIDRA_LIMITS.decompiledTotalChars,
46
- decompileDeadline: Date.now() + TIMEOUT_MS - AFTER_DECOMPILE_MS,
47
- }),
48
- );
49
- const run = await runHeadless({
50
- ghidra,
51
- workspace,
52
- file: "input/image.bin",
53
- baseAddress: base,
54
- scriptDirectories: [SCRIPT_DIRECTORY],
55
- preScripts: [{ name: "C64Prepare.java", args: [workspace.path("seeds.json")] }],
56
- postScripts: [{ name: "C64Export.java", args: [workspace.path("request.json"), workspace.path("out.json")] }],
57
- analyze: true,
58
- timeoutMs: TIMEOUT_MS,
59
- supervisor: context.supervisor,
60
- signal: context.signal,
61
- ...(context.env === undefined ? {} : { env: context.env }),
62
- }).catch((error: unknown) => {
63
- context.log?.(`Ghidra failed: ${describeError(error)}`);
64
- throw error;
65
- });
66
- const outPath = workspace.path("out.json");
67
- if (!existsSync(outPath)) {
68
- context.log?.(`Ghidra wrote no result:\n${run.stdout.slice(-4000)}\n${run.stderr.slice(-4000)}`);
69
- // Ghidra's own warnings and errors say why its export script wrote nothing.
70
- throw new WireFailure("operation-failed", `Ghidra finished without a result.${outputTail("Ghidra", run, workspace.root, /ERROR|WARN|Exception|Error:|SCRIPT/)}`);
32
+ loadImage(body, start);
33
+ walked = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels });
34
+ } catch (error) {
35
+ context.log?.(`The Ghidra decoder failed: ${describeError(error)}`);
36
+ throw new WireFailure("operation-failed", `The Ghidra decoder failed: ${describeError(error)}. Nothing was imported.`);
37
+ }
38
+ const { decompilations, notDecompiled } = decompileRoutines(params, walked.functions, body, start, context);
39
+
40
+ let result: GhidraResult;
41
+ try {
42
+ result = checkGhidraResult({ ...walked, decompilations, notDecompiled, completeness: { functions: true, regions: true, references: true }, toolVersion: SLEIGH_VERSION });
43
+ } catch (error) {
44
+ context.log?.(`Ghidra result rejected: ${describeError(error)}`);
45
+ throw new WireFailure("operation-failed", `Ghidra returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
46
+ }
47
+ return { result };
48
+ }
49
+
50
+ /** The requested routines as C text, within the character bounds; the labels name routines and data. */
51
+ function decompileRoutines(params: GhidraParams, functions: GhidraResult["functions"], body: Uint8Array, start: number, context: ToolContext): Pick<GhidraResult, "decompilations" | "notDecompiled"> {
52
+ const decompilations: GhidraResult["decompilations"] = [];
53
+ const notDecompiled: NonNullable<GhidraResult["notDecompiled"]> = [];
54
+ if (params.decompile.length === 0) return { decompilations, notDecompiled };
55
+ const entries = new Set(functions.map((fn) => fn.entry));
56
+ // A trap in the decompiler drops its image: the next routine loads it again.
57
+ let prepared = false;
58
+ const prepare = () => {
59
+ if (prepared) return;
60
+ loadImage(body, start);
61
+ for (const label of params.labels) {
62
+ try {
63
+ setName(label.address, label.name, entries.has(label.address) ? "function" : "data");
64
+ } catch (error) {
65
+ // The decompiler then prints its own name for the address.
66
+ context.log?.(`The Ghidra decompiler refused the name ${label.name}: ${describeError(error)}`);
67
+ }
68
+ }
69
+ prepared = true;
70
+ };
71
+ let remaining = GHIDRA_LIMITS.decompiledTotalChars;
72
+ for (const entry of params.decompile) {
73
+ if (!entries.has(entry)) {
74
+ notDecompiled.push({ entry, reason: "no function starts at this address" });
75
+ continue;
76
+ }
77
+ if (remaining <= 0) {
78
+ notDecompiled.push({ entry, reason: "the decompiled text of the other routines used the whole limit" });
79
+ continue;
71
80
  }
72
- let result: GhidraResult;
81
+ let text: string;
73
82
  try {
74
- const exported: unknown = JSON.parse(readFileSync(outPath, "utf8"));
75
- // The version comes from the installation's application.properties, which findGhidra read.
76
- result = checkGhidraResult(isObject(exported) ? { ...exported, toolVersion: ghidraVersion(ghidra) } : exported);
77
- const [range] = result.coverage;
78
- if (result.coverage.length !== 1 || range === undefined || range.start !== start || range.end !== end) throw new Refusal("operation-failed", "the coverage is not the loaded program");
83
+ prepare();
84
+ text = decompile(entry);
79
85
  } catch (error) {
80
- context.log?.(`Ghidra result rejected: ${describeError(error)}`);
81
- throw new WireFailure("operation-failed", `Ghidra returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
86
+ prepared = false;
87
+ context.log?.(`The Ghidra decompiler failed at ${entry}: ${describeError(error)}`);
88
+ notDecompiled.push({ entry, reason: describeError(error).slice(0, MAX_REASON) || "the decompiler gave no reason" });
89
+ continue;
82
90
  }
83
- return { result };
84
- } finally {
85
- workspace.remove();
91
+ const limit = Math.min(GHIDRA_LIMITS.decompiledChars, remaining);
92
+ const truncated = text.length > limit;
93
+ if (truncated) text = text.slice(0, limit);
94
+ remaining -= text.length;
95
+ decompilations.push({ entry, text, truncated });
86
96
  }
97
+ return { decompilations, notDecompiled };
87
98
  }