@henols/c64-re-tools 2.8.0-rc.2 → 2.8.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 (119) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +5 -2
  3. package/skills/c64-assembler/scripts/assembler.ts +55 -48
  4. package/skills/c64-disk/scripts/disk.ts +3 -3
  5. package/skills/c64-disk/scripts/lib/containers.ts +2 -2
  6. package/skills/c64-docs/SKILL.md +1 -1
  7. package/skills/c64-docs/scripts/docs.ts +12 -20
  8. package/skills/c64-docs/scripts/lib/links.ts +1 -1
  9. package/skills/c64-docs/scripts/lib/markdown.ts +1 -1
  10. package/skills/c64-docs/scripts/lib/reference.ts +59 -13
  11. package/skills/c64-knowledge/SKILL.md +17 -8
  12. package/skills/c64-knowledge/scripts/knowledge.ts +200 -218
  13. package/skills/c64-knowledge/scripts/lib/check.ts +2 -3
  14. package/skills/c64-knowledge/scripts/lib/listing.ts +56 -24
  15. package/skills/c64-packer/scripts/packer.ts +3 -3
  16. package/skills/c64-provenance/SKILL.md +25 -16
  17. package/skills/c64-provenance/scripts/lib/compare.ts +31 -21
  18. package/skills/c64-provenance/scripts/lib/leftovers.ts +17 -35
  19. package/skills/c64-provenance/scripts/lib/library.ts +10 -10
  20. package/skills/c64-provenance/scripts/lib/runtime.ts +3 -14
  21. package/skills/c64-provenance/scripts/provenance.ts +129 -98
  22. package/skills/c64-source/references/loader.md +2 -1
  23. package/skills/c64-source/scripts/lib/export.ts +54 -303
  24. package/skills/c64-source/scripts/lib/loader.ts +31 -51
  25. package/skills/c64-source/scripts/lib/source.ts +51 -41
  26. package/skills/c64-source/scripts/lib/stage.ts +9 -25
  27. package/skills/c64-source/scripts/source.ts +134 -294
  28. package/skills/c64-static-analysis/SKILL.md +12 -7
  29. package/skills/c64-static-analysis/scripts/lib/coverage.ts +1 -3
  30. package/skills/c64-static-analysis/scripts/lib/findings.ts +16 -3
  31. package/skills/c64-static-analysis/scripts/lib/idioms.ts +82 -10
  32. package/skills/c64-static-analysis/scripts/lib/triage.ts +112 -0
  33. package/skills/c64-static-analysis/scripts/static-analysis.ts +239 -147
  34. package/skills/c64-testing/SKILL.md +13 -7
  35. package/skills/c64-testing/scripts/lib/diff-files.ts +6 -13
  36. package/skills/c64-testing/scripts/lib/recording.ts +47 -66
  37. package/skills/c64-testing/scripts/lib/replay.ts +53 -9
  38. package/skills/c64-testing/scripts/lib/runs.ts +11 -29
  39. package/skills/c64-testing/scripts/lib/scenario.ts +30 -31
  40. package/skills/c64-testing/scripts/lib/start-screen.ts +42 -5
  41. package/skills/c64-testing/scripts/testing.ts +32 -7
  42. package/skills/c64-unpacker/SKILL.md +10 -7
  43. package/skills/c64-unpacker/scripts/lib/evidence.ts +23 -38
  44. package/skills/c64-unpacker/scripts/lib/loads.ts +24 -39
  45. package/skills/c64-unpacker/scripts/lib/machine.ts +38 -18
  46. package/skills/c64-unpacker/scripts/lib/stages.ts +142 -41
  47. package/skills/c64-unpacker/scripts/unpacker.ts +85 -68
  48. package/skills/emulator/SKILL.md +1 -0
  49. package/src/c64.ts +117 -10
  50. package/src/cli/ap-sdk.ts +1 -1
  51. package/src/cli/cleanup.ts +4 -2
  52. package/src/compare.ts +36 -16
  53. package/src/errors.ts +10 -1
  54. package/src/host/main.ts +2 -1
  55. package/src/host/server.ts +7 -11
  56. package/src/host/tools/c1541.ts +9 -3
  57. package/src/host/vice/adapter.ts +20 -43
  58. package/src/host/vice/binary-monitor.ts +22 -21
  59. package/src/host/vice/process.ts +31 -40
  60. package/src/host/vice/session.ts +187 -247
  61. package/src/host/vice/text-monitor.ts +3 -3
  62. package/src/host-client/autostart.ts +1 -1
  63. package/src/host-client/connect.ts +2 -1
  64. package/src/host-client/coverage.ts +0 -3
  65. package/src/host-client/entry-state.ts +4 -11
  66. package/src/host-client/image.ts +6 -11
  67. package/src/host-client/steps.ts +13 -113
  68. package/src/host-client/tools.ts +4 -4
  69. package/src/host-client/transfer.ts +10 -0
  70. package/src/host-client/vice-session.ts +10 -6
  71. package/src/knowledge/code-reach.ts +364 -0
  72. package/src/knowledge/conflicts.ts +34 -72
  73. package/src/knowledge/database.ts +40 -28
  74. package/src/knowledge/evidence.ts +2 -2
  75. package/src/knowledge/graph.ts +3 -3
  76. package/src/knowledge/history.ts +50 -90
  77. package/src/knowledge/import.ts +43 -71
  78. package/src/knowledge/join.ts +1 -1
  79. package/src/knowledge/names.ts +12 -7
  80. package/src/knowledge/program.ts +25 -46
  81. package/src/knowledge/read.ts +104 -100
  82. package/src/knowledge/schema.ts +9 -3
  83. package/src/knowledge/separate.ts +47 -19
  84. package/src/knowledge/start-screen.ts +7 -5
  85. package/src/knowledge/text.ts +56 -33
  86. package/src/knowledge/write.ts +274 -515
  87. package/src/loader.ts +7 -25
  88. package/src/mcp/inputs.ts +3 -3
  89. package/src/mcp/server.ts +19 -38
  90. package/src/mcp/session-source.ts +2 -1
  91. package/src/mcp/tools/debug.ts +97 -24
  92. package/src/mcp/tools/execution.ts +1 -1
  93. package/src/mcp/tools/input.ts +3 -3
  94. package/src/mcp/tools/machine.ts +3 -3
  95. package/src/mcp/tools/media.ts +4 -4
  96. package/src/mcp/tools/memory.ts +13 -17
  97. package/src/mcp/tools/video.ts +11 -25
  98. package/src/native/acme.ts +3 -3
  99. package/src/native/c64run.ts +2 -1
  100. package/src/native/decompiler/analyze.ts +10 -7
  101. package/src/native/decompiler/walk.ts +3 -4
  102. package/src/native/decompiler/wasm.ts +2 -2
  103. package/src/native/discover.ts +1 -1
  104. package/src/native/dxa.ts +9 -11
  105. package/src/native/exomizer.ts +1 -1
  106. package/src/native/processes.ts +4 -1
  107. package/src/native/run.ts +3 -3
  108. package/src/native/types.ts +5 -6
  109. package/src/opcodes.ts +3 -0
  110. package/src/platform.ts +9 -10
  111. package/src/program-code.ts +151 -0
  112. package/src/project.ts +8 -5
  113. package/src/protocol/framing.ts +51 -18
  114. package/src/protocol/messages.ts +1 -11
  115. package/src/protocol/tools.ts +0 -3
  116. package/src/protocol/vice.ts +588 -773
  117. package/src/script.ts +9 -14
  118. package/src/time.ts +1 -1
  119. package/src/trace.ts +3 -2
