@henols/c64-re-tools 2.1.2 → 2.1.4

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 (50) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +2 -2
  4. package/skills/c64-disk/scripts/lib/containers.ts +2 -1
  5. package/skills/c64-docs/SKILL.md +1 -1
  6. package/skills/c64-docs/scripts/docs.ts +5 -3
  7. package/skills/c64-emulator/SKILL.md +4 -0
  8. package/skills/c64-knowledge/SKILL.md +7 -2
  9. package/skills/c64-knowledge/scripts/knowledge.ts +6 -12
  10. package/skills/c64-knowledge/scripts/lib/listing.ts +8 -1
  11. package/skills/c64-memory-map/SKILL.md +3 -1
  12. package/skills/c64-memory-map/scripts/memory-map.ts +26 -5
  13. package/skills/c64-provenance/SKILL.md +5 -4
  14. package/skills/c64-provenance/scripts/lib/compare.ts +12 -0
  15. package/skills/c64-provenance/scripts/lib/library.ts +33 -5
  16. package/skills/c64-provenance/scripts/lib/separate.ts +34 -6
  17. package/skills/c64-provenance/scripts/provenance.ts +26 -11
  18. package/skills/c64-source/SKILL.md +3 -2
  19. package/skills/c64-source/scripts/lib/source.ts +18 -4
  20. package/skills/c64-source/scripts/source.ts +40 -28
  21. package/skills/c64-static-analysis/SKILL.md +4 -3
  22. package/skills/c64-static-analysis/scripts/lib/findings.ts +47 -10
  23. package/skills/c64-static-analysis/scripts/lib/pointers.ts +38 -25
  24. package/skills/c64-static-analysis/scripts/static-analysis.ts +17 -14
  25. package/skills/c64-testing/SKILL.md +6 -3
  26. package/skills/c64-testing/references/scenario-format.md +7 -3
  27. package/skills/c64-testing/scripts/lib/diff-files.ts +27 -8
  28. package/skills/c64-testing/scripts/lib/runs.ts +24 -8
  29. package/skills/c64-testing/scripts/lib/scenario.ts +133 -83
  30. package/skills/c64-testing/scripts/testing.ts +6 -3
  31. package/skills/c64-unpacker/SKILL.md +5 -4
  32. package/skills/c64-unpacker/scripts/lib/loads.ts +9 -3
  33. package/skills/c64-unpacker/scripts/lib/machine.ts +31 -0
  34. package/skills/c64-unpacker/scripts/unpacker.ts +4 -1
  35. package/src/host/vice/session.ts +118 -11
  36. package/src/host-client/image.ts +22 -8
  37. package/src/host-client/steps.ts +2 -2
  38. package/src/host-client/tools.ts +4 -3
  39. package/src/host-client/transfer.ts +8 -3
  40. package/src/host-client/vice-session.ts +3 -3
  41. package/src/knowledge/write.ts +110 -29
  42. package/src/mcp/output.ts +1 -1
  43. package/src/mcp/server.ts +7 -0
  44. package/src/mcp/tools/debug.ts +2 -1
  45. package/src/mcp/tools/media.ts +8 -5
  46. package/src/media.ts +18 -0
  47. package/src/opcodes.ts +31 -1
  48. package/src/platform.ts +14 -1
  49. package/src/project.ts +14 -3
  50. package/src/script.ts +71 -2
@@ -13,7 +13,7 @@ import { WireFailure } from "#src/host-client/tools.ts";
13
13
  import { readProjectFile, writeReported, type Written } from "#src/host-client/transfer.ts";
14
14
  import { ViceSessionClient } from "#src/host-client/vice-session.ts";
15
15
  import { UsageError } from "#src/script.ts";
16
- import { entryStateFile, json, machineState, readRam, readyState, vectorsOf } from "./machine.ts";
16
+ import { entryStateFile, json, machineState, readRam, readyState, removeStaleFiles, vectorsOf } from "./machine.ts";
17
17
  import { FIRST_SEGMENT_ADDRESS } from "./stages.ts";
18
18
 
19
19
 
