@henols/c64-re-tools 2.8.0-rc.2 → 2.8.0-rc.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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  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 +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  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 +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +12 -7
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +10 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +43 -71
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
@@ -1,7 +1,7 @@
1
1
  import { createServer, type Server, type Socket } from "node:net";
2
2
 
3
3
  import { encodeFrame, FrameTooLarge, MessageReader } from "../protocol/framing.ts";
4
- import { isRefusal } from "../errors.ts";
4
+ import { describeError, describeErrorStack, isRefusal } from "../errors.ts";
5
5
  import { PACKAGE } from "../package.ts";
6
6
  import { checkHello, isOneOf, HEARTBEAT_TIMEOUT_MS, parseClientMessage, ProtocolError, type HostMessage, type ReceivedRequest, type VideoStandard, type WireError, WireFailure } from "../protocol/messages.ts";
7
7
  import { TOOL_OPERATIONS, validateToolParams, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
@@ -64,10 +64,6 @@ const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
64
64
  const REFUSED_CLOSE_MS = 1_000;
65
65
 
66
66
  /** A caught value for the log, with its stack when it has one. */
67
- function describe(error: unknown): string {
68
- return error instanceof Error ? (error.stack ?? error.message) : String(error);
69
- }
70
-
71
67
  function toWireError(error: unknown, fallback: WireError): WireError {
72
68
  return isRefusal(error) ? { code: error.code, message: error.message } : fallback;
73
69
  }
@@ -182,13 +178,13 @@ class Connection {
182
178
  } catch (error) {
183
179
  // Any failure closes only this connection; the listener and the other connections go on.
184
180
  if (error instanceof ProtocolError) this.#abort(`protocol error: ${error.message}`);
185
- else this.#abort(`internal error: ${describe(error)}`);
181
+ else this.#abort(`internal error: ${describeErrorStack(error)}`);
186
182
  }
187
183
  }
188
184
 
189
185
  /** Closes this connection when work that runs after its message fails in an unexpected way. */
190
186
  #contain(work: Promise<void>): void {
