@henols/c64-re-tools 2.8.0-rc.2 → 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 (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 +10 -5
  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 +9 -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 +124 -40
  47. package/skills/c64-unpacker/scripts/unpacker.ts +81 -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 +28 -68
  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
@@ -21,6 +21,7 @@
21
21
 
22
22
  import type { Socket } from "node:net";
23
23
 
24
+ import { hexWord } from "../../c64.ts";
24
25
  import { connectWithTimeout } from "./connect.ts";
25
26
 
26
27
  export class TextMonitorError extends Error {
@@ -33,7 +34,7 @@ export class TextMonitorTimeoutError extends TextMonitorError {
33
34
  }
34
35
 
35
36
  const PROMPT = /\((?:C|\d+):\$[0-9a-f]{4}\) /g;
36
- export const DEFAULT_COMMAND_TIMEOUT_MS = 10_000;
37
+ const DEFAULT_COMMAND_TIMEOUT_MS = 10_000;
37
38
  /** The default of TextMonitor.resendAfterMs. */
38
39
  const RESEND_AFTER_MS = 3_000;
39
40
  /** The default of TextMonitor.overdueTimeoutMs. */
@@ -46,8 +47,7 @@ const ANY_SENTINEL_ANSWER = /\+\d+\n\$[0-9a-f]{4}\n[0-7]+\n%[01 ]+\n/g;
46
47
  const STEP_MESSAGE = /^Stepping through the next \d+ instruction\(s\)\.\n/gm;
47
48
 
48
49
  function sentinelPattern(nonce: number): RegExp {
49
- const hex = nonce.toString(16).padStart(4, "0");
50
- return new RegExp(`\\+${nonce}\\n\\$${hex}\\n[0-7]+\\n%[01 ]+\\n\\((?:C|\\d+):\\$[0-9a-f]{4}\\) `);
50
+ return new RegExp(`\\+${nonce}\\n\\$${hexWord(nonce)}\\n[0-7]+\\n%[01 ]+\\n\\((?:C|\\d+):\\$[0-9a-f]{4}\\) `);
51
51
  }
52
52
 
53
53
  /** Strips prompts, stray sentinel answers, step messages and surrounding blank space from a command's raw output. */
@@ -5,7 +5,7 @@ import { textToPetscii } from "../c64.ts";
5
5
  import type { ViceSessionClient } from "./vice-session.ts";
6
6
 
7
7
  /** How often, and for how long, a load is checked. */
8
- export const LOAD_POLL_FRAMES = 25;
8
+ const LOAD_POLL_FRAMES = 25;
9
9
  export const LOAD_LIMIT_FRAMES = 1500;
10
10
 
11
11
  /**
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { connect as connectTcp, type Socket } from "node:net";
4
4
 
5
+ import { describeError } from "../errors.ts";
5
6
  import { encodeFrame, MessageReader } from "../protocol/framing.ts";
6
7
  import { elapsedMs, trace } from "../trace.ts";
7
8
  import { DEFAULT_HOST_PORT, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, HOST_PROTOCOL_ID, HOST_PROTOCOL_VERSION, checkRelease, parseHostMessage, ProtocolError, WireFailure, withStopAndAsk, type Hello, type HostMessage, type Ping, type Request, type Role, type VideoStandard } from "../protocol/messages.ts";
@@ -117,7 +118,7 @@ export class HostConnection {
117
118
  this.#failure =
118
119
  error instanceof ProtocolError
119
120
  ? error
120
- : new Error(`could not handle a message from the host runtime: ${error instanceof Error ? error.message : String(error)}`);
121
+ : new Error(`could not handle a message from the host runtime: ${describeError(error)}`);
121
122
  socket.destroy();
122
123
  }
123
124
  });
@@ -5,9 +5,6 @@ import { COVERAGE, type CodeRange } from "../c64.ts";
5
5
  import { MAX_MEMMAP_RANGES, type MemmapRange } from "../protocol/vice.ts";
6
6
  import type { ViceSessionClient } from "./vice-session.ts";
7
7
 
8
- /** A full coverage file: offset n is address n. */
9
- export const FULL_COVERAGE = 0x10000;
10
-
11
8
  /** The coverage bytes of start..end, read from the session in parts. */
12
9
  export async function readCoverage(session: Pick<ViceSessionClient, "memmap">, start = 0x0000, end = 0xffff): Promise<Uint8Array> {
13
10
  const map = new Uint8Array(end - start + 1);
@@ -5,8 +5,9 @@
5
5
 
6
6
  import { c64AddressOf } from "../c64.ts";
7
7
  import { Refusal } from "../errors.ts";
8
+ import { isInteger, isObject } from "../protocol/messages.ts";
8
9
  import { MAX_MEMORY_WRITE } from "./tools.ts";
9
- import { readProjectFile } from "./transfer.ts";
10
+ import { readProjectJson } from "./transfer.ts";
10
11
  import type { ViceSessionClient } from "./vice-session.ts";
11
12
 
12
13
  /** Frames from a hard reset to the READY prompt, with margin. */
@@ -30,8 +31,7 @@ export interface EntryState {
30
31
  raw: Record<string, unknown>;
31
32
  }
32
33
 
33
- const isObject = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
34
- const isByte = (value: unknown): value is number => Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 0xff;
34
+ const isByte = (value: unknown): value is number => isInteger(value, 0, 0xff);
35
35
 
36
36
  /** The entry state of a value. `where` names it in a refusal, for example a file or "the entry state of the knowledge". */
37
37
  export function parseEntryState(value: unknown, where: string): EntryState {
@@ -64,14 +64,7 @@ export function parseEntryState(value: unknown, where: string): EntryState {
64
64
 
65
65
  /** Reads an entry_state.json of the project. Refuses a missing file with the remedy, and a file that is no entry state. */
66
66
  export function readEntryState(path: string): EntryState {
67
- const { bytes } = readProjectFile(path);
68
- let value: unknown;
69
- try {
70
- value = JSON.parse(bytes.toString("utf8"));
71
- } catch (error) {
72
- throw new Refusal("invalid-input", `${path} is not JSON: ${(error as Error).message}`);
73
- }
74
- return parseEntryState(value, path);
67
+ return parseEntryState(readProjectJson(path), path);
75
68
  }
76
69
 
77
70
  /** A hard reset, then the frames until the KERNAL shows READY. */
@@ -6,7 +6,8 @@ import { posix } from "node:path";
6
6
  import { isRefusal, Refusal } from "../errors.ts";
7
7
  import { formatC64Address, prgRange } from "../c64.ts";
8
8
  import { readEntryState, type EntryState } from "./entry-state.ts";
9
- import { readProjectFile } from "./transfer.ts";
9
+ import { isObject } from "../protocol/messages.ts";
10
+ import { readProjectFile, readProjectJson } from "./transfer.ts";
10
11
 
11
12
  export interface Image {
12
13
  segments: Array<{ start: number; end: number }>;
@@ -34,7 +35,7 @@ const MEDIA_KINDS: Record<string, string> = {
34
35
  };
35
36
 
36
37
  /** The remedy for a disk, tape or cartridge file where a PRG must be: get the PRG out of it. */
37
- export const MEDIA_REMEDY = "Get the PRG out of it, and give the path of that PRG";
38
+ const MEDIA_REMEDY = "Get the PRG out of it, and give the path of that PRG";
38
39
 
39
40
  /**
40
41
  * Refuses a file that is no PRG by its extension (`type`, lowercase, without
@@ -78,17 +79,11 @@ export function readImage(path: string): Image {
78
79
  const range = readPrg(path, MEDIA_REMEDY, "an image.json of an unpacked program or a PRG");
79
80
  return { segments: [{ start: range.start, end: range.end }], byteAt: (address) => range.body[address - range.start]! };
80
81
  }
81
- const { bytes } = readProjectFile(path);
82
+ const notImage = (what: string) => `${path} is not an image.json of an unpacked program: ${what}`;
82
83
  const fail = (what: string): never => {
83
- throw new Refusal("invalid-input", `${path} is not an image.json of an unpacked program: ${what}`);
84
+ throw new Refusal("invalid-input", notImage(what));
84
85
  };
85
- const isObject = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
86
- let parsed: unknown;
87
- try {
88
- parsed = JSON.parse(bytes.toString("utf8"));
89
- } catch (error) {
90
- return fail((error as Error).message);
91
- }
86
+ const parsed = readProjectJson(path, notImage);
92
87
  const manifest = isObject(parsed) ? parsed : fail("it is not a JSON object");
93
88
  const address = (value: unknown, what: string) => (typeof value === "string" && /^\$[0-9a-f]{4}$/i.test(value) ? Number.parseInt(value.slice(1), 16) : fail(`${what} is not a $ address`));
94
89
  if (typeof manifest.image !== "string") fail("it has no image");
@@ -13,9 +13,10 @@
13
13
  // The scripts install without packages, so this checker has no zod: the MCP
14
14
  // tools keep their zod schemas, and a test checks that both take the same inputs.
15
15
 
16
- import { c64AddressOf, SYMBOL_NAME, textToPetscii } from "../c64.ts";
16
+ import { isAddressText, textToPetscii } from "../c64.ts";
17
17
  import { keyTaps, MAX_PRESS_FRAMES, PRESS_FRAMES, type KeyTap } from "../c64-keys.ts";
18
18
  import { isRefusal, Refusal } from "../errors.ts";
19
+ import { isInteger, isObject, isOneOf } from "../protocol/messages.ts";
19
20
  import {
20
21
  COMPARISONS,
21
22
  CONDITION_REGISTERS,
@@ -30,7 +31,7 @@ import {
30
31
  type RunTarget,
31
32
  type RunUntilResult,
32
33
  } from "../protocol/vice.ts";
33
- import { readProjectFile } from "./transfer.ts";
34
+ import { readProjectJson } from "./transfer.ts";
34
35
  import type { ViceSessionClient } from "./vice-session.ts";
35
36
 
36
37
  /** A "$xxxx" address or a name, which the caller resolves. */
@@ -82,18 +83,18 @@ export const STEP_FIELDS = {
82
83
  flags: ["n", "v", "b", "d", "i", "z", "c"],
83
84
  } as const;
84
85
 
86
+ /** Hex bytes: two digits per byte, either case, at least one byte. The MCP tools take the same. */
87
+ export const HEX_BYTES = /^(?:[0-9a-fA-F]{2})+$/;
88
+ export const HEX_BYTES_RULE = "must be hex bytes, two digits per byte, no separators, for example a9008d20d0";
89
+
85
90
  /** The highest raster line of a PAL frame; an NTSC frame has fewer, which the emulator checks. */
86
91
  export const MAX_RASTER_LINE = 311;
87
92
  /** The wait of a runUntil step without timeoutFrames, as c64_run_until has it. */
88
93
  export const DEFAULT_TIMEOUT_FRAMES = 3000;
89
94
 
90
- export const isObject = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
91
- export const isInteger = (value: unknown, min: number, max: number): value is number => Number.isInteger(value) && (value as number) >= min && (value as number) <= max;
92
- const isOneOf = <T extends string>(values: readonly T[], value: unknown): value is T => (values as readonly unknown[]).includes(value);
93
-
94
95
  /** True for an address of a step or a file: $ and 1 to 4 hex digits, or a name. */
95
- export function isLocation(value: unknown): value is Location {
96
- return typeof value === "string" && (c64AddressOf(value) !== undefined || SYMBOL_NAME.test(value));
96
+ function isLocation(value: unknown): value is Location {
97
+ return typeof value === "string" && isAddressText(value);
97
98
  }
98
99
 
99
100
  /** Checks an address in a file: $ and 1 to 4 hex digits, or a name. */
@@ -112,32 +113,6 @@ export function keyboardBytes(input: { mode: "text" | "petscii"; text?: string |
112
113
  }
113
114
  }
114
115
 
115
- /**
116
- * One line of JSON with a space after each colon and comma: the form that a
117
- * refusal tells the caller to write.
118
- */
119
- export function jsonLine(value: unknown): string {
120
- if (Array.isArray(value)) return `[${value.map(jsonLine).join(", ")}]`;
121
- if (isObject(value)) return `{${Object.entries(value).filter(([, item]) => item !== undefined).map(([key, item]) => `${JSON.stringify(key)}: ${jsonLine(item)}`).join(", ")}}`;
122
- return JSON.stringify(value) ?? "null";
123
- }
124
-
125
- /** Field names of the 2.0 files and what a 2.1 object has in their place, when it has that field. */
126
- const RENAMED: Record<string, Array<{ field: string; write: string }>> = {
127
- at: [
128
- { field: "address", write: "address" },
129
- { field: "start", write: "start" },
130
- ],
131
- bytes: [{ field: "data", write: 'data, the bytes as hex text, for example "data": "a900",' }],
132
- equals: [{ field: "operator", write: '"operator": "eq" and "value"' }],
133
- };
134
-
135
- /** What to write in place of a field of the 2.0 files, for an object with these fields; undefined when the field has no 2.1 name there. */
136
- export function renamedField(key: string, fields: readonly string[]): string | undefined {
137
- const renamed = RENAMED[key]?.find((item) => fields.includes(item.field));
138
- return renamed === undefined ? undefined : `${key} is a 2.0 field. Write ${renamed.write} in place of ${key}`;
139
- }
140
-
141
116
  /** The checks of one input: `fail` names the field of the problem. */
142
117
  class Fields {
143
118
  readonly #value: Record<string, unknown>;
@@ -149,11 +124,7 @@ class Fields {
149
124
  this.#fail = fail;
150
125
  if (!isObject(value)) fail(`${where} must be an object with ${fields.join(", ")}`);
151
126
  this.#value = value as Record<string, unknown>;
152
- for (const key of Object.keys(this.#value)) {
153
- if (fields.includes(key)) continue;
154
- const renamed = renamedField(key, fields);
155
- fail(`${where} has the field ${key}, which it does not take. ${renamed === undefined ? "" : `${renamed}. `}Its fields are ${fields.join(", ")}`);
156
- }
127
+ for (const key of Object.keys(this.#value)) if (!fields.includes(key)) fail(`${where} has the field ${key}, which it does not take. Its fields are ${fields.join(", ")}`);
157
128
  }
158
129
 
159
130
  fail(field: string, message: string): never {
@@ -235,7 +206,7 @@ function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (mes
235
206
  case "write": {
236
207
  const fields = new Fields(value, where, STEP_FIELDS.write, fail);
237
208
  const data = fields.get("data");
238
- if (typeof data !== "string" || !/^(?:[0-9a-fA-F]{2})+$/.test(data)) fields.fail("data", "must be hex bytes, two digits per byte, no separators, for example a9008d20d0");
209
+ if (typeof data !== "string" || !HEX_BYTES.test(data)) fields.fail("data", HEX_BYTES_RULE);
239
210
  if ((data as string).length / 2 > MAX_MEMORY_WRITE) fields.fail("data", `has at most ${MAX_MEMORY_WRITE} bytes`);
240
211
  return { write: { address: fields.location("address"), data: (data as string).toLowerCase(), space: fields.oneOf("space", SPACES, "c64"), view: fields.oneOf("view", MEMORY_VIEWS, "cpu") } };
241
212
  }
@@ -290,78 +261,14 @@ function checkInput(kind: ActionStepKind, value: unknown, at: string, fail: (mes
290
261
  }
291
262
  }
292
263
 
293
- /** A "$xxxx" text of a number, or the value as it is. */
294
- const asAddress = (value: unknown) => (isInteger(value, 0, 0xffff) ? `$${value.toString(16).padStart(4, "0")}` : value);
295
-
296
- /** The hex text of a list of bytes, or the value as it is. */
297
- const asHex = (value: unknown) => (Array.isArray(value) && value.every((byte) => isInteger(byte, 0, 0xff)) ? Buffer.from(value as number[]).toString("hex") : value);
298
-
299
- /** A runUntil target from the 2.0 input: at (with raster), raster, or memory with at and equals. */
300
- function targetOf(input: Record<string, unknown>): unknown {
301
- if ("target" in input) return input.target;
302
- if (isObject(input.memory)) return { kind: "memory", address: input.memory.at ?? input.memory.address, operator: "eq", value: input.memory.equals };
303
- if ("at" in input) return { kind: "address", address: input.at, ...(input.raster === undefined ? {} : { condition: { kind: "raster", line: input.raster } }) };
304
- return { kind: "raster", line: input.raster };
305
- }
306
-
307
- /**
308
- * The 2.1 form of a step that has a form of the 2.0 files: the 2.0 fields
309
- * that it has and the step to write. Undefined when the step has no 2.0 form.
310
- * Keys of the step other than its kind (for example side) stay.
311
- */
312
- export function newStepForm(kind: string, step: Record<string, unknown>): { fields: string[]; step: Record<string, unknown> } | undefined {
313
- const input = step[kind];
314
- const { [kind]: _input, ...rest } = step;
315
- const form = (fields: string[], value: unknown, others = rest) => ({ fields, step: { [kind]: value, ...others } });
316
- switch (kind) {
317
- case "runUntil": {
318
- const { timeoutFrames: beside, ...others } = rest;
319
- const old = isObject(input) && !("target" in input) && ("at" in input || "raster" in input || "memory" in input);
320
- if (!isObject(input) || (!old && beside === undefined)) return undefined;
321
- const fields = [...(old ? ["at", "raster", "memory"].filter((key) => key in input).map((key) => `runUntil.${key}`) : []), ...(beside === undefined ? [] : ["timeoutFrames beside runUntil"])];
322
- const timeoutFrames = beside ?? input.timeoutFrames;
323
- return form(fields, { target: targetOf(input), ...(timeoutFrames === undefined ? {} : { timeoutFrames }) }, others);
324
- }
325
- case "type":
326
- return typeof input === "string" ? form(["type as text"], { mode: "text", text: input }) : undefined;
327
- case "write": {
328
- if (!isObject(input) || !("at" in input || "bytes" in input || Array.isArray(input.data))) return undefined;
329
- const { at: old, bytes, address, data, ...others } = input;
330
- return form(
331
- ["at", "bytes"].filter((key) => key in input).map((key) => `write.${key}`).concat(Array.isArray(data) ? ["write.data as a list"] : []),
332
- { address: address ?? old, data: asHex(data ?? bytes), ...others },
333
- );
334
- }
335
- case "registers": {
336
- if (!isObject(input)) return undefined;
337
- const fields = Object.entries(input).flatMap(([name, value]) => ((name === "pc" && typeof value === "number") || (name !== "pc" && name !== "flags" && typeof value === "string" && c64AddressOf(value) !== undefined) ? [`registers.${name} as ${typeof value === "number" ? "a number" : "text"}`] : []));
338
- if (fields.length === 0) return undefined;
339
- const values = Object.fromEntries(Object.entries(input).map(([name, value]) => [name, name === "pc" ? asAddress(value) : typeof value === "string" ? (c64AddressOf(value) ?? value) : value]));
340
- return form(fields, values);
341
- }
342
- default:
343
- return undefined;
344
- }
345
- }
346
-
347
264
  /** "a write step", "an observe step": the step kind with its article, for a refusal. */
348
265
  export const aStep = (kind: string): string => `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} step`;
349
266
 
350
- /** Refuses a step in a form of the 2.0 files: the message names its 2.0 fields and gives the step to write. */
351
- export function refuseOldStep(kind: string, step: Record<string, unknown>, at: string, fail: (message: string) => never): void {
352
- const found = newStepForm(kind, step);
353
- if (found === undefined) return;
354
- const petscii = kind === "type" ? ', or {"type": {"mode": "petscii", "bytes": [...]}} for PETSCII codes' : "";
355
- fail(`${at} has the 2.0 form (${found.fields.join(", ")}). Write ${jsonLine(found.step)}${petscii}`);
356
- }
357
-
358
267
  /**
359
268
  * Checks one action step of the given kind and returns it with the defaults
360
- * filled in. The step has no other key. A step in a form of the 2.0 files is
361
- * refused with the step to write.
269
+ * filled in. The step has no other key.
362
270
  */
363
271
  export function checkActionStep(kind: ActionStepKind, step: Record<string, unknown>, at: string, fail: (message: string) => never): ActionStep {
364
- refuseOldStep(kind, step, at, fail);
365
272
  for (const key of Object.keys(step)) if (key !== kind) fail(`${at} has the key ${key}, which ${aStep(kind)} does not have`);
366
273
  return checkInput(kind, step[kind], at, fail);
367
274
  }
@@ -426,14 +333,7 @@ export function readActionSteps(path: string, option: string, at?: (location: Lo
426
333
  const fail = (message: string): never => {
427
334
  throw new Refusal("invalid-input", `${option} ${path}: ${message}`);
428
335
  };
429
- let value: unknown;
430
- try {
431
- value = JSON.parse(readProjectFile(path).bytes.toString("utf8"));
432
- } catch (error) {
433
- if (error instanceof SyntaxError) return fail(`it is not JSON: ${error.message}`);
434
- throw error;
435
- }
436
- const steps = checkActionSteps(value, fail);
336
+ const steps = checkActionSteps(readProjectJson(path, (message) => `${option} ${path}: it is not JSON: ${message}`), fail);
437
337
  if (at !== undefined) checkStepNames(steps, at, `${option} ${path}`);
438
338
  return steps;
439
339
  }
@@ -84,8 +84,8 @@ export async function decodeBasic(request: { program: string }, options: ToolCal
84
84
  return (await callTool("petcat.decode", {}, [bytes], options)).result;
85
85
  }
86
86
 
87
- /** Skill scripts see failures and wire limits through the host-client, never the private protocol module. */
88
- export { WireFailure } from "../protocol/messages.ts";
89
- export { DISK_ACTIONS, DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, MAX_DISK_SECTORS } from "../protocol/tools.ts";
90
- export { JOYSTICK_DIRECTIONS, MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_KEYBOARD_BYTES, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, MAX_TIMEOUT_FRAMES, maskCoversFrame } from "../protocol/vice.ts";
87
+ /** Skill scripts see failures, value guards and wire limits through the host-client, never the private protocol module. */
88
+ export { isInteger, isObject, WireFailure } from "../protocol/messages.ts";
89
+ export { DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, MAX_DISK_SECTORS } from "../protocol/tools.ts";
90
+ export { MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, maskCoversFrame } from "../protocol/vice.ts";
91
91
  export { MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, type TraceHit, type TraceKind } from "../protocol/vice.ts";
@@ -64,6 +64,16 @@ export function readProjectFile(path: string, options: { root?: string; what?: s
64
64
  return { bytes: readFileSync(real), type: extname(path).slice(1).toLowerCase() };
65
65
  }
66
66
 
67
+ /** The JSON value of a project file. Text that is not JSON is invalid-input with `notJson` of the parse error. */
68
+ export function readProjectJson(path: string, notJson: (message: string) => string = (message) => `${path} is not JSON: ${message}`): unknown {
69
+ const text = readProjectFile(path).bytes.toString("utf8");
70
+ try {
71
+ return JSON.parse(text);
72
+ } catch (error) {
73
+ throw new WireFailure("invalid-input", notJson((error as Error).message));
74
+ }
75
+ }
76
+
67
77
  /**
68
78
  * The refusal for a write that the file system refused because of the path
69
79
  * (a folder, a file in place of a folder, no permission): invalid-input with
@@ -130,19 +130,19 @@ export class ViceSessionClient {
130
130
 
131
131
  /** Loads a project PRG into memory without reset or start; finishes stopped. `root` is the project folder; it stays on this side. */
132
132
  async programLoad(params: { path: string; address?: number; root?: string }): Promise<{ state: RunState; loadAddress: number; size: number }> {
133
- const file = readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
133
+ const file = projectFile(params);
134
134
  return this.#request("programLoad", params.address === undefined ? {} : { address: params.address }, [file.bytes]);
135
135
  }
136
136
 
137
137
  /** Autostarts a project program or image, as VICE's autostart does. `root` is the project folder; it stays on this side. */
138
138
  async autostart(params: { path: string; index: number; run: boolean; root?: string }): Promise<{ state: RunState }> {
139
- const file = readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
139
+ const file = projectFile(params);
140
140
  return this.#request("autostart", { type: file.type, index: params.index, run: params.run }, [file.bytes]);
141
141
  }
142
142
 
143
143
  /** Attaches a project disk image to drive 8. `root` is the project folder; it stays on this side. */
144
144
  async diskAttach(params: { path: string; root?: string }): Promise<{ attached: boolean }> {
145
- const file = readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
145
+ const file = projectFile(params);
146
146
  return this.#request("diskAttach", { type: file.type }, [file.bytes]);
147
147
  }
148
148
 
@@ -335,12 +335,16 @@ export class ViceSessionClient {
335
335
  }
336
336
  }
337
337
 
338
+ /** The file of a path in the project folder, or in `root` when it is given. */
339
+ function projectFile(params: { path: string; root?: string }) {
340
+ return readProjectFile(params.path, params.root === undefined ? { what: "path" } : { root: params.root, what: "path" });
341
+ }
338
342
 
339
- /** Reads `size` bytes from `address` of the C64 in reads of at most 4 KiB, in one view: up to all 64 KiB. */
340
- export async function readMemoryInParts(client: Pick<ViceSessionClient, "memoryRead">, address: number, size: number, view: "cpu" | "ram"): Promise<Buffer> {
343
+ /** Reads `size` bytes from `address` of a space (the C64 when not given) in reads of at most 4 KiB, in one view: up to all 64 KiB. */
344
+ export async function readMemoryInParts(client: Pick<ViceSessionClient, "memoryRead">, address: number, size: number, view: "cpu" | "ram", space: Space = "c64"): Promise<Buffer> {
341
345
  const parts: Buffer[] = [];
342
346
  for (let at = address; at < address + size; at += MAX_MEMORY_READ) {
343
- parts.push(Buffer.from((await client.memoryRead({ address: at, size: Math.min(MAX_MEMORY_READ, address + size - at), space: "c64", view })).data, "hex"));
347
+ parts.push(Buffer.from((await client.memoryRead({ address: at, size: Math.min(MAX_MEMORY_READ, address + size - at), space, view })).data, "hex"));
344
348
  }
345
349
  return Buffer.concat(parts);
346
350
  }