@henols/c64-re-tools 2.4.0-rc.2 → 2.4.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +8 -3
  3. package/skills/c64-assembler/scripts/assembler.ts +6 -16
  4. package/skills/c64-basic/SKILL.md +2 -0
  5. package/skills/c64-disk/SKILL.md +21 -4
  6. package/skills/c64-disk/scripts/disk.ts +43 -3
  7. package/skills/c64-docs/SKILL.md +2 -0
  8. package/skills/c64-docs/scripts/docs.ts +6 -6
  9. package/skills/c64-knowledge/SKILL.md +2 -0
  10. package/skills/c64-memory-map/SKILL.md +2 -0
  11. package/skills/c64-packer/SKILL.md +2 -0
  12. package/skills/c64-provenance/SKILL.md +11 -4
  13. package/skills/c64-provenance/scripts/lib/library.ts +99 -19
  14. package/skills/c64-provenance/scripts/provenance.ts +4 -3
  15. package/skills/c64-reverse-engineering/SKILL.md +3 -3
  16. package/skills/c64-source/SKILL.md +10 -2
  17. package/skills/c64-source/scripts/lib/export.ts +3 -3
  18. package/skills/c64-source/scripts/lib/source.ts +80 -24
  19. package/skills/c64-source/scripts/source.ts +49 -8
  20. package/skills/c64-static-analysis/SKILL.md +3 -1
  21. package/skills/c64-testing/SKILL.md +13 -1
  22. package/skills/c64-testing/references/recording-format.md +5 -1
  23. package/skills/c64-testing/references/scenario-format.md +5 -3
  24. package/skills/c64-testing/scripts/lib/recording.ts +32 -6
  25. package/skills/c64-testing/scripts/lib/runs.ts +13 -7
  26. package/skills/c64-testing/scripts/lib/scenario.ts +13 -6
  27. package/skills/c64-testing/scripts/testing.ts +6 -3
  28. package/skills/c64-unpacker/SKILL.md +2 -0
  29. package/src/host/server.ts +31 -6
  30. package/src/host/tools/c1541.ts +32 -8
  31. package/src/host/vice/binary-monitor.ts +19 -7
  32. package/src/host/vice/session.ts +6 -2
  33. package/src/host-client/connect.ts +12 -2
  34. package/src/host-client/tools.ts +9 -4
  35. package/src/host-client/transfer.ts +58 -4
  36. package/src/host-client/vice-session.ts +10 -3
  37. package/src/knowledge/import.ts +28 -5
  38. package/src/knowledge/write.ts +4 -0
  39. package/src/mcp/main.ts +4 -66
  40. package/src/mcp/session-source.ts +76 -0
  41. package/src/native/acme.ts +45 -12
  42. package/src/native/c64run.ts +1 -1
  43. package/src/native/types.ts +5 -2
  44. package/src/project.ts +58 -1
  45. package/src/protocol/framing.ts +15 -2
  46. package/src/protocol/messages.ts +77 -25
  47. package/src/protocol/tools.ts +33 -4
  48. package/src/protocol/vice.ts +40 -20
  49. package/src/script.ts +11 -6
  50. package/tools/c64run.c +48 -12
@@ -12,7 +12,7 @@ import { join } from "node:path";
12
12
 
13
13
  import { petsciiNameToText, textToPetsciiName } from "../../c64.ts";
14
14
  import { WireFailure } from "../../protocol/messages.ts";
15
- import { CBM_FILE_TYPES, type C1541Params, type C1541Result, type CbmFileType, type DiskFile, type DiskSector } from "../../protocol/tools.ts";
15
+ import { CBM_FILE_TYPES, MAX_DISK_SECTORS, type C1541Params, type C1541Result, type CbmFileType, type DiskFile, type DiskSector } from "../../protocol/tools.ts";
16
16
  import { Workspace } from "../../native/staging.ts";
17
17
  import { C1541, findTool } from "../../native/discover.ts";
18
18
  import { requireMinimumVersion } from "./version.ts";