191
- work.catch((error: unknown) => this.#abort(`internal error: ${describe(error)}`));
187
+ work.catch((error: unknown) => this.#abort(`internal error: ${describeErrorStack(error)}`));
192
188
  }
193
189
 
194
190
  #dispatch(raw: unknown, attachments: Buffer[]): void {
@@ -247,7 +243,7 @@ class Connection {
247
243
  try {
248
244
  return await this.#options.createViceSession({ videoStandard, log: this.#log });
249
245
  } catch (error) {
250
- this.#log(`VICE session failed to start: ${error instanceof Error ? error.message : String(error)}`);
246
+ this.#log(`VICE session failed to start: ${describeError(error)}`);
251
247
  trace().event("connection.session-failed", { connection: this.#id, error });
252
248
  this.#send({
253
249
  type: "error",
@@ -294,7 +290,7 @@ class Connection {
294
290
  record({ ok: true, result });
295
291
  } catch (error) {
296
292
  if (!isRefusal(error)) {
297
- this.#log(`operation ${request.op} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);
293
+ this.#log(`operation ${request.op} failed: ${describeErrorStack(error)}`);
298
294
  }
299
295
  const wire = toWireError(error, { code: "operation-failed", message: "The operation failed inside the host runtime." });
300
296
  this.#send({ type: "reply", id: request.id, error: wire });
@@ -318,7 +314,7 @@ class Connection {
318
314
  try {
319
315
  await session?.close();
320
316
  } catch (error) {
321
- this.#log(`session close failed: ${error instanceof Error ? error.message : String(error)}`);
317
+ this.#log(`session close failed: ${describeError(error)}`);
322
318
  }
323
319
  this.#log("closed");
324
320
  this.#resolveClosed();
@@ -361,7 +357,7 @@ export class ListenError extends Error {
361
357
  readonly port: number;
362
358
 
363
359
  constructor(cause: unknown, address: string, port: number) {
364
- super(`cannot listen on ${address} port ${port}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
360
+ super(`cannot listen on ${address} port ${port}: ${describeError(cause)}`, { cause });
365
361
  this.name = "ListenError";
366
362
  this.code = (cause as NodeJS.ErrnoException | undefined)?.code;
367
363
  this.address = address;
@@ -20,6 +20,8 @@ import { runToolOrFail, type ToolContext } from "../../native/run.ts";
20
20
 
21
21
  const TIMEOUT_MS = 30_000;
22
22
  const BLOCK_BYTES = 256;
23
+ /** The sector chains of the files that c1541 follows at the same time, each in its own c1541 run. */
24
+ const CHAINS_AT_ONCE = 4;
23
25
  /** Block reads in one c1541 call, so that its command line stays far below the Windows limit of 32767 characters. */
24
26
  export const READS_PER_CALL = 256;
25
27
 
@@ -273,9 +275,13 @@ export async function inspect(params: C1541Params, image: Buffer, context: ToolC
273
275
  if (params.action === "bam" || params.unreferenced === true) {
274
276
  // Every sector that the header, the directory or a file holds; a file without blocks has no chain.
275
277
  const referenced = [...headerChain, ...(RESERVED[info.format] ?? [])];
276
- for (const entry of directory.entries) {
277
- if (entry.startTrack !== 0) referenced.push(...(await c1541.chain({ track: entry.startTrack, sector: entry.startSector })));
278
- if (entry.sideStart !== undefined) referenced.push(...(await c1541.chain(entry.sideStart)));
278
+ const starts = directory.entries.flatMap((entry) => [...(entry.startTrack === 0 ? [] : [{ track: entry.startTrack, sector: entry.startSector }]), ...(entry.sideStart === undefined ? [] : [entry.sideStart])]);
279
+ for (let first = 0; first < starts.length; first += CHAINS_AT_ONCE) {
280
+ // The first damaged chain in directory order is the one that the refusal names.
281
+ for (const chain of await Promise.allSettled(starts.slice(first, first + CHAINS_AT_ONCE).map((start) => c1541.chain(start)))) {
282
+ if (chain.status === "rejected") throw chain.reason;
283
+ referenced.push(...chain.value);
284
+ }
279
285
  }
280
286
  unreferenced = unreferencedSectors(tracks, referenced);
281
287
  }
@@ -2,8 +2,8 @@
2
2
  // and register/bank id lookups live here; callers never see monitor details.
3
3
 
4
4
  import { WireFailure, type VideoStandard } from "../../protocol/messages.ts";
5
- import { type Comparison, type Condition, type BacktraceFrame, type HistoryEntry, type Instruction, type MemmapRange, type ProfileEntry, type JoystickState, type MemoryView, type RegisterValues, type Registers, type Space } from "../../protocol/vice.ts";
6
- import { COVERAGE, formatC64Address, formatC64Byte } from "../../c64.ts";
5
+ import { type Comparison, type Condition, type BacktraceFrame, FLAG_BITS, type HistoryEntry, type Instruction, type MemmapRange, type ProfileEntry, type JoystickState, type MemoryView, type RegisterValues, type Registers, type Space } from "../../protocol/vice.ts";
6
+ import { COVERAGE, formatC64Address, formatC64Byte, hexByte, hexWord } from "../../c64.ts";
7
7
  import type { IndexedFrame } from "../../graphics.ts";
8
8
  import { decodeDisplay, decodePalette, visibleFrame } from "./screen.ts";
9
9
  import type { TextMonitor } from "./text-monitor.ts";
@@ -105,9 +105,6 @@ export function inRasterWindow(position: { line: number; cycle: number }, line:
105
105
  return ahead > 0 && ahead < RASTER_WINDOW_LINES;
106
106
  }
107
107
 
108
- /** The 12 opcodes that jam an NMOS 6502/6510. */
109
- export const JAM_OPCODES = new Set([0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x92, 0xb2, 0xd2, 0xf2]);
110
-
111
108
  const DIRECTION_BITS: Record<JoystickState["direction"], number> = {
112
109
  center: 0,
113
110
  up: 0x01,
@@ -125,10 +122,6 @@ export function joystickLines(state: JoystickState): number {
125
122
  return 0x1f & ~(DIRECTION_BITS[state.direction] | (state.fire ? 0x10 : 0));
126
123
  }
127
124
 
128
- function hex4(value: number): string {
129
- return value.toString(16).padStart(4, "0");
130
- }
131
-
132
125
  /**
133
126
  * Parses monitor disassembly lines such as ".C:e5cf 85 CC STA $CC".
134
127
  * Hex numbers in the text become lowercase. A line that wraps past $ffff ends the list.
@@ -335,6 +328,11 @@ function expectQuiet(what: string, answer: string, known?: RegExp): void {
335
328
  if (other.length > 0) throw unknownForm(what, other);
336
329
  }
337
330
 
331
+ /** Refuses view ram for the drive: the view is the C64's RAM under its ROMs. */
332
+ function checkView(space: Space, view: MemoryView): void {
333
+ if (space === "drive8" && view === "ram") throw new WireFailure("unsupported-in-space", "view ram is available only in space c64; use view cpu for drive8.");
334
+ }
335
+
338
336
  /** Quotes a host file path for a text-monitor command. Session scratch paths never contain quotes. */
339
337
  function quoted(path: string): string {
340
338
  if (/["\r\n]/.test(path)) throw new Error(`a monitor file path cannot contain quotes or line breaks: ${path}`);
@@ -342,28 +340,13 @@ function quoted(path: string): string {
342
340
  }
343
341
 
344
342
  export function statusRegisterFromFlags(flags: Registers["flags"]): number {
345
- return (
346
- (flags.n ? 0x80 : 0) |
347
- (flags.v ? 0x40 : 0) |
348
- 0x20 | // bit 5 always reads as 1 on the 6502
349
- (flags.b ? 0x10 : 0) |
350
- (flags.d ? 0x08 : 0) |
351
- (flags.i ? 0x04 : 0) |
352
- (flags.z ? 0x02 : 0) |
353
- (flags.c ? 0x01 : 0)
354
- );
343
+ // Bit 5 always reads as 1 on the 6502.
344
+ return (Object.keys(FLAG_BITS) as Array<keyof Registers["flags"]>).reduce((value, flag) => (flags[flag] ? value | FLAG_BITS[flag] : value), 0x20);
355
345
  }
356
346
 
357
347
  export function flagsFromStatusRegister(value: number): Registers["flags"] {
358
- return {
359
- n: (value & 0x80) !== 0,
360
- v: (value & 0x40) !== 0,
361
- b: (value & 0x10) !== 0,
362
- d: (value & 0x08) !== 0,
363
- i: (value & 0x04) !== 0,
364
- z: (value & 0x02) !== 0,
365
- c: (value & 0x01) !== 0,
366
- };
348
+ const set = (flag: keyof Registers["flags"]) => (value & FLAG_BITS[flag]) !== 0;
349
+ return { n: set("n"), v: set("v"), b: set("b"), d: set("d"), i: set("i"), z: set("z"), c: set("c") };
367
350
  }
368
351
 
369
352
  /** Generous bound for commands that run the machine (step/next): they answer only once it stops again. */
@@ -419,9 +402,7 @@ export class ViceAdapter {
419
402
 
420
403
  /** Reads memory as the selected CPU (view cpu) or as plain RAM (view ram, c64 only). Returns lowercase hex. */
421
404
  async readMemory(options: { address: number; size: number; space: Space; view: MemoryView }): Promise<string> {
422
- if (options.space === "drive8" && options.view === "ram") {
423
- throw new WireFailure("unsupported-in-space", "view ram is available only in space c64; use view cpu for drive8.");
424
- }
405
+ checkView(options.space, options.view);
425
406
  const response = await this.#monitor.request(
426
407
  Command.memoryGet,
427
408
  memoryGetBody({
@@ -441,7 +422,7 @@ export class ViceAdapter {
441
422
  * text-monitor dump: no register read gives them.
442
423
  */
443
424
  async ciaHidden(base: 0xdc00 | 0xdd00): Promise<CiaHidden> {
444
- const answer = await this.#computerText(`io ${hex4(base)}`);
425
+ const answer = await this.#computerText(`io ${hexWord(base)}`);
445
426
  const mask = /\(mask: ([0-9a-f]{2})\)/i.exec(answer);
446
427
  const latchA = /Timer A: [0-9a-f]{4} \(latched ([0-9a-f]{4})\)/i.exec(answer);
447
428
  const latchB = /Timer B: [0-9a-f]{4} \(latched ([0-9a-f]{4})\)/i.exec(answer);
@@ -460,9 +441,7 @@ export class ViceAdapter {
460
441
 
461
442
  /** Writes memory as the selected CPU (view cpu) or into plain RAM (view ram, c64 only). */
462
443
  async writeMemory(options: { address: number; data: string; space: Space; view: MemoryView }): Promise<number> {
463
- if (options.space === "drive8" && options.view === "ram") {
464
- throw new WireFailure("unsupported-in-space", "view ram is available only in space c64; use view cpu for drive8.");
465
- }
444
+ checkView(options.space, options.view);
466
445
  const bytes = Buffer.from(options.data, "hex");
467
446
  const header = Buffer.alloc(8);
468
447
  header[0] = 0; // no side effects
@@ -639,7 +618,7 @@ export class ViceAdapter {
639
618
  * load address is skipped. Returns where it went.
640
619
  */
641
620
  async loadProgram(file: string, address?: number): Promise<{ loadAddress: number; size: number }> {
642
- const target = address === undefined ? "" : ` $${address.toString(16).padStart(4, "0")}`;
621
+ const target = address === undefined ? "" : ` ${formatC64Address(address)}`;
643
622
  const answer = await this.#computerText(`load ${quoted(file)} 0${target}`);
644
623
  const match = /from ([0-9A-Fa-f]{4}) to ([0-9A-Fa-f]{4}) \(([0-9A-Fa-f]+) bytes\)/.exec(answer);
645
624
  if (match === null) throw new WireFailure("media-error", "The emulator could not load the program.");
@@ -704,9 +683,7 @@ export class ViceAdapter {
704
683
  * a space and view, then restores the defaults (device c:, bank cpu).
705
684
  */
706
685
  async #inTextContext<T>(space: Space, view: MemoryView, work: () => Promise<T>): Promise<T> {
707
- if (space === "drive8" && view === "ram") {
708
- throw new WireFailure("unsupported-in-space", "view ram is available only in space c64; use view cpu for drive8.");
709
- }
686
+ checkView(space, view);
710
687
  if (space === "drive8") await this.#text.command("dev 8:");
711
688
  else await this.#computerText(`bank ${view}`);
712
689
  try {
@@ -719,9 +696,9 @@ export class ViceAdapter {
719
696
 
720
697
  /** Finds a byte pattern (null = any byte) with the monitor's hunt. Returns match addresses, at most `limit`. */
721
698
  async search(options: { start: number; end: number; pattern: Array<number | null>; space: Space; view: MemoryView; limit: number }): Promise<number[]> {
722
- const tokens = options.pattern.map((token) => (token === null ? "xx" : token.toString(16).padStart(2, "0"))).join(" ");
699
+ const tokens = options.pattern.map((token) => (token === null ? "xx" : hexByte(token))).join(" ");
723
700
  const answer = await this.#inTextContext(options.space, options.view, () =>
724
- this.#text.command(`hunt ${hex4(options.start)} ${hex4(options.end)} ${tokens}`, 30_000),
701
+ this.#text.command(`hunt ${hexWord(options.start)} ${hexWord(options.end)} ${tokens}`, 30_000),
725
702
  );
726
703
  return parseHunt(answer, options.limit);
727
704
  }
@@ -730,7 +707,7 @@ export class ViceAdapter {
730
707
  async disassemble(options: { address: number; count: number; space: Space; view: MemoryView }): Promise<Instruction[]> {
731
708
  const end = Math.min(0xffff, options.address + options.count * 3 - 1);
732
709
  const answer = await this.#inTextContext(options.space, options.view, () =>
733
- this.#text.command(`d ${hex4(options.address)} ${hex4(end)}`),
710
+ this.#text.command(`d ${hexWord(options.address)} ${hexWord(end)}`),
734
711
  );
735
712
  return parseDisassembly(answer, options.address).slice(0, options.count);
736
713
  }
@@ -788,7 +765,7 @@ export class ViceAdapter {
788
765
  /** How the C64 CPU accessed [start, end] since the memmap was last cleared, as merged ranges. */
789
766
  async memmap(start: number, end: number, maxRanges: number): Promise<{ ranges: MemmapRange[]; next?: number }> {
790
767
  // The first argument is the access mask ("ioRWXrwx"); ff shows every kind of access.
791
- return parseMemmap(await this.#computerText(`mmsh ff ${hex4(start)} ${hex4(end)}`, 60_000), maxRanges);
768
+ return parseMemmap(await this.#computerText(`mmsh ff ${hexWord(start)} ${hexWord(end)}`, 60_000), maxRanges);
792
769
  }
793
770
 
794
771
  async clearMemmap(): Promise<void> {
@@ -4,10 +4,11 @@
4
4
 
5
5
  import type { Socket } from "node:net";
6
6
 
7
+ import { StreamBuffer } from "../../protocol/framing.ts";
7
8
  import { connectWithTimeout } from "./connect.ts";
8
9
 
9
10
  export const STX = 0x02;
10
- export const API_VERSION = 0x02;
11
+ const API_VERSION = 0x02;
11
12
  /** Request id VICE uses for responses it sends unprompted (events). */
12
13
  export const EVENT_REQUEST_ID = 0xffff_ffff;
13
14
 
@@ -18,7 +19,6 @@ const RESPONSE_HEADER_BYTES = 12;
18
19
  export const Command = {
19
20
  memoryGet: 0x01,
20
21
  memorySet: 0x02,
21
- checkpointGet: 0x11,
22
22
  checkpointSet: 0x12,
23
23
  checkpointDelete: 0x13,
24
24
  checkpointList: 0x14,
@@ -29,7 +29,6 @@ export const Command = {
29
29
  dump: 0x41,
30
30
  undump: 0x42,
31
31
  resourceGet: 0x51,
32
- resourceSet: 0x52,
33
32
  advanceInstructions: 0x71,
34
33
  keyboardFeed: 0x72,
35
34
  executeUntilReturn: 0x73,
@@ -40,16 +39,13 @@ export const Command = {
40
39
  viceInfo: 0x85,
41
40
  paletteGet: 0x91,
42
41
  joyportSet: 0xa2,
43
- userportSet: 0xb2,
44
42
  exit: 0xaa,
45
- quit: 0xbb,
46
43
  reset: 0xcc,
47
44
  autostart: 0xdd,
48
45
  } as const;
49
46
 
50
47
  /** Response types that are not simply the command byte. */
51
48
  const TERMINAL_RESPONSE: Partial<Record<number, number>> = {
52
- [Command.checkpointGet]: 0x11,
53
49
  [Command.checkpointSet]: 0x11,
54
50
  [Command.registersSet]: 0x31,
55
51
  };
@@ -116,26 +112,31 @@ export function encodeCommand(requestId: number, command: number, body: Uint8Arr
116
112
 
117
113
  /** Splits the response stream into responses. Throws MonitorConnectionError on a bad header. */
118
114
  export class ResponseDecoder {
119
- #pending: Buffer = Buffer.alloc(0);
115
+ readonly #stream = new StreamBuffer();
116
+ /** The bytes that the response in front needs: its header, then its header and body. */
117
+ #needed = RESPONSE_HEADER_BYTES;
120
118
 
121
119
  push(chunk: Buffer): MonitorResponse[] {
122
- this.#pending = this.#pending.length === 0 ? chunk : Buffer.concat([this.#pending, chunk]);
120
+ this.#stream.push(chunk);
123
121
  const responses: MonitorResponse[] = [];
124
- while (this.#pending.length >= RESPONSE_HEADER_BYTES) {
125
- if (this.#pending[0] !== STX) throw new MonitorConnectionError("response does not start with STX");
126
- if (this.#pending[1] !== API_VERSION) {
127
- throw new MonitorConnectionError(`response has API version ${this.#pending[1]}, expected ${API_VERSION}`);
122
+ while (this.#stream.length >= this.#needed) {
123
+ const pending = this.#stream.bytes();
124
+ if (pending[0] !== STX) throw new MonitorConnectionError("response does not start with STX");
125
+ if (pending[1] !== API_VERSION) {
126
+ throw new MonitorConnectionError(`response has API version ${pending[1]}, expected ${API_VERSION}`);
128
127
  }
129
- const length = this.#pending.readUInt32LE(2);
130
- if (this.#pending.length < RESPONSE_HEADER_BYTES + length) break;
128
+ const length = pending.readUInt32LE(2);
129
+ this.#needed = RESPONSE_HEADER_BYTES + length;
130
+ if (pending.length < this.#needed) break;
131
131
  responses.push({
132
- type: this.#pending[6]!,
133
- error: this.#pending[7]!,
134
- requestId: this.#pending.readUInt32LE(8),
132
+ type: pending[6]!,
133
+ error: pending[7]!,
134
+ requestId: pending.readUInt32LE(8),
135
135
  // Copy so a retained body never pins the whole receive buffer.
136
- body: Buffer.from(this.#pending.subarray(RESPONSE_HEADER_BYTES, RESPONSE_HEADER_BYTES + length)),
136
+ body: Buffer.from(pending.subarray(RESPONSE_HEADER_BYTES, RESPONSE_HEADER_BYTES + length)),
137
137
  });
138
- this.#pending = this.#pending.subarray(RESPONSE_HEADER_BYTES + length);
138
+ this.#stream.drop(RESPONSE_HEADER_BYTES + length);
139
+ this.#needed = RESPONSE_HEADER_BYTES;
139
140
  }
140
141
  return responses;
141
142
  }
@@ -237,12 +238,12 @@ interface Pending {
237
238
  sequence: number;
238
239
  }
239
240
 
240
- export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
241
+ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
241
242
  /**
242
243
  * While an earlier command is overdue, later ones are still sent (VICE runs
243
244
  * them in order once it goes on, so cleanup lands) but waited for only this long.
244
245
  */
245
- export const OVERDUE_REQUEST_TIMEOUT_MS = 1_000;
246
+ const OVERDUE_REQUEST_TIMEOUT_MS = 1_000;
246
247
 
247
248
  /** One binary-monitor connection with request correlation and an event stream. */
248
249
  export class BinaryMonitor {
@@ -30,6 +30,7 @@ import { tmpdir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { setTimeout as sleep } from "node:timers/promises";
32
32
 
33
+ import { describeError } from "../../errors.ts";
33
34
  import { WireFailure, type VideoStandard } from "../../protocol/messages.ts";
34
35
  import { elapsedMs, trace } from "../../trace.ts";
35
36
  import { findTool, isOlderThanMinimum, MIN_VICE, VICE, type ViceVersion } from "../../native/discover.ts";
@@ -204,7 +205,7 @@ export async function launchVice(options: LaunchOptions): Promise<ViceProcess> {
204
205
  } catch (error) {
205
206
  lastError = error;
206
207
  if (error instanceof WireFailure && error.code === "installation-incomplete") throw error;
207
- options.log?.(`VICE launch attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}`);
208
+ options.log?.(`VICE launch attempt ${attempt} failed: ${describeError(error)}`);
208
209
  }
209
210
  }
210
211
  if (lastError instanceof WireFailure) throw lastError;
@@ -247,7 +248,7 @@ export async function checkViceStarts(options: Omit<LaunchOptions, "videoStandar
247
248
  } catch (error) {
248
249
  throw new WireFailure(
249
250
  "installation-incomplete",
250
- `VICE (${binary}) starts, but it did not tell its version (${error instanceof Error ? error.message : String(error)}). ` +
251
+ `VICE (${binary}) starts, but it did not tell its version (${describeError(error)}). ` +
251
252
  `c64-re-tools needs VICE ${MIN_VICE.major}.${MIN_VICE.minor} or later. ${VICE.remedy}`,
252
253
  );
253
254
  } finally {
@@ -333,13 +334,21 @@ async function launchOnce(options: LaunchOptions): Promise<ViceProcess> {
333
334
 
334
335
  try {
335
336
  const deadline = Date.now() + (options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS);
336
- monitor = await waitForMonitor(port, () => exited, deadline);
337
- text = await waitForText(textPort, () => exited, deadline);
337
+ monitor = await connectWhenReady(
338
+ () => BinaryMonitor.connect(port),
339
+ (connection, timeoutMs) => connection.request(Command.ping, undefined, timeoutMs),
340
+ { probeMs: PING_TIMEOUT_MS, hasExited: () => exited, deadline, late: "The emulator did not become ready in time." },
341
+ );
342
+ text = await connectWhenReady(
343
+ () => TextMonitor.connect(textPort),
344
+ (connection, timeoutMs) => connection.command("dev c:", timeoutMs),
345
+ { probeMs: TEXT_PROBE_MS, hasExited: () => exited, deadline, late: "The emulator's monitor did not become ready in time." },
346
+ );
338
347
  await checkSameMachine(monitor, text);
339
348
  // Readiness stopped the machine; let it run as a freshly started C64 does.
340
349
  await monitor.request(Command.exit);
341
350
  } catch (error) {
342
- log(`VICE failed to start: ${error instanceof Error ? error.message : String(error)}\n${outputTail()}`);
351
+ log(`VICE failed to start: ${describeError(error)}\n${outputTail()}`);
343
352
  trace().event("vice.launch-failed", { pid: child.pid, ms: elapsedMs(launched), error });
344
353
  await stop();
345
354
  if (error instanceof WireFailure) throw error;
@@ -351,29 +360,34 @@ async function launchOnce(options: LaunchOptions): Promise<ViceProcess> {
351
360
  }
352
361
 
353
362
  /**
354
- * Connects the text monitor and proves it answers. Like the binary one, VICE
355
- * can accept a connection during startup that it then never serves, so a
356
- * connection that does not answer a probe is dropped and made again.
363
+ * Connects a monitor and proves that it answers a probe, until the deadline.
364
+ * VICE can accept a connection during startup that it then never serves, so a
365
+ * connection that does not answer the probe is dropped and made again. `late`
366
+ * is the refusal when the deadline passes.
357
367
  */
358
- async function waitForText(port: number, hasExited: () => boolean, deadline: number): Promise<TextMonitor> {
359
- while (Date.now() < deadline) {
360
- if (hasExited()) throw new WireFailure("machine-unavailable", "The emulator exited while it was starting.");
361
- let text: TextMonitor;
368
+ async function connectWhenReady<T extends { close(): Promise<void> }>(
369
+ connect: () => Promise<T>,
370
+ probe: (connection: T, timeoutMs: number) => Promise<unknown>,
371
+ options: { probeMs: number; hasExited: () => boolean; deadline: number; late: string },
372
+ ): Promise<T> {
373
+ while (Date.now() < options.deadline) {
374
+ if (options.hasExited()) throw new WireFailure("machine-unavailable", "The emulator exited while it was starting.");
375
+ let connection: T;
362
376
  try {
363
- text = await TextMonitor.connect(port);
377
+ connection = await connect();
364
378
  } catch {
365
379
  await sleep(RETRY_MS);
366
380
  continue;
367
381
  }
368
382
  try {
369
- await text.command("dev c:", Math.min(TEXT_PROBE_MS, Math.max(1, deadline - Date.now())));
370
- return text;
383
+ await probe(connection, Math.min(options.probeMs, Math.max(1, options.deadline - Date.now())));
384
+ return connection;
371
385
  } catch {
372
- await text.close();
386
+ await connection.close();
373
387
  await sleep(RETRY_MS);
374
388
  }
375
389
  }
376
- throw new WireFailure("machine-unavailable", "The emulator's monitor did not become ready in time.");
390
+ throw new WireFailure("machine-unavailable", options.late);
377
391
  }
378
392
 
379
393
  const TEXT_PROBE_MS = 2_000;
@@ -405,26 +419,3 @@ async function checkSameMachine(monitor: BinaryMonitor, text: TextMonitor): Prom
405
419
  }
406
420
  await write(original);
407
421
  }
408
-
409
- /** Connects the binary monitor and proves it answers a ping, until `deadline`. */
410
- async function waitForMonitor(port: number, hasExited: () => boolean, deadline: number): Promise<BinaryMonitor> {
411
- while (Date.now() < deadline) {
412
- if (hasExited()) throw new WireFailure("machine-unavailable", "The emulator exited while it was starting.");
413
- let monitor: BinaryMonitor;
414
- try {
415
- monitor = await BinaryMonitor.connect(port);
416
- } catch {
417
- await sleep(RETRY_MS);
418
- continue;
419
- }
420
- try {
421
- await monitor.request(Command.ping, undefined, Math.min(PING_TIMEOUT_MS, Math.max(1, deadline - Date.now())));
422
- return monitor;
423
- } catch {
424
- // VICE can drop a connection it accepted during startup; connect again.
425
- await monitor.close();
426
- await sleep(RETRY_MS);
427
- }
428
- }
429
- throw new WireFailure("machine-unavailable", "The emulator did not become ready in time.");
430
- }