@@ -111,7 +111,7 @@ export async function loads(program: string, options: { out: string; steps: Load
111
111
  let emulatorFlaw: string | undefined;
112
112
  if (program.toLowerCase().endsWith(".prg")) {
113
113
  const { bytes } = readProjectFile(program);
114
- if (!(await autostartLoaded(client, program, bytes))) return { output: { loaded: false, reason: `The program was not in memory after ${LOAD_LIMIT_FRAMES} frames.` }, failed: true };
114
+ if (!(await autostartLoaded(client, program, bytes))) return { output: { loaded: false, reason: `The program was not in memory after ${LOAD_LIMIT_FRAMES} frames.`, captures: [] }, failed: true };
115
115
  // The RAM before RUN, without the program, so the first capture holds the program too.
116
116
  previous = await readRam(client, 0x0000, 0x10000);
117
117
  const load = bytes[0]! | (bytes[1]! << 8);
@@ -119,7 +119,10 @@ export async function loads(program: string, options: { out: string; steps: Load
119
119
  loadedProgram = bytes;
120
120
  await client.memmap({ action: "clear" });
121
121
  // RUN as c64-testing types it: the steps start at the same time as a scenario's.
122
- if (!(await typeRun(client))) return { output: { loaded: false, reason: `After RUN, BASIC ran no program line in ${RUN_LIMIT_FRAMES} frames.` }, failed: true };
122
+ if (!(await typeRun(client))) {
123
+ const reason = `After RUN, BASIC ran no program line in ${RUN_LIMIT_FRAMES} frames. loads starts a PRG with RUN, so it needs a program with a BASIC start line, for example 10 SYS 2061. For a PRG without a BASIC start, use capture with --entry.`;
124
+ return { output: { loaded: false, reason, captures: [] }, failed: true };
125
+ }
123
126
  } else {
124
127
  // A disk, tape or cartridge: VICE loads and starts it. The RAM test of the KERNAL puts back what it writes.
125
128
  previous = await readRam(client, 0x0000, 0x10000);
@@ -190,11 +193,14 @@ export async function loads(program: string, options: { out: string; steps: Load
190
193
  );
191
194
  const entry = entryStateFile(registers, state, vectors, clean);
192
195
  write("entry_state.json", entry.bytes);
196
+ // A capture again into the folder: the files of the earlier capture that image.json no longer lists go.
197
+ const removed = removeStaleFiles(directory, [...files, ...(drive === undefined ? [] : ["drive8.prg"])]);
193
198
  const keyWait = registers.pc >= KERNAL_KEY_WAIT.start && registers.pc <= KERNAL_KEY_WAIT.end;
194
199
  captures.push({
195
200
  capture: step.capture,
196
201
  out: directory,
197
202
  files: written,
203
+ ...(removed.length === 0 ? {} : { removed }),
198
204
  pc: formatC64Address(registers.pc),
199
205
  ...(keyWait ? { keyWait: true } : {}),
200
206
  segments: segments.map(showRange),
@@ -2,9 +2,14 @@
2
2
  // 0-3, the chip registers read without side effects, and the vectors. The
3
3
  // capture and loads commands of the unpacker share it.
4
4
 
5
+ import { readdirSync, rmSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
5
8
  import { formatC64Address } from "#src/c64.ts";
6
9
  import { resetToReady } from "#src/host-client/entry-state.ts";
10
+ import { writeRefusal } from "#src/host-client/transfer.ts";
7
11
  import type { ViceSessionClient } from "#src/host-client/vice-session.ts";
12
+ import { projectRoot, resolveProjectPath } from "#src/project.ts";
8
13
 
9
14
  type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
10
15
 
@@ -102,4 +107,30 @@ function entryState(registers: Registers, state: MachineState, vectors: ReturnTy
102
107
  };
103
108
  }
104
109
 
110
+ /** The names of the files that a capture writes for its content: a PRG for each segment, and the drive RAM. */
111
+ const CAPTURE_FILE = /^(?:segment-[0-9a-f]{4}-[0-9a-f]{4}\.prg|drive8\.prg)$/;
112
+
113
+ /**
114
+ * Removes from the capture folder `folder` (a project path) each file that an
115
+ * earlier capture wrote and this capture did not: a segment PRG of another
116
+ * range, or the drive RAM. image.json lists only the files of this capture.
117
+ * Every other file stays. Gives the removed files as project paths.
118
+ */
119
+ export function removeStaleFiles(folder: string, written: readonly string[]): string[] {
120
+ const path = resolveProjectPath(folder, projectRoot());
121
+ const removed: string[] = [];
122
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
123
+ // A symbolic link is not a file of a capture: it stays.
124
+ if (!entry.isFile() || !CAPTURE_FILE.test(entry.name) || written.includes(entry.name)) continue;
125
+ const file = `${folder}/${entry.name}`;
126
+ try {
127
+ rmSync(join(path, entry.name));
128
+ } catch (error) {
129
+ throw writeRefusal(error, file, "--out") ?? error;
130
+ }
131
+ removed.push(file);
132
+ }
133
+ return removed.sort();
134
+ }
135
+
105
136
  export const json = (value: unknown) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
@@ -19,7 +19,7 @@ import { listed, OPTIONS, runScript, UsageError, type Call, type CommandSpec, ty
19
19
  import { basicStart, inspect, readMemoryMap, underRom, writtenThenExecuted } from "./lib/evidence.ts";
20
20
  import { loads, readLoadSteps } from "./lib/loads.ts";
21
21
  import { callReturn, captureSegments, executedIn, inRanges, mergeMaps, stageCandidates, stagePoints, withoutRanges } from "./lib/stages.ts";
22
- import { entryStateFile, machineState, readRam, readyState, vectorsOf } from "./lib/machine.ts";
22
+ import { entryStateFile, machineState, readRam, readyState, removeStaleFiles, vectorsOf } from "./lib/machine.ts";
23
23
 
24
24
  /** Written-then-executed bytes from this many on are unpacking, decrypting or relocating, not self-changing code. */
25
25
  const UNPACKED_BYTES = 256;
@@ -537,12 +537,15 @@ async function capture(
537
537
  // A clean machine at the READY prompt shows what the loader and the stages changed.
538
538
  const entry = entryStateFile(registers, state, vectors, await readyState(client));
539
539
  write("entry_state.json", entry.bytes);
540
+ // A capture again into the folder: the segment PRGs of the earlier capture that image.json no longer lists go.
541
+ const removed = removeStaleFiles(options.out, files);
540
542
  return {
541
543
  output: {
542
544
  captured: true,
543
545
  pc: formatC64Address(registers.pc),
544
546
  out: options.out,
545
547
  files: written,
548
+ ...(removed.length === 0 ? {} : { removed }),
546
549
  segments: segments.map(showRange),
547
550
  ...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
548
551
  stages: followed.stages.length,
@@ -13,7 +13,7 @@ import { setTimeout as sleep } from "node:timers/promises";
13
13
 
14
14
  import { formatC64Address, instructionLength } from "../../c64.ts";
15
15
  import { encodePng, type IndexedFrame } from "../../graphics.ts";
16
- import { instructionText, operandAddress } from "../../opcodes.ts";
16
+ import { accessedValue, instructionText, operandAddress } from "../../opcodes.ts";
17
17
  import type { ProcessSupervisor } from "../../native/processes.ts";
18
18
  import { trace } from "../../trace.ts";
19
19
  import type { ViceSessionFactory, ViceSessionHandle } from "../server.ts";
@@ -31,7 +31,7 @@ import { decodeProgramCounter, MonitorConnectionError, MonitorError, MonitorTime
31
31
  import { decodeCia, decodeSid, decodeSprite, decodeVicii } from "./chips.ts";
32
32
  import { compareFrames, differenceImage } from "./screen.ts";
33
33
  import { isRefusal } from "../../errors.ts";
34
- import { checkMedia } from "../../media.ts";
34
+ import { checkMedia, hasSignature } from "../../media.ts";
35
35
  import { launchVice, startErrorLines, type ViceMode, type ViceProcess } from "./process.ts";
36
36
  import { TextMonitorError, TextMonitorTimeoutError } from "./text-monitor.ts";
37
37
 
@@ -80,7 +80,6 @@ const WINDOW_CLOSED =
80
80
 
81
81
  /** Emulator state that a move to another VICE cannot carry. */
82
82
  /** The first bytes of every VICE snapshot file. */
83
- const VSF_MAGIC = Buffer.from("VICE Snapshot File\x1a", "latin1");
84
83
  const NOT_CARRIED = ["cpu history", "memory map", "profile", "keyboard input not yet typed"];
85
84
 
86
85
  /** Starts another VICE for this session; `log` also gets that launch's lines. */
@@ -202,6 +201,23 @@ export class ViceSession implements ViceSessionHandle {
202
201
  #autostarting = false;
203
202
  /** The C64 clock just after the last snapshot restore: VICE keeps the history of before it. */
204
203
  #historySince: bigint | undefined;
204
+ /**
205
+ * A breakpoint or watchpoint stopped a step, next or until-return early. VICE
206
+ * keeps the rest of that step and stops the machine once more when it ends.
207
+ * No monitor command ends it without running the CPU, so the session takes
208
+ * that one stop as the end of the step and lets the machine run on.
209
+ */
210
+ #pendingStep = false;
211
+ /**
212
+ * The CPU stands at the stop of a reset without run, and nothing ran since. VICE
213
+ * (3.9, 3.10) stops answering at the restore of a snapshot saved here while the
214
+ * disk drive was busy, so a save here is refused.
215
+ */
216
+ #atResetStop = false;
217
+ /** Warp as the user set it: VICE also turns warp on by itself while an autostart loads. */
218
+ #userWarp = false;
219
+ /** The CPU that the last run stopped in, when it was the drive: status then gives the drive's pc. */
220
+ #stopSpace: "c64" | "drive8" = "c64";
205
221
  /** VICE records no CPU history after a JAM until the next reset. */
206
222
  #historyStopped = false;
207
223
  /** The CPU ran again after a JAM without a reset: the CPU history that VICE gives is old. */
@@ -445,6 +461,13 @@ export class ViceSession implements ViceSessionHandle {
445
461
  return this.#reset(params as ViceOperations["reset"]["params"]);
446
462
  case "keyboard": {
447
463
  const bytes = Buffer.from((params as ViceOperations["keyboard"]["params"]).data, "hex");
464
+ // VICE turns warp on for an autostart and off when it types RUN. A key in between ends the autostart with no message.
465
+ if (this.#autostarting && !this.#userWarp && (await this.#observe(() => this.#machine.warp()))) {
466
+ throw new WireFailure(
467
+ "operation-failed",
468
+ "The autostart still loads the program, and a key now stops it before RUN. Run frames with c64_execution advance-frames until c64_status gives warp false, then type.",
469
+ );
470
+ }
448
471
  await this.#observe(() => this.#machine.feedKeyboard(bytes));
449
472
  return { queuedBytes: bytes.length, ...(this.#inputFlaw === undefined ? {} : { emulatorFlaw: this.#inputFlaw }) };
450
473
  }
@@ -539,6 +562,7 @@ export class ViceSession implements ViceSessionHandle {
539
562
  case "warp": {
540
563
  const { enabled } = params as ViceOperations["warp"]["params"];
541
564
  await this.#observe(() => this.#machine.setWarp(enabled));
565
+ this.#userWarp = enabled;
542
566
  return { enabled };
543
567
  }
544
568
  case "window":
@@ -558,7 +582,7 @@ export class ViceSession implements ViceSessionHandle {
558
582
  if (stop !== undefined) Object.assign(status, stop);
559
583
  // A point in the drive stopped it: the pc is the drive's, as advance-frames and run-until give it.
560
584
  const point = status.pointId === undefined ? undefined : (status.stopReason === "watchpoint" ? this.#watchpoints : this.#breakpoints).get(status.pointId);
561
- status.space = point?.space === "drive8" ? "drive8" : "c64";
585
+ status.space = point?.space === "drive8" || this.#stopSpace === "drive8" ? "drive8" : "c64";
562
586
  if (status.space === "drive8") status.pc = (await this.#machine.readRegisters("drive8")).pc;
563
587
  }
564
588
  return status;
@@ -572,6 +596,7 @@ export class ViceSession implements ViceSessionHandle {
572
596
  if (this.#state === "stopped") {
573
597
  await this.#refuseJammed("resume");
574
598
  await this.#resume();
599
+ if (this.#pendingStep) await this.#endPendingStep();
575
600
  }
576
601
  return { state: "running" };
577
602
  }
@@ -600,6 +625,7 @@ export class ViceSession implements ViceSessionHandle {
600
625
  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}.`);
601
626
  }
602
627
  const outcome = await this.#runFrames(params.count, undefined, params.anchor);
628
+ this.#stopSpace = outcome.space;
603
629
  return {
604
630
  state: "stopped",
605
631
  // A stop event carries the computer's PC; a stop in the drive reports the drive's.
@@ -612,6 +638,8 @@ export class ViceSession implements ViceSessionHandle {
612
638
  }
613
639
  await this.#stop();
614
640
  await this.#refuseJammed(params.action);
641
+ // A new step replaces the rest of an earlier one in VICE.
642
+ this.#pendingStep = false;
615
643
  if (params.action === "until-return") {
616
644
  const stopped = this.#nextStop(this.#untilReturnLimitMs);
617
645
  await this.#resumingCommand(() => this.#machine.untilReturn());
@@ -623,18 +651,41 @@ export class ViceSession implements ViceSessionHandle {
623
651
  `The routine did not return within ${this.#untilReturnLimitMs / 1000} seconds. The machine is stopped at ${formatC64Address(await this.#pc())}.`,
624
652
  );
625
653
  }
626
- return { state: "stopped", pc: stop.pc };
654
+ return { state: "stopped", pc: stop.pc, ...this.#stepStoppedByPoint() };
627
655
  }
628
656
  const count = params.count ?? 1;
657
+ this.#atResetStop = false;
658
+ // The stop event of the step tells that it ended, and which point stopped it. A long step
659
+ // in warp can answer before it ends; a ping then would stop it early and leave the rest in VICE.
660
+ const stopped = this.#nextStop(this.#stepLimitMs);
629
661
  try {
630
662
  await this.#machine.step(count, params.action === "next", this.#stepLimitMs);
631
663
  } catch (error) {
632
664
  if (error instanceof MonitorTimeoutError) throw new StepTimeout(stepNotEnded(params.action, count, this.#stepLimitMs), error);
633
665
  throw error;
634
666
  }
635
- // VICE answers a step only after the machine stopped again.
667
+ if ((await stopped) === undefined) await this.#machine.stop();
636
668
  this.#state = "stopped";
637
- return { state: "stopped", pc: await this.#pc(), executed: count };
669
+ const point = this.#stepStoppedByPoint();
670
+ // A point stops the step early: VICE does not tell how many instructions ran.
671
+ return { state: "stopped", pc: await this.#pc(), ...(point.pointId === undefined ? { executed: count } : point) };
672
+ }
673
+
674
+ /** The breakpoint or watchpoint that stopped a step, next or until-return early; VICE then keeps the rest of the step. */
675
+ #stepStoppedByPoint(): { stopReason?: PointStopReason; pointId?: number } {
676
+ const stop = this.#lastStop;
677
+ if (stop?.pointId === undefined) return {};
678
+ this.#pendingStep = true;
679
+ return { stopReason: stop.stopReason, pointId: stop.pointId };
680
+ }
681
+
682
+ /** After a resume: waits for the stop that ends the rest of an earlier step, and runs on. */
683
+ async #endPendingStep(): Promise<void> {
684
+ const stop = await this.#nextStop(HALF_FRAME_LIMIT_MS);
685
+ if (stop === undefined) return;
686
+ this.#pendingStep = false;
687
+ // A user point or a JAM stopped the machine: it stays stopped and status tells why.
688
+ if (stop.hits.length === 0 && this.#lastStop === undefined) await this.#resume();
638
689
  }
639
690
 
640
691
  async #reset(params: { mode: "soft" | "hard"; run: boolean }): Promise<{ state: RunState; pc?: number }> {
@@ -659,6 +710,7 @@ export class ViceSession implements ViceSessionHandle {
659
710
  if (!reached) await this.#stop();
660
711
  await this.#machine.deleteCheckpoint(checkpoint);
661
712
  if (!reached) throw new WireFailure("operation-failed", "The C64 did not reach its reset vector after the reset.");
713
+ this.#atResetStop = true;
662
714
  return { state: "stopped", pc: vector };
663
715
  }
664
716
 
@@ -715,6 +767,11 @@ export class ViceSession implements ViceSessionHandle {
715
767
  }
716
768
  if (end === "unknown") {
717
769
  if (await this.#jamAt(stop.pc)) return { end: "jam", frames, pc: stop.pc, space: "c64" };
770
+ if (this.#pendingStep) {
771
+ // The rest of an earlier step ended: run on.
772
+ this.#pendingStep = false;
773
+ continue;
774
+ }
718
775
  throw new WireFailure("operation-failed", "The emulator stopped the machine for a reason outside this run.");
719
776
  }
720
777
  // A drive stop is completed before the result names the computer's pc; `space` says which CPU stopped.
@@ -748,6 +805,14 @@ export class ViceSession implements ViceSessionHandle {
748
805
  let frames = 0;
749
806
  const startPc = await this.#pc();
750
807
  if (await this.#jamAt(startPc)) return { hits, frames, end: "jam", pc: startPc };
808
+ // VICE checks no checkpoint at the pc that it resumes from: an exec point there gets its first hit here.
809
+ for (const [index, point] of params.points.entries()) {
810
+ if (point.kind === "exec" && point.start <= startPc && startPc <= point.end) {
811
+ hits.push(await this.#traceHit(index, "exec", 0));
812
+ if (hits.length >= params.maxHits) return { hits, frames, end: "hits", pc: startPc };
813
+ break;
814
+ }
815
+ }
751
816
  let clockPc = startPc;
752
817
  const clock = await this.#machine.addCheckpoint({ start: 0x0000, end: 0xffff, operation: 0x04, space: "c64" });
753
818
  try {
@@ -783,6 +848,10 @@ export class ViceSession implements ViceSessionHandle {
783
848
  const point = this.#userPoint(stop.hits);
784
849
  if (point !== undefined) return { hits, frames, end: point.stopReason, pc: stop.pc };
785
850
  if (await this.#jamAt(stop.pc)) return { hits, frames, end: "jam", pc: stop.pc };
851
+ if (this.#pendingStep) {
852
+ this.#pendingStep = false;
853
+ continue;
854
+ }
786
855
  throw new WireFailure("operation-failed", "The emulator stopped the machine for a reason outside this trace.");
787
856
  }
788
857
  } finally {
@@ -841,10 +910,22 @@ export class ViceSession implements ViceSessionHandle {
841
910
  frame,
842
911
  rasterLine: Math.floor(at / cycles),
843
912
  rasterCycle: at % cycles,
844
- ...(address === undefined ? {} : { address, value: await byteAt(address) }),
913
+ ...(address === undefined ? {} : { address, ...(await this.#accessed(bytes[0]!, entry, address, byteAt)) }),
845
914
  };
846
915
  }
847
916
 
917
+ /**
918
+ * The byte of a read or write hit. A read of an I/O register after the
919
+ * access can give another byte than the access did (raster bits, cleared
920
+ * flags), so for $D000-$DFFF only a load or a store gives a value.
921
+ */
922
+ async #accessed(opcode: number, before: { a: number; x: number; y: number }, address: number, byteAt: (address: number) => Promise<number>): Promise<{ value?: number }> {
923
+ const after = await this.#machine.readRegisters("c64");
924
+ const io = address >= 0xd000 && address <= 0xdfff;
925
+ const value = accessedValue(opcode, before, after, io ? undefined : await byteAt(address));
926
+ return value === undefined ? {} : { value };
927
+ }
928
+
848
929
  /**
849
930
  * Completes a stop that a drive 8 checkpoint caused: the computer runs to
850
931
  * its next instruction boundary, where a computer checkpoint stops it, so
@@ -975,6 +1056,7 @@ export class ViceSession implements ViceSessionHandle {
975
1056
  const stopReason = outcome.end === "frames" ? "timeout" : outcome.end;
976
1057
  // A stop event carries the computer's PC; a stop in the drive reports the drive's.
977
1058
  const pc = outcome.space === "drive8" ? (await this.#machine.readRegisters("drive8")).pc : outcome.pc;
1059
+ this.#stopSpace = outcome.space;
978
1060
  return { reached: stopReason === "target", stopReason, state: "stopped", pc, space: outcome.space, ...(outcome.pointId === undefined ? {} : { pointId: outcome.pointId }) };
979
1061
  } finally {
980
1062
  await this.#machine.deleteCheckpoint(checkpoint);
@@ -1030,7 +1112,10 @@ export class ViceSession implements ViceSessionHandle {
1030
1112
 
1031
1113
  #point<T>(registry: Map<number, T>, kind: string, id: number): T {
1032
1114
  const point = registry.get(id);
1033
- if (point === undefined) throw new WireFailure("not-found", `There is no ${kind} with id ${id}.`);
1115
+ if (point === undefined) {
1116
+ const other = kind === "breakpoint" ? (this.#watchpoints.has(id) ? "watchpoint" : undefined) : this.#breakpoints.has(id) ? "breakpoint" : undefined;
1117
+ throw new WireFailure("not-found", `There is no ${kind} with id ${id}.${other === undefined ? "" : ` Id ${id} is a ${other}: use c64_${other}.`}`);
1118
+ }
1034
1119
  return point;
1035
1120
  }
1036
1121
 
@@ -1145,7 +1230,11 @@ export class ViceSession implements ViceSessionHandle {
1145
1230
  }
1146
1231
  return this.#observe(async () => {
1147
1232
  const all = await this.#machine.history(params.limit, params.space);
1148
- if (params.space === "drive8") return { entries: all.map(({ clock: _clock, ...entry }) => entry) };
1233
+ if (params.space === "drive8") {
1234
+ // VICE records a wrong third byte for a 3-byte drive instruction ("JSR $00a6" for 20 a6 d5): the drive memory gives the bytes.
1235
+ const memory = await this.#machine.readAll("drive8");
1236
+ return { entries: all.map(({ clock: _clock, ...entry }) => driveEntry(entry, memory)) };
1237
+ }
1149
1238
  const now = await this.#machine.clock();
1150
1239
  const raw = entriesSince(all, this.#historySince, now);
1151
1240
  const position = await this.#machine.rasterPosition();
@@ -1221,6 +1310,13 @@ export class ViceSession implements ViceSessionHandle {
1221
1310
  if (params.action === "list") return { snapshots: [...this.#snapshots.keys()] };
1222
1311
  const existing = this.#snapshots.get(params.name);
1223
1312
  if (params.action === "save") {
1313
+ if (this.#atResetStop) {
1314
+ throw new WireFailure(
1315
+ "operation-failed",
1316
+ "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. " +
1317
+ "Step one instruction with c64_execution, then save the snapshot.",
1318
+ );
1319
+ }
1224
1320
  if (existing === undefined && this.#snapshots.size >= MAX_SNAPSHOTS) {
1225
1321
  throw new WireFailure("limit-exceeded", `A session keeps at most ${MAX_SNAPSHOTS} snapshots. Remove one first with action remove.`);
1226
1322
  }
@@ -1266,7 +1362,7 @@ export class ViceSession implements ViceSessionHandle {
1266
1362
  }
1267
1363
  const bytes = onlyAttachment(attachments);
1268
1364
  // Checked before the machine stops: VICE gives no reason for a file that is no snapshot.
1269
- if (!bytes.subarray(0, VSF_MAGIC.length).equals(VSF_MAGIC)) throw new WireFailure("invalid-input", "The file is not a VICE snapshot file (.vsf). Give a file that c64_snapshot save wrote.");
1365
+ if (!hasSignature("vsf", bytes)) throw new WireFailure("invalid-input", "The file is not a VICE snapshot file (.vsf). Give a file that c64_snapshot save wrote.");
1270
1366
  const file = this.#stage(bytes, "vsf");
1271
1367
  // VICE resets the machine after a snapshot file that it cannot read: a backup keeps the state before the restore.
1272
1368
  const backup = join(this.#workDir, "before-restore.vsf");
@@ -1452,6 +1548,8 @@ export class ViceSession implements ViceSessionHandle {
1452
1548
  * arrive together, and those events must have the last word.
1453
1549
  */
1454
1550
  async #resumingCommand(send: () => Promise<void>): Promise<void> {
1551
+ this.#atResetStop = false;
1552
+ this.#stopSpace = "c64";
1455
1553
  this.#state = "running";
1456
1554
  this.#lastStop = undefined;
1457
1555
  try {
@@ -1643,6 +1741,15 @@ export class ViceSession implements ViceSessionHandle {
1643
1741
  }
1644
1742
  }
1645
1743
 
1744
+ /** A drive history entry with its bytes and text from drive memory, when the opcode there is still the one that ran. */
1745
+ export function driveEntry<T extends { address: number; bytes: string; text: string }>(entry: T, memory: Uint8Array): T {
1746
+ const opcode = Number.parseInt(entry.bytes.slice(0, 2), 16);
1747
+ if (memory[entry.address] !== opcode) return entry;
1748
+ const length = instructionLength(opcode);
1749
+ const bytes = Array.from({ length }, (_, offset) => memory[(entry.address + offset) & 0xffff]!);
1750
+ return { ...entry, bytes: Buffer.from(bytes).toString("hex"), text: instructionText(bytes, entry.address) };
1751
+ }
1752
+
1646
1753
  /**
1647
1754
  * The history entries (oldest first) that the CPU executed after a restore at
1648
1755
  * clock `since`, with the clock at `now`: the last entries, back to the first
@@ -36,20 +36,34 @@ const MEDIA_KINDS: Record<string, string> = {
36
36
  /** The remedy for a disk, tape or cartridge file where a PRG must be: get the PRG out of it. */
37
37
  export const MEDIA_REMEDY = "Get the PRG out of it with disk.ts read (or disk.ts crt for a cartridge) of the c64-disk skill";
38
38
 
39
- /** Refuses a disk, tape or cartridge file by its extension (`type`, lowercase, without the dot): invalid-input with `remedy`. */
40
- function refuseMedia(path: string, type: string, remedy: string): void {
39
+ /**
40
+ * Refuses a file that is no PRG by its extension (`type`, lowercase, without
41
+ * the dot): invalid-input. A disk, tape or cartridge file gets `remedy`. A PRG
42
+ * ends in .prg in any letter case, or has no extension, as c1541 writes the
43
+ * names of the files that it reads from a disk; every other extension is
44
+ * refused. `accepted` names what the reader takes, for the message.
45
+ */
46
+ export function refuseNotPrg(path: string, type: string, remedy = MEDIA_REMEDY, accepted = "a PRG"): void {
41
47
  const media = MEDIA_KINDS[type];
42
48
  if (media !== undefined) throw new Refusal("invalid-input", `${path} is ${media} (.${type}), not a PRG. ${remedy}.`);
49
+ if (type !== "prg" && type !== "") {
50
+ throw new Refusal("invalid-input", `${path} is not ${accepted}: a PRG has the extension .prg or no extension, not .${type}. Give the PRG of the program, or rename the file to .prg when it is a PRG.`);
51
+ }
43
52
  }
44
53
 
45
54
  /**
46
55
  * Reads a PRG of the project: a 2-byte load address, and bytes that end at
47
- * $ffff or before. Refuses a disk, tape or cartridge file and any other file
48
- * that is no PRG with invalid-input; `remedy` tells what to do in its place.
56
+ * $ffff or before. Refuses with invalid-input a file that is no PRG by its
57
+ * extension (refuseNotPrg) or by its bytes; `remedy` tells what to do in place
58
+ * of a disk, tape or cartridge file. A file of fewer than 3 bytes is refused
59
+ * as too short: no remedy applies.
49
60
  */
50
- export function readPrg(path: string, remedy = MEDIA_REMEDY): { bytes: Buffer; start: number; end: number; body: Uint8Array } {
61
+ export function readPrg(path: string, remedy = MEDIA_REMEDY, accepted = "a PRG"): { bytes: Buffer; start: number; end: number; body: Uint8Array } {
51
62
  const { bytes, type } = readProjectFile(path);
52
- refuseMedia(path, type, remedy);
63
+ refuseNotPrg(path, type, remedy, accepted);
64
+ if (bytes.length < 3) {
65
+ throw new Refusal("invalid-input", `${path} is too short for a PRG: it has ${bytes.length} ${bytes.length === 1 ? "byte" : "bytes"}, and a PRG has a 2-byte load address and at least one byte. Give the complete PRG file.`);
66
+ }
53
67
  try {
54
68
  return { bytes, ...prgRange(bytes) };
55
69
  } catch (error) {
@@ -58,10 +72,10 @@ export function readPrg(path: string, remedy = MEDIA_REMEDY): { bytes: Buffer; s
58
72
  }
59
73
  }
60
74
 
61
- /** Reads an image.json or a PRG, relative to the project folder. Refuses a disk, tape or cartridge file as readPrg does. */
75
+ /** Reads an image.json or a PRG, relative to the project folder. Refuses every other file as readPrg does. */
62
76
  export function readImage(path: string): Image {
63
77
  if (!path.endsWith(".json")) {
64
- const range = readPrg(path);
78
+ const range = readPrg(path, MEDIA_REMEDY, "an image.json of the c64-unpacker skill or a PRG");
65
79
  return { segments: [{ start: range.start, end: range.end }], byteAt: (address) => range.body[address - range.start]! };
66
80
  }
67
81
  const { bytes } = readProjectFile(path);
@@ -228,8 +228,8 @@ 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. */
232
- const PRESS_REMEDY = "press pushes keys of the keyboard matrix, and only the record and replay commands of c64-testing have them. Use type for the KERNAL keyboard queue, or open the window and ask the user to press the key";
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 core of c64-testing has them. Use type for the KERNAL keyboard queue, or put the press step in a record file and play it with testing.ts record of c64-testing";
233
233
 
234
234
  /** Checks the input of one step kind and returns it with the defaults of its MCP tool. */
235
235
  function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (message: string) => never): ActionStep {
@@ -6,6 +6,7 @@
6
6
  import { ProtocolError, WireFailure } from "../protocol/messages.ts";
7
7
  import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type PetcatResult, type ToolOperation, type ToolOperations, type HostInfo, type ToolStatus } from "../protocol/tools.ts";
8
8
  import { HostConnection } from "./connect.ts";
9
+ import { readPrg } from "./image.ts";
9
10
  import { readProjectFile } from "./transfer.ts";
10
11
 
11
12
  export interface ToolCallOptions {
@@ -72,10 +73,10 @@ export async function inspectDisk(request: InspectDiskRequest, options: ToolCall
72
73
  return result.action === "read" && result.found ? { ...result, data: attachments[0]! } : result;
73
74
  }
74
75
 
75
- /** petcat.decode: the C64 BASIC V2 listing of a project program and its machine-code handoffs. */
76
+ /** petcat.decode: the C64 BASIC V2 listing of a project program and its machine-code handoffs. Refuses a file that is no PRG as readPrg does. */
76
77
  export async function decodeBasic(request: { program: string }, options: ToolCallOptions = {}): Promise<PetcatResult> {
77
- const file = readProjectFile(request.program);
78
- return (await callTool("petcat.decode", {}, [file.bytes], options)).result;
78
+ const { bytes } = readPrg(request.program);
79
+ return (await callTool("petcat.decode", {}, [bytes], options)).result;
79
80
  }
80
81
 
81
82
  /** host.status: the Host Runtime, and each native tool on the host, found and run once. */
@@ -20,6 +20,11 @@ export function projectFolder(project: string | undefined): string {
20
20
  return resolveProject(project, process.cwd(), { remedy: "Give project: <folder>" });
21
21
  }
22
22
 
23
+ /** Refuses an MCP `out` before the tool does any work, with the checks that every --out of a script gets. */
24
+ export function checkOut(path: string, project: string | undefined): void {
25
+ checkOutputPath(path, "file", { root: projectFolder(project), what: "out" });
26
+ }
27
+
23
28
  /** The project folder of this process (--project or the project lookup), or a WireFailure. */
24
29
  function currentProject(): string {
25
30
  return projectRoot();
@@ -36,17 +41,17 @@ export interface ProjectFile {
36
41
  * project rules refuse, not-found when nothing is there, limit-exceeded when
37
42
  * the file is too large to transfer.
38
43
  */
39
- export function readProjectFile(path: string, options: { root?: string } = {}): ProjectFile {
44
+ export function readProjectFile(path: string, options: { root?: string; what?: string } = {}): ProjectFile {
40
45
  const root = options.root ?? currentProject();
41
46
  let real: string;
42
47
  try {
43
48
  real = resolveProjectFile(path, root);
44
49
  } catch (error) {
45
50
  if ((error as NodeJS.ErrnoException).code === "ENOENT") {
46
- throw new WireFailure("not-found", `There is no file at ${path} in the project folder.`);
51
+ throw new WireFailure("not-found", `${options.what === undefined ? "" : `${options.what}: `}There is no file at ${path} in the project folder.`);
47
52
  }
48
53
  if (isRefusal(error) && error.code === "invalid-input") {
49
- throw new WireFailure("invalid-input", `${path}: give a path relative to the project folder that stays inside it.`);
54
+ throw new WireFailure("invalid-input", `${options.what ?? path}: give a path relative to the project folder that stays inside it, not ${path}.`);
50
55
  }
51
56
  throw error;
52
57
  }
@@ -129,19 +129,19 @@ export class ViceSessionClient {
129
129
 
130
130
  /** Loads a project PRG into memory without reset or start; finishes stopped. `root` is the project folder; it stays on this side. */
131
131
  async programLoad(params: { path: string; address?: number; root?: string }): Promise<{ state: RunState; loadAddress: number; size: number }> {
132
- const file = readProjectFile(params.path, params.root === undefined ? {} : { root: params.root });
132
+ const file = readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
133
133
  return this.#request("programLoad", params.address === undefined ? {} : { address: params.address }, [file.bytes]);
134
134
  }
135
135
 
136
136
  /** Autostarts a project program or image, as VICE's autostart does. `root` is the project folder; it stays on this side. */
137
137
  async autostart(params: { path: string; index: number; run: boolean; root?: string }): Promise<{ state: RunState; emulatorFlaw?: string }> {
138
- const file = readProjectFile(params.path, params.root === undefined ? {} : { root: params.root });
138
+ const file = readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
139
139
  return this.#request("autostart", { type: file.type, index: params.index, run: params.run }, [file.bytes]);
140
140
  }
141
141
 
142
142
  /** Attaches a project disk image to drive 8. `root` is the project folder; it stays on this side. */
143
143
  async diskAttach(params: { path: string; root?: string }): Promise<{ attached: boolean }> {
144
- const file = readProjectFile(params.path, params.root === undefined ? {} : { root: params.root });
144
+ const file = readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
145
145
  return this.#request("diskAttach", { type: file.type }, [file.bytes]);
146
146
  }
147
147