@@ -173,6 +173,23 @@ export function unreferencedSectors(tracks: ReadonlyArray<{ track: number; usedS
173
173
  return tracks.flatMap(({ track, usedSectors }) => usedSectors.filter((sector) => !known.has(`${track}/${sector}`)).map((sector) => ({ track, sector })));
174
174
  }
175
175
 
176
+ /**
177
+ * The sectors of a sectors request: the given ones in their order, then the
178
+ * unreferenced ones. Refuses a sector that the disk does not have (the BAM
179
+ * shows each sector of each track) and more than MAX_DISK_SECTORS sectors.
180
+ */
181
+ export function sectorsToRead(given: readonly DiskSector[], unreferenced: readonly DiskSector[], tracks: ReadonlyArray<{ track: number; freeSectors: number[]; usedSectors: number[] }>): DiskSector[] {
182
+ const sectors = [...given, ...unreferenced];
183
+ for (const at of sectors) {
184
+ const row = tracks[at.track - 1];
185
+ if (row === undefined || at.sector >= row.freeSectors.length + row.usedSectors.length) {
186
+ throw new WireFailure("invalid-input", `The disk has no track ${at.track} sector ${at.sector}. Give a track and a sector that the BAM shows.`);
187
+ }
188
+ }
189
+ if (sectors.length > MAX_DISK_SECTORS) throw new WireFailure("limit-exceeded", `The request reads ${sectors.length} sectors, and one request reads at most ${MAX_DISK_SECTORS}. Give fewer sectors.`);
190
+ return sectors;
191
+ }
192
+
176
193
  const toFile = (entry: DiskEntry): DiskFile => ({ name: entry.name, type: entry.type, blocks: entry.blocks, closed: entry.closed, locked: entry.locked });
177
194
 
178
195
  const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((byte, index) => byte === b[index]);
@@ -250,15 +267,22 @@ export async function inspect(params: C1541Params, image: Buffer, context: ToolC
250
267
 
251
268
  const headerChain = await c1541.chain(layout.header);
252
269
  const directory = parseDirectory(await c1541.blocks(headerChain), layout);
253
- if (params.action === "bam") {
270
+ if (params.action === "bam" || params.action === "sectors") {
254
271
  const tracks = parseBam(await c1541.run(["-bam"]), info.tracks);
255
- // Every sector that the header, the directory or a file holds; a file without blocks has no chain.
256
- const referenced = [...headerChain, ...(RESERVED[info.format] ?? [])];
257
- for (const entry of directory.entries) {
258
- if (entry.startTrack !== 0) referenced.push(...(await c1541.chain({ track: entry.startTrack, sector: entry.startSector })));
259
- if (entry.sideStart !== undefined) referenced.push(...(await c1541.chain(entry.sideStart)));
272
+ let unreferenced: DiskSector[] = [];
273
+ if (params.action === "bam" || params.unreferenced === true) {
274
+ // Every sector that the header, the directory or a file holds; a file without blocks has no chain.
275
+ const referenced = [...headerChain, ...(RESERVED[info.format] ?? [])];
276
+ for (const entry of directory.entries) {
277
+ if (entry.startTrack !== 0) referenced.push(...(await c1541.chain({ track: entry.startTrack, sector: entry.startSector })));
278
+ if (entry.sideStart !== undefined) referenced.push(...(await c1541.chain(entry.sideStart)));
279
+ }
280
+ unreferenced = unreferencedSectors(tracks, referenced);
260
281
  }
261
- return { result: { action: "bam", tracks, unreferenced: unreferencedSectors(tracks, referenced) } };
282
+ if (params.action === "bam") return { result: { action: "bam", tracks, unreferenced } };
283
+ const sectors = sectorsToRead(params.sectors ?? [], unreferenced, tracks);
284
+ const data = Buffer.concat(sectors.length === 0 ? [] : await c1541.blocks(sectors));
285
+ return { result: { action: "sectors", sectors, bytes: data.length }, attachments: [data] };
262
286
  }
263
287
  if (params.action === "directory") {
264
288
  const { diskName, diskId, dosType, entries } = directory;
@@ -233,6 +233,8 @@ interface Pending {
233
233
  resolve: (response: MonitorResponse & { extras: MonitorResponse[] }) => void;
234
234
  reject: (error: Error) => void;
235
235
  timer: NodeJS.Timeout | undefined;
236
+ /** The place of the request in the send order. */
237
+ sequence: number;
236
238
  }
237
239
 
238
240
  export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
@@ -257,8 +259,13 @@ export class BinaryMonitor {
257
259
  defaultTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS;
258
260
  /** The time limit of a request while an earlier one is overdue (see OVERDUE_REQUEST_TIMEOUT_MS). */
259
261
  overdueTimeoutMs = OVERDUE_REQUEST_TIMEOUT_MS;
260
- /** Requests that timed out and whose late answer has not come yet. */
261
- readonly #overdue = new Set<number>();
262
+ /**
263
+ * Requests that timed out and whose late answer has not come yet, with
264
+ * their place in the send order. VICE answers in order, so an answer to a
265
+ * later request tells that no answer comes for the earlier ones.
266
+ */
267
+ readonly #overdue = new Map<number, number>();
268
+ #sequence = 0;
262
269
 
263
270
  private constructor(socket: Socket) {
264
271
  this.#socket = socket;
@@ -308,13 +315,16 @@ export class BinaryMonitor {
308
315
  const requestId = this.#nextId;
309
316
  this.#nextId = this.#nextId >= EVENT_REQUEST_ID - 1 ? 1 : this.#nextId + 1;
310
317
  const limit = this.#overdue.size > 0 && timeoutMs !== Infinity ? Math.min(timeoutMs, this.overdueTimeoutMs) : timeoutMs;
318
+ const sequence = ++this.#sequence;
319
+ // An id that wrapped around belongs to this request now, not to a dead one.
320
+ this.#overdue.delete(requestId);
311
321
  return new Promise((resolve, reject) => {
312
322
  const timer =
313
323
  limit === Infinity
314
324
  ? undefined
315
325
  : setTimeout(() => {
316
326
  this.#pending.delete(requestId);
317
- this.#overdue.add(requestId);
327
+ this.#overdue.set(requestId, sequence);
318
328
  reject(new MonitorTimeoutError(`monitor command 0x${command.toString(16)} got no response in ${limit} ms`));
319
329
  }, limit);
320
330
  this.#pending.set(requestId, {
@@ -324,6 +334,7 @@ export class BinaryMonitor {
324
334
  resolve,
325
335
  reject,
326
336
  timer,
337
+ sequence,
327
338
  });
328
339
  this.#socket.write(encodeCommand(requestId, command, body));
329
340
  });
@@ -351,11 +362,12 @@ export class BinaryMonitor {
351
362
  continue;
352
363
  }
353
364
  const pending = this.#pending.get(response.requestId);
354
- if (pending === undefined) {
355
- // A late answer to a timed-out request: VICE went on.
356
- this.#overdue.delete(response.requestId);
357
- continue;
365
+ // An answer, also a late one to a timed-out request: VICE went on, past every request sent before it.
366
+ const sequence = pending?.sequence ?? this.#overdue.get(response.requestId);
367
+ if (sequence !== undefined) {
368
+ for (const [requestId, sent] of this.#overdue) if (sent <= sequence) this.#overdue.delete(requestId);
358
369
  }
370
+ if (pending === undefined) continue;
359
371
  if (response.error !== 0) {
360
372
  this.#settle(response.requestId, pending);
361
373
  pending.reject(new MonitorError(pending.command, response.error));
@@ -516,8 +516,12 @@ export class ViceSession implements ViceSessionHandle {
516
516
  return this.#snapshotFile(params as ViceOperations["snapshotFile"]["params"], attachments, reply);
517
517
  case "cpuHistory":
518
518
  return this.#cpuHistory(params as ViceOperations["cpuHistory"]["params"]);
519
- case "trace":
520
- return this.#trace(params as ViceOperations["trace"]["params"]);
519
+ case "trace": {
520
+ // The hits go as an attachment: thousands of them do not fit in one message.
521
+ const { hits, ...traced } = await this.#trace(params as ViceOperations["trace"]["params"]);
522
+ reply.push(Buffer.from(JSON.stringify(hits), "utf8"));
523
+ return { ...traced, hits: hits.length };
524
+ }
521
525
  case "backtrace": {
522
526
  const { depth, space } = params as ViceOperations["backtrace"]["params"];
523
527
  return this.#observe(async () => {
@@ -4,7 +4,7 @@ import { connect as connectTcp, type Socket } from "node:net";
4
4
 
5
5
  import { encodeFrame, MessageReader } from "../protocol/framing.ts";
6
6
  import { elapsedMs, trace } from "../trace.ts";
7
- import { DEFAULT_HOST_PORT, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, HOST_PROTOCOL_ID, HOST_PROTOCOL_VERSION, parseHostMessage, ProtocolError, WireFailure, withStopAndAsk, type Hello, type HostMessage, type Ping, type Request, type Role, type VideoStandard } from "../protocol/messages.ts";
7
+ import { DEFAULT_HOST_PORT, HEARTBEAT_INTERVAL_MS, HEARTBEAT_TIMEOUT_MS, HOST_PROTOCOL_ID, HOST_PROTOCOL_VERSION, checkRelease, parseHostMessage, ProtocolError, WireFailure, withStopAndAsk, type Hello, type HostMessage, type Ping, type Request, type Role, type VideoStandard } from "../protocol/messages.ts";
8
8
  import { PACKAGE } from "../package.ts";
9
9
 
10
10
  export interface Endpoint {
@@ -133,6 +133,8 @@ export class HostConnection {
133
133
  env?: NodeJS.ProcessEnv;
134
134
  /** Stops the connect and the handshake at once; the open then fails and its socket is closed. */
135
135
  signal?: AbortSignal;
136
+ /** The package version that this client gives in hello; PACKAGE.version when not given. */
137
+ release?: string;
136
138
  }): Promise<HostConnection> {
137
139
  const signal = options.signal;
138
140
  const started = performance.now();
@@ -151,7 +153,8 @@ export class HostConnection {
151
153
  if (socket === undefined) throw unreachable();
152
154
 
153
155
  const connection = new HostConnection(socket);
154
- const hello: Hello = { type: "hello", protocol: HOST_PROTOCOL_ID, version: HOST_PROTOCOL_VERSION, role: options.role };
156
+ const release = options.release ?? PACKAGE.version;
157
+ const hello: Hello = { type: "hello", protocol: HOST_PROTOCOL_ID, version: HOST_PROTOCOL_VERSION, release, role: options.role };
155
158
  if (options.videoStandard !== undefined) hello.videoStandard = options.videoStandard;
156
159
 
157
160
  const stop = () => void connection.close();
@@ -175,6 +178,13 @@ export class HostConnection {
175
178
  throw stopped();
176
179
  }
177
180
 
181
+ // The host checks the release of hello; the client checks the release of ready too, so neither side relies on the other.
182
+ const mismatch = !(answer instanceof Error) && answer.type === "ready" ? checkRelease(release, answer.release) : undefined;
183
+ if (mismatch !== undefined) {
184
+ trace().event("host.handshake-failed", { role: options.role, ms: elapsedMs(started), ...mismatch });
185
+ await connection.close();
186
+ throw new WireFailure(mismatch.code, mismatch.message);
187
+ }
178
188
  if (!(answer instanceof Error) && answer.type === "ready") {
179
189
  trace().event("host.ready", { role: options.role, ms: elapsedMs(started) });
180
190
  connection.#startHeartbeat();
@@ -4,7 +4,7 @@
4
4
  // ACME, DXA and Ghidra themselves through src/native.
5
5
 
6
6
  import { ProtocolError, WireFailure } from "../protocol/messages.ts";
7
- import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type PetcatResult, type ToolOperation, type ToolOperations, type HostInfo, type ToolStatus } from "../protocol/tools.ts";
7
+ import { DISK_IMAGE_TYPES, validateToolResult, type C1541Result, type DiskAction, type DiskImageType, type DiskSector, type PetcatResult, type ToolOperation, type ToolOperations, type HostInfo, type ToolStatus } from "../protocol/tools.ts";
8
8
  import { HostConnection } from "./connect.ts";
9
9
  import { readPrg } from "./image.ts";
10
10
  import { readProjectFile } from "./transfer.ts";
@@ -59,9 +59,12 @@ export interface InspectDiskRequest {
59
59
  action: DiskAction;
60
60
  /** entry, chain and read: the file name as the directory shows it. */
61
61
  name?: string;
62
+ /** sectors: the blocks to read in this order, then with unreferenced each used sector that no file holds. */
63
+ sectors?: DiskSector[];
64
+ unreferenced?: boolean;
62
65
  }
63
66
 
64
- /** c1541.inspect: a found read also returns the file's bytes. */
67
+ /** c1541.inspect: a found read also returns the file's bytes, and sectors the blocks, 256 bytes each. */
65
68
  export async function inspectDisk(request: InspectDiskRequest, options: ToolCallOptions = {}): Promise<C1541Result & { data?: Buffer }> {
66
69
  const file = readProjectFile(request.image);
67
70
  if (!(DISK_IMAGE_TYPES as readonly string[]).includes(file.type)) {
@@ -69,8 +72,10 @@ export async function inspectDisk(request: InspectDiskRequest, options: ToolCall
69
72
  }
70
73
  const params: ToolOperations["c1541.inspect"]["params"] = { action: request.action, imageType: file.type as DiskImageType };
71
74
  if (request.name !== undefined) params.name = request.name;
75
+ if (request.sectors !== undefined) params.sectors = request.sectors;
76
+ if (request.unreferenced !== undefined) params.unreferenced = request.unreferenced;
72
77
  const { result, attachments } = await callTool("c1541.inspect", params, [file.bytes], options);
73
- return result.action === "read" && result.found ? { ...result, data: attachments[0]! } : result;
78
+ return (result.action === "read" && result.found) || result.action === "sectors" ? { ...result, data: attachments[0]! } : result;
74
79
  }
75
80
 
76
81
  /** petcat.decode: the C64 BASIC V2 listing of a project program and its machine-code handoffs. Refuses a file that is no PRG as readPrg does. */
@@ -86,6 +91,6 @@ export async function hostTools(options: ToolCallOptions = {}): Promise<{ host:
86
91
 
87
92
  /** Skill scripts see failures and wire limits through the host-client, never the private protocol module. */
88
93
  export { WireFailure } from "../protocol/messages.ts";
89
- export { DISK_ACTIONS, DISK_IMAGE_TYPES } from "../protocol/tools.ts";
94
+ export { DISK_ACTIONS, DISK_BLOCK_BYTES, DISK_IMAGE_TYPES, MAX_DISK_SECTORS } from "../protocol/tools.ts";
90
95
  export { JOYSTICK_DIRECTIONS, MAX_BASELINES, MAX_EXECUTION_COUNT, MAX_KEYBOARD_BYTES, MAX_MASK_RECTANGLES, MAX_MEMORY_READ, MAX_MEMORY_WRITE, MAX_TIMEOUT_FRAMES, maskCoversFrame } from "../protocol/vice.ts";
91
96
  export { MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, type TraceHit, type TraceKind } from "../protocol/vice.ts";
@@ -3,9 +3,9 @@
3
3
 
4
4
  import { createHash } from "node:crypto";
5
5
  import { lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
6
- import { dirname, extname, join, relative, sep } from "node:path";
6
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
 
8
- import { checkOutputPath, isInside, projectRoot, resolveProject, resolveProjectFile, writeProblem } from "../project.ts";
8
+ import { checkOutputPath, isInside, projectRoot, readGroup, resolveProject, resolveProjectFile, resolveReadFile, writeProblem } from "../project.ts";
9
9
  import { isRefusal } from "../errors.ts";
10
10
  import { MAX_ATTACHMENT_BYTES } from "../protocol/framing.ts";
11
11
  import { WireFailure } from "../protocol/messages.ts";
@@ -45,13 +45,14 @@ export function readProjectFile(path: string, options: { root?: string; what?: s
45
45
  const root = options.root ?? currentProject();
46
46
  let real: string;
47
47
  try {
48
- real = resolveProjectFile(path, root);
48
+ real = resolveReadFile(path, root);
49
49
  } catch (error) {
50
50
  if ((error as NodeJS.ErrnoException).code === "ENOENT") {
51
51
  throw new WireFailure("not-found", `${options.what === undefined ? "" : `${options.what}: `}There is no file at ${path} in the project folder.`);
52
52
  }
53
53
  if (isRefusal(error) && error.code === "invalid-input") {
54
- throw new WireFailure("invalid-input", `${options.what ?? path}: give a path relative to the project folder that stays inside it, not ${path}.`);
54
+ const where = readGroup(root) === undefined ? "it" : "its group folder";
55
+ throw new WireFailure("invalid-input", `${options.what ?? path}: give a path relative to the project folder that stays inside ${where}, not ${path}.`);
55
56
  }
56
57
  throw error;
57
58
  }
@@ -178,3 +179,56 @@ export function readProjectTree(path: string, options: { root?: string } = {}):
178
179
  walk(sourceRoot, sourceRoot, new Set([sourceRoot]));
179
180
  return { files, contents };
180
181
  }
182
+
183
+ /** A path from `from` to `to`, with /. */
184
+ const posixRelative = (from: string, to: string) => relative(from, to).split(sep).join("/");
185
+
186
+ /**
187
+ * Reads a source root and its include folders as one source tree for
188
+ * staging, as readProjectTree does. An include folder is relative to the
189
+ * source root and can be anywhere in the project folder. The tree starts at
190
+ * the lowest folder that holds all these folders, but it holds only their
191
+ * files. `sourceDir` is the source root in the tree, "" at its top, and
192
+ * `includeDirs` are the include folders relative to the source root.
193
+ */
194
+ export function readSourceTree(sourceRoot: string, includes: readonly string[], options: { root?: string } = {}): { files: SourceTree; contents: Buffer[]; sourceDir: string; includeDirs: string[] } {
195
+ const projectRootPath = options.root ?? currentProject();
196
+ const sourceTree = readProjectTree(sourceRoot, { root: projectRootPath });
197
+ const project = realpathSync(projectRootPath);
198
+ const source = resolveProjectFile(sourceRoot, projectRootPath);
199
+ const missing = (folder: string) => new WireFailure("not-found", `There is no include folder ${folder} with files in the project folder. Give an include folder relative to the source root, inside the project folder.`);
200
+ const folders = includes.map((folder) => {
201
+ const outside = new WireFailure("invalid-input", `The include folder ${folder} is outside the project folder. Give an include folder relative to the source root, inside the project folder.`);
202
+ if (isAbsolute(folder)) throw outside;
203
+ const candidate = resolve(source, folder);
204
+ if (!isInside(project, candidate)) throw outside;
205
+ let real: string;
206
+ try {
207
+ real = realpathSync(candidate);
208
+ } catch {
209
+ throw missing(folder);
210
+ }
211
+ if (!isInside(project, real)) throw outside;
212
+ if (!statSync(real).isDirectory()) throw missing(folder);
213
+ return { folder, real };
214
+ });
215
+ let top = source;
216
+ for (const { real } of folders) while (!isInside(top, real)) top = dirname(top);
217
+ // Each folder is read once: a folder inside another comes with the files of that folder.
218
+ const roots = [...new Set([source, ...folders.map(({ real }) => real)])];
219
+ const files: SourceTree = [];
220
+ const contents: Buffer[] = [];
221
+ for (const root of roots.filter((root) => !roots.some((other) => other !== root && isInside(other, root)))) {
222
+ const tree = root === source ? sourceTree : readProjectTree(posixRelative(project, root) || ".", { root: project });
223
+ const prefix = posixRelative(top, root);
224
+ files.push(...tree.files.map((file) => ({ ...file, path: prefix === "" ? file.path : `${prefix}/${file.path}` })));
225
+ contents.push(...tree.contents);
226
+ }
227
+ if (files.length > MAX_TREE_FILES) throw new WireFailure("limit-exceeded", `The source root and the include folders have more than ${MAX_TREE_FILES} files.`);
228
+ if (files.reduce((total, file) => total + file.size, 0) > MAX_ATTACHMENT_BYTES) throw new WireFailure("limit-exceeded", `The source root and the include folders hold more than ${MAX_ATTACHMENT_BYTES} bytes.`);
229
+ for (const { folder, real } of folders) {
230
+ const inside = posixRelative(top, real);
231
+ if (!files.some((file) => inside === "" || file.path.startsWith(`${inside}/`))) throw missing(folder);
232
+ }
233
+ return { files, contents, sourceDir: posixRelative(top, source), includeDirs: folders.map(({ real }) => posixRelative(source, real) || ".") };
234
+ }
@@ -2,7 +2,7 @@
2
2
  // one VICE. Exposes C64-domain operations only.
3
3
 
4
4
  import { ProtocolError, WireFailure, type VideoStandard } from "../protocol/messages.ts";
5
- import { MAX_MEMORY_READ, validateViceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
5
+ import { MAX_MEMORY_READ, traceHitsFromAttachment, validateViceResult, type TraceResult, type Breakpoint, type BreakpointParams, type PointRemoved, type Watchpoint, type WatchpointParams, type ExecutionParams, type ExecutionResult, type JoystickState, type MachineStatus, type MemmapRange, type MemoryWriteParams, type ProfileEntry, type RegisterValues, type ResetMode, type RunState, type RunTarget, type RunUntilResult, type MemoryReadParams, type MemoryReadResult, type Registers, type Space, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
6
6
  import { HostConnection } from "./connect.ts";
7
7
  import { readProjectFile } from "./transfer.ts";
8
8
 
@@ -179,8 +179,15 @@ export class ViceSessionClient {
179
179
  }
180
180
 
181
181
  /** Records each hit of the points while the program runs on. */
182
- trace(params: ViceOperations["trace"]["params"]): Promise<ViceOperations["trace"]["result"]> {
183
- return this.#request("trace", params);
182
+ async trace(params: ViceOperations["trace"]["params"]): Promise<TraceResult> {
183
+ const { result, attachments } = await this.#requestWithAttachments("trace", params);
184
+ try {
185
+ return { ...result, hits: traceHitsFromAttachment(attachments, result.hits) };
186
+ } catch (error) {
187
+ if (!(error instanceof ProtocolError)) throw error;
188
+ this.#fail();
189
+ throw new WireFailure("operation-failed", "The c64-re-tools host runtime sent an invalid reply.");
190
+ }
184
191
  }
185
192
 
186
193
  backtrace(params: ViceOperations["backtrace"]["params"]): Promise<ViceOperations["backtrace"]["result"]> {
@@ -30,7 +30,7 @@ import {
30
30
  type RegionRow,
31
31
  type SymbolRow,
32
32
  } from "./read.ts";
33
- import { ANALYZERS, CODE_REGION_TYPES, DEFAULT_SPACE, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type Analyzer, type Origin, type ReferenceKind, type RegionType, type Space, type SymbolKind } from "./schema.ts";
33
+ import { ANALYZERS, CODE_REGION_TYPES, DEFAULT_SPACE, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SEMANTIC_ORIGINS, SYMBOL_KINDS, type Analyzer, type Origin, type ReferenceKind, type RegionType, type Space, type SymbolKind } from "./schema.ts";
34
34
  import { Change, checkAddress, checkSpace, subtract, SYMBOL_NAME, type Evidence } from "./write.ts";
35
35
 
36
36
 
@@ -107,7 +107,10 @@ export interface ImportResult {
107
107
  /** The analyzer's own rows from an older version that the run closed in symbols: only `retired` counts. */
108
108
  symbols: ImportCounts;
109
109
  regions: ImportCounts;
110
- references: ImportCounts;
110
+ references: ImportCounts & {
111
+ /** Findings from an address in a data region of the user, the LLM or a heuristic: false code, not written. */
112
+ inData: number;
113
+ };
111
114
  conflicts: ImportConflict[];
112
115
  }
113
116
 
@@ -429,15 +432,35 @@ function keepPiece(desired: Map<string, { start: number; end: number; type: Regi
429
432
  desired.set(`${joined.start}-${joined.end}`, joined);
430
433
  }
431
434
 
435
+ /** Origins whose data regions are not code: an analyzer reference from there is false code. */
436
+ const DATA_HOLDS_NO_REFERENCES = new Set<Origin>([...SEMANTIC_ORIGINS, "heuristic"]);
437
+
438
+ /** True for an address in a data region of the user, the LLM or a heuristic, other than the analyzer itself; dual-use bytes are also code. */
439
+ function inDataRegion(db: DatabaseSync, analyzer: Analyzer, coverage: AddressRange[], space: Space): (address: number) => boolean {
440
+ const data = coverage
441
+ .flatMap((range) => regionsOverlapping(db, range.start, range.end, space))
442
+ .filter((row) => row.origin !== analyzer && DATA_HOLDS_NO_REFERENCES.has(row.origin) && !isCode(row.type) && row.type !== "dual-use");
443
+ return (address) => data.some((row) => row.start <= address && address <= row.end);
444
+ }
445
+
446
+ /**
447
+ * References replace the analyzer's own in its coverage. A reference from a
448
+ * data region of the user, the LLM or a heuristic comes from bytes that the
449
+ * analyzer decoded as code by mistake: it is not imported, and the analyzer's
450
+ * own reference from there closes.
451
+ */
432
452
  function importReferences(db: DatabaseSync, change: Change, findings: NormalizedFindings, coverage: AddressRange[], result: ImportResult): void {
433
453
  const { analyzer } = findings;
434
454
  const space = findings.space ?? DEFAULT_SPACE;
435
455
  const key = (reference: { from: number; to: number; kind: ReferenceKind }) => `${reference.from}|${reference.to}|${reference.kind}`;
436
- const wanted = new Map(findings.references.map((reference) => [key(reference), reference]));
456
+ const inData = inDataRegion(db, analyzer, coverage, space);
457
+ const kept = findings.references.filter((reference) => !inData(reference.from));
458
+ result.references.inData = findings.references.length - kept.length;
459
+ const wanted = new Map(kept.map((reference) => [key(reference), reference]));
437
460
  for (const range of coverage) {
438
461
  for (const own of ownReferences(db, analyzer, range, space)) {
439
462
  if (wanted.has(key(own))) continue;
440
- if (!findings.authoritative.references) continue;
463
+ if (!findings.authoritative.references && !inData(own.from)) continue;
441
464
  change.close('"references"', "space = ? AND from_address = ? AND to_address = ? AND kind = ? AND origin = ?", space, own.from, own.to, own.kind, analyzer);
442
465
  result.references.retired++;
443
466
  }
@@ -460,7 +483,7 @@ export function importFindings(db: DatabaseSync, findings: NormalizedFindings, c
460
483
  const coverage = validateFindings(findings);
461
484
  return transaction(db, () => {
462
485
  const change = new Change(db, { origin: findings.analyzer, ...context }, `import-${findings.analyzer}`);
463
- const result: ImportResult = { revision: null, names: counts(), symbols: counts(), regions: counts(), references: counts(), conflicts: [] };
486
+ const result: ImportResult = { revision: null, names: counts(), symbols: counts(), regions: counts(), references: { ...counts(), inData: 0 }, conflicts: [] };
464
487
  importNames(db, change, findings, coverage, result);
465
488
  importRegions(db, change, findings, coverage, result);
466
489
  importReferences(db, change, findings, coverage, result);
@@ -509,6 +509,10 @@ function classifyStep(db: DatabaseSync, change: Change, origin: Origin, request:
509
509
  clearRange(db, change, request.start, request.end, space);
510
510
  change.insertRegion({ space, start: request.start, end: request.end, type: request.type, ...(request.element === undefined ? {} : { element: request.element }), origin });
511
511
  liftRegionSuppressions(db, change, request.start, request.end, space);
512
+ // Data is not code: an analyzer reference from there is false code. dual-use bytes are also code.
513
+ if (!CODE_REGION_TYPES.includes(request.type) && request.type !== "dual-use") {
514
+ change.close('"references"', "space = ? AND from_address BETWEEN ? AND ? AND origin NOT IN ('user', 'llm')", space, request.start, request.end);
515
+ }
512
516
  const previous = overlapping.filter((row) => row.origin !== origin);
513
517
  const current = regionsOverlapping(db, request.start, request.end, space);
514
518
  return previous.length === 0 ? { current } : { current, previous };
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
+ }