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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +1 -1
  3. package/skills/c64-assembler/scripts/assembler.ts +78 -24
  4. package/skills/c64-docs/scripts/docs.ts +31 -10
  5. package/skills/c64-knowledge/SKILL.md +4 -3
  6. package/skills/c64-knowledge/scripts/knowledge.ts +31 -12
  7. package/skills/c64-packer/scripts/packer.ts +9 -2
  8. package/skills/c64-provenance/SKILL.md +1 -1
  9. package/skills/c64-provenance/scripts/lib/runtime.ts +5 -16
  10. package/skills/c64-source/references/loader.md +8 -7
  11. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  12. package/skills/c64-source/scripts/source.ts +49 -78
  13. package/skills/c64-static-analysis/SKILL.md +2 -2
  14. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  15. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  16. package/skills/c64-testing/SKILL.md +6 -0
  17. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  18. package/skills/c64-testing/scripts/lib/recording.ts +218 -12
  19. package/skills/c64-testing/scripts/lib/replay.ts +7 -3
  20. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  21. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  22. package/skills/c64-testing/scripts/testing.ts +24 -11
  23. package/skills/c64-unpacker/SKILL.md +6 -4
  24. package/skills/c64-unpacker/scripts/lib/loads.ts +4 -2
  25. package/skills/c64-unpacker/scripts/lib/machine.ts +128 -5
  26. package/skills/c64-unpacker/scripts/lib/stages.ts +5 -1
  27. package/skills/c64-unpacker/scripts/unpacker.ts +13 -12
  28. package/skills/emulator/SKILL.md +2 -2
  29. package/src/host/vice/adapter.ts +2 -1
  30. package/src/host-client/image.ts +33 -4
  31. package/src/host-client/tools.ts +1 -1
  32. package/src/host-client/transfer.ts +48 -26
  33. package/src/host-client/vice-session.ts +15 -0
  34. package/src/knowledge/database.ts +72 -19
  35. package/src/knowledge/import.ts +31 -8
  36. package/src/knowledge/names.ts +2 -2
  37. package/src/knowledge/program.ts +67 -7
  38. package/src/knowledge/schema.ts +6 -0
  39. package/src/knowledge/start-screen.ts +55 -2
  40. package/src/knowledge/write.ts +18 -12
  41. package/src/loader.ts +101 -33
  42. package/src/mcp/output.ts +13 -12
  43. package/src/mcp/server.ts +33 -22
  44. package/src/mcp/tools/debug.ts +21 -24
  45. package/src/mcp/tools/media.ts +27 -27
  46. package/src/mcp/tools/memory.ts +13 -17
  47. package/src/mcp/tools/video.ts +10 -12
  48. package/src/native/c64run.ts +39 -1
  49. package/src/native/decompiler/analyze.ts +1 -1
  50. package/src/native/dxa.ts +2 -2
  51. package/src/native/types.ts +26 -7
  52. package/src/program-code.ts +4 -2
  53. package/src/project.ts +224 -71
  54. package/src/protocol/vice.ts +5 -3
  55. package/src/script.ts +60 -15
  56. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  57. package/tools/c64run.c +18 -5
@@ -52,7 +52,7 @@ import {
52
52
  type SwitchRow,
53
53
  type SymbolRow,
54
54
  } from "./read.ts";
55
- import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MEMORY_ROW, MODULE_FILE, DEFAULT_SPACE, spaceOf, GENERATED_FILES, GENERATED_FOLDERS, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, POINTER_KIND, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type Origin, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
55
+ import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MEMORY_ROW, MODULE_FILE, DEFAULT_SPACE, spaceOf, inSpace, spaceOption, GENERATED_FILES, GENERATED_FOLDERS, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, POINTER_KIND, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type Origin, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
56
56
  import { newRevisionId, rowId, sqlName, TABLES, tableSpec } from "./text.ts";
57
57
 
58
58
  type Raw = Record<string, unknown>;
@@ -94,8 +94,10 @@ export interface WriteResult<T, P = never> {
94
94
  }
95
95
 
96
96
  const MAX_COMMENT = 4000;
97
- /** The most characters of patch code and of a macro body. */
97
+ /** The most characters of a macro body, and of the code of a patch of a small range. */
98
98
  const MAX_CODE = 8000;
99
+ /** The most characters of patch code for each byte of its range, when that is more than MAX_CODE: the bytes of a release as !byte lines (releaseCode) need less than 5. */
100
+ const CODE_PER_BYTE = 8;
99
101
  /** The most parameters of a macro. */
100
102
  const MAX_PARAMS = 16;
101
103
  const MAX_EVIDENCE_REF = 1000;
