@henols/c64-re-tools 2.2.0 → 2.3.0-rc.1

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 (40) hide show
  1. package/README.md +4 -3
  2. package/package.json +1 -1
  3. package/skills/c64-assembler/SKILL.md +4 -3
  4. package/skills/c64-assembler/scripts/assembler.ts +1 -1
  5. package/skills/c64-basic/SKILL.md +3 -3
  6. package/skills/c64-development/SKILL.md +9 -9
  7. package/skills/c64-disk/SKILL.md +2 -2
  8. package/skills/c64-docs/SKILL.md +2 -2
  9. package/skills/c64-knowledge/SKILL.md +1 -1
  10. package/skills/c64-memory-map/SKILL.md +2 -2
  11. package/skills/c64-packer/SKILL.md +109 -0
  12. package/skills/c64-packer/scripts/packer.ts +113 -0
  13. package/skills/c64-provenance/SKILL.md +3 -3
  14. package/skills/c64-reverse-engineering/SKILL.md +3 -3
  15. package/skills/c64-static-analysis/SKILL.md +3 -3
  16. package/skills/c64-testing/SKILL.md +4 -4
  17. package/skills/c64-unpacker/SKILL.md +5 -5
  18. package/skills/emulator/SKILL.md +137 -0
  19. package/src/cli/main.ts +1 -1
  20. package/{skills/c64-assembler/scripts/lib → src}/compare.ts +3 -3
  21. package/src/host/main.ts +3 -1
  22. package/src/host/server.ts +7 -7
  23. package/src/host/vice/session.ts +4 -1
  24. package/src/mcp/main.ts +3 -3
  25. package/src/mcp/output.ts +4 -4
  26. package/src/mcp/server.ts +7 -2
  27. package/src/mcp/tools/debug.ts +6 -3
  28. package/src/mcp/tools/execution.ts +1 -0
  29. package/src/mcp/tools/input.ts +1 -0
  30. package/src/mcp/tools/machine.ts +1 -1
  31. package/src/mcp/tools/media.ts +4 -2
  32. package/src/native/c64run.ts +34 -4
  33. package/src/native/discover.ts +8 -0
  34. package/src/native/exomizer.ts +90 -0
  35. package/src/native/local.ts +2 -2
  36. package/src/native/processes.ts +20 -3
  37. package/src/native/status.ts +3 -2
  38. package/tools/install-container.sh +2 -1
  39. package/tools/install-exomizer.sh +70 -0
  40. package/skills/c64-emulator/SKILL.md +0 -160