package/src/loader.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  // loaded ranges are the segments of the program without the leftovers: a
8
8
  // leftover file of the source gives its range in its first line.
9
9
 
10
- import { type AddressRange, formatC64Address, prgRange } from "./c64.ts";
10
+ import { type AddressRange, formatC64Address, formatC64Range, prgOf, prgRange, subtract } from "./c64.ts";
11
11
  import { compareBuild, mergedPrograms } from "./compare.ts";
12
12
  import { Refusal } from "./errors.ts";
13
13
  import { pack } from "./native/exomizer.ts";
@@ -18,7 +18,7 @@ import type { AssembledSymbol } from "./native/types.ts";
18
18
  export const COPIER_SOURCE = "loader_copier_src";
19
19
 
20
20
  /** The memory configuration at the start of the copier of the packed form: all RAM visible. */
21
- export const PACKED_EXIT_MEMORY = 0x34;
21
+ const PACKED_EXIT_MEMORY = 0x34;
22
22
 
23
23
  /** The pages that the unpacker of Exomizer uses: the copier of the packed form writes them, so main.asm is packed from here. */
24
24
  const PACKED_FROM = 0x0400;
@@ -32,23 +32,6 @@ export function leftoverRange(text: string): AddressRange | undefined {
32
32
  return found === null ? undefined : { start: Number.parseInt(found[1]!.slice(1), 16), end: Number.parseInt(found[2]!.slice(1), 16) };
33
33
  }
34
34
 
35
- const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
36
-
37
- /** The parts of `range` outside every hole, in address order. */
38
- function without(range: AddressRange, holes: readonly AddressRange[]): AddressRange[] {
39
- let pieces = [range];
40
- for (const hole of holes) {
41
- pieces = pieces.flatMap((piece) => {
42
- if (hole.end < piece.start || hole.start > piece.end) return [piece];
43
- return [
44
- ...(hole.start > piece.start ? [{ start: piece.start, end: hole.start - 1 }] : []),
45
- ...(hole.end < piece.end ? [{ start: hole.end + 1, end: piece.end }] : []),
46
- ];
47
- });
48
- }
49
- return pieces;
50
- }
51
-
52
35
  /**
53
36
  * The ranges that the packed loader loads from a build of main.asm: the
54
37
  * segments of the program without the leftovers. Refuses what only the loader
@@ -60,10 +43,10 @@ export function packedRanges(segments: readonly AddressRange[], leftovers: reado
60
43
  if (stage !== undefined) {
61
44
  throw new Refusal("invalid-input", `The start screen is of the captured stage ${stage}, and only the generation of the source with the loader makes that loader program. Set the switch values in config.asm, and generate the source with the loader.`);
62
45
  }
63
- const loaded = [...segments].sort((a, b) => a.start - b.start).flatMap((segment) => without(segment, leftovers));
46
+ const loaded = [...segments].sort((a, b) => a.start - b.start).flatMap((segment) => subtract(segment, leftovers));
64
47
  const low = loaded.find((range) => range.start < PACKED_FROM);
65
48
  if (low !== undefined) {
66
- throw new Refusal("invalid-input", `The segment ${show(low)} starts below $0400, and loader.asm holds its bytes there with the switch values of generate. Set the switch values in config.asm, and generate the source with the loader.`);
49
+ throw new Refusal("invalid-input", `The segment ${formatC64Range(low)} starts below $0400, and loader.asm holds its bytes there with the switch values of generate. Set the switch values in config.asm, and generate the source with the loader.`);
67
50
  }
68
51
  return loaded;
69
52
  }
@@ -79,7 +62,7 @@ export function checkPackedBuilds(main: Uint8Array, copier: Uint8Array, loaded:
79
62
  const program = prgRange(main);
80
63
  const outside = loaded.find((range) => range.start < program.start || range.end > program.end);
81
64
  if (outside !== undefined) {
82
- throw new Refusal("invalid-input", `The build of main.asm does not hold ${show(outside)} of the program in the knowledge. Generate the source again from the knowledge.`);
65
+ throw new Refusal("invalid-input", `The build of main.asm does not hold ${formatC64Range(outside)} of the program in the knowledge. Generate the source again from the knowledge.`);
83
66
  }
84
67
  const build = prgRange(copier);
85
68
  for (const range of loaded) {
@@ -87,7 +70,7 @@ export function checkPackedBuilds(main: Uint8Array, copier: Uint8Array, loaded:
87
70
  if (build.body[address - build.start] === program.body[address - program.start]) continue;
88
71
  throw new Refusal(
89
72
  "invalid-input",
90
- `These switch values change the byte at ${formatC64Address(address)}, between the free ranges of loader.asm (${show(build)}), and loader.asm holds the byte of generate there. Set the switch values in config.asm, and generate the source with the loader.`,
73
+ `These switch values change the byte at ${formatC64Address(address)}, between the free ranges of loader.asm (${formatC64Range(build)}), and loader.asm holds the byte of generate there. Set the switch values in config.asm, and generate the source with the loader.`,
91
74
  );
92
75
  }
93
76
  }
@@ -133,8 +116,7 @@ function packedParts(main: Uint8Array, copier: Uint8Array, loaded: readonly Addr
133
116
  * to the entry. Refuses by name when it does not hold.
134
117
  */