@@ -813,7 +815,11 @@ function checkSwitchName(name: unknown, what = "A switch name"): void {
813
815
  function checkPatch(request: PatchRequest): void {
814
816
  checkRange(request);
815
817
  checkSwitchName(request.switch, "The switch of a patch");
816
- if (typeof request.code !== "string" || request.code.length > MAX_CODE) throw new Refusal("invalid-input", `Patch code has at most ${MAX_CODE} characters; empty code fills the range with NOP.`);
818
+ // The limit grows with the range: the bytes of a release fit a patch of any range.
819
+ const limit = Math.max(MAX_CODE, CODE_PER_BYTE * (request.end - request.start + 1));
820
+ if (typeof request.code !== "string" || request.code.length > limit) {
821
+ throw new Refusal("invalid-input", `The patch code of ${formatC64Range(request)} has at most ${limit} characters: ${MAX_CODE}, or ${CODE_PER_BYTE} for each byte of the range when that is more. Make the code shorter. Empty code fills the range with NOP.`);
822
+ }
817
823
  checkBraces(request.code, "The patch code");
818
824
  checkCommentText(request.comment, "A patch comment");
819
825
  }
@@ -870,7 +876,7 @@ function patchStep(db: DatabaseSync, change: Change, request: PatchRequest, cont
870
876
  throw new Refusal("invalid-input", `The patch code is at least ${least} bytes, and the range ${range} has ${length}. Make the code shorter, or make the range larger.`);
871
877
  }
872
878
  const owner = switchNamed(db, request.switch, space);
873
- if (owner === undefined) throw new Refusal("not-found", `There is no switch ${request.switch}. Write it first (switch ${request.switch} --kind <kind> --releases <labels>).`);
879
+ if (owner === undefined) throw new Refusal("not-found", `There is no switch ${request.switch}${inSpace(space)}. Write it first (switch ${request.switch} --kind <kind> --releases <labels>${spaceOption(space)}).`);
874
880
  // A write at the start of a patch of the same switch changes that patch. Another switch can have the same range: an alternative.
875
881
  const mine = (row: PatchRow) => row.start === request.start && row.switch === request.switch;
876
882
  const other = patchesOverlapping(db, request.start, request.end, space).find((row) => !mine(row) && (row.start !== request.start || row.end !== request.end || row.switch === request.switch));
@@ -962,10 +968,10 @@ function defaultOf(request: SwitchRequest, existing: SwitchRow | undefined): 0 |
962
968
  function switchStep(db: DatabaseSync, change: Change, request: SwitchRequest, context: StepContext): Step<SwitchRow, SwitchRow> {
963
969
  const space = spaceOf(request);
964
970
  const base = baseLabel(db, space);
965
- if (base === undefined) throw new Refusal("not-found", "The knowledge has no base release. Record the release whose bytes are the program first (release <label> --file <file> --base).");
971
+ if (base === undefined) throw new Refusal("not-found", `The knowledge has no base release${inSpace(space)}. Record the release whose bytes are the program${inSpace(space)} first (release <label> --file <file> --base${spaceOption(space)}).`);
966
972
  const existing = switchNamed(db, request.name, space);
967
973
  const releases = [...new Set(request.releases ?? existing?.releases ?? [])].sort();
968
- for (const label of releases) if (releaseLabeled(db, label, space) === undefined) throw new Refusal("not-found", `There is no release ${label}. Record it first (release ${label} --file <file>).`);
974
+ for (const label of releases) if (releaseLabeled(db, label, space) === undefined) throw new Refusal("not-found", `There is no release ${label}${inSpace(space)}. Record it first (release ${label} --file <file>${spaceOption(space)}).`);
969
975
  const value = defaultOf(request, existing);
970
976
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
971
977
  const origin = context.origin as SwitchRow["origin"];
@@ -1039,11 +1045,11 @@ function releaseStep(db: DatabaseSync, change: Change, request: ReleaseRequest,
1039
1045
  const sameBytes = held.length === wanted.size && held.every((row) => wanted.get(row.address) === row.bytes);
1040
1046
  if (existing !== undefined && existing.base === base && existing.comment === comment && sameFile && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1041
1047
  const other = baseLabel(db, space);
1042
- if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release. A space has one base release.`);
1048
+ if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release${inSpace(space)}. A space has one base release.`);
1043
1049
  // Every switch takes its base value from the base release: it cannot change under them.
1044
1050
  if ((existing?.base ?? false) !== base) {
1045
1051
  const switches = listSwitches(db, undefined, space);
1046
- if (switches.length > 0) throw new Refusal("conflict", `The base release decides the state of the program for the switches ${switches.map((row) => row.name).join(", ")}. Remove them first (unswitch) to change the base release.`);
1052
+ if (switches.length > 0) throw new Refusal("conflict", `The base release decides the state of the program for the switches ${switches.map((row) => row.name).join(", ")}. Remove them first (unswitch${spaceOption(space)}) to change the base release${inSpace(space)}.`);
1047
1053
  }
1048
1054
  const symbol = symbolNamed(db, `${RELEASE_DEFINE}${request.label}`, space);
1049
1055
  if (symbol !== undefined) throw new Refusal("conflict", `The build of the release defines ${RELEASE_DEFINE}${request.label}, and that is the name of the symbol at ${formatC64Address(symbol.address)}. Give the release another label.`);
@@ -1065,7 +1071,7 @@ function releaseStep(db: DatabaseSync, change: Change, request: ReleaseRequest,
1065
1071
  function unreleaseStep(db: DatabaseSync, change: Change, request: InSpace & { label: string }): Step<null> {
1066
1072
  const space = spaceOf(request);
1067
1073
  const existing = releaseLabeled(db, request.label, space);
1068
- if (existing === undefined) throw new Refusal("not-found", `There is no release ${request.label}.`);
1074
+ if (existing === undefined) throw new Refusal("not-found", `There is no release ${request.label}${inSpace(space)}.`);
1069
1075
  const switches = listSwitches(db, undefined, space).filter((row) => existing.base || row.releases.includes(request.label));
1070
1076
  if (switches.length > 0) {
1071
1077
  const why = existing.base ? "decides the state of the program for" : "is named by";
@@ -1523,10 +1529,10 @@ export function revert(db: DatabaseSync, context: WriteContext, request: { revis
1523
1529
  // The coverage maps that the knowledge has follow the revert, also when no coverage range changes.
1524
1530
  const maps = (runs: CoverageRun[]) => JSON.stringify(runs.filter((run) => only === undefined || run.space === only).map((run) => [run.name, run.sha256, run.space, run.revision]));
1525
1531
  if (maps(coverageRuns(db, restored)) !== maps(coverageRuns(db))) change.id();
1526
- const inSpace = only === undefined ? "" : " AND space = ?";
1532
+ const spaceWhere = only === undefined ? "" : " AND space = ?";
1527
1533
  const spaceArgs = only === undefined ? [] : [only];
1528
- const at = `valid_from_revision <= ? AND (valid_to_revision IS NULL OR valid_to_revision > ?)${inSpace}`;
1529
- const current = `valid_to_revision IS NULL${inSpace}`;
1534
+ const at = `valid_from_revision <= ? AND (valid_to_revision IS NULL OR valid_to_revision > ?)${spaceWhere}`;
1535
+ const current = `valid_to_revision IS NULL${spaceWhere}`;
1530
1536
  // A row is the same when all its values are the same.
1531
1537
  for (const spec of TABLES) {
1532
1538
  const columns = spec.fields.map((field) => field.column);
package/src/loader.ts CHANGED
@@ -5,14 +5,16 @@
5
5
  // c64-source packs it for the loader that it checks; c64-assembler packs it
6
6
  // for other switch values, from the same files and with the same parts. The
7
7
  // loaded ranges are the segments of the program without the leftovers: a
8
- // leftover file of the source gives its range in its first line.
8
+ // leftover file of the source gives its range in its first line. Also the
9
+ // placement of pieces in free ranges, which the packed form and the show
10
+ // stage of a start screen use.
9
11
 
10
- import { type AddressRange, formatC64Address, formatC64Range, prgOf, prgRange, subtract } from "./c64.ts";
12
+ import { type AddressRange, formatC64Address, formatC64Range, hexWord, prgOf, prgRange, subtract } from "./c64.ts";
11
13
  import { compareBuild, mergedPrograms } from "./compare.ts";
12
14
  import { Refusal } from "./errors.ts";
13
15
  import { pack } from "./native/exomizer.ts";
14
16
  import type { ToolContext } from "./native/run.ts";
15
- import type { AssembledSymbol } from "./native/types.ts";
17
+ import { type AssembledSymbol, symbolValue, symbolValues } from "./native/types.ts";
16
18
 
17
19
  /** The label of the copier in loader.asm. In the packed form, its address is the copier address, where the unpack jumps. */
18
20
  export const COPIER_SOURCE = "loader_copier_src";
@@ -23,6 +25,11 @@ const PACKED_EXIT_MEMORY = 0x34;
23
25
  /** The pages that the unpacker of Exomizer uses: the copier of the packed form writes them, so main.asm is packed from here. */
24
26
  const PACKED_FROM = 0x0400;
25
27
 
28
+ /** The label of a block of loader.asm: its first byte and the byte after it in the loader file, and its first address where it runs. A piece of pages 0-3 of the packed form has the labels of its target. */
29
+ export const blockLabel = (start: number, part: "from" | "end" | "to") => `loader_${part}_${hexWord(start)}`;
30
+ /** The first label of a block, with its first address where it runs. */
31
+ const BLOCK_FROM = /^loader_from_([0-9a-f]{4})$/;
32
+
26
33
  /** The first line of a leftover file: `; Leftovers $xxxx-$yyyy: ...`. */
27
34
  const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
28
35
 
@@ -32,46 +39,52 @@ export function leftoverRange(text: string): AddressRange | undefined {
32
39
  return found === null ? undefined : { start: Number.parseInt(found[1]!.slice(1), 16), end: Number.parseInt(found[2]!.slice(1), 16) };
33
40
  }
34
41
 
35
- /**
36
- * The ranges that the packed loader loads from a build of main.asm: the
37
- * segments of the program without the leftovers. Refuses what only the loader
38
- * of generate can have: a start screen of a captured stage, which is a program
39
- * of its own in front of the packed loader, and a segment below $0400, whose
40
- * bytes loader.asm holds with the switch values of generate.
41
- */
42
- export function packedRanges(segments: readonly AddressRange[], leftovers: readonly AddressRange[], stage: string | undefined): AddressRange[] {
43
- if (stage !== undefined) {
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.`);
45
- }
46
- const loaded = [...segments].sort((a, b) => a.start - b.start).flatMap((segment) => subtract(segment, leftovers));
47
- const low = loaded.find((range) => range.start < PACKED_FROM);
48
- if (low !== undefined) {
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.`);
50
- }
51
- return loaded;
42
+ /** The ranges that the packed loader loads from a build of main.asm: the segments of the program without the leftovers. */
43
+ export function packedRanges(segments: readonly AddressRange[], leftovers: readonly AddressRange[]): AddressRange[] {
44
+ return [...segments].sort((a, b) => a.start - b.start).flatMap((segment) => subtract(segment, leftovers));
52
45
  }
53
46
 
54
47
  /**
55
48
  * Checks the two builds of the packed form before the pack: the build of
56
- * main.asm holds each loaded range, and the build of loader.asm, which holds
57
- * the bytes of the program between its free ranges, has the bytes of the build
58
- * of main.asm there. A patch of a switch between the free ranges changes them,
59
- * and the copier build would put the old bytes back. Refuses by name.
49
+ * main.asm holds each loaded range, and the build of loader.asm has the bytes
50
+ * of the build of main.asm where it holds them. These are the bytes of the
51
+ * program between its free ranges, and the pieces of the loaded ranges below
52
+ * $0400, which the copier copies into place after the unpack (`symbols`, the
53
+ * labels of the build of loader.asm, give the pieces). A patch of a switch
54
+ * there changes the bytes, and the copier build would put the old bytes
55
+ * back. Refuses by name.
60
56
  */
61
- export function checkPackedBuilds(main: Uint8Array, copier: Uint8Array, loaded: readonly AddressRange[]): void {
57
+ export function checkPackedBuilds(main: Uint8Array, copier: Uint8Array, symbols: readonly AssembledSymbol[], loaded: readonly AddressRange[]): void {
62
58
  const program = prgRange(main);
63
59
  const outside = loaded.find((range) => range.start < program.start || range.end > program.end);
64
60
  if (outside !== undefined) {
65
61
  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.`);
66
62
  }
67
63
  const build = prgRange(copier);
64
+ const changed = (address: number, where: string) =>
65
+ new Refusal("invalid-input", `These switch values change the byte at ${formatC64Address(address)}, ${where}, and loader.asm holds the byte of generate there. Set the switch values in config.asm, and generate the source with the loader.`);
68
66
  for (const range of loaded) {
69
67
  for (let address = Math.max(range.start, build.start); address <= Math.min(range.end, build.end); address++) {
70
- if (build.body[address - build.start] === program.body[address - program.start]) continue;
71
- throw new Refusal(
72
- "invalid-input",
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.`,
74
- );
68
+ if (build.body[address - build.start] !== program.body[address - program.start]) throw changed(address, `between the free ranges of loader.asm (${formatC64Range(build)})`);
69
+ }
70
+ }
71
+ // The pieces below $0400: each from its first label to its end label in the build of loader.asm.
72
+ const labels = symbolValues(symbols);
73
+ const pieces = [...labels].flatMap(([name, at]) => {
74
+ const found = BLOCK_FROM.exec(name);
75
+ if (found === null) return [];
76
+ const target = Number.parseInt(found[1]!, 16);
77
+ const end = labels.get(blockLabel(target, "end"));
78
+ return end === undefined ? [] : [{ target, at, length: end - at }];
79
+ });
80
+ for (const range of loaded) {
81
+ for (let address = Math.max(range.start, 0x0002); address <= Math.min(range.end, PACKED_FROM - 1); address++) {
82
+ const piece = pieces.find((item) => address >= item.target && address < item.target + item.length);
83
+ const at = piece === undefined ? undefined : piece.at + address - piece.target;
84
+ if (at === undefined || at < build.start || at > build.end) {
85
+ throw new Refusal("invalid-input", `loader.asm holds no byte for ${formatC64Address(address)} of the program. Generate the source with the loader again.`);
86
+ }
87
+ if (build.body[at - build.start] !== program.body[address - program.start]) throw changed(address, "below $0400");
75
88
  }
76
89
  }
77
90
  }
@@ -134,12 +147,11 @@ export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint
134
147
  * a show stage. A test takes one symbols file. Refuses a name with two values.
135
148
  */
136
149
  export function loaderSymbols(...builds: ReadonlyArray<readonly AssembledSymbol[]>): AssembledSymbol[] {
137
- const valueOf = (symbol: AssembledSymbol) => (symbol.kind === "address" ? symbol.address : symbol.value);
138
150
  const byName = new Map<string, AssembledSymbol>();
139
151
  for (const symbol of builds.flat()) {
140
152
  const known = byName.get(symbol.name);
141
- if (known !== undefined && valueOf(known) !== valueOf(symbol)) {
142
- throw new Refusal("operation-failed", `The builds of the loader program give ${symbol.name} two values, ${valueOf(known)} and ${valueOf(symbol)}. This is a defect of the script.`);
153
+ if (known !== undefined && symbolValue(known) !== symbolValue(symbol)) {
154
+ throw new Refusal("operation-failed", `The builds of the loader program give ${symbol.name} two values, ${symbolValue(known)} and ${symbolValue(symbol)}. This is a defect of the script.`);
143
155
  }
144
156
  // An address in one build can be outside the load range of the other build, where it is a constant.
145
157
  const kept = known === undefined || (known.kind === "constant" && symbol.kind === "address") ? symbol : known;
@@ -147,3 +159,59 @@ export function loaderSymbols(...builds: ReadonlyArray<readonly AssembledSymbol[
147
159
  }
148
160
  return [...byName.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
149
161
  }
162
+
163
+ /** The settings that loader.asm and the show stage include: switches.asm, else config.asm for a start screen, else none. */
164
+ export function settingsLines(source: { switches?: boolean; config?: boolean }): string[] {
165
+ if (source.switches === true) return ['!source "switches.asm"'];
166
+ return source.config === true ? ['!source "config.asm"'] : [];
167
+ }
168
+
169
+ /** The free ranges that a refusal names. */
170
+ const SHOWN_FREE = 8;
171
+
172
+ /** The largest free ranges with their sizes, for a refusal: at most SHOWN_FREE of them, or none. */
173
+ export function largestFree(ranges: readonly AddressRange[]): string {
174
+ const shown = [...ranges].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
175
+ return shown.length === 0 ? "none" : shown.map((range) => `${formatC64Range(range)} (${range.end - range.start + 1} bytes)`).join(", ");
176
+ }
177
+
178
+ /** A piece of bytes in a free range: its target and where a copy reads it. */
179
+ export interface Piece {
180
+ what: string;
181
+ target: AddressRange;
182
+ at: number;
183
+ bytes: (address: number) => number;
184
+ }
185
+
186
+ /**
187
+ * Puts the parts (of pages 0-3, or of a stash) into the free ranges, in their
188
+ * order: each time into the nearest range that holds the rest, else into the
189
+ * largest range. A part that does not fit in one range is split, and each
190
+ * piece is a copy. Undefined when the ranges are too small.
191
+ */
192
+ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: string; range: AddressRange; bytes: (address: number) => number }>, distance: (range: AddressRange) => number): Piece[] | undefined {
193
+ const left = ranges.map((range) => ({ ...range }));
194
+ const pieces: Piece[] = [];
195
+ let rest = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
196
+ const length = (range: AddressRange) => range.end - range.start + 1;
197
+ let target: AddressRange | undefined;
198
+ for (const block of low) {
199
+ let next = block.range.start;
200
+ while (next <= block.range.end) {
201
+ if (target === undefined || target.start > target.end) {
202
+ const open = left.filter((range) => range.start <= range.end);
203
+ if (open.length === 0) return undefined;
204
+ const holding = open.filter((range) => length(range) >= rest).sort((a, b) => distance(a) - distance(b));
205
+ target = holding[0] ?? open.sort((a, b) => length(b) - length(a))[0]!;
206
+ }
207
+ const count = Math.min(block.range.end - next + 1, length(target));
208
+ const part = { start: next, end: next + count - 1 };
209
+ const cut = part.start !== block.range.start || part.end !== block.range.end;
210
+ pieces.push({ what: cut ? `${block.what}, bytes ${formatC64Range(part)}` : block.what, target: part, at: target.start, bytes: block.bytes });
211
+ target.start += count;
212
+ next += count;
213
+ rest -= count;
214
+ }
215
+ }
216
+ return pieces;
217
+ }
package/src/mcp/output.ts CHANGED
@@ -1,23 +1,20 @@
1
1
  // Tool results written to a project file instead of the context. The
2
2
  // MCP server runs on the agent's machine, so it writes the file itself; the
3
- // host never sees the path. The project is the folder that `project` names,
4
- // or the one that the project rules find from the folder the agent started in.
3
+ // host never sees the path. The path is absolute, and the project is the one
4
+ // that the project rules find at or above the file.
5
5
 
6
6
  import { z } from "zod";
7
7
 
8
- import { projectFolder, writeReported, type Written } from "../host-client/transfer.ts";
8
+ import { writeReported, type ToolFile, type Written } from "../host-client/transfer.ts";
9
9
 
10
- export const OutInput = z.string().min(1).describe("write the data to this file, relative to the project folder. An existing file is overwritten. The result then gives the file (out), the number of bytes (bytes) and a SHA-256 (sha256) in place of the data");
11
-
12
- /** The project of a tool with a path. */
13
- export const ProjectInput = z
10
+ export const OutInput = z
14
11
  .string()
15
12
  .min(1)
16
- .describe("the project folder, relative to the folder where the agent started. Give it when that folder is not in a project and has projects below it. The paths of this call are relative to the project folder");
13
+ .describe("write the data to this file: the absolute path of a file in a project folder. An existing file is overwritten. The result then gives the absolute path of the file (out), the number of bytes (bytes) and a SHA-256 (sha256) in place of the data");
17
14
 
18
15
  /** The fields of a result with out, optional in an output schema that also has the inline form. */
19
16
  export const WrittenOutput = {
20
- out: z.string().optional().describe("with out: the file that the tool wrote"),
17
+ out: z.string().optional().describe("with out: the absolute path of the file that the tool wrote"),
21
18
  bytes: z.number().int().min(0).optional().describe("with out: the number of bytes in the file"),
22
19
  sha256: z.string().regex(/^[0-9a-f]{64}$/).optional().describe("with out: the SHA-256 of the file"),
23
20
  };
@@ -27,7 +24,11 @@ export function linesText(lines: readonly string[]): string {
27
24
  return lines.map((line) => `${line}\n`).join("");
28
25
  }
29
26
 
30
- /** Writes `data` to the file `path` of the project that `project` names (or the project lookup finds), and gives what the result shows in its place. */
31
- export function writeOut(path: string, data: Uint8Array | string, project: string | undefined): Written {
32
- return writeReported(path, data, { what: "out", root: projectFolder(project) });
27
+ /**
28
+ * Writes `data` to the file of out, checked before the tool ran (checkOut),
29
+ * and gives what the result shows in its place: the absolute path, the size
30
+ * and the SHA-256.
31
+ */
32
+ export function writeOut(target: ToolFile, data: Uint8Array | string): Written {
33
+ return writeReported(target.file, data, { what: "out", root: target.root });
33
34
  }
package/src/mcp/server.ts CHANGED
@@ -8,7 +8,7 @@ import { z } from "zod";
8
8
  import { formatC64Address } from "../c64.ts";
9
9
  import { Byte, TOOL_INPUTS } from "./inputs.ts";
10
10
  import { LostBeforeAnswer, type ViceSessionClient } from "../host-client/vice-session.ts";
11
- import { checkOut } from "../host-client/transfer.ts";
11
+ import { checkOut, type ToolFile } from "../host-client/transfer.ts";
12
12
  import { describeErrorStack, isRefusal } from "../errors.ts";
13
13
  import { PACKAGE } from "../package.ts";
14
14
  import { shownMessage, WireFailure, type WireError } from "../protocol/messages.ts";
@@ -91,17 +91,6 @@ export function requireFields(action: string, given: Record<string, unknown>, al
91
91
  }
92
92
  }
93
93
 
94
- /**
95
- * Checks the fields that go with out: project only with out, and the
96
- * fields of `notWithOut` only without it.
97
- */
98
- export function requireOut(given: { out?: unknown; project?: unknown } & Record<string, unknown>, notWithOut: readonly string[] = []): void {
99
- if (given.out === undefined && given.project !== undefined) throw new WireFailure("invalid-input", "project is used only with out.");
100
- for (const field of notWithOut) {
101
- if (given.out !== undefined && given[field] !== undefined) throw new WireFailure("invalid-input", `${field} is not used with out.`);
102
- }
103
- }
104
-
105
94
  /** A tool result that carries content blocks (for example an image) beside its structured result. */
106
95
  export class ToolOutput<T> {
107
96
  readonly structured: T;
@@ -121,7 +110,17 @@ export interface ToolDefinition<I extends z.ZodObject = z.ZodObject, O extends z
121
110
  outputSchema: O;
122
111
  /** True for operations that only observe the machine. */
123
112
  readOnly: boolean;
124
- run(input: z.output<I>, session: ViceSessionApi): Promise<z.input<O> | ToolOutput<z.input<O>>>;
113
+ /**
114
+ * `out` is the file of the input out, checked before the tool does any
115
+ * work; undefined without out. The tool branches on it, not on the input.
116
+ * The server gives it from prepare; a direct call gives none, and run of
117
+ * defineTool checks it then.
118
+ */
119
+ run(input: z.output<I>, session: ViceSessionApi, out?: ToolFile): Promise<z.input<O> | ToolOutput<z.input<O>>>;
120
+ /** The actions that take out, for a tool with actions where only some take it. */
121
+ outActions?: readonly string[];
122
+ /** Set by defineTool: checks the input out before any work, also before a session starts, and gives its file. */
123
+ prepare?(input: z.output<I>): ToolFile | undefined;
125
124
  }
126
125
 
127
126
  /** A condition as a result shows it: the input form, with the memory address as "$xxxx". */
@@ -148,9 +147,22 @@ export function toCondition(input: z.output<typeof TOOL_INPUTS.condition>): Cond
148
147
  return defined(input) as Condition;
149
148
  }
150
149
 
151
- /** Keeps a tool's handler typed against its own schemas. */
150
+ /**
151
+ * Keeps a tool's handler typed against its own schemas, and owns the rule of
152
+ * out: prepare checks the input out and gives its file. The server calls
153
+ * prepare before it gets a session and gives the file to run. run checks out
154
+ * itself when it gets no file, for example when another tool calls it.
155
+ */
152
156
  export function defineTool<I extends z.ZodObject, O extends z.ZodObject>(tool: ToolDefinition<I, O>): ToolDefinition {
153
- return tool as unknown as ToolDefinition;
157
+ const prepare = (input: z.output<I>): ToolFile | undefined => {
158
+ const { out: given, action } = input as { out?: unknown; action?: unknown };
159
+ if (given === undefined) return undefined;
160
+ // An action that takes no out is the error to show, not the path.
161
+ if (tool.outActions !== undefined && typeof action === "string" && !tool.outActions.includes(action)) throw new WireFailure("invalid-input", `out is not used with action ${action}.`);
162
+ return typeof given === "string" ? checkOut(given) : undefined;
163
+ };
164
+ const run: ToolDefinition<I, O>["run"] = async (input, session, out) => tool.run(input, session, out ?? prepare(input));
165
+ return { ...tool, run, prepare } as unknown as ToolDefinition;
154
166
  }
155
167
 
156
168
  function jsonSchema(schema: z.ZodObject, io: "input" | "output"): McpTool["inputSchema"] {
@@ -222,16 +234,15 @@ async function runCall(
222
234
  const parsed = tool.inputSchema.safeParse(args ?? {});
223
235
  if (!parsed.success) return { failed: { code: "invalid-input", message: describeIssues(parsed.error, tool.inputSchema) } };
224
236
  try {
225
- // An out path is checked before the tool runs: a refused path must not lose the work or leave its side effects.
226
- const fields = parsed.data as { out?: unknown; project?: unknown };
227
- if (typeof fields.out === "string") checkOut(fields.out, typeof fields.project === "string" ? fields.project : undefined);
237
+ // out is checked before any work and before a session starts: a refused path must not lose the work or leave its side effects.
238
+ const out = tool.prepare?.(parsed.data);
228
239
  let output: unknown;
229
240
  try {
230
- output = await tool.run(parsed.data, await session());
241
+ output = await tool.run(parsed.data, await session(), out);
231
242
  } catch (error) {
232
243
  // A session that the emulator never answered had no machine state: the call goes again on a new session.
233
244
  if (!(error instanceof LostBeforeAnswer)) throw error;
234
- output = await tool.run(parsed.data, await session());
245
+ output = await tool.run(parsed.data, await session(), out);
235
246
  }
236
247
  // The result goes out in the shape that the tool listing advertises: keys
237
248
  // that the output schema does not name are removed, and a result that does
@@ -261,8 +272,8 @@ const INSTRUCTIONS =
261
272
  "Space c64 is the computer. Space drive8 is the CPU of the 1541 disk drive. " +
262
273
  "Memory view cpu gives what the CPU sees now, with ROM and I/O where the memory configuration puts them. Memory view ram gives the RAM under them. " +
263
274
  "A write to memory or registers needs a stopped CPU: stop it with c64_execution action pause. " +
264
- "Paths are relative to the project folder, the folder that holds .c64-re-tools/. " +
265
- "With out, a tool writes a large result to a project file in place of the result.";
275
+ "Give each path as an absolute path, for example /home/me/game/build/game.prg. A tool reads and writes only the files of a project folder. " +
276
+ "With out, a tool writes a large result to a file in place of the result. The result then gives the absolute path of the file.";
266
277
 
267
278
  export function createMcpServer(options: { tools: readonly ToolDefinition[]; session: SessionSource; log?: (line: string) => void }): Server {
268
279
  const tools = new Map(options.tools.map((tool) => [tool.name, tool]));
@@ -8,9 +8,9 @@ import { WireFailure } from "../../protocol/messages.ts";
8
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
10
  import { readMemoryInParts } from "../../host-client/vice-session.ts";
11
- import { linesText, OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
11
+ import { linesText, OutInput, writeOut, WrittenOutput } from "../output.ts";
12
12
  import { AddressInput, Byte, SpaceInput, TOOL_INPUTS } from "../inputs.ts";
13
- import { AddressOutput, ConditionOutput, defineTool, HexData, requireFields, requireOut, showCondition, toCondition } from "../server.ts";
13
+ import { AddressOutput, ConditionOutput, defineTool, HexData, requireFields, showCondition, toCondition } from "../server.ts";
14
14
  import { spaced } from "./memory.ts";
15
15
 
16
16
  /** No default here: a filled-in default would count as a field the other actions refuse. */
@@ -141,10 +141,10 @@ const c64CpuHistory = defineTool({
141
141
  `limit is the number of instructions (1 to ${MAX_HISTORY}, default 50). ` +
142
142
  "Each entry gives the address, the bytes, the instruction and the registers a, x, y and sp before the instruction executed. " +
143
143
  "In space c64, it also gives the raster line and cycle when the instruction started. " +
144
- "With out, it writes the entries as text lines to that project file, and the result gives the file in place of the entries. " +
144
+ "With out, it writes the entries as text lines to that file, and the result gives the file in place of the entries. " +
145
145
  "After a JAM, the emulator records no history until the next reset. If the CPU ran again after a snapshot restore, this tool refuses. Then use c64_reset, or use c64_trace. " +
146
146
  "This does not change the run state of the machine.",
147
- inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_HISTORY).default(50), space: SpaceInput, out: OutInput.optional(), project: ProjectInput.optional() }).strict(),
147
+ inputSchema: z.object({ limit: z.number().int().min(1).max(MAX_HISTORY).default(50), space: SpaceInput, out: OutInput.optional() }).strict(),
148
148
  outputSchema: z.object({
149
149
  entries: z.array(
150
150
  z.object({
@@ -163,16 +163,15 @@ const c64CpuHistory = defineTool({
163
163
  ...WrittenOutput,
164
164
  }),
165
165
  readOnly: false,
166
- async run(input, session) {
167
- const { out, project, ...request } = input;
168
- requireOut(input);
166
+ async run(input, session, file) {
167
+ const { out: _given, ...request } = input;
169
168
  const { entries } = await session.cpuHistory(request);
170
- if (out === undefined) return { entries: entries.map((entry) => ({ ...entry, address: formatC64Address(entry.address) })) };
169
+ if (file === undefined) return { entries: entries.map((entry) => ({ ...entry, address: formatC64Address(entry.address) })) };
171
170
  const lines = entries.map((entry) => {
172
171
  const raster = entry.rasterLine === undefined ? "" : ` line ${entry.rasterLine} cycle ${entry.rasterCycle ?? 0}`;
173
172
  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
173
  });
175
- return { count: entries.length, ...writeOut(out, linesText(lines), project) };
174
+ return { count: entries.length, ...writeOut(file, linesText(lines)) };
176
175
  },
177
176
  });
178
177
 
@@ -260,7 +259,7 @@ const c64Trace = defineTool({
260
259
  "A read or write hit also gives the address that the instruction used, and value, the byte that it read or wrote. " +
261
260
  "At $D000-$DFFF only a load or a store gives value: a read after the access can give another byte. " +
262
261
  `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. ` +
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. ` +
262
+ `The result lists the first ${TRACE_LISTED} hits. With out, it writes all hits as JSON lines to that file, and the result gives no hits. ` +
264
263
  "summary counts all hits, also with out. " +
265
264
  `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
265
  `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}. ` +
@@ -274,7 +273,6 @@ const c64Trace = defineTool({
274
273
  frames: z.number().int().min(1).max(MAX_TRACE_FRAMES),
275
274
  maxHits: z.number().int().min(1).max(MAX_TRACE_HITS).default(MAX_TRACE_HITS),
276
275
  out: OutInput.optional(),
277
- project: ProjectInput.optional(),
278
276
  })
279
277
  .strict(),
280
278
  outputSchema: z.object({
@@ -305,17 +303,16 @@ const c64Trace = defineTool({
305
303
  ...WrittenOutput,
306
304
  }),
307
305
  readOnly: false,
308
- async run(input, session) {
309
- const { out, project, points, ...request } = input;
310
- requireOut(input);
306
+ async run(input, session, file) {
307
+ const { out: _given, points, ...request } = input;
311
308
  const ranges = points.map((point) => ({ kind: point.kind, start: point.start, end: point.end ?? point.start }));
312
309
  if (ranges.some((point) => point.end < point.start)) throw new WireFailure("invalid-input", "A point end must not be before its start.");
313
310
  const traced = await session.trace({ points: ranges, ...request });
314
311
  const shown = traced.hits.map(({ address, ...hit }) => ({ ...hit, pc: formatC64Address(hit.pc), ...(address === undefined ? {} : { address: formatC64Address(address) }) }));
315
312
  const head = { end: traced.end, frames: traced.frames, pc: formatC64Address(traced.pc), count: traced.hits.length };
316
313
  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) };
314
+ if (file === undefined) return { ...head, summary, hits: shown.slice(0, TRACE_LISTED) };
315
+ return { ...head, summary, ...writeOut(file, linesText(shown.map((hit) => JSON.stringify(hit)))) };
319
316
  },
320
317
  });
321
318
 
@@ -407,6 +404,7 @@ const RangeOutput = z.object({ start: AddressOutput, end: AddressOutput });
407
404
  const showRanges = (ranges: CodeRange[]) => ranges.slice(0, MAX_SUMMARY_RANGES).map(formatC64RangeFields);
408
405
 
409
406
  const c64Memmap = defineTool({
407
+ outActions: ["read"],
410
408
  name: "c64_memmap",
411
409
  title: "Memory access map",
412
410
  description:
@@ -414,7 +412,7 @@ const c64Memmap = defineTool({
414
412
  "Action read gives ranges of addresses with the same access (execute, read, write) from start to end. Each range also tells if the access was in RAM, ROM or I/O. " +
415
413
  `It gives at most maxRanges ranges (1 to ${MAX_MEMMAP_RANGES}, default 256). Addresses the CPU did not touch are not in the result. ` +
416
414
  "If more ranges follow, the result also gives truncated: true and next. Read again with start set to next. " +
417
- "With out, read writes a coverage map to that project file, one byte for each address from start to end. " +
415
+ "With out, read writes a coverage map to that file, one byte for each address from start to end. " +
418
416
  "Bits 0 to 2 are RAM read, write and execute. Bits 3 and 4 are ROM read and execute. Bits 5 to 7 are I/O read, write and execute. " +
419
417
  "Execute is set only on the first byte of each executed instruction. Thus read gives a new range at each instruction of code. For code, use summary or read with out. " +
420
418
  "A read on a byte right after executed code, or at a return address, can be a dummy read that the CPU does not use. " +
@@ -429,8 +427,7 @@ const c64Memmap = defineTool({
429
427
  start: AddressInput.optional().describe("read and summary. Default $0000"),
430
428
  end: AddressInput.optional().describe("read and summary. Default $ffff"),
431
429
  maxRanges: z.number().int().min(1).max(MAX_MEMMAP_RANGES).optional().describe("read without out only. Default 256"),
432
- out: OutInput.optional().describe("read only: write a coverage map to this project file, one byte for each address. An existing file is overwritten. The result then gives the file, the number of bytes and a SHA-256"),
433
- project: ProjectInput.optional().describe("read with out only: the project folder, relative to the folder where the agent started. Give it when that folder is not in a project and has projects below it"),
430
+ out: OutInput.optional().describe("read only: write a coverage map to this file, the absolute path of a file in a project folder, one byte for each address. An existing file is overwritten. The result then gives the absolute path of the file, the number of bytes and a SHA-256"),
434
431
  })
435
432
  .strict(),
436
433
  outputSchema: z.object({
@@ -449,7 +446,7 @@ const c64Memmap = defineTool({
449
446
  ...WrittenOutput,
450
447
  }),
451
448
  readOnly: false,
452
- async run(input, session) {
449
+ async run(input, session, file) {
453
450
  const { action, ...fields } = input;
454
451
  if (action === "clear") {
455
452
  requireFields("clear", fields, []);
@@ -476,11 +473,11 @@ const c64Memmap = defineTool({
476
473
  ...basicRomFlaw(romInBasicArea(map, start)),
477
474
  };
478
475
  }
479
- requireOut(fields, ["maxRanges"]);
480
- requireFields("read", fields, ["start", "end", "maxRanges", "out", "project"]);
481
- if (fields.out !== undefined) {
476
+ if (fields.out !== undefined && fields.maxRanges !== undefined) throw new WireFailure("invalid-input", "maxRanges is not used with out.");
477
+ requireFields("read", fields, ["start", "end", "maxRanges", "out"]);
478
+ if (file !== undefined) {
482
479
  const map = await readCoverage(session, start, end);
483
- return { ...writeOut(fields.out, map, fields.project), ...basicRomFlaw(romInBasicArea(map, start)) };
480
+ return { ...writeOut(file, map), ...basicRomFlaw(romInBasicArea(map, start)) };
484
481
  }
485
482
  const result = await session.memmap({ action: "read", start, end, maxRanges: fields.maxRanges ?? 256 });
486
483
  const ranges = result.ranges.map((range) => ({