@@ -99,12 +99,12 @@ The scripts refuse a step in the form of version 2.0, for example `{ "runUntil":
99
99
  2. Run `trace`. It gives the evidence from the run. `writtenThenExecuted` lists the ranges that the program wrote and then executed. Read `packing`:
100
100
  - `likely`: the program wrote code and then executed it. It unpacked, decrypted or moved code. `runningRange` is the written code that runs at the end of the trace. When the trace ends in ROM code, for example in an interrupt, it is the written code that runs next. Its `start` is code that runs after the unpacking. It is not always the entry point of the program. When no written code runs in 50 more frames, the result has no `runningRange` and no `suggestedUntil`.
101
101
  - `unclear`: the program executed a small quantity of code that it wrote. This can be code that changes itself.
102
- - `unlikely`: the program executed no code that it wrote. If the program waits for a key or a joystick, it can move code after that input. Then use the c64-emulator skill.
102
+ - `unlikely`: the program executed no code that it wrote. If the program waits for a key or a joystick, it can move code after that input. Then use the emulator skill.
103
103
  3. Find the address where the unpacked program starts:
104
104
  - Run `stages`. The `entry` of the last stage is usually the start of the program. A routine that a stage writes and calls is part of that stage when it returns to the stage.
105
105
  - Or use `runningRange.start` from `trace`, or `suggestedUntil`. The CPU gets to `suggestedUntil` after the unpacking.
106
- - Or use the c64-emulator skill: set a breakpoint after the unpack loop, or look at the last JMP of the unpacker.
107
- - Disassemble the code at the address with the c64-emulator skill. Make sure that it is the start of the program. The start of a program often sets the stack pointer, the interrupts and the vectors.
106
+ - Or use the emulator skill: set a breakpoint after the unpack loop, or look at the last JMP of the unpacker.
107
+ - Disassemble the code at the address with the emulator skill. Make sure that it is the start of the program. The start of a program often sets the stack pointer, the interrupts and the vectors.
108
108
  - A program can be relocated and not packed. Then a short copier moves the code and jumps to it. The moved code is the last stage. Make sure that the `entry` of the last stage is not code that the program writes later. An example is a routine that the program makes at run time. Disassemble the entry to make sure.
109
109
  4. Run `capture` with that address and a directory in `--out`. Give the same `--steps` as before. The directory gets:
110
110
  - `image.bin`: all 64 KiB of RAM at the entry.
@@ -162,7 +162,7 @@ For `loads`: `captures`, with the name, the PC, the segments, `differsFromReset`
162
162
 
163
163
  - `traced: false` or `followed: false`: the emulator did not load the program into memory in the time limit. The reason gives the load address. Make sure that the file is a PRG that the C64 can load.
164
164
  - `traced: false` or `followed: false` with `stopReason`: the CPU stopped before the frames ran, for example at a JAM instruction. `pc` gives the address. Make sure that `--entry` is the start of the code that the file holds at that time, and that the steps are correct.
165
- - `captured: false`: the program did not get to the address in the time limit. The reason tells where it stopped. Find a better address with the c64-emulator skill, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
165
+ - `captured: false`: the program did not get to the address in the time limit. The reason tells where it stopped. Find a better address with the emulator skill, or give more frames. If it stopped in a key wait, give `--steps` with a `type` step.
166
166
  - A step did not reach its target: the reason names the step. Change the step or give it more frames.
167
167
  - `loaded: false` with an empty `captures` and the reason `BASIC ran no program line`: the PRG has no BASIC start line. Use `capture` with `--entry`.
168
168
  - `loaded: false` and no capture has a segment: the program did not load a part, or it did not start. `keyWait: true` on a capture tells that the C64 waited for a key at the READY prompt or at an INPUT statement. For a tape image, read `emulatorFlaw`. A known VICE flaw can stop a tape load. Tell the user to install the latest VICE.
@@ -174,4 +174,4 @@ For `loads`: `captures`, with the name, the PC, the segments, `differsFromReset`
174
174
  ## Handoffs
175
175
 
176
176
  - Unpacked machine code → c64-static-analysis
177
- - Find the start address at run time → c64-emulator
177
+ - Find the start address at run time → emulator
@@ -0,0 +1,137 @@
1
+ ---
2
+ name: emulator
3
+ description: Use this skill to operate and debug the live emulator through the MCP tools of the c64-re-tools machine server. For the C64, the tool names start with c64_. It loads programs and disks, controls and steps the CPU, and sets breakpoints and watchpoints. It reads and writes memory and registers, gives keyboard and joystick input, advances frames and captures the screen. Do not use it for static analysis, project knowledge, assembly or disk inspection.
4
+ ---
5
+
6
+ # emulator
7
+
8
+ ## Purpose
9
+
10
+ Operate and debug the one live machine that belongs to this MCP session. Get runtime evidence and runtime state from it.
11
+
12
+ This skill does not analyse code statically. It does not write project knowledge. It does not assemble source code.
13
+
14
+ The MCP server knows the machine and the emulator. Its instructions, its tool descriptions, its result fields and its error messages give the facts of the machine and the known flaws of the emulator. This skill tells how to use the tools for a task. If this skill and a tool description do not agree, obey the tool description.
15
+
16
+ ## Inputs
17
+
18
+ - The machine action or the runtime question.
19
+ - The target address, state or condition, when the question needs one.
20
+ - The project path of the program or disk to load, when the question needs one.
21
+
22
+ A tool takes addresses, not names. The server instructions give the address format. Get the address of a name with `knowledge.ts at <name>` of the c64-knowledge skill.
23
+
24
+ ## Tools / execution path
25
+
26
+ Use only the MCP tools. Each MCP session has its own machine. Nothing else can change that machine.
27
+
28
+ | Need | C64 tool |
29
+ |---|---|
30
+ | Run state, warp mode, window, version of the MCP server | `c64_status` |
31
+ | Reset, power cycle | `c64_reset` |
32
+ | Fast emulation | `c64_warp` |
33
+ | Show the machine to the user in a window, hide it again | `c64_window` |
34
+ | Stop, start, step, step over, step out, exact frames | `c64_execution` |
35
+ | Run until an address, a memory value or a raster position | `c64_run_until` |
36
+ | Run to a place and read the machine there in one call | `c64_run_until` with `observe` and `history` |
37
+ | Each access or routine entry over many frames | `c64_trace` |
38
+ | Stop on an instruction address, stop on a memory access | `c64_breakpoint`, `c64_watchpoint` |
39
+ | Memory | `c64_memory_read`, `c64_memory_write`, `c64_memory_search`, `c64_memory_compare` |
40
+ | CPU registers | `c64_registers` |
41
+ | Code as it is in memory now | `c64_disassemble` |
42
+ | Executed instructions, call chain | `c64_cpu_history`, `c64_backtrace` |
43
+ | Cycles of each routine, memory use, cycles between two points | `c64_profile`, `c64_memmap`, `c64_timing` |
44
+ | Chips of the machine | `c64_vicii`, `c64_sprite`, `c64_cia`, `c64_sid` |
45
+ | Screen image, screen compare | `c64_screen` |
46
+ | Several of these from one moment | `c64_observe` |
47
+ | Keyboard, joystick | `c64_keyboard`, `c64_joystick` |
48
+ | Program and disk media | `c64_autostart`, `c64_program_load`, `c64_disk_attach` |
49
+ | Machine state to go back to, also in a later session | `c64_snapshot` |
50
+
51
+ Read the description of a tool before you use it for the first time. It gives the limits of the tool and the facts of the machine that change the result.
52
+
53
+ A result field `emulatorFlaw` names a known flaw of the emulator. Tell the user about the flaw. Do not use a result that the flaw can make wrong as a fact.
54
+
55
+ For a large result, give `out`. Write a file that is only for your work in `.c64-re-tools/local/` of the project. Git ignores that folder. When a tool needs `project`, give the same folder as the `--project` of the skill scripts.
56
+
57
+ To keep a coverage run:
58
+
59
+ 1. Clear the memory map with `c64_memmap` action `clear`.
60
+ 2. Run the part of the program that you want to keep.
61
+ 3. Read the map with `c64_memmap` action `read` and `out`, for example to `.c64-re-tools/local/attract.bin`.
62
+ 4. Add the file to the knowledge with `coverage` of the c64-knowledge skill.
63
+
64
+ ## Workflow
65
+
66
+ 1. Read the project knowledge for the addresses in the question. Use the c64-knowledge skill.
67
+ 2. Get the machine state with `c64_status`.
68
+ 3. Load the subject if it is not loaded. Use `c64_autostart` to start it as a user does. Use `c64_program_load` to put a program in memory with no start.
69
+ 4. Set the stop condition. Use a breakpoint, a watchpoint or a `c64_run_until` target. Add a condition when the stop must occur only in one state.
70
+ 5. Run, step or give input. Prefer `c64_run_until` and `advance-frames` to waits. They stop at the same emulated time on every run.
71
+ 6. Read only the state that answers the question. To read several things from one moment, use `c64_observe`.
72
+ 7. Interpret the evidence. Keep the observed facts apart from your conclusions.
73
+
74
+ Before a risky experiment, save the state with `c64_snapshot`. Restore it to try again from the same point.
75
+
76
+ ### Input that the tools cannot give
77
+
78
+ Some programs read input in a way that the input tools cannot give. The tool description tells when. Then use one of these ways:
79
+
80
+ - Open the window and ask the user to give the input.
81
+ - Record a session with a `press` step. Use `testing.ts record` of the c64-testing skill.
82
+
83
+ Do not change the program to make it accept the input.
84
+
85
+ ### The window
86
+
87
+ The emulator has no window. When the user must type, play or look at the machine, do these steps:
88
+
89
+ 1. Open the window with `c64_window` action `open`.
90
+ 2. Tell the user that the window is open and what to do in it.
91
+ 3. Wait until the user tells you that they finished.
92
+ 4. Close the window with `c64_window` action `close`.
93
+
94
+ The result field `notCarried` names the data that the move cleared.
95
+
96
+ ## Knowledge
97
+
98
+ Read:
99
+ - the current knowledge for each address and range that the question touches.
100
+
101
+ Automatic write:
102
+ - none.
103
+
104
+ Write after interpretation:
105
+ - a symbol, a region or a comment that the runtime evidence justifies. Record it with the c64-knowledge skill.
106
+
107
+ Do not store:
108
+ - breakpoints or watchpoints
109
+ - memory reads
110
+ - temporary machine state
111
+ - a screen capture, unless the user asks for it as an artifact
112
+
113
+ ## Result
114
+
115
+ The result is the runtime state or evidence that the question asks for.
116
+
117
+ If you cannot get the machine into the necessary state, say which state you could not get. Say what you tried.
118
+
119
+ ## Failure and conflicts
120
+
121
+ An error is `{"error": {"code": "...", "message": "..."}}`. The message tells what is wrong and what to do. Obey the message. These rules also apply:
122
+
123
+ - `installation-incomplete`, or `machine-unavailable` with a message that the host runtime does not run: stop the task. Give the message to the user and wait for the user. Do not make a replacement for the tool or the host runtime, for example your own disk parser, disassembler or emulator script. Do not try to repair the installation.
124
+ - `machine-unavailable` with a message that names a pause or a dialog in the window: do not send more operations. Give the message to the user. When the user tells you that the emulator runs again, do the operation again.
125
+ - `machine-unavailable` for a different cause: wait a few seconds. Then do the operation again one time. If you get the same error again, stop the task. Tell the user to restart the c64-re-tools MCP server, and wait for the user.
126
+ - `machine-state-lost`: do not use results from before the error. Do what the message tells. Then read the machine state again.
127
+ - `stopReason` `timeout` or `jam`: this is evidence too. Report it. For `jam`, report the address.
128
+ - A different code: the message names the cause. Change the call, or report the cause.
129
+
130
+ If the runtime evidence does not agree with the current knowledge, do not change the knowledge. Report the conflict and hand it to c64-knowledge.
131
+
132
+ ## Handoffs
133
+
134
+ - Static explanation of code → c64-static-analysis
135
+ - Durable conclusion or a knowledge conflict → c64-knowledge
136
+ - Comparison or assertion between runs → c64-testing
137
+ - Meaning of a C64 address or register → c64-memory-map
package/src/cli/main.ts CHANGED
@@ -36,7 +36,7 @@ project folder below the root uses that install; a project is a folder with
36
36
  through npx. The Host Runtime runs on the machine with VICE: start it there
37
37
  with npx -y --package=${PACKAGE.name}@${PACKAGE.tag} c64-re-tools-host.
38
38
  It runs VICE and the tools that come with it (c1541, petcat). The skill
39
- scripts run ACME, DXA, Ghidra and c64run in the dev container.`;
39
+ scripts run ACME, DXA, Exomizer, Ghidra and c64run in the dev container.`;
40
40
 
41
41
  const here = dirname(fileURLToPath(import.meta.url));
42
42
 
@@ -1,7 +1,7 @@
1
- // The byte check of a build: the assembled program against the program
2
- // in the knowledge, segment by segment.
1
+ // The byte check of a program: a PRG against a reference program, for example
2
+ // the program in the knowledge, segment by segment.
3
3
 
4
- import { formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
4
+ import { formatC64Address, formatC64Byte, prgRange } from "./c64.ts";
5
5
 
6
6
  export interface SegmentCheck {
7
7
  start: string;
package/src/host/main.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env tsx
2
2
 
3
+ import { constants } from "node:os";
3
4
  import { parseArgs } from "node:util";
4
5
 
5
6
  import { DEFAULT_HOST_PORT } from "../protocol/messages.ts";
@@ -138,7 +139,8 @@ async function main(): Promise<number> {
138
139
  process.stdout.write(`c64-re-tools-host listening on ${address}\n`);
139
140
  trace().event("host.listening", { addresses: [address] });
140
141
 
141
- trace().event("host.stop", { signal: await stopSignal(log) });
142
+ // A second signal exits at once: the exit guard SIGKILLs every group that is still running.
143
+ trace().event("host.stop", { signal: await stopSignal(log, (signal) => process.exit(128 + constants.signals[signal])) });
142
144
  await server.close();
143
145
  await supervisor.stopAll();
144
146
  return 0;
@@ -308,24 +308,24 @@ export function parsePort(text: string): number | undefined {
308
308
  }
309
309
 
310
310
  /**
311
- * Resolves with the first SIGINT or SIGTERM. The handlers stay: a later
312
- * signal is logged and ignored, so a second Ctrl+C cannot cut the shutdown
313
- * short before every emulator and tool is stopped.
311
+ * Resolves with the first SIGINT, SIGTERM or SIGHUP. The handlers stay: a
312
+ * later signal is logged and calls again, which stops the host at once
313
+ * instead of waiting for the graceful stop of each emulator and tool.
314
314
  */
315
- export function stopSignal(log: (line: string) => void): Promise<NodeJS.Signals> {
315
+ export function stopSignal(log: (line: string) => void, again: (signal: NodeJS.Signals) => void): Promise<NodeJS.Signals> {
316
316
  return new Promise((resolve) => {
317
317
  let stopping = false;
318
318
  const stop = (signal: NodeJS.Signals) => {
319
319
  if (stopping) {
320
- log(`received ${signal} again; the host is already stopping`);
320
+ log(`received ${signal} again; stopping at once`);
321
+ again(signal);
321
322
  return;
322
323
  }
323
324
  stopping = true;
324
325
  log(`received ${signal}, stopping`);
325
326
  resolve(signal);
326
327
  };
327
- process.on("SIGINT", stop);
328
- process.on("SIGTERM", stop);
328
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, stop);
329
329
  });
330
330
  }
331
331
 
@@ -288,7 +288,9 @@ export class ViceSession implements ViceSessionHandle {
288
288
  /**
289
289
  * A VICE ended or dropped its monitor without the session asking. A window
290
290
  * VICE goes back headless from the state of when the window opened;
291
- * any other loss is final.
291
+ * any other loss is final, and the lost VICE is stopped at once: a VICE
292
+ * that hangs without its monitor ends, and its group and scratch directory
293
+ * do not wait for the session to close.
292
294
  */
293
295
  #ended(vice: ViceProcess, why: string): void {
294
296
  if (this.#closed || this.#vice !== vice || this.#lost || this.#windowClosing) return;
@@ -302,6 +304,7 @@ export class ViceSession implements ViceSessionHandle {
302
304
  return;
303
305
  }
304
306
  this.#lost = true;
307
+ void vice.stop().catch((error: unknown) => this.#log(`stopping the lost VICE failed: ${error instanceof Error ? error.message : String(error)}`));
305
308
  }
306
309
 
307
310
  /** Restarts headless from the handover saved when the window opened. */
package/src/mcp/main.ts CHANGED
@@ -123,10 +123,10 @@ async function main(): Promise<void> {
123
123
  process.exit(0);
124
124
  };
125
125
  // The harness ends the server by closing stdin or by a signal; both end the session and its emulator.
126
+ // Only the client holds the writing end of stdin: its end, close or error means that the client is gone.
126
127
  server.onclose = () => void stop();
127
- process.stdin.once("end", () => void stop());
128
- process.once("SIGINT", () => void stop());
129
- process.once("SIGTERM", () => void stop());
128
+ for (const event of ["end", "close", "error"] as const) process.stdin.once(event, () => void stop());
129
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.once(signal, () => void stop());
130
130
 
131
131
  await server.connect(new StdioServerTransport());
132
132
  }
package/src/mcp/output.ts CHANGED
@@ -7,7 +7,7 @@ import { z } from "zod";
7
7
 
8
8
  import { projectFolder, writeReported, type Written } from "../host-client/transfer.ts";
9
9
 
10
- export const OutInput = z.string().min(1).describe("write the data to this file, relative to the project folder. An existing file is overwritten. The tool description tells what the result then gives");
10
+ export const OutInput = z.string().min(1).describe("write the data to this file, relative to the project folder. An existing file is overwritten. The result then gives the file (out), the number of bytes (bytes) and a SHA-256 (sha256) in place of the data");
11
11
 
12
12
  /** The project of a tool with a path. */
13
13
  export const ProjectInput = z
@@ -17,9 +17,9 @@ export const ProjectInput = z
17
17
 
18
18
  /** The fields of a result with out, optional in an output schema that also has the inline form. */
19
19
  export const WrittenOutput = {
20
- out: z.string().optional(),
21
- bytes: z.number().int().min(0).optional(),
22
- sha256: z.string().regex(/^[0-9a-f]{64}$/).optional(),
20
+ out: z.string().optional().describe("with out: the file that the tool wrote"),
21
+ bytes: z.number().int().min(0).optional().describe("with out: the number of bytes in the file"),
22
+ sha256: z.string().regex(/^[0-9a-f]{64}$/).optional().describe("with out: the SHA-256 of the file"),
23
23
  };
24
24
 
25
25
  /** Lines as file text: each line ends with a newline, and no lines give an empty file. */
package/src/mcp/server.ts CHANGED
@@ -274,10 +274,15 @@ function packageVersion(): string {
274
274
  const INSTRUCTIONS =
275
275
  "These tools control one live Commodore 64 emulator that belongs to this session. " +
276
276
  "An address is a dollar sign and 1 to 4 hex digits, for example $c000 or $fb. A result gives four hex digits. " +
277
- "An error is {\"error\": {\"code\", \"message\"}}. " +
277
+ "An error is {\"error\": {\"code\", \"message\"}}. The message tells what is wrong and what to do. " +
278
278
  "Memory data is lowercase hex without separators. " +
279
279
  "Other register values and chip values are decimal numbers. " +
280
- "A read does not change the run state of the machine.";
280
+ "A read does not change the run state of the machine. " +
281
+ "Space c64 is the computer. Space drive8 is the CPU of the 1541 disk drive. " +
282
+ "Memory view cpu gives what the CPU sees now, with ROM and I/O where the memory configuration puts them. Memory view ram gives the RAM under them. " +
283
+ "A write to memory or registers needs a stopped CPU: stop it with c64_execution action pause. " +
284
+ "Paths are relative to the project folder, the folder that holds .c64-re-tools/. " +
285
+ "With out, a tool writes a large result to a project file in place of the result.";
281
286
 
282
287
  export function createMcpServer(options: { tools: readonly ToolDefinition[]; session: SessionSource; log?: (line: string) => void }): Server {
283
288
  const tools = new Map(options.tools.map((tool) => [tool.name, tool]));
@@ -44,7 +44,8 @@ export const c64Breakpoint = defineTool({
44
44
  "Action add sets one at address in space c64 or drive8. With a condition, it stops only when the condition is true. " +
45
45
  "add returns the new id. Breakpoints and watchpoints take their ids from one counter, so the ids of one kind can have gaps. " +
46
46
  "Actions remove, enable and disable take that id. remove returns removed true and the id. Action list gives all breakpoints. Each breakpoint shows its condition, when it has one. " +
47
- "Breakpoints stay through a reset.",
47
+ "Breakpoints stay through a reset. " +
48
+ "In space drive8, the drive can execute a few more instructions before it stops. pc in the stop result is the drive address where it stopped.",
48
49
  inputSchema: z
49
50
  .object({
50
51
  action: z.enum(CHECKPOINT_ACTIONS),
@@ -87,7 +88,8 @@ export const c64Watchpoint = defineTool({
87
88
  `Action add sets one from start to end (at most ${MAX_WATCH_SIZE} bytes, end defaults to start), with access read, write or read-write. ` +
88
89
  "With a condition, it stops only when the condition is true. For a write, a memory condition sees the memory after the write. " +
89
90
  "add returns the new id. Breakpoints and watchpoints take their ids from one counter, so the ids of one kind can have gaps. " +
90
- "Actions remove, enable and disable take that id. remove returns removed true and the id. Action list gives all watchpoints. Each watchpoint shows its condition, when it has one.",
91
+ "Actions remove, enable and disable take that id. remove returns removed true and the id. Action list gives all watchpoints. Each watchpoint shows its condition, when it has one. " +
92
+ "In space drive8, the drive can execute a few more instructions before it stops. pc in the stop result is the drive address where it stopped.",
91
93
  inputSchema: z
92
94
  .object({
93
95
  action: z.enum(CHECKPOINT_ACTIONS),
@@ -139,6 +141,7 @@ export const c64CpuHistory = defineTool({
139
141
  "Each entry gives the address, the bytes, the instruction and the registers a, x, y and sp before the instruction executed. " +
140
142
  "In space c64, it also gives the raster line and cycle when the instruction started. " +
141
143
  "With out, it writes the entries as text lines to that project file, and the result gives the file in place of the entries. " +
144
+ "After a JAM, the emulator records no history until the next reset. If the CPU ran again after a snapshot restore, this tool refuses. Then use c64_reset, or use c64_trace. " +
142
145
  "This does not change the run state of the machine.",
143
146
  inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_HISTORY).default(50), space: SpaceInput, out: OutInput.optional(), project: ProjectInput.optional() }).strict(),
144
147
  outputSchema: z.object({
@@ -349,7 +352,7 @@ export const c64Memmap = defineTool({
349
352
  start: AddressInput.optional().describe("read and summary. Default $0000"),
350
353
  end: AddressInput.optional().describe("read and summary. Default $ffff"),
351
354
  maxRanges: z.number().int().min(1).max(MAX_MEMMAP_RANGES).optional().describe("read without out only. Default 256"),
352
- out: OutInput.optional().describe("read only: write a coverage map to this project file, one byte for each address. An existing file is overwritten"),
355
+ out: OutInput.optional().describe("read only: write a coverage map to this project file, one byte for each address. An existing file is overwritten. The result then gives the file, the number of bytes and a SHA-256"),
353
356
  project: ProjectInput.optional().describe("read 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"),
354
357
  })
355
358
  .strict(),
@@ -75,6 +75,7 @@ export const c64RunUntil = defineTool({
75
75
  "reached tells if the target occurred. stopReason tells why the CPU stopped: target, breakpoint, watchpoint, jam (a JAM opcode) or timeout. " +
76
76
  "pointId gives the id of the breakpoint or watchpoint that stopped the CPU. " +
77
77
  "space tells which CPU stopped: c64, or drive8 for a stop in the disk drive. pc is the address in that space. " +
78
+ "The drive can execute a few more instructions before it stops. " +
78
79
  "With observe, the result also gives what c64_observe gives at the stop, in observed. " +
79
80
  `With history (1 to ${MAX_HISTORY}), it also gives the last instructions before the stop, as c64_cpu_history gives them. ` +
80
81
  "Thus one call runs to a place and reads the machine there. " +
@@ -18,6 +18,7 @@ export const c64Keyboard = defineTool({
18
18
  "No tool presses one key of the keyboard matrix. For one specific key, ask the user to press it in the window, or give a press step in a record file of c64-testing. " +
19
19
  'Mode text types text, for example "RUN\\n". Letters of either case type the normal (unshifted) key. A line break types RETURN. ' +
20
20
  "Mode petscii types PETSCII codes 1 to 255 in bytes, for example [147] to clear the screen. " +
21
+ "While c64_autostart loads a program, this tool refuses keys: see c64_autostart. " +
21
22
  "This does not change the run state of the machine. emulatorFlaw in the result names a known flaw of the emulator version that affects input, and the version that fixes it.",
22
23
  inputSchema: TOOL_INPUTS.keyboard,
23
24
  outputSchema: z.object({ queuedBytes: z.number().int().min(1).max(MAX_KEYBOARD_BYTES), emulatorFlaw: EMULATOR_FLAW }),
@@ -76,7 +76,7 @@ export const c64Reset = defineTool({
76
76
  description:
77
77
  "Reset the C64. Mode soft is the reset button. Mode hard is a power cycle that also resets the disk drive. " +
78
78
  "With run false (the default), the CPU stops at the first instruction of the reset routine, and the result gives that program counter (pc). " +
79
- "With run true, the C64 starts normally. Breakpoints and watchpoints stay.",
79
+ "With run true, the C64 starts normally. Breakpoints and watchpoints stay. The c64_timing stopwatch starts again from zero.",
80
80
  inputSchema: z
81
81
  .object({
82
82
  mode: z.enum(RESET_MODES).describe("soft is the reset button. hard is a power cycle"),
@@ -29,7 +29,9 @@ export const c64Autostart = defineTool({
29
29
  "Both joysticks are centred first: joystick port 1 uses the keyboard lines, and a held direction changes the RUN that the autostart types. " +
30
30
  "Without index, a disk image loads like LOAD\"*\",8,1. index selects one directory entry by its number in the c64-disk directory list (0 is the first entry). " +
31
31
  "The tool refuses an index of a DEL entry, or an index after the last entry. " +
32
- "The machine runs when this tool returns, and the load continues.",
32
+ "The machine runs when this tool returns, and the load continues. The emulator keeps warp mode on until it types RUN. " +
33
+ "A key in that time stops the autostart, so c64_keyboard refuses keys until then. Run frames with c64_execution advance-frames until c64_status gives warp false. " +
34
+ "The c64_timing stopwatch starts again from zero.",
33
35
  inputSchema: z
34
36
  .object({
35
37
  path: ProjectPath,
@@ -107,7 +109,7 @@ export const c64Snapshot = defineTool({
107
109
  .object({
108
110
  action: z.enum(["save", "restore", "list", "remove"]),
109
111
  name: TransientName.optional().describe("save and remove, and restore without file: 1 to 64 letters, digits, dots, underscores or hyphens"),
110
- out: OutInput.optional().describe("save only: also write the snapshot to this project file, for example snapshots/room0.vsf. An existing file is overwritten"),
112
+ 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"),
111
113
  file: ProjectPath.optional().describe("restore only: a .vsf file in the project, in place of name"),
112
114
  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"),
113
115
  })
@@ -18,6 +18,21 @@ export const C64RUN_PROTOCOL = 2;
18
18
  export const PAL_FRAME_CYCLES = 19_656;
19
19
 
20
20
  const STOP_MS = 5_000;
21
+ /** How long c64run may take to answer a command, beyond the run up to a target tick. */
22
+ const COMMAND_MS = 30_000;
23
+ /** The slowest run that a command limit allows for: c64run runs about 6 million cycles per second. */
24
+ const SLOWEST_CYCLES_PER_SECOND = 1_000_000;
25
+
26
+ /**
27
+ * The time limit of a command, so that a core that hangs cannot keep the
28
+ * script running. run, run-pc and run-reads end with the absolute tick that
29
+ * they run to at most; the others answer at once.
30
+ */
31
+ export function commandLimitMs(text: string): number {
32
+ const [name, ...rest] = text.split(" ");
33
+ const target = name === "run" || name === "run-pc" || name === "run-reads" ? Number(rest.at(-1)) : 0;
34
+ return COMMAND_MS + (Number.isFinite(target) ? (target * 1000) / SLOWEST_CYCLES_PER_SECOND : 0);
35
+ }
21
36
 
22
37
  /** The machine state that most commands answer with. */
23
38
  export interface CoreStatus {
@@ -82,7 +97,8 @@ export class C64RunSession {
82
97
  createInterface({ input: child.stdout! }).on("line", (line) => this.#waiting.shift()?.resolve(line));
83
98
  void process.exited.then((status) => {
84
99
  const how = status.spawnError !== undefined ? `did not start (${status.spawnError})` : `ended (exit ${status.code ?? status.signal})`;
85
- this.#ended = new WireFailure(status.spawnError !== undefined ? "installation-incomplete" : "operation-failed", `c64run ${how}.${this.#stderr === "" ? "" : ` ${this.#stderr.trim()}`}`);
100
+ // A core stopped because it did not answer keeps that reason.
101
+ this.#ended ??= new WireFailure(status.spawnError !== undefined ? "installation-incomplete" : "operation-failed", `c64run ${how}.${this.#stderr === "" ? "" : ` ${this.#stderr.trim()}`}`);
86
102
  for (const waiting of this.#waiting.splice(0)) waiting.reject(this.#ended);
87
103
  });