135
118
  export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint8Array }>, entry: number, exitMemory: number, what: string, entryName: string, context: ToolContext): Promise<PackedLoader> {
136
- const prg = (part: { start: number; body: Uint8Array }) => Buffer.concat([Buffer.from([part.start & 0xff, part.start >> 8]), part.body]);
137
- const packed = await pack({ programs: parts.map(prg), entry, exitMemory }, context);
119
+ const packed = await pack({ programs: parts.map((part) => prgOf(part.start, part.body)), entry, exitMemory }, context);
138
120
  if (packed.entry !== entry) throw new Refusal("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to ${entryName} at ${formatC64Address(entry)}.`);
139
121
  const reference = mergedPrograms(parts);
140
122
  const wrong = compareBuild(packed.unpacked, reference).segments.find((segment) => segment.result !== "identical");
package/src/mcp/inputs.ts CHANGED
@@ -7,15 +7,15 @@ import { z } from "zod";
7
7
 
8
8
  import { c64AddressOf } from "../c64.ts";
9
9
  import { keyTaps, MAX_PRESS_FRAMES, PRESS_FRAMES } from "../c64-keys.ts";
10
- import { DEFAULT_TIMEOUT_FRAMES, keyboardBytes, MAX_RASTER_LINE } from "../host-client/steps.ts";
10
+ import { DEFAULT_TIMEOUT_FRAMES, HEX_BYTES, HEX_BYTES_RULE, keyboardBytes, MAX_RASTER_LINE } from "../host-client/steps.ts";
11
11
  import { COMPARISONS, CONDITION_REGISTERS, JOYSTICK_DIRECTIONS, MAX_KEYBOARD_BYTES, MAX_MEMORY_WRITE, MAX_TIMEOUT_FRAMES, MEMORY_VIEWS, SPACES } from "../protocol/vice.ts";
12
12
 
13
13
  export const Byte = z.number().int().min(0).max(255);
14
14
 
15
15
  /** Input bytes: hex in either case, two digits per byte, at least one byte. Parses to lowercase. */
16
- export const HexDataInput = z
16
+ const HexDataInput = z
17
17
  .string()
18
- .regex(/^(?:[0-9a-fA-F]{2})+$/, "must be hex bytes, two digits per byte, no separators, for example a9008d20d0")
18
+ .regex(HEX_BYTES, HEX_BYTES_RULE)
19
19
  .transform((value) => value.toLowerCase());
20
20
 
21
21
  export const SpaceInput = z.enum(SPACES).default("c64").describe("c64 is the computer. drive8 is the 1541 disk drive CPU");
package/src/mcp/server.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  // MCP server creation, tool registration and the one place where failures
2
2
  // become MCP results. Tool groups live in tools/; nothing here knows VICE.
3
3
 
4
- import { createRequire } from "node:module";
5
-
6
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
5
  import { CallToolRequestSchema, ListToolsRequestSchema, type CallToolResult, type Tool as McpTool } from "@modelcontextprotocol/sdk/types.js";
8
6
  import { z } from "zod";
@@ -11,7 +9,8 @@ import { formatC64Address } from "../c64.ts";
11
9
  import { Byte, TOOL_INPUTS } from "./inputs.ts";
12
10
  import { LostBeforeAnswer, type ViceSessionClient } from "../host-client/vice-session.ts";
13
11
  import { checkOut } from "../host-client/transfer.ts";
14
- import { isRefusal } from "../errors.ts";
12
+ import { describeErrorStack, isRefusal } from "../errors.ts";
13
+ import { PACKAGE } from "../package.ts";
15
14
  import { shownMessage, WireFailure, type WireError } from "../protocol/messages.ts";
16
15
  import { COMPARISONS, CONDITION_REGISTERS, MEMORY_VIEWS, SPACES, type Condition } from "../protocol/vice.ts";
17
16
  import { elapsedMs, trace, type TraceFields } from "../trace.ts";
@@ -159,7 +158,7 @@ function jsonSchema(schema: z.ZodObject, io: "input" | "output"): McpTool["input
159
158
  return rest as McpTool["inputSchema"];
160
159
  }
161
160
 
162
- export function toolListing(tool: ToolDefinition): McpTool {
161
+ function toolListing(tool: ToolDefinition): McpTool {
163
162
  return {
164
163
  name: tool.name,
165
164
  title: tool.title,
@@ -204,21 +203,11 @@ export async function callTool(
204
203
  log: (line: string) => void = () => {},
205
204
  ): Promise<CallToolResult> {
206
205
  const started = performance.now();
207
- const result = await runCall(tools, name, args, session, log);
208
- trace().event("tool.call", { name, args, ms: elapsedMs(started), ...outcome(result) });
209
- return result;
210
- }
211
-
212
- /** What the trace records of a result: the structured result, or the code and message of the error. */
213
- function outcome(result: CallToolResult): TraceFields {
214
- if (result.isError !== true) return { ok: true, result: result.structuredContent };
215
- const first = result.content[0];
216
- const text = first?.type === "text" ? first.text : "";
217
- try {
218
- return { ok: false, ...(JSON.parse(text) as { error: WireError }).error };
219
- } catch {
220
- return { ok: false, message: text };
221
- }
206
+ const done = await runCall(tools, name, args, session, log);
207
+ // The trace records the structured result, or the code and message of the error.
208
+ const outcome: TraceFields = "failed" in done ? { ok: false, code: done.failed.code, message: shownMessage(done.failed) } : { ok: true, result: done.result.structuredContent };
209
+ trace().event("tool.call", { name, args, ms: elapsedMs(started), ...outcome });
210
+ return "failed" in done ? errorResult(done.failed) : done.result;
222
211
  }
223
212
 
224
213
  async function runCall(
@@ -227,11 +216,11 @@ async function runCall(
227
216
  args: unknown,
228
217
  session: SessionSource,
229
218
  log: (line: string) => void,
230
- ): Promise<CallToolResult> {
219
+ ): Promise<{ result: CallToolResult } | { failed: WireError }> {
231
220
  const tool = tools.get(name);
232
- if (tool === undefined) return errorResult({ code: "invalid-input", message: `There is no tool named ${name}.` });
221
+ if (tool === undefined) return { failed: { code: "invalid-input", message: `There is no tool named ${name}.` } };
233
222
  const parsed = tool.inputSchema.safeParse(args ?? {});
234
- if (!parsed.success) return errorResult({ code: "invalid-input", message: describeIssues(parsed.error, tool.inputSchema) });
223
+ if (!parsed.success) return { failed: { code: "invalid-input", message: describeIssues(parsed.error, tool.inputSchema) } };
235
224
  try {
236
225
  // An out path is checked before the tool runs: a refused path must not lose the work or leave its side effects.
237
226
  const fields = parsed.data as { out?: unknown; project?: unknown };
@@ -250,25 +239,16 @@ async function runCall(
250
239
  const checked = tool.outputSchema.safeParse(output instanceof ToolOutput ? output.structured : output);
251
240
  if (!checked.success) {
252
241
  log(`${name} gave a result outside its output schema: ${describeIssues(checked.error)}`);
253
- return errorResult(INTERNAL_FAILURE);
242
+ return { failed: INTERNAL_FAILURE };
254
243
  }
255
244
  const result = checked.data as JsonObject;
256
245
  const extra = output instanceof ToolOutput ? output.content : [];
257
- return { content: [{ type: "text", text: JSON.stringify(result) }, ...extra], structuredContent: result };
246
+ return { result: { content: [{ type: "text", text: JSON.stringify(result) }, ...extra], structuredContent: result } };
258
247
  } catch (error) {
259
- if (isRefusal(error)) return errorResult({ code: error.code, message: error.message });
260
- log(`${name} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);
261
- return errorResult(INTERNAL_FAILURE);
262
- }
263
- }
264
-
265
- /** The version of this package. A package.json without a version is a broken installation. */
266
- function packageVersion(): string {
267
- const { version } = createRequire(import.meta.url)("../../package.json") as { version?: unknown };
268
- if (typeof version !== "string" || version === "") {
269
- throw new Error("The package.json of c64-re-tools has no version. Install c64-re-tools again.");
248
+ if (isRefusal(error)) return { failed: { code: error.code, message: error.message } };
249
+ log(`${name} failed: ${describeErrorStack(error)}`);
250
+ return { failed: INTERNAL_FAILURE };
270
251
  }
271
- return version;
272
252
  }
273
253
 
274
254
  const INSTRUCTIONS =
@@ -287,10 +267,11 @@ const INSTRUCTIONS =
287
267
  export function createMcpServer(options: { tools: readonly ToolDefinition[]; session: SessionSource; log?: (line: string) => void }): Server {
288
268
  const tools = new Map(options.tools.map((tool) => [tool.name, tool]));
289
269
  const server = new Server(
290
- { name: "c64-re-tools", version: packageVersion() },
270
+ { name: "c64-re-tools", version: PACKAGE.version },
291
271
  { capabilities: { tools: {} }, instructions: INSTRUCTIONS },
292
272
  );
293
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: options.tools.map(toolListing) }));
273
+ const listing = options.tools.map(toolListing);
274
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: listing }));
294
275
  server.setRequestHandler(CallToolRequestSchema, async (request) =>
295
276
  callTool(tools, request.params.name, request.params.arguments, options.session, options.log),
296
277
  );
@@ -1,6 +1,7 @@
1
1
  // The C64 session of the MCP server: one at a time, opened again after a loss.
2
2
 
3
3
  import type { ViceSessionClient } from "../host-client/vice-session.ts";
4
+ import { describeError } from "../errors.ts";
4
5
  import { WireFailure } from "../protocol/messages.ts";
5
6
  import { elapsedMs, trace } from "../trace.ts";
6
7
  import type { SessionSource } from "./server.ts";
@@ -32,7 +33,7 @@ export function sessionSource(openClient: (signal: AbortSignal) => Promise<ViceS
32
33
  () => {},
33
34
  );
34
35
  current.catch((error: unknown) => {
35
- log(`session not opened: ${error instanceof Error ? error.message : String(error)}`);
36
+ log(`session not opened: ${describeError(error)}`);
36
37
  if (opening === current) opening = undefined;
37
38
  });
38
39
  return current;
@@ -3,10 +3,11 @@
3
3
 
4
4
  import { z } from "zod";
5
5
 
6
- import { COVERAGE, executedRamCode, EXECUTE, formatC64Address, READ, WRITE, type CodeRange } from "../../c64.ts";
6
+ import { COVERAGE, executedRamCode, EXECUTE, formatC64Address, formatC64RangeFields, hexByte, READ, WRITE, type CodeRange } from "../../c64.ts";
7
7
  import { WireFailure } from "../../protocol/messages.ts";
8
- import { CHECKPOINT_ACTIONS, MAX_BACKTRACE, MAX_HISTORY, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, TRACE_ENDS, MAX_MEMMAP_RANGES, MAX_MEMORY_READ, MAX_PROFILE, MAX_WATCH_SIZE, SPACES, TIMING_ACTIONS, WATCH_ACCESS, type Breakpoint, type Watchpoint } from "../../protocol/vice.ts";
8
+ import { CHECKPOINT_ACTIONS, MAX_BACKTRACE, MAX_HISTORY, MAX_TRACE_FRAMES, MAX_TRACE_HITS, MAX_TRACE_POINTS, TRACE_KINDS, TRACE_ENDS, MAX_MEMMAP_RANGES, MAX_PROFILE, MAX_WATCH_SIZE, SPACES, TIMING_ACTIONS, WATCH_ACCESS, type Breakpoint, type TraceHit, type TraceKind, type Watchpoint } from "../../protocol/vice.ts";
9
9
  import { readCoverage } from "../../host-client/coverage.ts";
10
+ import { readMemoryInParts } from "../../host-client/vice-session.ts";
10
11
  import { linesText, OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
11
12
  import { AddressInput, Byte, SpaceInput, TOOL_INPUTS } from "../inputs.ts";
12
13
  import { AddressOutput, ConditionOutput, defineTool, HexData, requireFields, requireOut, showCondition, toCondition } from "../server.ts";
@@ -33,10 +34,10 @@ function showBreakpoint(point: Breakpoint) {
33
34
 
34
35
  function showWatchpoint(point: Watchpoint) {
35
36
  const { condition, address, size, ...rest } = point;
36
- return { ...rest, start: formatC64Address(address), end: formatC64Address(address + size - 1), ...(condition === undefined ? {} : { condition: showCondition(condition) }) };
37
+ return { ...rest, ...formatC64RangeFields({ start: address, end: address + size - 1 }), ...(condition === undefined ? {} : { condition: showCondition(condition) }) };
37
38
  }
38
39
 
39
- export const c64Breakpoint = defineTool({
40
+ const c64Breakpoint = defineTool({
40
41
  name: "c64_breakpoint",
41
42
  title: "C64 breakpoints",
42
43
  description:
@@ -80,7 +81,7 @@ export const c64Breakpoint = defineTool({
80
81
  },
81
82
  });
82
83
 
83
- export const c64Watchpoint = defineTool({
84
+ const c64Watchpoint = defineTool({
84
85
  name: "c64_watchpoint",
85
86
  title: "C64 watchpoints",
86
87
  description:
@@ -132,7 +133,7 @@ export const c64Watchpoint = defineTool({
132
133
  },
133
134
  });
134
135
 
135
- export const c64CpuHistory = defineTool({
136
+ const c64CpuHistory = defineTool({
136
137
  name: "c64_cpu_history",
137
138
  title: "CPU history",
138
139
  description:
@@ -164,22 +165,89 @@ export const c64CpuHistory = defineTool({
164
165
  readOnly: false,
165
166
  async run(input, session) {
166
167
  const { out, project, ...request } = input;
167
- if (out === undefined && project !== undefined) throw new WireFailure("invalid-input", "project is used only with out.");
168
+ requireOut(input);
168
169
  const { entries } = await session.cpuHistory(request);
169
170
  if (out === undefined) return { entries: entries.map((entry) => ({ ...entry, address: formatC64Address(entry.address) })) };
170
- const byte = (value: number) => value.toString(16).padStart(2, "0");
171
171
  const lines = entries.map((entry) => {
172
172
  const raster = entry.rasterLine === undefined ? "" : ` line ${entry.rasterLine} cycle ${entry.rasterCycle ?? 0}`;
173
- return `${formatC64Address(entry.address)} ${spaced(entry.bytes).padEnd(9)} ${entry.text.padEnd(16)} a=${byte(entry.a)} x=${byte(entry.x)} y=${byte(entry.y)} sp=${byte(entry.sp)}${raster}`;
173
+ return `${formatC64Address(entry.address)} ${spaced(entry.bytes).padEnd(9)} ${entry.text.padEnd(16)} a=${hexByte(entry.a)} x=${hexByte(entry.x)} y=${hexByte(entry.y)} sp=${hexByte(entry.sp)}${raster}`;
174
174
  });
175
175
  return { count: entries.length, ...writeOut(out, linesText(lines), project) };
176
176
  },
177
177
  });
178
178
 
179
- /** The hits that a trace result gives inline; out gives all of them in the file, and none inline. */
180
- const TRACE_LISTED = 200;
179
+ /** The hits that a trace result gives inline; out gives all of them in the file, and none inline. The summary counts all hits. */
180
+ const TRACE_LISTED = 50;
181
+ /** The addresses and the pcs that the summary of a trace lists, the values of each address, and the pcs of each address. */
182
+ const SUMMARY_LISTED = 20;
183
+ const SUMMARY_VALUES = 16;
184
+ const SUMMARY_PCS = 4;
181
185
 
182
- export const c64Trace = defineTool({
186
+ /** Most hits first, then the lowest address. */
187
+ const byHits = <T extends { hits: number }>(entries: Iterable<T>, at: (entry: T) => number) => [...entries].sort((a, b) => b.hits - a.hits || at(a) - at(b));
188
+
189
+ /**
190
+ * The summary of all hits of a trace: the read and write hits of each address
191
+ * (with the kind of its point) and the hits of each pc, most hits first. An
192
+ * address gives its values from low to high and the pcs with the most hits
193
+ * there. A pc gives its instruction and the numbers of its first and last hit.
194
+ */
195
+ export function traceSummary(hits: readonly TraceHit[], kinds: readonly TraceKind[]) {
196
+ const addresses = new Map<string, { kind: TraceKind; address: number; hits: number; values: Set<number>; pcs: Map<number, number> }>();
197
+ const pcs = new Map<number, { pc: number; text: string; hits: number; firstHit: number; lastHit: number }>();
198
+ hits.forEach((hit, index) => {
199
+ const pc = pcs.get(hit.pc) ?? pcs.set(hit.pc, { pc: hit.pc, text: hit.text, hits: 0, firstHit: index, lastHit: index }).get(hit.pc)!;
200
+ pc.hits++;
201
+ pc.lastHit = index;
202
+ if (hit.address === undefined) return;
203
+ const kind = kinds[hit.point]!;
204
+ const key = `${kind} ${hit.address}`;
205
+ const address = addresses.get(key) ?? addresses.set(key, { kind, address: hit.address, hits: 0, values: new Set(), pcs: new Map() }).get(key)!;
206
+ address.hits++;
207
+ if (hit.value !== undefined) address.values.add(hit.value);
208
+ address.pcs.set(hit.pc, (address.pcs.get(hit.pc) ?? 0) + 1);
209
+ });
210
+ return {
211
+ addresses: addresses.size,
212
+ byAddress: byHits(addresses.values(), (entry) => entry.address)
213
+ .slice(0, SUMMARY_LISTED)
214
+ .map((entry) => {
215
+ const values = [...entry.values].sort((a, b) => a - b);
216
+ return {
217
+ address: formatC64Address(entry.address),
218
+ kind: entry.kind,
219
+ hits: entry.hits,
220
+ values: values.slice(0, SUMMARY_VALUES),
221
+ ...(values.length > SUMMARY_VALUES ? { moreValues: values.length - SUMMARY_VALUES } : {}),
222
+ pcs: byHits([...entry.pcs].map(([pc, count]) => ({ pc, hits: count })), (item) => item.pc)
223
+ .slice(0, SUMMARY_PCS)
224
+ .map((item) => ({ pc: formatC64Address(item.pc), hits: item.hits })),
225
+ };
226
+ }),
227
+ pcs: pcs.size,
228
+ byPc: byHits(pcs.values(), (entry) => entry.pc)
229
+ .slice(0, SUMMARY_LISTED)
230
+ .map((entry) => ({ ...entry, pc: formatC64Address(entry.pc) })),
231
+ };
232
+ }
233
+
234
+ const TraceSummaryOutput = z.object({
235
+ addresses: z.number().int().min(0),
236
+ byAddress: z.array(
237
+ z.object({
238
+ address: AddressOutput,
239
+ kind: z.enum(TRACE_KINDS),
240
+ hits: z.number().int().min(1),
241
+ values: z.array(Byte),
242
+ moreValues: z.number().int().min(1).optional(),
243
+ pcs: z.array(z.object({ pc: AddressOutput, hits: z.number().int().min(1) })),
244
+ }),
245
+ ),
246
+ pcs: z.number().int().min(0),
247
+ byPc: z.array(z.object({ pc: AddressOutput, text: z.string(), hits: z.number().int().min(1), firstHit: z.number().int().min(0), lastHit: z.number().int().min(0) })),
248
+ });
249
+
250
+ const c64Trace = defineTool({
183
251
  name: "c64_trace",
184
252
  title: "Trace accesses and instructions",
185
253
  description:
@@ -193,6 +261,11 @@ export const c64Trace = defineTool({
193
261
  "At $D000-$DFFF only a load or a store gives value: a read after the access can give another byte. " +
194
262
  `The trace ends after frames frames (1 to ${MAX_TRACE_FRAMES}), at maxHits hits (at most ${MAX_TRACE_HITS}), or at a breakpoint, a watchpoint or a JAM. ` +
195
263
  `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that project file, and the result gives no hits. ` +
264
+ "summary counts all hits, also with out. " +
265
+ `summary.byAddress gives the read and write hits of each address, most hits first, at most ${SUMMARY_LISTED}. An address with read hits and write hits has an item for each kind. ` +
266
+ `Each item gives kind, hits and values, the values from low to high, at most ${SUMMARY_VALUES}. moreValues is the number of the other values. pcs are the pcs with the most hits at the address, at most ${SUMMARY_PCS}. ` +
267
+ `summary.byPc gives the hits of each pc, most hits first, at most ${SUMMARY_LISTED}, with text. firstHit and lastHit are the numbers of its first and last hit. The first hit of the trace is 0. ` +
268
+ "summary.addresses and summary.pcs are the numbers of all different addresses and pcs. " +
196
269
  "Each hit stops the machine for a short time. Thus a point with many hits in each frame makes the trace slow. Use a small range and a maxHits. " +
197
270
  "The machine is stopped after the trace.",
198
271
  inputSchema: z
@@ -209,6 +282,7 @@ export const c64Trace = defineTool({
209
282
  frames: z.number().int().min(0),
210
283
  pc: AddressOutput,
211
284
  count: z.number().int().min(0),
285
+ summary: TraceSummaryOutput,
212
286
  hits: z
213
287
  .array(
214
288
  z.object({
@@ -233,18 +307,19 @@ export const c64Trace = defineTool({
233
307
  readOnly: false,
234
308
  async run(input, session) {
235
309
  const { out, project, points, ...request } = input;
236
- if (out === undefined && project !== undefined) throw new WireFailure("invalid-input", "project is used only with out.");
310
+ requireOut(input);
237
311
  const ranges = points.map((point) => ({ kind: point.kind, start: point.start, end: point.end ?? point.start }));
238
312
  if (ranges.some((point) => point.end < point.start)) throw new WireFailure("invalid-input", "A point end must not be before its start.");
239
313
  const traced = await session.trace({ points: ranges, ...request });
240
314
  const shown = traced.hits.map(({ address, ...hit }) => ({ ...hit, pc: formatC64Address(hit.pc), ...(address === undefined ? {} : { address: formatC64Address(address) }) }));
241
- const summary = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length };
242
- if (out === undefined) return { ...summary, hits: shown.slice(0, TRACE_LISTED) };
243
- return { ...summary, ...writeOut(out, linesText(shown.map((hit) => JSON.stringify(hit))), project) };
315
+ const head = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length };
316
+ const summary = traceSummary(traced.hits, ranges.map((point) => point.kind));
317
+ if (out === undefined) return { ...head, summary, hits: shown.slice(0, TRACE_LISTED) };
318
+ return { ...head, summary, ...writeOut(out, linesText(shown.map((hit) => JSON.stringify(hit))), project) };
244
319
  },
245
320
  });
246
321
 
247
- export const c64Backtrace = defineTool({
322
+ const c64Backtrace = defineTool({
248
323
  name: "c64_backtrace",
249
324
  title: "Call backtrace",
250
325
  description:
@@ -265,7 +340,7 @@ export const c64Backtrace = defineTool({
265
340
  },
266
341
  });
267
342
 
268
- export const c64Timing = defineTool({
343
+ const c64Timing = defineTool({
269
344
  name: "c64_timing",
270
345
  title: "Cycle stopwatch",
271
346
  description:
@@ -280,7 +355,7 @@ export const c64Timing = defineTool({
280
355
  },
281
356
  });
282
357
 
283
- export const c64Profile = defineTool({
358
+ const c64Profile = defineTool({
284
359
  name: "c64_profile",
285
360
  title: "Cycle profile",
286
361
  description:
@@ -329,9 +404,9 @@ function sources(flags: number): Array<"ram" | "rom" | "io"> {
329
404
 
330
405
  const count = (map: Uint8Array, bit: number) => map.reduce((sum, flags) => sum + ((flags & bit) === 0 ? 0 : 1), 0);
331
406
  const RangeOutput = z.object({ start: AddressOutput, end: AddressOutput });
332
- const showRanges = (ranges: CodeRange[]) => ranges.slice(0, MAX_SUMMARY_RANGES).map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) }));
407
+ const showRanges = (ranges: CodeRange[]) => ranges.slice(0, MAX_SUMMARY_RANGES).map(formatC64RangeFields);
333
408
 
334
- export const c64Memmap = defineTool({
409
+ const c64Memmap = defineTool({
335
410
  name: "c64_memmap",
336
411
  title: "Memory access map",
337
412
  description:
@@ -387,9 +462,7 @@ export const c64Memmap = defineTool({
387
462
  requireFields("summary", fields, ["start", "end"]);
388
463
  const map = await readCoverage(session, start, end);
389
464
  // The opcodes give the instruction lengths: RAM as it is now.
390
- const parts: Buffer[] = [];
391
- for (let at = 0; at < 0x10000; at += MAX_MEMORY_READ) parts.push(Buffer.from((await session.memoryRead({ address: at, size: MAX_MEMORY_READ, space: "c64", view: "ram" })).data, "hex"));
392
- const memory = Buffer.concat(parts);
465
+ const memory = await readMemoryInParts(session, 0x0000, 0x10000, "ram");
393
466
  const code = executedRamCode(map, start, memory);
394
467
  const written = executedRamCode(map.map((flags) => ((flags & COVERAGE.ramWrite) === 0 ? 0 : flags)), start, memory);
395
468
  return {
@@ -9,7 +9,7 @@ import { Byte, SpaceInput, TOOL_INPUTS } from "../inputs.ts";
9
9
  import { AddressOutput, defineTool, toCondition, ToolOutput, type ViceSessionApi } from "../server.ts";
10
10
  import { c64Observe } from "./video.ts";
11
11
 
12
- export const c64Execution = defineTool({
12
+ const c64Execution = defineTool({
13
13
  name: "c64_execution",
14
14
  title: "Control C64 execution",
15
15
  description:
@@ -10,7 +10,7 @@ import { TOOL_INPUTS } from "../inputs.ts";
10
10
  import { AddressOutput, defineTool } from "../server.ts";
11
11
 
12
12
 
13
- export const c64Keyboard = defineTool({
13
+ const c64Keyboard = defineTool({
14
14
  name: "c64_keyboard",
15
15
  title: "Type on the C64 keyboard",
16
16
  description:
@@ -31,7 +31,7 @@ export const c64Keyboard = defineTool({
31
31
  },
32
32
  });
33
33
 
34
- export const c64Press = defineTool({
34
+ const c64Press = defineTool({
35
35
  name: "c64_press",
36
36
  title: "Press keys of the C64 keyboard",
37
37
  description:
@@ -62,7 +62,7 @@ export const c64Press = defineTool({
62
62
  },
63
63
  });
64
64
 
65
- export const c64Joystick = defineTool({
65
+ const c64Joystick = defineTool({
66
66
  name: "c64_joystick",
67
67
  title: "Move a joystick",
68
68
  description:
@@ -6,7 +6,7 @@ import { formatC64Address } from "../../c64.ts";
6
6
  import { RESET_MODES, RUN_STATES, WINDOW_ACTIONS } from "../../protocol/vice.ts";
7
7
  import { AddressOutput, defineTool } from "../server.ts";
8
8
 
9
- export const c64Window = defineTool({
9
+ const c64Window = defineTool({
10
10
  name: "c64_window",
11
11
  title: "Emulator window",
12
12
  description:
@@ -27,7 +27,7 @@ export const c64Window = defineTool({
27
27
  },
28
28
  });
29
29
 
30
- export const c64Reset = defineTool({
30
+ const c64Reset = defineTool({
31
31
  name: "c64_reset",
32
32
  title: "Reset the C64",
33
33
  description:
@@ -51,7 +51,7 @@ export const c64Reset = defineTool({
51
51
  },
52
52
  });
53
53
 
54
- export const c64Warp = defineTool({
54
+ const c64Warp = defineTool({
55
55
  name: "c64_warp",
56
56
  title: "Warp mode",
57
57
  description:
@@ -19,7 +19,7 @@ const ProjectPath = z.string().min(1).describe("path relative to the project fol
19
19
 
20
20
  const list = (types: readonly string[]) => types.map((type) => `.${type}`).join(", ");
21
21
 
22
- export const c64Autostart = defineTool({
22
+ const c64Autostart = defineTool({
23
23
  name: "c64_autostart",
24
24
  title: "Autostart a program or image",
25
25
  description:
@@ -55,7 +55,7 @@ export const c64Autostart = defineTool({
55
55
  },
56
56
  });
57
57
 
58
- export const c64ProgramLoad = defineTool({
58
+ const c64ProgramLoad = defineTool({
59
59
  name: "c64_program_load",
60
60
  title: "Load a PRG into memory",
61
61
  description:
@@ -80,7 +80,7 @@ export const c64ProgramLoad = defineTool({
80
80
  },
81
81
  });
82
82
 
83
- export const c64DiskAttach = defineTool({
83
+ const c64DiskAttach = defineTool({
84
84
  name: "c64_disk_attach",
85
85
  title: "Attach a disk image",
86
86
  description:
@@ -95,7 +95,7 @@ export const c64DiskAttach = defineTool({
95
95
  },
96
96
  });
97
97
 
98
- export const c64Snapshot = defineTool({
98
+ const c64Snapshot = defineTool({
99
99
  name: "c64_snapshot",
100
100
  title: "Machine snapshots",
101
101
  description:
@@ -3,12 +3,13 @@
3
3
 
4
4
  import { z } from "zod";
5
5
 
6
- import { formatC64Address } from "../../c64.ts";
6
+ import { formatC64Address, hexByte } from "../../c64.ts";
7
7
  import { WireFailure } from "../../protocol/messages.ts";
8
8
  import { MAX_COMPARE_DIFFERENCES, MAX_COMPARE_SIZE, MAX_DISASSEMBLE, MAX_MEMORY_READ, MAX_MEMORY_WRITE, MAX_SEARCH_PATTERN, MAX_SEARCH_RESULTS, type RegisterValues } from "../../protocol/vice.ts";
9
9
  import { linesText, OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
10
10
  import { AddressInput, Byte, MemoryViewInput, SpaceInput, TOOL_INPUTS } from "../inputs.ts";
11
- import { AddressOutput, defineTool, HexData, requireFields } from "../server.ts";
11
+ import { readMemoryInParts } from "../../host-client/vice-session.ts";
12
+ import { AddressOutput, defineTool, HexData, requireFields, requireOut } from "../server.ts";
12
13
 
13
14
  /** With out, a read or a disassembly can be larger than one answer of the session: it is read in parts. */
14
15
  const MAX_MEMORY_READ_OUT = 0x10000;
@@ -16,7 +17,7 @@ const MAX_DISASSEMBLE_OUT = 32768;
16
17
  /** A memory byte in a result: two lowercase hex digits, as memory data is. */
17
18
  const HexByte = z.string().regex(/^[0-9a-f]{2}$/);
18
19
 
19
- export const c64MemoryRead = defineTool({
20
+ const c64MemoryRead = defineTool({
20
21
  name: "c64_memory_read",
21
22
  title: "Read C64 memory",
22
23
  description:
@@ -38,23 +39,19 @@ export const c64MemoryRead = defineTool({
38
39
  readOnly: false,
39
40
  async run(input, session) {
40
41
  const { out, project, ...read } = input;
41
- if (out === undefined && project !== undefined) throw new WireFailure("invalid-input", "project is used only with out.");
42
+ requireOut(input);
42
43
  if (out === undefined) {
43
44
  if (read.size > MAX_MEMORY_READ) throw new WireFailure("invalid-input", `size can be at most ${MAX_MEMORY_READ} without out.`);
44
45
  const result = await session.memoryRead(read);
45
46
  return { address: formatC64Address(result.address), size: result.data.length / 2, data: result.data };
46
47
  }
47
48
  if (read.address + read.size > 0x10000) throw new WireFailure("invalid-input", "The range must not go past $ffff.");
48
- const parts: Buffer[] = [];
49
- for (let at = read.address; at < read.address + read.size; at += MAX_MEMORY_READ) {
50
- const part = await session.memoryRead({ ...read, address: at, size: Math.min(MAX_MEMORY_READ, read.address + read.size - at) });
51
- parts.push(Buffer.from(part.data, "hex"));
52
- }
53
- return { address: formatC64Address(read.address), size: read.size, ...writeOut(out, Buffer.concat(parts), project) };
49
+ const bytes = await readMemoryInParts(session, read.address, read.size, read.view, read.space);
50
+ return { address: formatC64Address(read.address), size: read.size, ...writeOut(out, bytes, project) };
54
51
  },
55
52
  });
56
53
 
57
- export const c64MemoryWrite = defineTool({
54
+ const c64MemoryWrite = defineTool({
58
55
  name: "c64_memory_write",
59
56
  title: "Write C64 memory",
60
57
  description:
@@ -118,7 +115,7 @@ const SearchPattern = z
118
115
  .transform((value) => value.trim().split(/\s+/).map((token) => (token === "??" ? null : Number.parseInt(token, 16))))
119
116
  .describe("hex bytes and ?? (any byte), separated by spaces, for example a9 ?? 8d 20 d0");
120
117
 
121
- export const c64MemorySearch = defineTool({
118
+ const c64MemorySearch = defineTool({
122
119
  name: "c64_memory_search",
123
120
  title: "Search C64 memory",
124
121
  description:
@@ -156,7 +153,7 @@ const Location = z
156
153
  .object({ address: AddressInput, space: SpaceInput, view: MemoryViewInput })
157
154
  .strict();
158
155
 
159
- export const c64MemoryCompare = defineTool({
156
+ const c64MemoryCompare = defineTool({
160
157
  name: "c64_memory_compare",
161
158
  title: "Compare C64 memory",
162
159
  description:
@@ -175,12 +172,11 @@ export const c64MemoryCompare = defineTool({
175
172
  readOnly: true,
176
173
  async run(input, session) {
177
174
  const result = await session.memoryCompare(input);
178
- const hex = (byte: number) => byte.toString(16).padStart(2, "0");
179
- return { ...result, firstDifferences: result.firstDifferences.map((difference) => ({ ...difference, left: hex(difference.left), right: hex(difference.right) })) };
175
+ return { ...result, firstDifferences: result.firstDifferences.map((difference) => ({ ...difference, left: hexByte(difference.left), right: hexByte(difference.right) })) };
180
176
  },
181
177
  });
182
178
 
183
- export const c64Disassemble = defineTool({
179
+ const c64Disassemble = defineTool({
184
180
  name: "c64_disassemble",
185
181
  title: "Disassemble live C64 memory",
186
182
  description:
@@ -202,7 +198,7 @@ export const c64Disassemble = defineTool({
202
198
  readOnly: false,
203
199
  async run(input, session) {
204
200
  const { out, project, ...request } = input;
205
- if (out === undefined && project !== undefined) throw new WireFailure("invalid-input", "project is used only with out.");
201
+ requireOut(input);
206
202
  if (out === undefined) {
207
203
  if (request.count > MAX_DISASSEMBLE) throw new WireFailure("invalid-input", `count can be at most ${MAX_DISASSEMBLE} without out.`);
208
204
  const result = await session.disassemble(request);