@henols/c64-re-tools 2.4.0-rc.2 → 2.4.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 (40) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +6 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +6 -16
  4. package/skills/c64-disk/SKILL.md +19 -4
  5. package/skills/c64-disk/scripts/disk.ts +43 -3
  6. package/skills/c64-provenance/SKILL.md +8 -4
  7. package/skills/c64-provenance/scripts/lib/library.ts +85 -11
  8. package/skills/c64-provenance/scripts/provenance.ts +4 -3
  9. package/skills/c64-source/SKILL.md +8 -2
  10. package/skills/c64-source/scripts/lib/export.ts +3 -3
  11. package/skills/c64-source/scripts/lib/source.ts +80 -24
  12. package/skills/c64-source/scripts/source.ts +49 -8
  13. package/skills/c64-static-analysis/SKILL.md +1 -1
  14. package/skills/c64-testing/SKILL.md +11 -1
  15. package/skills/c64-testing/references/recording-format.md +5 -1
  16. package/skills/c64-testing/references/scenario-format.md +5 -3
  17. package/skills/c64-testing/scripts/lib/recording.ts +32 -6
  18. package/skills/c64-testing/scripts/lib/runs.ts +13 -7
  19. package/skills/c64-testing/scripts/lib/scenario.ts +13 -6
  20. package/skills/c64-testing/scripts/testing.ts +6 -3
  21. package/src/host/server.ts +31 -6
  22. package/src/host/tools/c1541.ts +32 -8
  23. package/src/host/vice/binary-monitor.ts +19 -7
  24. package/src/host/vice/session.ts +6 -2
  25. package/src/host-client/connect.ts +12 -2
  26. package/src/host-client/tools.ts +9 -4
  27. package/src/host-client/transfer.ts +54 -1
  28. package/src/host-client/vice-session.ts +10 -3
  29. package/src/knowledge/import.ts +28 -5
  30. package/src/knowledge/write.ts +4 -0
  31. package/src/mcp/main.ts +4 -66
  32. package/src/mcp/session-source.ts +76 -0
  33. package/src/native/acme.ts +45 -12
  34. package/src/native/c64run.ts +1 -1
  35. package/src/native/types.ts +5 -2
  36. package/src/protocol/framing.ts +15 -2
  37. package/src/protocol/messages.ts +77 -25
  38. package/src/protocol/tools.ts +33 -4
  39. package/src/protocol/vice.ts +40 -20
  40. package/tools/c64run.c +48 -12
package/src/mcp/main.ts CHANGED
@@ -3,9 +3,10 @@
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
 
5
5
  import { ViceSessionClient } from "../host-client/vice-session.ts";
6
- import { elapsedMs, startTrace, trace } from "../trace.ts";
6
+ import { startTrace, trace } from "../trace.ts";
7
7
  import { VIDEO_STANDARDS, WireFailure, type VideoStandard } from "../protocol/messages.ts";
8
- import { createMcpServer, type SessionSource } from "./server.ts";
8
+ import { createMcpServer } from "./server.ts";
9
+ import { sessionSource } from "./session-source.ts";
9
10
  import { debugTools } from "./tools/debug.ts";
10
11
  import { executionTools } from "./tools/execution.ts";
11
12
  import { inputTools } from "./tools/input.ts";
@@ -42,76 +43,13 @@ function videoStandard(env: NodeJS.ProcessEnv): VideoStandard {
42
43
  throw new WireFailure("installation-incomplete", "C64RT_VIDEO must be pal or ntsc. Fix the MCP server configuration and restart it.");
43
44
  }
44
45
 
45
- /**
46
- * One session at a time (1 MCP = 1 session = 1 VICE). It opens at start; if
47
- * that fails (for example the host was not running yet), the next tool call
48
- * tries again. When the host connection is lost, the next call opens a new
49
- * session. A lost session that the emulator answered first gives its
50
- * machine-state-lost once, unless a pending call got it already. Close stops
51
- * an open that is still waiting for the host at once.
52
- */
53
- function sessionSource(): { get: SessionSource; close(): Promise<void> } {
54
- let opening: Promise<ViceSessionClient> | undefined;
55
- let lostNotice: WireFailure | undefined;
56
- let closed = false;
57
- const stop = new AbortController();
58
- const open = () => {
59
- const started = performance.now();
60
- const current = (async () => ViceSessionClient.open({ videoStandard: videoStandard(process.env), signal: stop.signal }))();
61
- opening = current;
62
- void current.then(
63
- (client) => {
64
- trace().event("session.opened", { ms: elapsedMs(started) });
65
- void client.closed.then(() => drop(current, client));
66
- },
67
- () => {},
68
- );
69
- current.catch((error: unknown) => {
70
- log(`session not opened: ${error instanceof Error ? error.message : String(error)}`);
71
- if (opening === current) opening = undefined;
72
- });
73
- return current;
74
- };
75
- /** Forgets a lost session, once; the next call opens a new one. */
76
- const drop = (current: Promise<ViceSessionClient>, client: ViceSessionClient) => {
77
- if (closed || opening !== current) return;
78
- log("the connection to the host runtime was lost; the next call opens a new session");
79
- opening = undefined;
80
- if (client.answered) lostNotice = client.unreportedLoss;
81
- };
82
- open();
83
- const get = async (): Promise<ViceSessionClient> => {
84
- if (closed) throw new WireFailure("machine-unavailable", "The C64 session is shutting down.");
85
- if (lostNotice !== undefined) {
86
- const notice = lostNotice;
87
- lostNotice = undefined;
88
- throw notice;
89
- }
90
- const current = opening ?? open();
91
- const client = await current;
92
- if (!client.lost) return client;
93
- // The loss is known here before the close event reaches drop.
94
- drop(current, client);
95
- return get();
96
- };
97
- return {
98
- get,
99
- async close() {
100
- closed = true;
101
- stop.abort();
102
- const session = await opening?.catch(() => undefined);
103
- await session?.close();
104
- },
105
- };
106
- }
107
-
108
46
  async function main(): Promise<void> {
109
47
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
110
48
  process.stdout.write(`${HELP}\n`);
111
49
  return;
112
50
  }
