@henols/c64-re-tools 2.8.0-rc.5 → 2.8.0-rc.6

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 (57) 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 +78 -24
  4. package/skills/c64-docs/scripts/docs.ts +31 -10
  5. package/skills/c64-knowledge/SKILL.md +4 -3
  6. package/skills/c64-knowledge/scripts/knowledge.ts +31 -12
  7. package/skills/c64-packer/scripts/packer.ts +9 -2
  8. package/skills/c64-provenance/SKILL.md +1 -1
  9. package/skills/c64-provenance/scripts/lib/runtime.ts +5 -16
  10. package/skills/c64-source/references/loader.md +8 -7
  11. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  12. package/skills/c64-source/scripts/source.ts +49 -78
  13. package/skills/c64-static-analysis/SKILL.md +2 -2
  14. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  15. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  16. package/skills/c64-testing/SKILL.md +6 -0
  17. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  18. package/skills/c64-testing/scripts/lib/recording.ts +218 -12
  19. package/skills/c64-testing/scripts/lib/replay.ts +7 -3
  20. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  21. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  22. package/skills/c64-testing/scripts/testing.ts +24 -11
  23. package/skills/c64-unpacker/SKILL.md +6 -4
  24. package/skills/c64-unpacker/scripts/lib/loads.ts +4 -2
  25. package/skills/c64-unpacker/scripts/lib/machine.ts +128 -5
  26. package/skills/c64-unpacker/scripts/lib/stages.ts +5 -1
  27. package/skills/c64-unpacker/scripts/unpacker.ts +13 -12
  28. package/skills/emulator/SKILL.md +2 -2
  29. package/src/host/vice/adapter.ts +2 -1
  30. package/src/host-client/image.ts +33 -4
  31. package/src/host-client/tools.ts +1 -1
  32. package/src/host-client/transfer.ts +48 -26
  33. package/src/host-client/vice-session.ts +15 -0
  34. package/src/knowledge/database.ts +72 -19
  35. package/src/knowledge/import.ts +31 -8
  36. package/src/knowledge/names.ts +2 -2
  37. package/src/knowledge/program.ts +67 -7
  38. package/src/knowledge/schema.ts +6 -0
  39. package/src/knowledge/start-screen.ts +55 -2
  40. package/src/knowledge/write.ts +18 -12
  41. package/src/loader.ts +101 -33
  42. package/src/mcp/output.ts +13 -12
  43. package/src/mcp/server.ts +33 -22
  44. package/src/mcp/tools/debug.ts +21 -24
  45. package/src/mcp/tools/media.ts +27 -27
  46. package/src/mcp/tools/memory.ts +13 -17
  47. package/src/mcp/tools/video.ts +10 -12
  48. package/src/native/c64run.ts +39 -1
  49. package/src/native/decompiler/analyze.ts +1 -1
  50. package/src/native/dxa.ts +2 -2
  51. package/src/native/types.ts +26 -7
  52. package/src/program-code.ts +4 -2
  53. package/src/project.ts +224 -71
  54. package/src/protocol/vice.ts +5 -3
  55. package/src/script.ts +60 -15
  56. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  57. package/tools/c64run.c +18 -5
@@ -1,6 +1,6 @@
1
1
  // Media tools: c64_autostart, c64_program_load, c64_disk_attach and
2
- // c64_snapshot. Paths are relative to the project folder; the host-client
3
- // reads the file and the Host Runtime receives only its bytes.
2
+ // c64_snapshot. Paths are absolute; the host-client reads the file and the
3
+ // Host Runtime receives only its bytes.
4
4
 
5
5
  import { extname } from "node:path";
6
6
 
@@ -8,14 +8,14 @@ import { z } from "zod";
8
8
 
9
9
  import { formatC64Address } from "../../c64.ts";
10
10
  import { refuseNotPrg } from "../../host-client/image.ts";
11
- import { projectFolder, readProjectFile } from "../../host-client/transfer.ts";
11
+ import { readProjectFile, toolFile } from "../../host-client/transfer.ts";
12
12
  import { WireFailure } from "../../protocol/messages.ts";
13
13
  import { AUTOSTART_TYPES, DISK_TYPES, MAX_SNAPSHOTS, RUN_STATES } from "../../protocol/vice.ts";
