@henols/c64-re-tools 2.8.0-rc.1 → 2.8.0-rc.3

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 (120) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +7 -4
  3. package/skills/c64-assembler/scripts/assembler.ts +73 -44
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +62 -31
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +28 -18
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +144 -113
  22. package/skills/c64-source/SKILL.md +6 -1
  23. package/skills/c64-source/references/loader.md +2 -1
  24. package/skills/c64-source/scripts/lib/export.ts +54 -301
  25. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  26. package/skills/c64-source/scripts/lib/source.ts +53 -45
  27. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  28. package/skills/c64-source/scripts/source.ts +134 -294
  29. package/skills/c64-static-analysis/SKILL.md +13 -7
  30. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  31. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  32. package/skills/c64-static-analysis/scripts/lib/idioms.ts +98 -19
  33. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  34. package/skills/c64-static-analysis/scripts/static-analysis.ts +249 -147
  35. package/skills/c64-testing/SKILL.md +13 -7
  36. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  37. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  38. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  39. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  40. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  41. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  42. package/skills/c64-testing/scripts/testing.ts +32 -7
  43. package/skills/c64-unpacker/SKILL.md +9 -7
  44. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  45. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  46. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  47. package/skills/c64-unpacker/scripts/lib/stages.ts +124 -40
  48. package/skills/c64-unpacker/scripts/unpacker.ts +81 -68
  49. package/skills/emulator/SKILL.md +1 -0
  50. package/src/c64.ts +133 -10
  51. package/src/cli/ap-sdk.ts +1 -1
  52. package/src/cli/cleanup.ts +4 -2
  53. package/src/compare.ts +36 -16
  54. package/src/errors.ts +10 -1
  55. package/src/host/main.ts +2 -1
  56. package/src/host/server.ts +7 -11
  57. package/src/host/tools/c1541.ts +9 -3
  58. package/src/host/vice/adapter.ts +20 -43
  59. package/src/host/vice/binary-monitor.ts +22 -21
  60. package/src/host/vice/process.ts +31 -40
  61. package/src/host/vice/session.ts +187 -247
  62. package/src/host/vice/text-monitor.ts +3 -3
  63. package/src/host-client/autostart.ts +1 -1
  64. package/src/host-client/connect.ts +2 -1
  65. package/src/host-client/coverage.ts +0 -3
  66. package/src/host-client/entry-state.ts +4 -11
  67. package/src/host-client/image.ts +6 -11
  68. package/src/host-client/steps.ts +13 -113
  69. package/src/host-client/tools.ts +4 -4
  70. package/src/host-client/transfer.ts +10 -0
  71. package/src/host-client/vice-session.ts +10 -6
  72. package/src/knowledge/code-reach.ts +364 -0
  73. package/src/knowledge/conflicts.ts +34 -72
  74. package/src/knowledge/database.ts +40 -28
  75. package/src/knowledge/evidence.ts +2 -2
  76. package/src/knowledge/graph.ts +3 -3
  77. package/src/knowledge/history.ts +50 -90
  78. package/src/knowledge/import.ts +28 -68
  79. package/src/knowledge/join.ts +1 -1
  80. package/src/knowledge/names.ts +12 -7
  81. package/src/knowledge/program.ts +59 -72
  82. package/src/knowledge/read.ts +104 -100
  83. package/src/knowledge/schema.ts +9 -3
  84. package/src/knowledge/separate.ts +175 -80
  85. package/src/knowledge/start-screen.ts +7 -5
  86. package/src/knowledge/text.ts +56 -33
  87. package/src/knowledge/write.ts +274 -515
  88. package/src/loader.ts +7 -25
  89. package/src/mcp/inputs.ts +3 -3
  90. package/src/mcp/server.ts +19 -38
  91. package/src/mcp/session-source.ts +2 -1
  92. package/src/mcp/tools/debug.ts +97 -24
  93. package/src/mcp/tools/execution.ts +1 -1
  94. package/src/mcp/tools/input.ts +3 -3
  95. package/src/mcp/tools/machine.ts +3 -3
  96. package/src/mcp/tools/media.ts +4 -4
  97. package/src/mcp/tools/memory.ts +13 -17
  98. package/src/mcp/tools/video.ts +11 -25
  99. package/src/native/acme.ts +3 -3
  100. package/src/native/c64run.ts +2 -1
  101. package/src/native/decompiler/analyze.ts +11 -8
  102. package/src/native/decompiler/walk.ts +3 -4
  103. package/src/native/decompiler/wasm.ts +2 -2
  104. package/src/native/discover.ts +1 -1
  105. package/src/native/dxa.ts +9 -11
  106. package/src/native/exomizer.ts +1 -1
  107. package/src/native/processes.ts +4 -1
  108. package/src/native/run.ts +3 -3
  109. package/src/native/types.ts +9 -8
  110. package/src/opcodes.ts +3 -0
  111. package/src/platform.ts +9 -10
  112. package/src/program-code.ts +151 -0
  113. package/src/project.ts +8 -5
  114. package/src/protocol/framing.ts +51 -18
  115. package/src/protocol/messages.ts +1 -11
  116. package/src/protocol/tools.ts +0 -3
  117. package/src/protocol/vice.ts +588 -773
  118. package/src/script.ts +25 -23
  119. package/src/time.ts +1 -1
  120. package/src/trace.ts +3 -2
@@ -14,7 +14,7 @@ import { setTimeout as sleep } from "node:timers/promises";
14
14
  import { formatC64Address, instructionLength } from "../../c64.ts";
15
15
  import { matrixRows } from "../../c64-keys.ts";
16
16
  import { encodePng, type IndexedFrame } from "../../graphics.ts";