113
51
  startTrace("mcp", { warn: log });
114
- const session = sessionSource();
52
+ const session = sessionSource((signal) => ViceSessionClient.open({ videoStandard: videoStandard(process.env), signal }), log);
115
53
  const server = createMcpServer({ tools: [...machineTools, ...executionTools, ...debugTools, ...memoryTools, ...videoTools, ...inputTools, ...mediaTools], session: session.get, log });
116
54
 
117
55
  let stopping = false;
@@ -0,0 +1,76 @@
1
+ // The C64 session of the MCP server: one at a time, opened again after a loss.
2
+
3
+ import type { ViceSessionClient } from "../host-client/vice-session.ts";
4
+ import { WireFailure } from "../protocol/messages.ts";
5
+ import { elapsedMs, trace } from "../trace.ts";
6
+ import type { SessionSource } from "./server.ts";
7
+
8
+ /**
9
+ * One session at a time (1 MCP = 1 session = 1 VICE). It opens at start; if
10
+ * that fails (for example the host was not running yet), the next tool call
11
+ * tries again. When the host connection is lost, the next call opens a new
12
+ * session. A lost session that the emulator answered first gives its
13
+ * machine-state-lost once, unless a pending call got it already. Close stops
14
+ * an open that is still waiting for the host at once. A host of another
15
+ * release refuses the new session: then that refusal comes instead of the
16
+ * machine-state-lost, since it tells what to do.
17
+ */
18
+ export function sessionSource(openClient: (signal: AbortSignal) => Promise<ViceSessionClient>, log: (line: string) => void): { get: SessionSource; close(): Promise<void> } {
19
+ let opening: Promise<ViceSessionClient> | undefined;
20
+ let lostNotice: WireFailure | undefined;
21
+ let closed = false;
22
+ const stop = new AbortController();
23
+ const open = () => {
24
+ const started = performance.now();
25
+ const current = (async () => openClient(stop.signal))();
26
+ opening = current;
27
+ void current.then(
28
+ (client) => {
29
+ trace().event("session.opened", { ms: elapsedMs(started) });
30
+ void client.closed.then(() => drop(current, client));
31
+ },
32
+ () => {},
33
+ );
34
+ current.catch((error: unknown) => {
35
+ log(`session not opened: ${error instanceof Error ? error.message : String(error)}`);
36
+ if (opening === current) opening = undefined;
37
+ });
38
+ return current;
39
+ };
40
+ /** Forgets a lost session, once; the next call opens a new one. */
41
+ const drop = (current: Promise<ViceSessionClient>, client: ViceSessionClient) => {
42
+ if (closed || opening !== current) return;
43
+ log("the connection to the host runtime was lost; the next call opens a new session");
44
+ opening = undefined;
45
+ if (client.answered) lostNotice = client.unreportedLoss;
46
+ };
47
+ open();
48
+ const get = async (): Promise<ViceSessionClient> => {
49
+ if (closed) throw new WireFailure("machine-unavailable", "The C64 session is shutting down.");
50
+ if (lostNotice !== undefined) {
51
+ const notice = lostNotice;
52
+ lostNotice = undefined;
53
+ // A host of another release refuses the new session: that refusal tells what to do, the lost machine state does not.
54
+ const refusal = await (opening ?? open()).then(
55
+ () => undefined,
56
+ (error: unknown) => (error instanceof WireFailure && error.code === "installation-incomplete" ? error : undefined),
57
+ );
58
+ throw refusal ?? notice;
59
+ }
60
+ const current = opening ?? open();
61
+ const client = await current;
62
+ if (!client.lost) return client;
63
+ // The loss is known here before the close event reaches drop.
64
+ drop(current, client);
65
+ return get();
66
+ };
67
+ return {
68
+ get,
69
+ async close() {
70
+ closed = true;
71
+ stop.abort();
72
+ const session = await opening?.catch(() => undefined);
73
+ await session?.close();
74
+ },
75
+ };
76
+ }
@@ -2,7 +2,7 @@
2
2
  // diagnostics and symbols, and a validated C64 PRG as the result.