14
- import { OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
14
+ import { OutInput, writeOut, WrittenOutput } from "../output.ts";
15
15
  import { AddressInput } from "../inputs.ts";
16
- import { AddressOutput, defineTool, requireFields, requireOut, TransientName } from "../server.ts";
16
+ import { AddressOutput, defineTool, requireFields, TransientName } from "../server.ts";
17
17
 
18
- const ProjectPath = z.string().min(1).describe("path relative to the project folder, for example build/game.prg");
18
+ const FilePath = z.string().min(1).describe("the absolute path of a file in a project folder, for example /home/me/game/build/game.prg");
19
19
 
20
20
  const list = (types: readonly string[]) => types.map((type) => `.${type}`).join(", ");
21
21
 
@@ -34,8 +34,7 @@ const c64Autostart = defineTool({
34
34
  "The c64_timing stopwatch starts again from zero.",
35
35
  inputSchema: z
36
36
  .object({
37
- path: ProjectPath,
38
- project: ProjectInput.optional(),
37
+ path: FilePath,
39
38
  index: z.number().int().min(0).max(0xfffe).optional().describe("directory entry of a disk image, 0 is the first entry. Without it, the first file loads as with LOAD\"*\""),
40
39
  run: z.boolean().default(true).describe("true runs the program after it loads"),
41
40
  })
@@ -51,7 +50,8 @@ const c64Autostart = defineTool({
51
50
  throw new WireFailure("invalid-input", `index selects an entry of a disk image (${list(DISK_TYPES)}). A .${type} file has no directory: leave out index.`);
52
51
  }
53
52
  // VICE numbers the directory entries from 1, and its 0 loads "*".
54
- return session.autostart({ path: input.path, index: input.index === undefined ? 0 : input.index + 1, run: input.run, root: projectFolder(input.project) });
53
+ const { file, root } = toolFile(input.path, "read");
54
+ return session.autostart({ path: file, index: input.index === undefined ? 0 : input.index + 1, run: input.run, root });
55
55
  },
56
56
  });
57
57
 
@@ -64,8 +64,7 @@ const c64ProgramLoad = defineTool({
64
64
  "With address, it goes there instead.",
65
65
  inputSchema: z
66
66
  .object({
67
- path: ProjectPath,
68
- project: ProjectInput.optional(),
67
+ path: FilePath,
69
68
  address: AddressInput.optional().describe("load here instead of at the file's own load address"),
70
69
  })
71
70
  .strict(),
@@ -74,8 +73,8 @@ const c64ProgramLoad = defineTool({
74
73
  async run(input, session) {
75
74
  // The same rule as every PRG reader of the scripts: .prg or no extension.
76
75
  refuseNotPrg(input.path, extname(input.path).slice(1).toLowerCase(), "Use c64_autostart, or c64_disk_attach for a disk image");
77
- const root = projectFolder(input.project);
78
- const result = await session.programLoad(input.address === undefined ? { path: input.path, root } : { path: input.path, address: input.address, root });
76
+ const { file, root } = toolFile(input.path, "read");
77
+ const result = await session.programLoad(input.address === undefined ? { path: file, root } : { path: file, address: input.address, root });
79
78
  return { state: result.state, loadAddress: formatC64Address(result.loadAddress), size: result.size };
80
79
  },
81
80
  });
@@ -87,30 +86,31 @@ const c64DiskAttach = defineTool({
87
86
  `Put a disk image from the project into drive 8 (${list(DISK_TYPES)}). ` +
88
87
  "Nothing loads or runs. To load from the disk, type LOAD on the C64 or use c64_autostart. " +
89
88
  "This does not change the run state of the machine.",
90
- inputSchema: z.object({ path: ProjectPath, project: ProjectInput.optional() }).strict(),
89
+ inputSchema: z.object({ path: FilePath }).strict(),
91
90
  outputSchema: z.object({ attached: z.boolean() }),
92
91
  readOnly: false,
93
92
  async run(input, session) {
94
- return session.diskAttach({ path: input.path, root: projectFolder(input.project) });
93
+ const { file, root } = toolFile(input.path, "read");
94
+ return session.diskAttach({ path: file, root });
95
95
  },
96
96
  });
97
97
 
98
98
  const c64Snapshot = defineTool({
99
+ outActions: ["save"],
99
100
  name: "c64_snapshot",
100
101
  title: "Machine snapshots",
101
102
  description:
102
103
  "Save and restore the whole machine state, attached disks included. Action save keeps a snapshot under a name you choose. " +
103
- "With out, save also writes it to that project file as a snapshot file (.vsf), so a later session can use it. " +
104
- "Action restore puts the machine back in that state and stops the CPU. Give name for a snapshot of this session, or file for a .vsf in the project. " +
104
+ "With out, save also writes it to that file as a snapshot file (.vsf), so a later session can use it. " +
105
+ "Action restore puts the machine back in that state and stops the CPU. Give name for a snapshot of this session, or file for a .vsf file. " +
105
106
  "A file restores only in the emulator version and with the machine settings that saved it. The c64_timing stopwatch keeps its reading. " +
106
107
  `Action list gives the names, and action remove removes one. A session keeps at most ${MAX_SNAPSHOTS} snapshots until it ends.`,
107
108
  inputSchema: z
108
109
  .object({
109
110
  action: z.enum(["save", "restore", "list", "remove"]),
110
111
  name: TransientName.optional().describe("save and remove, and restore without file: 1 to 64 letters, digits, dots, underscores or hyphens"),
111
- out: OutInput.optional().describe("save only: also write the snapshot to this project file, for example snapshots/room0.vsf. An existing file is overwritten. The result then also gives the file, the number of bytes and a SHA-256"),
112
- file: ProjectPath.optional().describe("restore only: a .vsf file in the project, in place of name"),
113
- project: ProjectInput.optional().describe("save with out, and restore with file: the project folder, relative to the folder where the agent started. Give it when that folder is not in a project and has projects below it"),
112
+ out: OutInput.optional().describe("save only: also write the snapshot to this file, the absolute path of a file in a project folder, for example /home/me/game/snapshots/room0.vsf. An existing file is overwritten. The result then also gives the absolute path of the file, the number of bytes and a SHA-256"),
113
+ file: FilePath.optional().describe("restore only: the absolute path of a .vsf file in a project folder, in place of name"),
114
114
  })
115
115
  .strict(),
116
116
  outputSchema: z.object({
@@ -123,7 +123,7 @@ const c64Snapshot = defineTool({
123
123
  ...WrittenOutput,
124
124
  }),
125
125
  readOnly: false,
126
- async run(input, session) {
126
+ async run(input, session, out) {
127
127
  const { action, ...fields } = input;
128
128
  if (action === "list") {
129
129
  requireFields(action, fields, []);
@@ -131,17 +131,17 @@ const c64Snapshot = defineTool({
131
131
  }
132
132
  if (action === "restore") {
133
133
  if (fields.name !== undefined && fields.file !== undefined) throw new WireFailure("invalid-input", "Action restore takes name or file, not both.");
134
- if (fields.name === undefined && fields.file === undefined) throw new WireFailure("invalid-input", "Action restore needs name (a snapshot of this session) or file (a .vsf in the project).");
134
+ if (fields.name === undefined && fields.file === undefined) throw new WireFailure("invalid-input", "Action restore needs name (a snapshot of this session) or file (the absolute path of a .vsf file).");
135
135
  }
136
136
  if (action === "restore" && fields.file !== undefined) {
137
- requireFields(action, fields, ["file", "project"], ["file"]);
138
- return session.snapshotRestore(readProjectFile(fields.file, { root: projectFolder(fields.project), what: "file" }).bytes);
137
+ requireFields(action, fields, ["file"], ["file"]);
138
+ const { file, root } = toolFile(fields.file, "read");
139
+ return session.snapshotRestore(readProjectFile(file, { root, what: "file" }).bytes);
139
140
  }
140
141
  if (action === "save") {
141
- requireOut(fields);
142
- requireFields(action, fields, ["name", "out", "project"], ["name"]);
142
+ requireFields(action, fields, ["name", "out"], ["name"]);
143
143
  const saved = await session.snapshot({ action, name: fields.name! });
144
- return fields.out === undefined ? saved : { ...saved, ...writeOut(fields.out, await session.snapshotExport(fields.name!), fields.project) };
144
+ return out === undefined ? saved : { ...saved, ...writeOut(out, await session.snapshotExport(fields.name!)) };
145
145
  }
146
146
  requireFields(action, fields, ["name"], ["name"]);
147
147
  return session.snapshot({ action, name: fields.name! });
@@ -6,10 +6,10 @@ import { z } from "zod";
6
6
  import { formatC64Address, hexByte } from "../../c64.ts";
7
7
  import { WireFailure } from "../../protocol/messages.ts";
8
8
  import { MAX_COMPARE_DIFFERENCES, MAX_COMPARE_SIZE, MAX_DISASSEMBLE, MAX_MEMORY_READ, MAX_MEMORY_WRITE, MAX_SEARCH_PATTERN, MAX_SEARCH_RESULTS, type RegisterValues } from "../../protocol/vice.ts";
9
- import { linesText, OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
9
+ import { linesText, OutInput, writeOut, WrittenOutput } from "../output.ts";
10
10
  import { AddressInput, Byte, MemoryViewInput, SpaceInput, TOOL_INPUTS } from "../inputs.ts";
11
11
  import { readMemoryInParts } from "../../host-client/vice-session.ts";
12
- import { AddressOutput, defineTool, HexData, requireFields, requireOut } from "../server.ts";
12
+ import { AddressOutput, defineTool, HexData, requireFields } from "../server.ts";
13
13
 
14
14
  /** With out, a read or a disassembly can be larger than one answer of the session: it is read in parts. */
15
15
  const MAX_MEMORY_READ_OUT = 0x10000;
@@ -23,7 +23,7 @@ const c64MemoryRead = defineTool({
23
23
  description:
24
24
  `Read 1 to ${MAX_MEMORY_READ} bytes of memory, starting at an address. ` +
25
25
  "The range must not go past $ffff. Use space drive8 to read the memory of the 1541 disk drive. " +
26
- `With out, it reads up to ${MAX_MEMORY_READ_OUT} bytes and writes them as raw bytes to that project file. The result then gives the file, the number of bytes and a SHA-256 in place of data. ` +
26
+ `With out, it reads up to ${MAX_MEMORY_READ_OUT} bytes and writes them as raw bytes to that file. The result then gives the file, the number of bytes and a SHA-256 in place of data. ` +
27
27
  "This does not change the run state of the machine.",
28
28
  inputSchema: z
29
29
  .object({
@@ -32,22 +32,20 @@ const c64MemoryRead = defineTool({
32
32
  space: SpaceInput,
33
33
  view: MemoryViewInput,
34
34
  out: OutInput.optional(),
35
- project: ProjectInput.optional(),
36
35
  })
37
36
  .strict(),
38
37
  outputSchema: z.object({ address: AddressOutput, size: z.number().int().min(1).max(MAX_MEMORY_READ_OUT), data: HexData.optional(), ...WrittenOutput }),
39
38
  readOnly: false,
40
- async run(input, session) {
41
- const { out, project, ...read } = input;
42
- requireOut(input);
43
- if (out === undefined) {
39
+ async run(input, session, file) {
40
+ const { out: _given, ...read } = input;
41
+ if (file === undefined) {
44
42
  if (read.size > MAX_MEMORY_READ) throw new WireFailure("invalid-input", `size can be at most ${MAX_MEMORY_READ} without out.`);
45
43
  const result = await session.memoryRead(read);
46
44
  return { address: formatC64Address(result.address), size: result.data.length / 2, data: result.data };
47
45
  }
48
46
  if (read.address + read.size > 0x10000) throw new WireFailure("invalid-input", "The range must not go past $ffff.");
49
47
  const bytes = await readMemoryInParts(session, read.address, read.size, read.view, read.space);
50
- return { address: formatC64Address(read.address), size: read.size, ...writeOut(out, bytes, project) };
48
+ return { address: formatC64Address(read.address), size: read.size, ...writeOut(file, bytes) };
51
49
  },
52
50
  });
53
51
 
@@ -182,7 +180,7 @@ const c64Disassemble = defineTool({
182
180
  description:
183
181
  `Disassemble count instructions (1 to ${MAX_DISASSEMBLE}) from an address, as the bytes are in the live machine now. ` +
184
182
  "Use it to read code that a program changed or unpacked at run time. It includes the undocumented opcodes. " +
185
- `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that project file. The result then gives the file in place of the instructions. A file name that ends in .json gets a JSON list of the instructions, as the result without out gives them. ` +
183
+ `With out, it disassembles up to ${MAX_DISASSEMBLE_OUT} instructions, or to $ffff, and writes them as a listing to that file. The result then gives the file in place of the instructions. A file name that ends in .json gets a JSON list of the instructions, as the result without out gives them. ` +
186
184
  "This does not change the run state of the machine.",
187
185
  inputSchema: z
188
186
  .object({
@@ -191,15 +189,13 @@ const c64Disassemble = defineTool({
191
189
  space: SpaceInput,
192
190
  view: MemoryViewInput,
193
191
  out: OutInput.optional(),
194
- project: ProjectInput.optional(),
195
192
  })
196
193
  .strict(),
197
194
  outputSchema: z.object({ instructions: z.array(z.object({ address: AddressOutput, bytes: HexData, text: z.string() })).optional(), count: z.number().int().min(0).optional(), ...WrittenOutput }),
198
195
  readOnly: false,
199
- async run(input, session) {
200
- const { out, project, ...request } = input;
201
- requireOut(input);
202
- if (out === undefined) {
196
+ async run(input, session, file) {
197
+ const { out: _given, ...request } = input;
198
+ if (file === undefined) {
203
199
  if (request.count > MAX_DISASSEMBLE) throw new WireFailure("invalid-input", `count can be at most ${MAX_DISASSEMBLE} without out.`);
204
200
  const result = await session.disassemble(request);
205
201
  return { instructions: result.instructions.map((instruction) => ({ ...instruction, address: formatC64Address(instruction.address) })) };
@@ -221,10 +217,10 @@ const c64Disassemble = defineTool({
221
217
  address = instruction.address + instruction.bytes.length / 2;
222
218
  }
223
219
  }
224
- const text = out.toLowerCase().endsWith(".json")
220
+ const text = file.file.toLowerCase().endsWith(".json")
225
221
  ? `${JSON.stringify(instructions, null, 1)}\n`
226
222
  : linesText(instructions.map((instruction) => `${instruction.address} ${spaced(instruction.bytes).padEnd(9)} ${instruction.text}`));
227
- return { count: instructions.length, ...writeOut(out, text, project) };
223
+ return { count: instructions.length, ...writeOut(file, text) };
228
224
  },
229
225
  });
230
226
 
@@ -6,9 +6,9 @@ import { z } from "zod";
6
6
  import { formatC64Address, formatSprite, formatVicii } from "../../c64.ts";
7
7
  import { WireFailure } from "../../protocol/messages.ts";
8
8
  import { CIA_SELECTIONS, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_OBSERVE_BYTES, MAX_OBSERVE_RANGES, SPACES, VICII_MODES, type ObserveParams } from "../../protocol/vice.ts";
9
- import { OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
9
+ import { OutInput, writeOut, WrittenOutput } from "../output.ts";
10
10
  import { AddressInput, Byte, MemoryViewInput, SpaceInput } from "../inputs.ts";
11
- import { AddressOutput, defineTool, HexData, requireFields, requireOut, ToolOutput, TransientName } from "../server.ts";
11
+ import { AddressOutput, defineTool, HexData, requireFields, ToolOutput, TransientName } from "../server.ts";
12
12
  import { c64Registers } from "./memory.ts";
13
13
 
14
14
  const Color = z.number().int().min(0).max(15);
@@ -130,11 +130,12 @@ const Rectangle = z
130
130
  .strict();
131
131
 
132
132
  const c64Screen = defineTool({
133
+ outActions: ["capture", "compare"],
133
134
  name: "c64_screen",
134
135
  title: "Capture and compare the C64 screen",
135
136
  description:
136
137
  "Action capture returns the last frame the C64 drew, with its borders, as a PNG image, plus its width and height in pixels. " +
137
- "With out, capture writes the PNG to that project file, and compare writes its difference image there. The result then has no image. " +
138
+ "With out, capture writes the PNG to that file, and compare writes its difference image there. The result then has no image. " +
138
139
  "With baseline, the session also keeps that frame under the name. " +
139
140
  "Action compare compares the current frame with a baseline, pixel by pixel. mask lists rectangles to ignore. " +
140
141
  "A mask that covers the whole frame is invalid input. comparedPixels is the number of pixels outside the mask. " +
@@ -151,7 +152,6 @@ const c64Screen = defineTool({
151
152
  mask: z.array(Rectangle).max(MAX_MASK_RECTANGLES).optional().describe("compare only: rectangles to ignore, in frame pixels"),
152
153
  includeDiff: z.boolean().optional().describe("compare only: also return a difference image"),
153
154
  out: OutInput.optional(),
154
- project: ProjectInput.optional().describe("capture and compare with out only: the project folder, relative to the folder where the agent started. Give it when that folder is not in a project and has projects below it"),
155
155
  })
156
156
  .strict(),
157
157
  outputSchema: z.object({
@@ -168,26 +168,24 @@ const c64Screen = defineTool({
168
168
  ...WrittenOutput,
169
169
  }),
170
170
  readOnly: false,
171
- async run(input, session) {
171
+ async run(input, session, file) {
172
172
  const { action, ...fields } = input;
173
173
  if (action === "capture") {
174
- requireOut(fields);
175
- requireFields(action, fields, ["baseline", "out", "project"]);
174
+ requireFields(action, fields, ["baseline", "out"]);
176
175
  const shot = await session.screenCapture(fields.baseline);
177
176
  const result = { width: shot.width, height: shot.height, ...(shot.baseline === undefined ? {} : { baseline: shot.baseline }) };
178
- if (fields.out !== undefined) return { ...result, ...writeOut(fields.out, Buffer.from(shot.png, "base64"), fields.project) };
177
+ if (file !== undefined) return { ...result, ...writeOut(file, Buffer.from(shot.png, "base64")) };
179
178
  return new ToolOutput(result, [{ type: "image", data: shot.png, mimeType: "image/png" }]);
180
179
  }
181
180
  if (action === "compare") {
182
- requireOut(fields);
183
- requireFields(action, fields, ["baseline", "maxMismatchRatio", "mask", "includeDiff", "out", "project"], ["baseline"]);
181
+ requireFields(action, fields, ["baseline", "maxMismatchRatio", "mask", "includeDiff", "out"], ["baseline"]);
184
182
  const { diffPng, ...result } = await session.screenCompare({
185
183
  baseline: fields.baseline!,
186
184
  maxMismatchRatio: fields.maxMismatchRatio ?? 0,
187
185
  mask: fields.mask ?? [],
188
- includeDiff: (fields.includeDiff ?? false) || fields.out !== undefined,
186
+ includeDiff: (fields.includeDiff ?? false) || file !== undefined,
189
187
  });
190
- if (fields.out !== undefined && diffPng !== undefined) return { ...result, ...writeOut(fields.out, Buffer.from(diffPng, "base64"), fields.project) };
188
+ if (file !== undefined && diffPng !== undefined) return { ...result, ...writeOut(file, Buffer.from(diffPng, "base64")) };
191
189
  return diffPng === undefined ? result : new ToolOutput(result, [{ type: "image", data: diffPng, mimeType: "image/png" }]);
192
190
  }
193
191
  if (action === "list") {
@@ -12,7 +12,7 @@ import type { SupervisedProcess } from "./processes.ts";
12
12
  import type { ToolContext } from "./run.ts";
13
13
 
14
14
  /** The command protocol that this module speaks; c64run --version and version name it. */
15
- export const C64RUN_PROTOCOL = 7;
15
+ export const C64RUN_PROTOCOL = 8;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
@@ -37,6 +37,13 @@ export function commandLimitMs(text: string): number {
37
37
  return COMMAND_MS + (Number.isFinite(target) ? (target * 1000) / SLOWEST_CYCLES_PER_SECOND : 0);
38
38
  }
39
39
 
40
+ /** The tick of an answer "ok tick=<n>". */
41
+ function tickOf(answer: string): number {
42
+ const tick = /tick=(\d+)/.exec(answer);
43
+ if (tick === null) throw new WireFailure("operation-failed", `c64run gave no tick: ${answer}`);
44
+ return Number(tick[1]);
45
+ }
46
+
40
47
  /** The machine state that most commands answer with. */
41
48
  export interface CoreStatus {
42
49
  /** CPU cycles since the opcode fetch at the reset vector. */
@@ -84,8 +91,15 @@ export function parseStatus(answer: string): CoreStatus {
84
91
  };
85
92
  }
86
93
 
94
+ /** Input that the core got: a key of the matrix (80 + its place) or RESTORE (ff), or the masks of both joysticks. */
95
+ export type CoreInput = { kind: "key"; code: number; down: boolean } | { kind: "joy"; masks: [number, number] };
96
+
97
+ /** The commands of the input, which go only through key() and joy(), so that each input reaches the input listener. */
98
+ const INPUT_COMMANDS = /^(key|joy)( |$)/;
99
+
87
100
  export class C64RunSession {
88
101
  readonly #process: SupervisedProcess;
102
+ #onInput: ((input: CoreInput, tick: number) => void) | undefined;
89
103
  readonly #waiting: Array<{ resolve: (line: string) => void; reject: (error: Error) => void }> = [];
90
104
  #stderr = "";
91
105
  #ended: WireFailure | undefined;
@@ -127,6 +141,30 @@ export class C64RunSession {
127
141
  * A core that does not answer within the limit is stopped: every command then fails.
128
142
  */
129
143
  command(text: string, limitMs = commandLimitMs(text)): Promise<string> {
144
+ if (INPUT_COMMANDS.test(text)) return Promise.reject(new WireFailure("operation-failed", `c64run ${text.split(" ")[0]}: send input with key() or joy()`));
145
+ return this.#send(text, limitMs);
146
+ }
147
+
148
+ /** The listener of each key and joystick input, with the tick of the input; undefined for none. */
149
+ onInput(listener: ((input: CoreInput, tick: number) => void) | undefined): void {
150
+ this.#onInput = listener;
151
+ }
152
+
153
+ /** A key of the matrix (80 + its place) or RESTORE (ff) down or up. Gives the tick. */
154
+ async key(code: number, down: boolean): Promise<number> {
155
+ const tick = tickOf(await this.#send(`key ${code.toString(16)} ${down ? "down" : "up"}`));
156
+ this.#onInput?.({ kind: "key", code, down }, tick);
157
+ return tick;
158
+ }
159
+
160
+ /** The masks of joystick 1 and 2. Gives the tick. */
161
+ async joy(port1: number, port2: number): Promise<number> {
162
+ const tick = tickOf(await this.#send(`joy ${port1.toString(16)} ${port2.toString(16)}`));
163
+ this.#onInput?.({ kind: "joy", masks: [port1, port2] }, tick);
164
+ return tick;
165
+ }
166
+
167
+ #send(text: string, limitMs = commandLimitMs(text)): Promise<string> {
130
168
  if (this.#ended !== undefined) return Promise.reject(this.#ended);
131
169
  const answer = new Promise<string>((resolve, reject) => {
132
170
  const timer = setTimeout(() => {
@@ -18,7 +18,7 @@ export async function analyze(
18
18
  image: Buffer,
19
19
  context: ToolContext,
20
20
  ): Promise<{ result: DecompilerResult; seeds: SeedReport }> {
21
- checkRequestBounds(params);
21
+ checkRequestBounds(params, DECOMPILER_LIMITS);
22
22
  const { start, end, body } = imageRange(params.imageKind, image);
23
23
 
24
24
  // The decoder sees only the loaded bytes; labels may name any address.
package/src/native/dxa.ts CHANGED
@@ -11,7 +11,7 @@ import { stripVTControlCharacters } from "node:util";
11
11
  import { describeError, Refusal } from "../errors.ts";
12
12
  import { hexWord, SYMBOL_NAME } from "../c64.ts";
13
13
  import { WireFailure } from "../protocol/messages.ts";
14
- import { checkDxaResult, checkRequestBounds, imageRange, seedsInside, type DxaParams, type DxaResult, type SeedReport } from "./types.ts";
14
+ import { checkDxaResult, checkRequestBounds, DXA_LIMITS, imageRange, seedsInside, type DxaParams, type DxaResult, type SeedReport } from "./types.ts";
15
15
  import { Workspace } from "./staging.ts";
16
16
  import { DXA, findTool } from "./discover.ts";
17
17
  import { outputTail, runTool, runToolOrFail, type ToolContext } from "./run.ts";
@@ -117,7 +117,7 @@ export async function analyze(
117
117
  image: Buffer,
118
118
  context: ToolContext,
119
119
  ): Promise<{ result: DxaResult; attachments: Buffer[]; seeds: SeedReport }> {
120
- checkRequestBounds(params);
120
+ checkRequestBounds(params, DXA_LIMITS);
121
121
  const executable = findTool(DXA, context.env);
122
122
  const { start, end } = imageRange(params.imageKind, image);
123
123
  const { entryPoints, dataRanges, report } = seedsInside(params, start, end);
@@ -32,6 +32,19 @@ export interface AcmeParams {
32
32
  /** A symbol from the assembly: an address inside the program, or a constant value. */
33
33
  export type AssembledSymbol = { name: string; kind: "address"; address: number; used: boolean } | { name: string; kind: "constant"; value: number; used: boolean };
34
34
 
35
+ /** The value of a symbol: the address of a label, or the value of a constant. */
36
+ export const symbolValue = (symbol: AssembledSymbol): number => (symbol.kind === "address" ? symbol.address : symbol.value);
37
+
38
+ /** The value of each symbol, by name. */
39
+ export const symbolValues = (symbols: readonly AssembledSymbol[]): Map<string, number> => new Map(symbols.map((symbol) => [symbol.name, symbolValue(symbol)]));
40
+
41
+ /** The value of a label that the script itself put into a build (`what`, for example "The assembled loader"): a label that `labels` (symbolValues) does not have is a defect of the script. */
42
+ export function requiredLabel(labels: ReadonlyMap<string, number>, name: string, what: string): number {
43
+ const value = labels.get(name);
44
+ if (value === undefined) throw new Refusal("operation-failed", `${what} has no ${name} label. This is a defect of the script.`);
45
+ return value;
46
+ }
47
+
35
48
  export interface AcmeResult {
36
49
  assembled: boolean;
37
50
  /** Present when assembled: where the program loads. The program bytes are the one attachment that assemble returns. */
@@ -44,6 +57,12 @@ const IMAGE_KINDS = ["prg", "flat64k"] as const;
44
57
  export type ImageKind = (typeof IMAGE_KINDS)[number];
45
58
 
46
59
  export const DECOMPILER_LIMITS = { entryPoints: 1024, codeStarts: 8192, dataRanges: 1024, labels: 4096, decompile: 32, decompiledChars: 16_000, decompiledTotalChars: 128_000 } as const;
60
+ /**
61
+ * DXA also gets the jump and call targets of the knowledge as entry points, so
62
+ * it takes more of them than the decompiler. dxa itself has no limit: it took a
63
+ * routine at each of the 65536 addresses in 2.2 s.
64
+ */
65
+ export const DXA_LIMITS = { ...DECOMPILER_LIMITS, entryPoints: 8192 } as const;
47
66
 
48
67
  /** The analysis. Its image is given next to these fields: a PRG, or 64 KiB from $0000. */
49
68
  export interface DecompilerParams {
@@ -85,14 +104,14 @@ export interface DecompilerResult {
85
104
  toolVersion?: string;
86
105
  }
87
106
 
88
- /** Refuses a DXA or decompiler request with more seeds or decompilations than the request bounds allow, by name. */
89
- export function checkRequestBounds(params: DxaParams & { decompile?: number[]; codeStarts?: number[] }): void {
107
+ /** Refuses a DXA or decompiler request with more seeds or decompilations than the request bounds of the analyzer allow, by name. */
108
+ export function checkRequestBounds(params: DxaParams & { decompile?: number[]; codeStarts?: number[] }, limits: typeof DECOMPILER_LIMITS | typeof DXA_LIMITS): void {
90
109
  const bounds = [
91
- ["entry points", params.entryPoints.length, DECOMPILER_LIMITS.entryPoints],
92
- ["code starts", params.codeStarts?.length ?? 0, DECOMPILER_LIMITS.codeStarts],
93
- ["data ranges", params.dataRanges.length, DECOMPILER_LIMITS.dataRanges],
94
- ["labels", params.labels.length, DECOMPILER_LIMITS.labels],
95
- ["routines to decompile", params.decompile?.length ?? 0, DECOMPILER_LIMITS.decompile],
110
+ ["entry points", params.entryPoints.length, limits.entryPoints],
111
+ ["code starts", params.codeStarts?.length ?? 0, limits.codeStarts],
112
+ ["data ranges", params.dataRanges.length, limits.dataRanges],
113
+ ["labels", params.labels.length, limits.labels],
114
+ ["routines to decompile", params.decompile?.length ?? 0, limits.decompile],
96
115
  ] as const;
97
116
  for (const [name, count, limit] of bounds) {
98
117
  if (count > limit) throw new WireFailure("invalid-input", `The request has ${count} ${name}. Give at most ${limit} ${name}.`);
@@ -51,16 +51,18 @@ export async function decodeProgram(image: ProgramImage, knowledge: Pick<CodeKno
51
51
  .flatMap((region) => image.segments.filter((segment) => rangesOverlap(region, segment)).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end) })));
52
52
  // A JSR into ROM runs the ROM: the RAM bytes of the image under it are data, not the code of the call.
53
53
  for (const range of romOf(image, knowledge, entries, coverage)) if (!dataRanges.some((data) => rangesOverlap(range, data))) dataRanges.push(range);
54
+ // The bytes that the decompiler reads: one copy of the memory with the pages of the entry state.
55
+ const analyzed = analyzedBytes(image);
54
56
  const { result } = await analyze(
55
57
  {
56
- imageKind: analyzedBytes(image).kind,
58
+ imageKind: analyzed.kind,
57
59
  entryPoints: entryPoints.slice(0, DECOMPILER_LIMITS.entryPoints),
58
60
  codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, DECOMPILER_LIMITS.codeStarts),
59
61
  dataRanges: dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges),
60
62
  labels: [],
61
63
  decompile: [],
62
64
  },
63
- analyzedBytes(image).bytes,
65
+ analyzed.bytes,
64
66
  localToolContext(),
65
67
  );
66
68
  const instructions = new Map<number, number>();