17
- import { accessedValue, instructionText, operandAddress } from "../../opcodes.ts";
17
+ import { accessedValue, instructionText, JAM_OPCODES, OPCODES, operandAddress } from "../../opcodes.ts";
18
18
  import type { ProcessSupervisor } from "../../native/processes.ts";
19
19
  import { trace } from "../../trace.ts";
20
20
  import type { ViceSessionFactory, ViceSessionHandle } from "../server.ts";
@@ -22,7 +22,6 @@ import {
22
22
  backtraceFromStack,
23
23
  conditionExpression,
24
24
  inRasterWindow,
25
- JAM_OPCODES,
26
25
  rasterLinesExpression,
27
26
  rasterWindowExpression,
28
27
  RUNNING_COMMAND_TIMEOUT_MS,
@@ -31,7 +30,7 @@ import {
31
30
  import { decodeProgramCounter, MonitorConnectionError, MonitorError, MonitorTimeoutError, ResponseType, type MonitorResponse } from "./binary-monitor.ts";
32
31
  import { decodeCia, decodeSid, decodeSprite, decodeVicii } from "./chips.ts";
33
32
  import { compareFrames, differenceImage } from "./screen.ts";
34
- import { isRefusal } from "../../errors.ts";
33
+ import { describeError, isRefusal } from "../../errors.ts";
35
34
  import type { ViceFeature, ViceFlaw } from "../../native/discover.ts";
36
35
  import { checkMedia, hasSignature } from "../../media.ts";
37
36
  import { pressSnapshotRestore, setSnapshotMatrix } from "../../vsf.ts";
@@ -68,7 +67,7 @@ class StepTimeout extends Error {
68
67
  override name = "StepTimeout";
69
68
  readonly why: string;
70
69
  constructor(why: string, cause: unknown) {
71
- super(cause instanceof Error ? cause.message : String(cause));
70
+ super(describeError(cause));
72
71
  this.why = why;
73
72
  }
74
73
  }
@@ -243,13 +242,12 @@ export class ViceSession implements ViceSessionHandle {
243
242
  #heldWhy = VICE_HELD;
244
243
  /** Session-local snapshots by name, as files in the session directory. */
245
244
  readonly #snapshots = new Map<string, string>();
246
- #snapshotFiles = 0;
247
245
  /** Session-local screen baselines, lost with the session. */
248
246
  readonly #baselines = new Map<string, { frame: IndexedFrame; palette: Array<[number, number, number]> }>();
249
247
  /** The CPU clock when the session stopwatch last started (c64_timing). */
250
248
  #timingStart = 0n;
251
- /** Counts staged media files, for unique names. */
252
- #staged = 0;
249
+ /** Counts the snapshot and staged media files, for unique names. */
250
+ #files = 0;
253
251
  /** True after an autostart of a cartridge, until an autostart of another file detaches it. */
254
252
  #cartridge = false;
255
253
  /** The last staged file of each kind that VICE took; VICE can still read it. */
@@ -316,7 +314,7 @@ export class ViceSession implements ViceSessionHandle {
316
314
  return;
317
315
  }
318
316
  this.#lost = true;
319
- void vice.stop().catch((error: unknown) => this.#log(`stopping the lost VICE failed: ${error instanceof Error ? error.message : String(error)}`));
317
+ void vice.stop().catch((error: unknown) => this.#log(`stopping the lost VICE failed: ${describeError(error)}`));
320
318
  }
321
319
 
322
320
  /** Restarts headless from the handover saved when the window opened. */
@@ -331,7 +329,7 @@ export class ViceSession implements ViceSessionHandle {
331
329
  this.#log("the session is headless again, in the state of when the window opened");
332
330
  } catch (error) {
333
331
  this.#lost = true;
334
- this.#log(`going back headless failed: ${error instanceof Error ? error.message : String(error)}`);
332
+ this.#log(`going back headless failed: ${describeError(error)}`);
335
333
  } finally {
336
334
  this.#windowClosing = false;
337
335
  }
@@ -369,8 +367,9 @@ export class ViceSession implements ViceSessionHandle {
369
367
  attachments: Buffer[] = [],
370
368
  reply: Buffer[] = [],
371
369
  ): Promise<ViceOperations[O]["result"]> {
370
+ if (!Object.hasOwn(this.#operations, op)) return Promise.reject(new WireFailure("invalid-input", `unknown operation: ${String(op)}`));
372
371
  // A window request for the mode the session is in sends nothing to VICE, so a held VICE does not stop it.
373
- return this.#enqueue(() => this.#run(op, params, attachments, reply), { whileHeld: op === "window" }) as Promise<ViceOperations[O]["result"]>;
372
+ return this.#enqueue(() => this.#operations[op](params, attachments, reply), { whileHeld: op === "window" });
374
373
  }
375
374
 
376
375
  async close(): Promise<void> {
@@ -389,205 +388,151 @@ export class ViceSession implements ViceSessionHandle {
389
388
  return this.#adapter;
390
389
  }
391
390
 
392
- async #run(op: ViceOperation, params: unknown, attachments: Buffer[], reply: Buffer[]): Promise<unknown> {
393
- switch (op) {
394
- case "status":
395
- return this.#status();
396
- case "ioRead": {
397
- const read = params as ViceOperations["ioRead"]["params"];
398
- const bytes = await this.#observe(() => this.#machine.readIo(read.address, read.size));
399
- return { address: read.address, data: Buffer.from(bytes).toString("hex") };
391
+ /** The work of each operation, with its parameters checked on the wire. */
392
+ readonly #operations: { [O in ViceOperation]: (params: ViceOperations[O]["params"], attachments: Buffer[], reply: Buffer[]) => Promise<ViceOperations[O]["result"]> } = {
393
+ status: () => this.#status(),
394
+ ioRead: async ({ address, size }) => {
395
+ const bytes = await this.#observe(() => this.#machine.readIo(address, size));
396
+ return { address, data: Buffer.from(bytes).toString("hex") };
397
+ },
398
+ memoryRead: async (read) => ({ address: read.address, data: await this.#observe(() => this.#machine.readMemory(read)) }),
399
+ registersGet: ({ space }) => this.#observe(() => this.#machine.readRegisters(space)),
400
+ memoryWrite: async (write) => {
401
+ this.#requireStopped();
402
+ return { address: write.address, bytesWritten: await this.#machine.writeMemory(write) };
403
+ },
404
+ memorySearch: async (search) => ({ matches: await this.#observe(() => this.#machine.search({ ...search, limit: search.maxResults })) }),
405
+ memoryCompare: (params) => this.#memoryCompare(params),
406
+ disassemble: async (request) => ({ instructions: await this.#observe(() => this.#machine.disassemble(request)) }),
407
+ registersSet: async ({ space, values }) => {
408
+ this.#requireStopped();
409
+ return this.#machine.writeRegisters(space, values);
410
+ },
411
+ execution: (params) => this.#execution(params),
412
+ runUntil: (params) => this.#runUntil(params),
413
+ programLoad: async (params, attachments) => this.#programLoad(params, onlyAttachment(attachments)),
414
+ autostart: async ({ type, index, run }, attachments) => {
415
+ if (type === "tap") this.#refuseBroken("tape", "c64_autostart of a tape image");
416
+ const bytes = onlyAttachment(attachments);
417
+ checkMedia(type, bytes);
418
+ if (index > 0 && this.#directory !== undefined && isOneOf(DISK_IMAGE_TYPES, type)) checkDirectoryEntry(await this.#directory(type, bytes, this.#abort.signal), index);
419
+ const file = this.#stage(bytes, type);
420
+ // VICE keeps a cartridge through every reset and autostart, as a real C64 does.
421
+ if (type !== "crt" && this.#cartridge) {
422
+ await this.#observe(() => this.#machine.detachCartridge());
423
+ this.#cartridge = false;
424
+ this.#replaceStaged("cartridge", undefined);
400
425
  }
401
- case "memoryRead": {
402
- const read = params as ViceOperations["memoryRead"]["params"];
403
- const data = await this.#observe(() => this.#machine.readMemory(read));
404
- return { address: read.address, data };
426
+ // Port 1 shares the keyboard lines: a held direction types keys into the RUN that the autostart types.
427
+ const centred: Array<1 | 2> = [];
428
+ for (const [port, joystick] of this.#joysticks) {
429
+ if (joystick.direction === "center" && !joystick.fire) continue;
430
+ const centre: JoystickState = { port, direction: "center", fire: false };
431
+ await this.#observe(() => this.#machine.setJoystick(centre));
432
+ this.#joysticks.set(port, centre);
433
+ centred.push(port);
405
434
  }
406
- case "registersGet": {
407
- const { space } = params as ViceOperations["registersGet"]["params"];
408
- return this.#observe(() => this.#machine.readRegisters(space));
409
- }
410
- case "memoryWrite": {
411
- const write = params as ViceOperations["memoryWrite"]["params"];
412
- this.#requireStopped();
413
- return { address: write.address, bytesWritten: await this.#machine.writeMemory(write) };
414
- }
415
- case "memorySearch": {
416
- const search = params as ViceOperations["memorySearch"]["params"];
417
- const matches = await this.#observe(() => this.#machine.search({ ...search, limit: search.maxResults }));
418
- return { matches };
419
- }
420
- case "memoryCompare":
421
- return this.#memoryCompare(params as ViceOperations["memoryCompare"]["params"]);
422
- case "disassemble": {
423
- const request = params as ViceOperations["disassemble"]["params"];
424
- return { instructions: await this.#observe(() => this.#machine.disassemble(request)) };
425
- }
426
- case "registersSet": {
427
- const { space, values } = params as ViceOperations["registersSet"]["params"];
428
- this.#requireStopped();
429
- return this.#machine.writeRegisters(space, values);
430
- }
431
- case "execution":
432
- return this.#execution(params as ExecutionParams);
433
- case "runUntil":
434
- return this.#runUntil(params as ViceOperations["runUntil"]["params"]);
435
- case "programLoad":
436
- return this.#programLoad(params as ViceOperations["programLoad"]["params"], onlyAttachment(attachments));
437
- case "autostart": {
438
- const { type, index, run } = params as ViceOperations["autostart"]["params"];
439
- if (type === "tap") this.#refuseBroken("tape", "c64_autostart of a tape image");
440
- const bytes = onlyAttachment(attachments);
441
- checkMedia(type, bytes);
442
- if (index > 0 && this.#directory !== undefined && isOneOf(DISK_IMAGE_TYPES, type)) checkDirectoryEntry(await this.#directory(type, bytes, this.#abort.signal), index);
443
- const file = this.#stage(bytes, type);
444
- // VICE keeps a cartridge through every reset and autostart, as a real C64 does.
445
- if (type !== "crt" && this.#cartridge) {
446
- await this.#observe(() => this.#machine.detachCartridge());
447
- this.#cartridge = false;
448
- this.#replaceStaged("cartridge", undefined);
449
- }
450
- // Port 1 shares the keyboard lines: a held direction types keys into the RUN that the autostart types.
451
- const centred: Array<1 | 2> = [];
452
- for (const [port, joystick] of this.#joysticks) {
453
- if (joystick.direction === "center" && !joystick.fire) continue;
454
- const centre: JoystickState = { port, direction: "center", fire: false };
455
- await this.#observe(() => this.#machine.setJoystick(centre));
456
- this.#joysticks.set(port, centre);
457
- centred.push(port);
458
- }
459
- await this.#runningCommand(() => this.#machine.autostart(file, index, run));
460
- this.#clearJam();
461
- this.#autostarting = true;
462
- if (type === "crt") this.#cartridge = true;
463
- this.#replaceStaged(stagedKind(type), file);
464
- // A reset sets the CPU clock back, so the stopwatch starts again.
465
- this.#timingStart = 0n;
466
- return { state: "running", ...(centred.length === 0 ? {} : { joysticksCentred: centred }) };
467
- }
468
- case "diskAttach": {
469
- const { type } = params as ViceOperations["diskAttach"]["params"];
470
- const bytes = onlyAttachment(attachments);
471
- checkMedia(type, bytes);
472
- const file = this.#stage(bytes, type);
473
- await this.#observe(() => this.#machine.attachDisk(file));
474
- this.#replaceStaged("disk", file);
475
- return { attached: true };
476
- }
477
- case "reset":
478
- return this.#reset(params as ViceOperations["reset"]["params"]);
479
- case "keyboard": {
480
- const bytes = Buffer.from((params as ViceOperations["keyboard"]["params"]).data, "hex");
481
- await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "type");
482
- await this.#observe(() => this.#machine.feedKeyboard(bytes));
483
- return { queuedBytes: bytes.length };
484
- }
485
- case "press":
486
- return this.#press(params as ViceOperations["press"]["params"]);
487
- case "breakpoint":
488
- return this.#breakpoint(params as BreakpointParams);
489
- case "watchpoint":
490
- return this.#watchpoint(params as WatchpointParams);
491
- case "screenCapture": {
492
- const { baseline } = params as ViceOperations["screenCapture"]["params"];
493
- if (baseline !== undefined && !this.#baselines.has(baseline) && this.#baselines.size >= MAX_BASELINES) {
494
- throw new WireFailure("limit-exceeded", `A session keeps at most ${MAX_BASELINES} baselines. Remove one first with c64_screen action remove.`);
495
- }
496
- const shot = await this.#observe(() => this.#machine.captureFrame(this.#videoStandard));
497
- if (baseline !== undefined) this.#baselines.set(baseline, shot);
498
- const result: ViceOperations["screenCapture"]["result"] = {
499
- width: shot.frame.width,
500
- height: shot.frame.height,
501
- png: encodePng(shot.frame, shot.palette).toString("base64"),
502
- };
503
- if (baseline !== undefined) result.baseline = baseline;
504
- return result;
505
- }
506
- case "screenCompare":
507
- return this.#screenCompare(params as ViceOperations["screenCompare"]["params"]);
508
- case "screenBaselines":
509
- return { baselines: [...this.#baselines.keys()] };
510
- case "screenDiscard": {
511
- const { baseline } = params as ViceOperations["screenDiscard"]["params"];
512
- if (!this.#baselines.delete(baseline)) throw new WireFailure("not-found", `There is no baseline named ${baseline}.`);
513
- return { removed: true };
514
- }
515
- case "snapshot":
516
- return this.#snapshot(params as ViceOperations["snapshot"]["params"]);
517
- case "snapshotFile":
518
- return this.#snapshotFile(params as ViceOperations["snapshotFile"]["params"], attachments, reply);
519
- case "cpuHistory":
520
- return this.#cpuHistory(params as ViceOperations["cpuHistory"]["params"]);
521
- case "trace": {
522
- // The hits go as an attachment: thousands of them do not fit in one message.
523
- const { hits, ...traced } = await this.#trace(params as ViceOperations["trace"]["params"]);
524
- reply.push(Buffer.from(JSON.stringify(hits), "utf8"));
525
- return { ...traced, hits: hits.length };
526
- }
527
- case "backtrace": {
528
- const { depth, space } = params as ViceOperations["backtrace"]["params"];
529
- return this.#observe(async () => {
530
- const { sp } = await this.#machine.readRegisters(space);
531
- return { frames: backtraceFromStack(sp, await this.#machine.readAll(space), depth) };
532
- });
533
- }
534
- case "timing": {
535
- const { action } = params as ViceOperations["timing"]["params"];
536
- const now = await this.#observe(() => this.#machine.clock());
537
- if (action === "start") {
538
- this.#timingStart = now;
539
- return { started: true };
540
- }
541
- return { cycles: (now - this.#timingStart).toString() };
542
- }
543
- case "profile": {
544
- const request = params as ViceOperations["profile"]["params"];
545
- if (request.action === "clear") {
546
- await this.#observe(() => this.#machine.startProfiler());
547
- return { cleared: true };
548
- }
549
- return { entries: await this.#observe(() => this.#machine.profile(request.limit)) };
550
- }
551
- case "memmap": {
552
- const request = params as ViceOperations["memmap"]["params"];
553
- if (request.action === "clear") {
554
- await this.#observe(() => this.#machine.clearMemmap());
555
- return { cleared: true };
556
- }
557
- return await this.#observe(() => this.#machine.memmap(request.start, request.end, request.maxRanges));
558
- }
559
- case "vicii":
560
- return this.#observe(() => this.#vicii());
561
- case "sprites": {
562
- const { indexes } = params as ViceOperations["sprites"]["params"];
563
- return this.#observe(async () => ({ sprites: await this.#sprites(indexes) }));
435
+ await this.#runningCommand(() => this.#machine.autostart(file, index, run));
436
+ this.#clearJam();
437
+ this.#autostarting = true;
438
+ if (type === "crt") this.#cartridge = true;
439
+ this.#replaceStaged(stagedKind(type), file);
440
+ // A reset sets the CPU clock back, so the stopwatch starts again.
441
+ this.#timingStart = 0n;
442
+ return { state: "running", ...(centred.length === 0 ? {} : { joysticksCentred: centred }) };
443
+ },
444
+ diskAttach: async ({ type }, attachments) => {
445
+ const bytes = onlyAttachment(attachments);
446
+ checkMedia(type, bytes);
447
+ const file = this.#stage(bytes, type);
448
+ await this.#observe(() => this.#machine.attachDisk(file));
449
+ this.#replaceStaged("disk", file);
450
+ return { attached: true };
451
+ },
452
+ reset: (params) => this.#reset(params),
453
+ keyboard: async ({ data }) => {
454
+ const bytes = Buffer.from(data, "hex");
455
+ await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "type");
456
+ await this.#observe(() => this.#machine.feedKeyboard(bytes));
457
+ return { queuedBytes: bytes.length };
458
+ },
459
+ press: (params) => this.#press(params),
460
+ breakpoint: (params) => this.#breakpoint(params),
461
+ watchpoint: (params) => this.#watchpoint(params),
462
+ screenCapture: async ({ baseline }) => {
463
+ if (baseline !== undefined && !this.#baselines.has(baseline) && this.#baselines.size >= MAX_BASELINES) {
464
+ throw new WireFailure("limit-exceeded", `A session keeps at most ${MAX_BASELINES} baselines. Remove one first with c64_screen action remove.`);
564
465
  }
565
- case "cia": {
566
- const { which } = params as ViceOperations["cia"]["params"];
567
- return this.#observe(async () => ({ chips: await this.#cias(which) }));
466
+ const shot = await this.#observe(() => this.#machine.captureFrame(this.#videoStandard));
467
+ if (baseline !== undefined) this.#baselines.set(baseline, shot);
468
+ const result: ViceOperations["screenCapture"]["result"] = {
469
+ width: shot.frame.width,
470
+ height: shot.frame.height,
471
+ png: encodePng(shot.frame, shot.palette).toString("base64"),
472
+ };
473
+ if (baseline !== undefined) result.baseline = baseline;
474
+ return result;
475
+ },
476
+ screenCompare: (params) => this.#screenCompare(params),
477
+ screenBaselines: async () => ({ baselines: [...this.#baselines.keys()] }),
478
+ screenDiscard: async ({ baseline }) => {
479
+ if (!this.#baselines.delete(baseline)) throw new WireFailure("not-found", `There is no baseline named ${baseline}.`);
480
+ return { removed: true };
481
+ },
482
+ snapshot: (params) => this.#snapshot(params),
483
+ snapshotFile: (params, attachments, reply) => this.#snapshotFile(params, attachments, reply),
484
+ cpuHistory: (params) => this.#cpuHistory(params),
485
+ trace: async (params, _attachments, reply) => {
486
+ // The hits go as an attachment: thousands of them do not fit in one message.
487
+ const { hits, ...traced } = await this.#trace(params);
488
+ reply.push(Buffer.from(JSON.stringify(hits), "utf8"));
489
+ return { ...traced, hits: hits.length };
490
+ },
491
+ backtrace: ({ depth, space }) =>
492
+ this.#observe(async () => {
493
+ const { sp } = await this.#machine.readRegisters(space);
494
+ return { frames: backtraceFromStack(sp, await this.#machine.readAll(space), depth) };
495
+ }),
496
+ timing: async ({ action }) => {
497
+ const now = await this.#observe(() => this.#machine.clock());
498
+ if (action === "start") {
499
+ this.#timingStart = now;
500
+ return { started: true };
568
501
  }
569
- case "sid":
570
- return this.#observe(() => this.#sid());
571
- case "observe":
572
- return this.#observeAll(params as ObserveParams);
573
- case "joystick": {
574
- this.#refuseBroken("joystick", "c64_joystick");
575
- const joystick = params as JoystickState;
576
- await this.#observe(() => this.#machine.setJoystick(joystick));
577
- this.#joysticks.set(joystick.port, joystick);
578
- return joystick;
502
+ return { cycles: (now - this.#timingStart).toString() };
503
+ },
504
+ profile: async (request) => {
505
+ if (request.action === "clear") {
506
+ await this.#observe(() => this.#machine.startProfiler());
507
+ return { cleared: true };
579
508
  }
580
- case "warp": {
581
- const { enabled } = params as ViceOperations["warp"]["params"];
582
- await this.#observe(() => this.#machine.setWarp(enabled));
583
- this.#userWarp = enabled;
584
- return { enabled };
509
+ return { entries: await this.#observe(() => this.#machine.profile(request.limit)) };
510
+ },
511
+ memmap: async (request) => {
512
+ if (request.action === "clear") {
513
+ await this.#observe(() => this.#machine.clearMemmap());
514
+ return { cleared: true };
585
515
  }
586
- case "window":
587
- return this.#window((params as ViceOperations["window"]["params"]).action === "open" ? "window" : "headless");
588
- }
589
- throw new WireFailure("invalid-input", `unknown operation: ${String(op)}`);
590
- }
516
+ return await this.#observe(() => this.#machine.memmap(request.start, request.end, request.maxRanges));
517
+ },
518
+ vicii: () => this.#observe(() => this.#vicii()),
519
+ sprites: ({ indexes }) => this.#observe(async () => ({ sprites: await this.#sprites(indexes) })),
520
+ cia: ({ which }) => this.#observe(async () => ({ chips: await this.#cias(which) })),
521
+ sid: () => this.#observe(() => this.#sid()),
522
+ observe: (params) => this.#observeAll(params),
523
+ joystick: async (joystick) => {
524
+ this.#refuseBroken("joystick", "c64_joystick");
525
+ await this.#observe(() => this.#machine.setJoystick(joystick));
526
+ this.#joysticks.set(joystick.port, joystick);
527
+ return joystick;
528
+ },
529
+ warp: async ({ enabled }) => {
530
+ await this.#observe(() => this.#machine.setWarp(enabled));
531
+ this.#userWarp = enabled;
532
+ return { enabled };
533
+ },
534
+ window: ({ action }) => this.#window(action === "open" ? "window" : "headless"),
535
+ };
591
536
 
592
537
  async #status(): Promise<MachineStatus> {
593
538
  const warp = await this.#observe(() => this.#machine.warp());
@@ -643,11 +588,9 @@ export class ViceSession implements ViceSessionHandle {
643
588
  throw new WireFailure("invalid-input", `The anchor is outside the frame: a ${this.#videoStandard} frame has lines 0-${raster.lines - 1} and cycles 0-${raster.cycles - 1}.`);
644
589
  }
645
590
  const outcome = await this.#runFrames(params.count, undefined, params.anchor);
646
- this.#stopSpace = outcome.space;
647
591
  return {
648
592
  state: "stopped",
649
- // A stop event carries the computer's PC; a stop in the drive reports the drive's.
650
- pc: outcome.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : outcome.pc,
593
+ pc: await this.#recordStop(outcome),
651
594
  space: outcome.space,
652
595
  advancedFrames: outcome.frames,
653
596
  stopReason: outcome.end === "target" ? "frames" : outcome.end,
@@ -689,6 +632,12 @@ export class ViceSession implements ViceSessionHandle {
689
632
  return { state: "stopped", pc: await this.#pc(), ...(point.pointId === undefined ? { executed: count } : point) };
690
633
  }
691
634
 
635
+ /** Records the CPU that a frame-clocked run stopped in, which status gives from then on, and returns its pc: a stop event carries the computer's pc, a stop in the drive reports the drive's. */
636
+ async #recordStop(outcome: { pc: number; space: "c64" | "drive8" }): Promise<number> {
637
+ this.#stopSpace = outcome.space;
638
+ return outcome.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : outcome.pc;
639
+ }
640
+
692
641
  /** The breakpoint or watchpoint that stopped a step, next or until-return early; VICE then keeps the rest of the step. */
693
642
  #stepStoppedByPoint(): { stopReason?: PointStopReason; pointId?: number } {
694
643
  const stop = this.#lastStop;
@@ -891,7 +840,6 @@ export class ViceSession implements ViceSessionHandle {
891
840
  */
892
841
  async #traceHit(point: number, kind: TraceKind, frame: number): Promise<TraceHit> {
893
842
  const position = await this.#machine.rasterPosition();
894
- const byteAt = async (address: number) => Number.parseInt(await this.#machine.readMemory({ address, size: 1, space: "c64", view: "cpu" }), 16);
895
843
  if (kind === "exec") {
896
844
  const registers = await this.#machine.readRegisters("c64");
897
845
  const bytes = [...Buffer.from(await this.#machine.readMemory({ address: registers.pc, size: 3, space: "c64", view: "cpu" }), "hex")];
@@ -918,9 +866,10 @@ export class ViceSession implements ViceSessionHandle {
918
866
  const at = Number((((BigInt(position.line * cycles + position.cycle) - (now - entry.clock)) % span) + span) % span);
919
867
  const bytes = [...Buffer.from(entry.bytes, "hex")];
920
868
  // A zero-page pointer is read now: the instruction did not change it.
921
- const pointer = new Map<number, number>();
922
- for (const address of [bytes[1] ?? 0, ((bytes[1] ?? 0) + 1) & 0xff, ((bytes[1] ?? 0) + entry.x) & 0xff, ((bytes[1] ?? 0) + entry.x + 1) & 0xff]) pointer.set(address, await byteAt(address));
923
- const address = operandAddress(bytes, entry.x, entry.y, (zp) => pointer.get(zp) ?? 0);
869
+ const { mode } = OPCODES[bytes[0]!]!;
870
+ const zeroPage = mode === "izx" || mode === "izy" ? Buffer.from(await this.#machine.readMemory({ address: 0, size: 0x100, space: "c64", view: "cpu" }), "hex") : undefined;
871
+ const address = operandAddress(bytes, entry.x, entry.y, (zp) => zeroPage?.[zp] ?? 0);
872
+ const byteAt = async (at: number) => Number.parseInt(await this.#machine.readMemory({ address: at, size: 1, space: "c64", view: "cpu" }), 16);
924
873
  return {
925
874
  point,
926
875
  pc: entry.address,
@@ -1077,9 +1026,7 @@ export class ViceSession implements ViceSessionHandle {
1077
1026
  if (expression !== undefined) await this.#machine.setCondition(checkpoint, expression);
1078
1027
  const outcome = await this.#runFrames(params.timeoutFrames, { checkpoint, deferred });
1079
1028
  const stopReason = outcome.end === "frames" ? "timeout" : outcome.end;
1080
- // A stop event carries the computer's PC; a stop in the drive reports the drive's.
1081
- const pc = outcome.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : outcome.pc;
1082
- this.#stopSpace = outcome.space;
1029
+ const pc = await this.#recordStop(outcome);
1083
1030
  return { reached: stopReason === "target", stopReason, state: "stopped", pc, space: outcome.space, ...(outcome.pointId === undefined ? {} : { pointId: outcome.pointId }) };
1084
1031
  } finally {
1085
1032
  await this.#machine.deleteCheckpoint(checkpoint);
@@ -1150,7 +1097,7 @@ export class ViceSession implements ViceSessionHandle {
1150
1097
  if (params.action !== "add") return publicView(await this.#changePoint(this.#breakpoints, "breakpoint", params));
1151
1098
  // A breakpoint over a range stops at the first instruction executed in it: exec, not a watch.
1152
1099
  const added = await this.#addPoint({
1153
- ...(params.size === undefined ? pointRange({ address: params.address }) : { start: params.address, end: params.address + params.size - 1, operation: 0x04 }),
1100
+ ...pointRange(params),
1154
1101
  space: params.space,
1155
1102
  ...(params.condition === undefined ? {} : { condition: params.condition }),
1156
1103
  });
@@ -1174,7 +1121,7 @@ export class ViceSession implements ViceSessionHandle {
1174
1121
  if (params.action === "remove") return this.#removePoint(this.#watchpoints, "watchpoint", params.id);
1175
1122
  if (params.action !== "add") return publicView(await this.#changePoint(this.#watchpoints, "watchpoint", params));
1176
1123
  const added = await this.#addPoint({
1177
- ...pointRange({ address: params.address, size: params.size, access: params.access }),
1124
+ ...pointRange(params),
1178
1125
  space: params.space,
1179
1126
  ...(params.condition === undefined ? {} : { condition: params.condition }),
1180
1127
  });
@@ -1205,13 +1152,15 @@ export class ViceSession implements ViceSessionHandle {
1205
1152
  }
1206
1153
  }
1207
1154
 
1208
- /** VICE (3.9, 3.10) stops answering at the restore of a snapshot saved at the reset stop while the disk drive was busy. */
1209
- #refuseAtResetStop(verb: string): void {
1155
+ /**
1156
+ * VICE (3.9, 3.10) stops answering at the restore of a snapshot saved at the
1157
+ * reset stop while the disk drive was busy, and at keys pressed there; `when` names the case.
1158
+ */
1159
+ #refuseAtResetStop(verb: string, when = "at the restore of a snapshot saved here when the disk drive was busy"): void {
1210
1160
  if (!this.#atResetStop) return;
1211
1161
  throw new WireFailure(
1212
1162
  "operation-failed",
1213
- "The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering at the restore of a snapshot saved here when the disk drive was busy. " +
1214
- `Step one instruction with c64_execution, then ${verb}.`,
1163
+ `The CPU stands at the reset stop of c64_reset with run false. The emulator stops answering ${when}. Step one instruction with c64_execution, then ${verb}.`,
1215
1164
  );
1216
1165
  }
1217
1166
 
@@ -1226,13 +1175,7 @@ export class ViceSession implements ViceSessionHandle {
1226
1175
  async #press(params: ViceOperations["press"]["params"]): Promise<PressResult> {
1227
1176
  this.#refuseBroken("keyboard", "c64_press");
1228
1177
  await this.#refuseWhileAutostartLoads("a key now stops it before RUN", "press the keys");
1229
- if (this.#atResetStop) {
1230
- throw new WireFailure(
1231
- "operation-failed",
1232
- "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. " +
1233
- "Step one instruction with c64_execution, then press the keys.",
1234
- );
1235
- }
1178
+ this.#refuseAtResetStop("press the keys", "when keys are pressed here while the disk drive is busy");
1236
1179
  const running = this.#state === "running";
1237
1180
  await this.#stop();
1238
1181
  await this.#refuseJammed("press");
@@ -1243,12 +1186,11 @@ export class ViceSession implements ViceSessionHandle {
1243
1186
  await this.#setKeys(matrixRows([]), false);
1244
1187
  const end = held.end === "frames" ? await this.#runFrames(params.frames) : held;
1245
1188
  if (end.end !== "frames") {
1246
- this.#stopSpace = end.space;
1247
1189
  return {
1248
1190
  taps,
1249
1191
  state: "stopped",
1250
1192
  stopReason: end.end as PointStopReason,
1251
- pc: end.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : end.pc,
1193
+ pc: await this.#recordStop(end),
1252
1194
  space: end.space,
1253
1195
  ...(end.pointId === undefined ? {} : { pointId: end.pointId }),
1254
1196
  };
@@ -1266,10 +1208,7 @@ export class ViceSession implements ViceSessionHandle {
1266
1208
  await this.#machine.saveSnapshot(file);
1267
1209
  const bytes = readFileSync(file);
1268
1210
  const why = setSnapshotMatrix(bytes, rows) ?? (restore ? pressSnapshotRestore(bytes) : undefined);
1269
- if (why !== undefined) {
1270
- this.#log(`c64_press was used, and this VICE writes snapshots that c64-re-tools does not know: ${why}.`);
1271
- throw new WireFailure("not-implemented", BROKEN_MESSAGES.keyboard);
1272
- }
1211
+ if (why !== undefined) this.#notImplemented("keyboard", `c64_press was used, and this VICE writes snapshots that c64-re-tools does not know: ${why}.`);
1273
1212
  writeFileSync(file, bytes);
1274
1213
  await this.#machine.restoreSnapshot(file);
1275
1214
  } finally {
@@ -1286,8 +1225,12 @@ export class ViceSession implements ViceSessionHandle {
1286
1225
  */
1287
1226
  #refuseBroken(feature: ViceFeature, tool: string): void {
1288
1227
  const flaw = this.#broken.get(feature);
1289
- if (flaw === undefined) return;
1290
- this.#log(`${tool} was used, and this VICE does not support it. ${flaw}`);
1228
+ if (flaw !== undefined) this.#notImplemented(feature, `${tool} was used, and this VICE does not support it. ${flaw}`);
1229
+ }
1230
+
1231
+ /** Refuses a feature as not implemented; `log` tells the host console why. */
1232
+ #notImplemented(feature: ViceFeature, log: string): never {
1233
+ this.#log(log);
1291
1234
  throw new WireFailure("not-implemented", BROKEN_MESSAGES[feature]);
1292
1235
  }
1293
1236
 
@@ -1297,8 +1240,7 @@ export class ViceSession implements ViceSessionHandle {
1297
1240
  * replaces it (#replaceStaged).
1298
1241
  */
1299
1242
  #stage(bytes: Buffer, type: string): string {
1300
- this.#staged++;
1301
- const file = join(this.#workDir, `media-${this.#staged}${type === "" ? "" : `.${type}`}`);
1243
+ const file = join(this.#workDir, `media-${++this.#files}${type === "" ? "" : `.${type}`}`);
1302
1244
  writeFileSync(file, bytes);
1303
1245
  return file;
1304
1246
  }
@@ -1436,7 +1378,7 @@ export class ViceSession implements ViceSessionHandle {
1436
1378
  if (existing === undefined && this.#snapshots.size >= MAX_SNAPSHOTS) {
1437
1379
  throw new WireFailure("limit-exceeded", `A session keeps at most ${MAX_SNAPSHOTS} snapshots. Remove one first with action remove.`);
1438
1380
  }
1439
- const file = existing ?? join(this.#workDir, `snapshot-${++this.#snapshotFiles}.vsf`);
1381
+ const file = existing ?? join(this.#workDir, `snapshot-${++this.#files}.vsf`);
1440
1382
  await this.#observe(() => this.#machine.saveSnapshot(file));
1441
1383
  this.#snapshots.set(params.name, file);
1442
1384
  return { saved: true, name: params.name };
@@ -1551,7 +1493,7 @@ export class ViceSession implements ViceSessionHandle {
1551
1493
  if (running && !this.#closed) await this.#resume().catch(() => {});
1552
1494
  throw error;
1553
1495
  }
1554
- await old.stop().catch((error: unknown) => this.#log(`stopping the earlier VICE failed: ${error instanceof Error ? error.message : String(error)}`));
1496
+ await old.stop().catch((error: unknown) => this.#log(`stopping the earlier VICE failed: ${describeError(error)}`));
1555
1497
  if (mode === "window") {
1556
1498
  this.#handover = handover;
1557
1499
  } else {
@@ -1608,10 +1550,10 @@ export class ViceSession implements ViceSessionHandle {
1608
1550
  } catch (error) {
1609
1551
  await vice.stop().catch(() => {});
1610
1552
  if (error instanceof WireFailure) throw error;
1611
- this.#log(`moving the machine to a new VICE failed: ${error instanceof Error ? error.message : String(error)}\n${vice.outputTail()}`);
1553
+ this.#log(`moving the machine to a new VICE failed: ${describeError(error)}\n${vice.outputTail()}`);
1612
1554
  throw new WireFailure(
1613
1555
  "operation-failed",
1614
- `The new emulator did not take the machine state (${error instanceof Error ? error.message : String(error)}). ` +
1556
+ `The new emulator did not take the machine state (${describeError(error)}). ` +
1615
1557
  `The machine stays ${this.#mode === "window" ? "in the window" : "headless"}, as it was.`,
1616
1558
  );
1617
1559
  }
@@ -1834,14 +1776,13 @@ export class ViceSession implements ViceSessionHandle {
1834
1776
  #recover(runningBefore: boolean, halts: number): void {
1835
1777
  if (this.#held !== undefined) return;
1836
1778
  this.#log("VICE takes no commands (paused in its window, a dialog is open, or a step does not end); waiting until it goes on");
1837
- const why = (error: unknown) => (error instanceof Error ? error.message : String(error));
1838
1779
  this.#held = (async () => {
1839
1780
  try {
1840
1781
  try {
1841
1782
  await this.#machine.answered();
1842
1783
  await this.#machine.drainText();
1843
1784
  } catch (error) {
1844
- if (!this.#closed) this.#log(`VICE did not come back: ${why(error)}`);
1785
+ if (!this.#closed) this.#log(`VICE did not come back: ${describeError(error)}`);
1845
1786
  }
1846
1787
  if (this.#closed || this.#lost) return;
1847
1788
  // The ping that answered stopped the machine; put back the run state of before the operation.
@@ -1849,7 +1790,7 @@ export class ViceSession implements ViceSessionHandle {
1849
1790
  if (runningBefore && this.#haltCount === halts) await this.#resume();
1850
1791
  this.#log(`VICE takes commands again; the machine is ${this.#state} as before`);
1851
1792
  } catch (error) {
1852
- if (!this.#closed) this.#log(`restoring the run state failed: ${why(error)}`);
1793
+ if (!this.#closed) this.#log(`restoring the run state failed: ${describeError(error)}`);
1853
1794
  } finally {
1854
1795
  this.#held = undefined;
1855
1796
  }
@@ -1908,11 +1849,10 @@ function onlyAttachment(attachments: Buffer[]): Buffer {
1908
1849
  return bytes;
1909
1850
  }
1910
1851
 
1911
- /** The VICE checkpoint range and operation of a breakpoint (no size) or a watchpoint. */
1852
+ /** The VICE checkpoint range and operation of a breakpoint (exec, one address without a size) or a watchpoint (its access). */
1912
1853
  function pointRange(point: { address: number; size?: number; access?: Watchpoint["access"] }): { start: number; end: number; operation: number } {
1913
- if (point.size === undefined) return { start: point.address, end: point.address, operation: 0x04 }; // exec
1914
- const operation = point.access === "read" ? 0x01 : point.access === "write" ? 0x02 : 0x03;
1915
- return { start: point.address, end: point.address + point.size - 1, operation };
1854
+ const operation = point.access === undefined ? 0x04 : point.access === "read" ? 0x01 : point.access === "write" ? 0x02 : 0x03;
1855
+ return { start: point.address, end: point.address + (point.size ?? 1) - 1, operation };
1916
1856
  }
1917
1857
 
1918
1858
  /** Sets a user checkpoint with its condition; removes it again if the condition is refused. */