3
3
 
4
4
  import { existsSync, readFileSync } from "node:fs";
5
- import { isAbsolute, join, relative, sep } from "node:path";
5
+ import { isAbsolute, join, posix, relative, sep } from "node:path";
6
6
 
7
7
  import { formatC64Address } from "../c64.ts";
8
8
  import { WireFailure } from "../protocol/messages.ts";
@@ -29,12 +29,31 @@ const TIMEOUT_MS = 60_000;
29
29
  /** True for a relative path that stays inside the source root: no absolute path, no drive letter and no "..". */
30
30
  const insideSourceRoot = (path: string) => isRelativePath(path) && !/^[A-Za-z]:/.test(path);
31
31
 
32
- /** Refuses an entry source or include directory that ACME could read outside the source root, by name. */
32
+ /** The path of a staged file or directory from the top of the staged tree, for a path relative to the source root. Can start with "..". */
33
+ const fromTree = (sourceDir: string, path: string) => posix.normalize(posix.join(sourceDir, path));
34
+
35
+ /** The path from the source root to a path from the top of the staged tree. */
36
+ const fromSourceRoot = (sourceDir: string, path: string) => posix.relative(`/${sourceDir}`, `/${path}`);
37
+
38
+ /**
39
+ * True for an include directory that stays inside the staged tree: a relative
40
+ * path of names, "." and "..", with no drive letter and no backslash, that
41
+ * does not go above the top of the tree from the source root.
42
+ */
43
+ function insideTree(sourceDir: string, path: string): boolean {
44
+ if (!path.split("/").every((part) => part === "." || part === ".." || isRelativePath(part)) || /^[A-Za-z]:/.test(path)) return false;
45
+ const inside = fromTree(sourceDir, path);
46
+ return inside !== ".." && !inside.startsWith("../") && !posix.isAbsolute(inside);
47
+ }
48
+
49
+ /** Refuses an entry source or include directory that ACME could read outside the staged tree, by name. */
33
50
  export function checkAcmeParams(params: AcmeParams): void {
51
+ const sourceDir = params.sourceDir ?? "";
52
+ if (sourceDir !== "" && !insideSourceRoot(sourceDir)) throw new WireFailure("invalid-input", `The source directory ${sourceDir} is not a relative path inside the staged tree.`);
34
53
  if (!insideSourceRoot(params.entrySource)) throw new WireFailure("invalid-input", `The entry source ${params.entrySource} is not a relative path inside the source root.`);
35
54
  if (params.entrySource.startsWith("-")) throw new WireFailure("invalid-input", `The entry source ${params.entrySource} starts with a hyphen, which ACME reads as an option. Give the file a different name.`);
36
55
  for (const directory of params.includeDirs) {
37
- if (!insideSourceRoot(directory)) throw new WireFailure("invalid-input", `The include directory ${directory} is not a relative path inside the source root.`);
56
+ if (!insideTree(sourceDir, directory)) throw new WireFailure("invalid-input", `The include directory ${directory} is not a relative path inside the staged source files.`);
38
57
  }
39
58
  }
40
59
 