88
104
  }
@@ -103,10 +119,24 @@ export class C64RunSession {
103
119
  return session;
104
120
  }
105
121
 
106
- /** Sends one command and gives its "ok ..." answer. An "err ..." answer throws operation-failed. */
107
- command(text: string): Promise<string> {
122
+ /**
123
+ * Sends one command and gives its "ok ..." answer. An "err ..." answer throws operation-failed.
124
+ * A core that does not answer within the limit is stopped: every command then fails.
125
+ */
126
+ command(text: string, limitMs = commandLimitMs(text)): Promise<string> {
108
127
  if (this.#ended !== undefined) return Promise.reject(this.#ended);
109
- const answer = new Promise<string>((resolve, reject) => this.#waiting.push({ resolve, reject }));
128
+ const answer = new Promise<string>((resolve, reject) => {
129
+ const timer = setTimeout(() => {
130
+ this.#ended = new WireFailure("operation-failed", `c64run ${text.split(" ")[0]} did not answer in ${Math.ceil(limitMs / 1000)} s; the core is stopped.`);
131
+ for (const waiting of this.#waiting.splice(0)) waiting.reject(this.#ended);
132
+ void this.#process.stop().catch(() => {});
133
+ }, limitMs);
134
+ const done = () => clearTimeout(timer);
135
+ this.#waiting.push({
136
+ resolve: (line) => (done(), resolve(line)),
137
+ reject: (error) => (done(), reject(error)),
138
+ });
139
+ });
110
140
  this.#process.child.stdin!.write(`${text}\n`);
111
141
  return answer.then((line) => {
112
142
  if (line.startsWith("ok")) return line;
@@ -55,6 +55,14 @@ export const DXA: ToolSpec = {
55
55
  remedy: INSTALL_STEPS,
56
56
  };
57
57
 
58
+ export const EXOMIZER: ToolSpec = {
59
+ name: "Exomizer",
60
+ envVar: "C64RT_EXOMIZER",
61
+ binaries: ["exomizer"],
62
+ where: "on this machine",
63
+ remedy: INSTALL_STEPS,
64
+ };
65
+
58
66
  export const C64RUN: ToolSpec = {
59
67
  name: "c64run",
60
68
  envVar: "C64RT_C64RUN",
@@ -0,0 +1,90 @@
1
+ // The Exomizer adapter: packs PRG files into one C64 program that unpacks
2
+ // itself (exomizer sfx), then unpacks that program again in the 6502
3
+ // emulator of Exomizer (exomizer desfx), so the caller can check the bytes
4
+ // and the entry of the result before anyone runs it.
5
+
6
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+
9
+ import { formatC64Address } from "../c64.ts";
10
+ import { WireFailure } from "../protocol/messages.ts";
11
+ import { EXOMIZER, findTool } from "./discover.ts";
12
+ import { outputTail, runToolOrFail, type ToolContext } from "./run.ts";
13
+ import { Workspace } from "./staging.ts";
14
+
15
+ /** A full 64 KiB program with all optimization passes can take minutes. */
16
+ const TIMEOUT_MS = 600_000;
17
+ const PACKED = "packed.prg";
18
+ const UNPACKED = "unpacked.prg";
19
+
20
+ /** The unpacker of Exomizer runs below $0400; the emulator of desfx stops when the program counter leaves that area. */
21
+ export const MIN_ENTRY = 0x0400;
22
+
23
+ export interface PackParams {
24
+ /** The PRG files in load order: where two overlap, the later one wins. */
25
+ programs: readonly Uint8Array[];
26
+ /** Where the unpacked program starts, at MIN_ENTRY or above. */
27
+ entry: number;
28
+ /** The value of $01 when the program starts, $34 to $37. Without it, the value at the start of the packed program ($37). */
29
+ exitMemory?: number;
30
+ }
31
+
32
+ export interface Packed {
33
+ /** The packed PRG: a BASIC SYS line at $0801 with the unpacker, then the packed data. */
34
+ program: Buffer;
35
+ /** What the emulator of Exomizer unpacked: a PRG of the largest range that the unpacker wrote. */
36
+ unpacked: Buffer;
37
+ /** Where the unpacker jumped when it was done. */
38
+ entry: number;
39
+ /** The CPU cycles of the unpacking, when Exomizer gives them. */
40
+ cycles?: number;
41
+ }
42
+
43
+ /** The argv of the pack: the entry comes first, then the options, then the input files in load order. */
44
+ export function sfxArguments(executable: string, params: Omit<PackParams, "programs">, inputs: readonly string[], output: string): string[] {
45
+ const argv = [executable, "sfx", String(params.entry), "-t64", "-n", "-o", output];
46
+ if (params.exitMemory !== undefined) argv.push(`-Di_ram_exit=${params.exitMemory}`);
47
+ argv.push(...inputs);
48
+ return argv;
49
+ }
50
+
51
+ /** The entry and the cycles in the output of desfx: ' Decrunch took 1.234567 Mcycles, ...' and ' Writing "x" as prg, saving from $0801 to $9000, entry at $0810.' */
52
+ export function parseDesfx(output: string): { entry: number; cycles?: number } | undefined {
53
+ const entry = /entry at \$([0-9a-fA-F]{4})\./.exec(output)?.[1];
54
+ if (entry === undefined) return undefined;
55
+ const mcycles = /Decrunch took ([0-9.]+) Mcycles/.exec(output)?.[1];
56
+ return { entry: Number.parseInt(entry, 16), ...(mcycles === undefined ? {} : { cycles: Math.round(Number(mcycles) * 1_000_000) }) };
57
+ }
58
+
59
+ /** Lines of Exomizer output that tell why it stopped. */
60
+ const PROBLEM = /error|warning|can't|cannot|overlap/i;
61
+
62
+ export async function pack(params: PackParams, context: ToolContext): Promise<Packed> {
63
+ if (params.programs.length === 0) throw new WireFailure("invalid-input", "Give at least one PRG to pack.");
64
+ if (params.entry < MIN_ENTRY) throw new WireFailure("invalid-input", `The entry ${formatC64Address(params.entry)} is below $0400. The unpacker of Exomizer runs there. Give an entry at $0400 or above.`);
65
+ const executable = findTool(EXOMIZER, context.env);
66
+ const workspace = Workspace.create(context.supervisor);
67
+ try {
68
+ // Plain names: Exomizer reads "name,address" as a file with a new load address.
69
+ const input = workspace.directory("in");
70
+ const inputs = params.programs.map((program, index) => {
71
+ const path = join(input, `${index}.prg`);
72
+ writeFileSync(path, program, { flag: "wx" });
73
+ return path;
74
+ });
75
+ const output = workspace.directory("out");
76
+ const packedPath = join(output, PACKED);
77
+ const packing = await runToolOrFail("Exomizer", "The pack", { argv: sfxArguments(executable, params, inputs, packedPath), cwd: workspace.root, timeoutMs: TIMEOUT_MS }, context);
78
+ if (packing.code !== 0) throw new WireFailure("operation-failed", `Exomizer could not pack the program (exit ${packing.code}).${outputTail("Exomizer", packing, workspace.root, PROBLEM)}`);
79
+ if (!existsSync(packedPath)) throw new WireFailure("operation-failed", "Exomizer reported success but wrote no program.");
80
+ const unpackedPath = join(output, UNPACKED);
81
+ const unpacking = await runToolOrFail("Exomizer", "The unpack check", { argv: [executable, "desfx", "-o", unpackedPath, packedPath], cwd: workspace.root, timeoutMs: TIMEOUT_MS }, context);
82
+ const found = parseDesfx(`${unpacking.stdout}\n${unpacking.stderr}`);
83
+ if (unpacking.code !== 0 || found === undefined || !existsSync(unpackedPath)) {
84
+ throw new WireFailure("operation-failed", `Exomizer could not unpack the packed program in its emulator (exit ${unpacking.code}).${outputTail("Exomizer", unpacking, workspace.root)}`);
85
+ }
86
+ return { program: readFileSync(packedPath), unpacked: readFileSync(unpackedPath), ...found };
87
+ } finally {
88
+ workspace.remove();
89
+ }
90
+ }
@@ -1,6 +1,6 @@
1
1
  // The context for running native tools inside a skill script or the CLI:
2
2
  // one supervisor whose exit guard stops every tool process group when
3
- // the script ends, also on Ctrl+C or SIGTERM, and whose watchdog does the same
3
+ // the script ends, also on Ctrl+C, SIGTERM or SIGHUP, and whose watchdog does the same
4
4
  // when the script dies without its exit guard, for example by SIGKILL.
5
5
  // A line that a tool adapter logs goes to the trace of the script.
6
6
 
@@ -23,7 +23,7 @@ export function localToolContext(): LocalToolContext {
23
23
  supervisor.startWatchdog("skill-script");
24
24
  const controller = new AbortController();
25
25
  // A signal ends the script through process.exit, so the exit guard runs.
26
- for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]] as const) {
26
+ for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]] as const) {
27
27
  process.once(signal, () => {
28
28
  controller.abort();
29
29
  process.exit(code);