@@ -50,17 +69,29 @@ export function acmeArguments(executable: string, params: AcmeParams, outputDire
50
69
 
51
70
  const DIAGNOSTIC = /^(Error|Warning|Serious error) - File (.+?), line (\d+)(?: \(.*?\))?: (.*)$/;
52
71
 
53
- /** Parses ACME's "Error - File main.a, line 4 (Zone ...): message" lines. Files become source-root relative. */
54
- export function parseDiagnostics(output: string, sourceRoot: string): Diagnostic[] {
72
+ /**
73
+ * Parses ACME's "Error - File main.a, line 4 (Zone ...): message" lines. Files
74
+ * become source-root relative: an absolute path through `tree`, the top of
75
+ * the staged tree, and a name that ACME found in an include directory
76
+ * through the staged files, in the order that ACME searches them.
77
+ */
78
+ export function parseDiagnostics(output: string, tree: string, params: Pick<AcmeParams, "files" | "includeDirs" | "sourceDir"> = { files: [], includeDirs: [] }): Diagnostic[] {
79
+ const sourceDir = params.sourceDir ?? "";
80
+ const staged = new Set(params.files.map((file) => file.path));
81
+ const sourcePath = (file: string): string => {
82
+ if (isAbsolute(file)) {
83
+ const inside = relative(tree, file);
84
+ return inside.startsWith("..") || isAbsolute(inside) ? "(outside the source files)" : fromSourceRoot(sourceDir, inside.split(sep).join("/"));
85
+ }
86
+ if (staged.has(fromTree(sourceDir, file))) return file;
87
+ const directory = params.includeDirs.find((candidate) => staged.has(fromTree(sourceDir, posix.join(candidate, file))));
88
+ return directory === undefined ? file : fromSourceRoot(sourceDir, fromTree(sourceDir, posix.join(directory, file)));
89
+ };
55
90
  const diagnostics: Diagnostic[] = [];
56
91
  for (const line of output.split(/\r?\n/)) {
57
92
  const match = DIAGNOSTIC.exec(line.trim());
58
93
  if (match !== null) {
59
- let file = match[2]!;
60
- if (isAbsolute(file)) {
61
- const inside = relative(sourceRoot, file);
62
- file = inside.startsWith("..") || isAbsolute(inside) ? "(outside the source root)" : inside.split(sep).join("/");
63
- }
94
+ const file = sourcePath(match[2]!);
64
95
  diagnostics.push({ severity: match[1] === "Warning" ? "warning" : "error", file, line: Number(match[3]), message: match[4]! });
65
96
  } else if (/^(Error|Serious error|Warning)\b/.test(line.trim())) {
66
97
  diagnostics.push({ severity: line.trim().startsWith("Warning") ? "warning" : "error", message: line.trim() });
@@ -96,11 +127,13 @@ export async function assemble(
96
127
  const executable = findTool(ACME, context.env);
97
128
  const workspace = Workspace.create(context.supervisor);
98
129
  try {
99
- const source = workspace.materialize("source", params.files, files);
130
+ const tree = workspace.materialize("source", params.files, files);
131
+ // ACME runs in the source root, which can be a folder of the staged tree.
132
+ const source = params.sourceDir === undefined || params.sourceDir === "" ? tree : workspace.path(`source/${params.sourceDir}`);
100
133
  // A fresh output directory, so no stale file can pass for this run's output.
101
134
  const output = workspace.directory("out");
102
135
  const run = await runToolOrFail("ACME", "The assembly", { argv: acmeArguments(executable, params, output), cwd: source, timeoutMs: TIMEOUT_MS }, context);
103
- const diagnostics = parseDiagnostics(`${run.stdout}\n${run.stderr}`, source);
136
+ const diagnostics = parseDiagnostics(`${run.stdout}\n${run.stderr}`, tree, params);
104
137
  const programPath = join(output, PROGRAM);
105
138
  if (run.code !== 0) {
106
139
  if (diagnostics.every((diagnostic) => diagnostic.severity !== "error")) {
@@ -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 = 2;
15
+ export const C64RUN_PROTOCOL = 3;
16
16
 
17
17
  /** CPU cycles in one PAL frame: 312 lines of 63 cycles. */
18
18
  export const PAL_FRAME_CYCLES = 19_656;
@@ -10,17 +10,20 @@ import { type SourceTree } from "../protocol/tools.ts";
10
10
 
11
11
  export interface Diagnostic {
12
12
  severity: "error" | "warning" | "note";
13
- /** Relative to the source root; absent when the message has no source location. */
13
+ /** Relative to the source root, with ".." for a file of an include folder outside it; absent when the message has no source location. */
14
14
  file?: string;
15
15
  line?: number;
16
16
  message: string;
17
17
  }
18
18
 
19
19
  export interface AcmeParams {
20
+ /** Relative to the top of the staged tree. */
20
21
  files: SourceTree;
22
+ /** The source root, where ACME runs, relative to the top of the staged tree; absent or "" when the source root is the top. */
23
+ sourceDir?: string;
21
24
  /** Relative to the source root. */
22
25
  entrySource: string;
23
- /** Directories relative to the source root. */
26
+ /** Directories relative to the source root. A directory can start with ".." when it stays inside the staged tree. */
24
27
  includeDirs: string[];
25
28
  defines: Record<string, number | boolean>;
26
29
  setPc?: number;
@@ -15,6 +15,19 @@ const HEADER_BYTES = 4;
15
15
  /** Total attachment bytes one message may carry. */
16
16
  export const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024;
17
17
 
18
+ /** A message that encodeFrame cannot send: its body or its attachments are larger than the limit. */
19
+ export class FrameTooLarge extends ProtocolError {
20
+ override name = "FrameTooLarge";
21
+ readonly bytes: number;
22
+ readonly limit: number;
23
+
24
+ constructor(what: string, bytes: number, limit: number) {
25
+ super(`${what} of ${bytes} bytes exceed${what === "frame" ? "s" : ""} ${limit}`);
26
+ this.bytes = bytes;
27
+ this.limit = limit;
28
+ }
29
+ }
30
+
18
31
  function frame(body: Uint8Array): Buffer {
19
32
  const header = Buffer.allocUnsafe(HEADER_BYTES);
20
33
  header.writeUInt32BE(body.length, 0);
@@ -24,10 +37,10 @@ function frame(body: Uint8Array): Buffer {
24
37
  /** Encodes one message and its attachments as one buffer, so writes never interleave. */
25
38
  export function encodeFrame(message: ClientMessage | HostMessage, attachments: readonly Uint8Array[] = []): Buffer {
26
39
  const total = attachments.reduce((sum, attachment) => sum + attachment.length, 0);
27
- if (total > MAX_ATTACHMENT_BYTES) throw new ProtocolError(`attachments of ${total} bytes exceed ${MAX_ATTACHMENT_BYTES}`);
40
+ if (total > MAX_ATTACHMENT_BYTES) throw new FrameTooLarge("attachments", total, MAX_ATTACHMENT_BYTES);
28
41
  const announced = attachments.length === 0 ? message : { ...message, attachments: attachments.map((attachment) => attachment.length) };
29
42
  const body = Buffer.from(JSON.stringify(announced), "utf8");
30
- if (body.length > MAX_FRAME_BYTES) throw new ProtocolError(`frame of ${body.length} bytes exceeds ${MAX_FRAME_BYTES}`);
43
+ if (body.length > MAX_FRAME_BYTES) throw new FrameTooLarge("frame", body.length, MAX_FRAME_BYTES);
31
44
  const frames = [frame(body)];
32
45
  for (const attachment of attachments) {
33
46
  for (let offset = 0; offset < attachment.length; offset += MAX_FRAME_BYTES) {
@@ -8,7 +8,7 @@ import type { ViceOperation, ViceOperations } from "./vice.ts";
8
8
  /** Private Host Runtime protocol identifier. */
9
9
  export const HOST_PROTOCOL_ID = "c64-re-tools-host" as const;
10
10
  /** Bumped on any incompatible change; a mismatch fails the handshake. */
11
- export const HOST_PROTOCOL_VERSION = 4;
11
+ export const HOST_PROTOCOL_VERSION = 5;
12
12
  /** After ready, the client pings this often, on every connection. */
13
13
  export const HEARTBEAT_INTERVAL_MS = 10_000;
14
14
  /** Either side closes a connection that has sent nothing for this long. */
@@ -38,6 +38,8 @@ export interface Hello {
38
38
  type: "hello";
39
39
  protocol: string;
40
40
  version: number;
41
+ /** The package version of the client (see checkRelease). A client of an older protocol version sends none. */
42
+ release?: string;
41
43
  role: Role;
42
44
  /** vice-session only; fixed for the session. */
43
45
  videoStandard?: VideoStandard;
@@ -45,6 +47,8 @@ export interface Hello {
45
47
 
46
48
  export interface Ready {
47
49
  type: "ready";
50
+ /** The package version of the host (see checkRelease). */
51
+ release: string;
48
52
  }
49
53
 
50
54
  /** Sent instead of `ready` when the handshake fails; the host then closes. */
@@ -155,11 +159,13 @@ export function parseClientMessage(value: unknown): ReceivedClientMessage {
155
159
  if (typeof value.protocol !== "string" || typeof value.version !== "number") {
156
160
  throw new ProtocolError("hello lacks protocol or version");
157
161
  }
162
+ if (value.release !== undefined && typeof value.release !== "string") throw new ProtocolError("hello has a release that is not a string");
158
163
  if (!isOneOf(ROLES, value.role)) throw new ProtocolError("hello has an unknown role");
159
164
  if (value.videoStandard !== undefined && !isOneOf(VIDEO_STANDARDS, value.videoStandard)) {
160
165
  throw new ProtocolError("hello has an unknown video standard");
161
166
  }
162
167
  const hello: Hello = { type: "hello", protocol: value.protocol, version: value.version, role: value.role };
168
+ if (value.release !== undefined) hello.release = value.release;
163
169
  if (value.videoStandard !== undefined) hello.videoStandard = value.videoStandard;
164
170
  return hello;
165
171
  }
@@ -176,7 +182,10 @@ export function parseClientMessage(value: unknown): ReceivedClientMessage {
176
182
  /** Validates a message the client received. Throws ProtocolError on any contract break. */
177
183
  export function parseHostMessage(value: unknown): HostMessage {
178
184
  if (!isObject(value)) throw new ProtocolError("message is not an object");
179
- if (value.type === "ready") return { type: "ready" };
185
+ if (value.type === "ready") {
186
+ if (typeof value.release !== "string") throw new ProtocolError("ready lacks the release");
187
+ return { type: "ready", release: value.release };
188
+ }
180
189
  if (value.type === "pong") return { type: "pong" };
181
190
  if (value.type === "error") {
182
191
  if (!isWireError(value.error)) throw new ProtocolError("handshake error is malformed");
@@ -194,13 +203,71 @@ export function parseHostMessage(value: unknown): HostMessage {
194
203
  throw new ProtocolError("unknown message type");
195
204
  }
196
205
 
197
- /** Checks a hello against this build's protocol. Returns the failure to send, or undefined. */
206
+ const OLDER_HOST: WireError = {
207
+ code: "installation-incomplete",
208
+ message:
209
+ "The c64-re-tools host runtime is from an older release than this client. " +
210
+ "Stop the host runtime and start it again with the same npx command. npx then starts the newest release.",
211
+ };
212
+ const OLDER_CLIENT: WireError = {
213
+ code: "installation-incomplete",
214
+ message:
215
+ "This client is from an older release of c64-re-tools than the host runtime. " +
216
+ "Restart the agent session, so that npx starts the newest MCP server. " +
217
+ "For the skill scripts, run c64-re-tools update in the project.",
218
+ };
219
+
220
+ /** A development checkout (0.0.0-development) can run against any release; the protocol version still applies. */
221
+ function isDevelopment(release: string): boolean {
222
+ return release.startsWith("0.0.0-");
223
+ }
224
+
225
+ /** The numbers and the prerelease of a version such as 2.1.4 or 2.2.0-rc.1, for the order of releases. */
226
+ function releaseOrder(release: string): { core: number[]; prerelease: string[] } {
227
+ const [core = "", ...rest] = release.split("-");
228
+ const prerelease = rest.join("-");
229
+ return { core: core.split(".").map((part) => Number(part) || 0), prerelease: prerelease === "" ? [] : prerelease.split(".") };
230
+ }
231
+
232
+ /** Negative when release a is older than b, as semantic versioning orders them. */
233
+ function compareReleases(a: string, b: string): number {
234
+ const left = releaseOrder(a);
235
+ const right = releaseOrder(b);
236
+ for (let index = 0; index < 3; index++) {
237
+ const difference = (left.core[index] ?? 0) - (right.core[index] ?? 0);
238
+ if (difference !== 0) return difference;
239
+ }
240
+ // A prerelease comes before its release.
241
+ if (left.prerelease.length === 0 || right.prerelease.length === 0) return right.prerelease.length - left.prerelease.length;
242
+ for (let index = 0; index < Math.max(left.prerelease.length, right.prerelease.length); index++) {
243
+ const l = left.prerelease[index];
244
+ const r = right.prerelease[index];
245
+ if (l === undefined || r === undefined) return l === undefined ? -1 : 1;
246
+ if (l === r) continue;
247
+ const numeric = /^\d+$/.test(l) && /^\d+$/.test(r);
248
+ return numeric ? Number(l) - Number(r) : l < r ? -1 : 1;
249
+ }
250
+ return 0;
251
+ }
252
+
198
253
  /**
199
- * Refuses a client of another protocol version, and names the older side and
200
- * how to update it. A release that changes the wire increments the protocol
201
- * version, so the first client of a new release refuses an older host.
254
+ * Refuses a client and a host of different releases, and names the older side
255
+ * and how to update it. The protocol version is bumped by hand and a release
256
+ * can change the wire without it, so both sides also compare their package
257
+ * versions. A development checkout passes against any release.
202
258
  */
203
- export function checkHello(hello: Hello): WireError | undefined {
259
+ export function checkRelease(client: string, host: string): WireError | undefined {
260
+ if (client === host || isDevelopment(client) || isDevelopment(host)) return undefined;
261
+ return { ...(compareReleases(host, client) < 0 ? OLDER_HOST : OLDER_CLIENT) };
262
+ }
263
+
264
+ /**
265
+ * Checks a hello against this build's protocol and the host's release
266
+ * (`release`). Returns the failure to send, or undefined. Refuses a client of
267
+ * another protocol version or release, and names the older side and how to
268
+ * update it.
269
+ */
270
+ export function checkHello(hello: Hello, release: string): WireError | undefined {
204
271
  if (hello.protocol !== HOST_PROTOCOL_ID) {
205
272
  return {
206
273
  code: "installation-incomplete",
@@ -209,24 +276,9 @@ export function checkHello(hello: Hello): WireError | undefined {
209
276
  "Install the same c64-re-tools release for both and restart the host runtime.",
210
277
  };
211
278
  }
212
- if (hello.version > HOST_PROTOCOL_VERSION) {
213
- return {
214
- code: "installation-incomplete",
215
- message:
216
- "The c64-re-tools host runtime is from an older release than this client. " +
217
- "Stop the host runtime and start it again with the same npx command. npx then starts the newest release.",
218
- };
219
- }
220
- if (hello.version < HOST_PROTOCOL_VERSION) {
221
- return {
222
- code: "installation-incomplete",
223
- message:
224
- "This client is from an older release of c64-re-tools than the host runtime. " +
225
- "Restart the agent session, so that npx starts the newest MCP server. " +
226
- "For the skill scripts, run c64-re-tools update in the project.",
227
- };
228
- }
229
- return undefined;
279
+ if (hello.version > HOST_PROTOCOL_VERSION) return { ...OLDER_HOST };
280
+ if (hello.version < HOST_PROTOCOL_VERSION || hello.release === undefined) return { ...OLDER_CLIENT };
281
+ return checkRelease(hello.release, release);
230
282
  }
231
283
 
232
284
  export function invalid(message: string): never {
@@ -13,7 +13,7 @@ export const MAX_TREE_FILES = 4096;
13
13
 
14
14
  export const DISK_IMAGE_TYPES = ["d64", "d71", "d81", "g64"] as const;
15
15
  export type DiskImageType = (typeof DISK_IMAGE_TYPES)[number];
16
- export const DISK_ACTIONS = ["directory", "bam", "entry", "chain", "read"] as const;
16
+ export const DISK_ACTIONS = ["directory", "bam", "entry", "chain", "read", "sectors"] as const;
17
17
  export type DiskAction = (typeof DISK_ACTIONS)[number];
18
18
  export const CBM_FILE_TYPES = ["del", "seq", "prg", "usr", "rel", "unknown"] as const;
19
19
  export type CbmFileType = (typeof CBM_FILE_TYPES)[number];
@@ -24,8 +24,16 @@ export interface C1541Params {
24
24
  imageType: DiskImageType;
25
25
  /** entry, chain and read only: the file name as petsciiNameToText shows it. */
26
26
  name?: string;
27
+ /** sectors only: the blocks to read, in this order; with unreferenced, then each used sector that no file holds (see bam). */
28
+ sectors?: DiskSector[];
29
+ unreferenced?: boolean;
27
30
  }
28
31
 
32
+ /** The most blocks of one sectors request, more than a disk image holds: a D81 has 3200. */
33
+ export const MAX_DISK_SECTORS = 4096;
34
+ /** The size of a disk block. */
35
+ export const DISK_BLOCK_BYTES = 256;
36
+
29
37
  export interface DiskFile {
30
38
  name: string;
31
39
  type: CbmFileType;
@@ -49,7 +57,9 @@ export type C1541Result =
49
57
  | { action: "chain"; found: true; sectors: DiskSector[] }
50
58
  | { action: "read"; found: false }
51
59
  /** The file's bytes are the reply's attachment. */
52
- | { action: "read"; found: true; name: string; bytes: number };
60
+ | { action: "read"; found: true; name: string; bytes: number }
61
+ /** The blocks of the sectors, 256 bytes each in this order, are the reply's attachment. */
62
+ | { action: "sectors"; sectors: DiskSector[]; bytes: number };
53
63
 
54
64
  /** petcat.decode takes no fields: the program bytes are the request's one attachment. */
55
65
  export type PetcatParams = Record<string, never>;
@@ -119,11 +129,22 @@ export function validateToolParams<O extends ToolOperation>(op: O, params: unkno
119
129
  if (!isObject(params)) invalid("parameters must be an object");
120
130
  switch (op) {
121
131
  case "c1541.inspect": {
122
- onlyFields(params, ["action", "imageType", "name"]);
132
+ onlyFields(params, ["action", "imageType", "name", "sectors", "unreferenced"]);
123
133
  if (!isOneOf(DISK_ACTIONS, params.action)) invalid(`action must be one of ${DISK_ACTIONS.join(", ")}`);
124
134
  if (!isOneOf(DISK_IMAGE_TYPES, params.imageType)) invalid(`imageType must be one of ${DISK_IMAGE_TYPES.join(", ")}`);
125
135
  oneFile(attachments, "the disk image");
126
136
  const result: C1541Params = { action: params.action, imageType: params.imageType };
137
+ if (params.action === "sectors") {
138
+ const { sectors, unreferenced } = params;
139
+ if (sectors !== undefined && (!Array.isArray(sectors) || !sectors.every(isTrackSector))) invalid("sectors must be a list of track and sector numbers from 0 to 255");
140
+ if (sectors !== undefined && sectors.length > MAX_DISK_SECTORS) invalid(`sectors holds at most ${MAX_DISK_SECTORS} sectors`);
141
+ if (unreferenced !== undefined && typeof unreferenced !== "boolean") invalid("unreferenced must be true or false");
142
+ if ((sectors === undefined || sectors.length === 0) && unreferenced !== true) invalid("action sectors needs sectors, unreferenced, or both");
143
+ if (sectors !== undefined) result.sectors = sectors.map((at) => ({ track: at.track, sector: at.sector }));
144
+ if (unreferenced === true) result.unreferenced = true;
145
+ } else if (params.sectors !== undefined || params.unreferenced !== undefined) {
146
+ invalid(`action ${params.action} takes no sectors`);
147
+ }
127
148
  const named = params.action === "entry" || params.action === "chain" || params.action === "read";
128
149
  if (!named) {
129
150
  if (params.name !== undefined) invalid(`action ${params.action} takes no name`);
@@ -198,7 +219,7 @@ function isDiskFile(value: unknown): value is DiskFile {
198
219
  }
199
220
 
200
221
  function isC1541Result(value: Fields, attachments: readonly Uint8Array[]): boolean {
201
- const carries = value.action === "read" && value.found === true ? 1 : 0;
222
+ const carries = (value.action === "read" && value.found === true) || value.action === "sectors" ? 1 : 0;
202
223
  if (attachments.length !== carries) return false;
203
224
  switch (value.action) {
204
225
  case "directory":
@@ -226,6 +247,14 @@ function isC1541Result(value: Fields, attachments: readonly Uint8Array[]): boole
226
247
  return value.found === false || (value.found === true && Array.isArray(value.sectors) && value.sectors.every(isTrackSector));
227
248
  case "read":
228
249
  return value.found === false || (value.found === true && typeof value.name === "string" && value.bytes === attachments[0]!.length);
250
+ case "sectors":
251
+ return (
252
+ Array.isArray(value.sectors) &&
253
+ value.sectors.length <= MAX_DISK_SECTORS &&
254
+ value.sectors.every(isTrackSector) &&
255
+ value.bytes === value.sectors.length * DISK_BLOCK_BYTES &&
256
+ value.bytes === attachments[0]!.length
257
+ );
229
258
  }
230
259
  return false;
231
260
  }
@@ -261,6 +261,13 @@ export interface TraceResult {
261
261
  pc: number;
262
262
  }
263
263
 
264
+ /**
265
+ * A trace result on the wire: the hits are the count, and the hits themselves
266
+ * come as the one attachment, a JSON list (traceHitsFromAttachment). Thousands
267
+ * of hits do not fit in one message.
268
+ */
269
+ export type TraceReply = Omit<TraceResult, "hits"> & { hits: number };
270
+
264
271
  export interface BacktraceFrame {
265
272
  /** The routine's entry address. */
266
273
  address: number;
@@ -524,7 +531,7 @@ export interface ViceOperations {
524
531
  breakpoint: { params: BreakpointParams; result: Breakpoint | PointRemoved | { breakpoints: Breakpoint[] } };
525
532
  watchpoint: { params: WatchpointParams; result: Watchpoint | PointRemoved | { watchpoints: Watchpoint[] } };
526
533
  cpuHistory: { params: { limit: number; space: Space }; result: { entries: HistoryEntry[] } };
527
- trace: { params: { points: TracePoint[]; frames: number; maxHits: number }; result: TraceResult };
534
+ trace: { params: { points: TracePoint[]; frames: number; maxHits: number }; result: TraceReply };
528
535
  backtrace: { params: { depth: number; space: Space }; result: { frames: BacktraceFrame[] } };
529
536
  /** `cycles` is a decimal string. */
530
537
  timing: { params: { action: (typeof TIMING_ACTIONS)[number] }; result: { started: boolean } | { cycles: string } };
@@ -1266,25 +1273,7 @@ export function validateViceResult<O extends ViceOperation>(op: O, value: unknow
1266
1273
  break;
1267
1274
  }
1268
1275
  case "trace": {
1269
- const ok =
1270
- Array.isArray(value.hits) &&
1271
- isInteger(value.frames, 0, MAX_TRACE_FRAMES) &&
1272
- isOneOf(TRACE_ENDS, value.end) &&
1273
- isInteger(value.pc, 0, 0xffff) &&
1274
- value.hits.every(
1275
- (hit) =>
1276
- isObject(hit) &&
1277
- isInteger(hit.point, 0, MAX_TRACE_POINTS - 1) &&
1278
- isInteger(hit.pc, 0, 0xffff) &&
1279
- isHexData(hit.bytes) &&
1280
- typeof hit.text === "string" &&
1281
- (["a", "x", "y", "sp"] as const).every((name) => isInteger(hit[name], 0, 0xff)) &&
1282
- isInteger(hit.frame, 0, MAX_TRACE_FRAMES) &&
1283
- isInteger(hit.rasterLine, 0, 511) &&
1284
- isInteger(hit.rasterCycle, 0, 127) &&
1285
- (hit.address === undefined || isInteger(hit.address, 0, 0xffff)) &&
1286
- (hit.value === undefined || isInteger(hit.value, 0, 0xff)),
1287
- );
1276
+ const ok = isInteger(value.hits, 0, MAX_TRACE_HITS) && isInteger(value.frames, 0, MAX_TRACE_FRAMES) && isOneOf(TRACE_ENDS, value.end) && isInteger(value.pc, 0, 0xffff);
1288
1277
  if (!ok) throw new ProtocolError("trace result is malformed");
1289
1278
  break;
1290
1279
  }
@@ -1455,3 +1444,34 @@ export function validateViceResult<O extends ViceOperation>(op: O, value: unknow
1455
1444
  }
1456
1445
  return value as unknown as ViceOperations[O]["result"];
1457
1446
  }
1447
+
1448
+ /** The hits of a trace reply from its attachment: a JSON list of `count` hits. Throws ProtocolError. */
1449
+ export function traceHitsFromAttachment(attachments: readonly Buffer[], count: number): TraceHit[] {
1450
+ const [bytes] = attachments;
1451
+ if (bytes === undefined || attachments.length !== 1) throw new ProtocolError("trace reply has no hits attachment");
1452
+ let hits: unknown;
1453
+ try {
1454
+ hits = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1455
+ } catch {
1456
+ throw new ProtocolError("trace hits are not valid JSON");
1457
+ }
1458
+ const ok =
1459
+ Array.isArray(hits) &&
1460
+ hits.length === count &&
1461
+ hits.every(
1462
+ (hit) =>
1463
+ isObject(hit) &&
1464
+ isInteger(hit.point, 0, MAX_TRACE_POINTS - 1) &&
1465
+ isInteger(hit.pc, 0, 0xffff) &&
1466
+ isHexData(hit.bytes) &&
1467
+ typeof hit.text === "string" &&
1468
+ (["a", "x", "y", "sp"] as const).every((name) => isInteger(hit[name], 0, 0xff)) &&
1469
+ isInteger(hit.frame, 0, MAX_TRACE_FRAMES) &&
1470
+ isInteger(hit.rasterLine, 0, 511) &&
1471
+ isInteger(hit.rasterCycle, 0, 127) &&
1472
+ (hit.address === undefined || isInteger(hit.address, 0, 0xffff)) &&
1473
+ (hit.value === undefined || isInteger(hit.value, 0, 0xff)),
1474
+ );
1475
+ if (!ok) throw new ProtocolError("trace hits are malformed");
1476
+ return hits as TraceHit[];
1477
+ }