@henols/c64-re-tools 2.8.0-rc.4 → 2.8.0-rc.6

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 (67) 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 +11 -7
  6. package/skills/c64-knowledge/references/batches.md +2 -1
  7. package/skills/c64-knowledge/references/source-knowledge.md +1 -1
  8. package/skills/c64-knowledge/scripts/knowledge.ts +46 -29
  9. package/skills/c64-packer/scripts/packer.ts +9 -2
  10. package/skills/c64-provenance/SKILL.md +2 -2
  11. package/skills/c64-provenance/scripts/lib/runtime.ts +45 -10
  12. package/skills/c64-provenance/scripts/provenance.ts +10 -3
  13. package/skills/c64-source/references/loader.md +8 -7
  14. package/skills/c64-source/scripts/lib/loader.ts +4 -111
  15. package/skills/c64-source/scripts/lib/source.ts +3 -1
  16. package/skills/c64-source/scripts/source.ts +49 -78
  17. package/skills/c64-static-analysis/SKILL.md +2 -2
  18. package/skills/c64-static-analysis/scripts/lib/coverage.ts +56 -4
  19. package/skills/c64-static-analysis/scripts/lib/idioms.ts +92 -42
  20. package/skills/c64-static-analysis/scripts/static-analysis.ts +32 -21
  21. package/skills/c64-testing/SKILL.md +7 -0
  22. package/skills/c64-testing/scripts/lib/play.ts +8 -7
  23. package/skills/c64-testing/scripts/lib/recording.ts +278 -27
  24. package/skills/c64-testing/scripts/lib/replay.ts +9 -8
  25. package/skills/c64-testing/scripts/lib/runs.ts +5 -1
  26. package/skills/c64-testing/scripts/lib/scenario.ts +4 -0
  27. package/skills/c64-testing/scripts/testing.ts +30 -11
  28. package/skills/c64-unpacker/SKILL.md +13 -11
  29. package/skills/c64-unpacker/scripts/lib/loads.ts +10 -5
  30. package/skills/c64-unpacker/scripts/lib/machine.ts +163 -3
  31. package/skills/c64-unpacker/scripts/lib/stages.ts +13 -6
  32. package/skills/c64-unpacker/scripts/unpacker.ts +34 -15
  33. package/skills/emulator/SKILL.md +2 -2
  34. package/src/c64.ts +21 -0
  35. package/src/host/vice/adapter.ts +2 -1
  36. package/src/host/vice/chips.ts +6 -9
  37. package/src/host/vice/session.ts +2 -2
  38. package/src/host-client/image.ts +40 -4
  39. package/src/host-client/tools.ts +1 -1
  40. package/src/host-client/transfer.ts +48 -26
  41. package/src/host-client/vice-session.ts +15 -0
  42. package/src/knowledge/database.ts +72 -19
  43. package/src/knowledge/import.ts +32 -7
  44. package/src/knowledge/join.ts +50 -2
  45. package/src/knowledge/names.ts +2 -2
  46. package/src/knowledge/program.ts +103 -24
  47. package/src/knowledge/schema.ts +6 -0
  48. package/src/knowledge/start-screen.ts +57 -7
  49. package/src/knowledge/write.ts +20 -13
  50. package/src/loader.ts +101 -33
  51. package/src/mcp/output.ts +13 -12
  52. package/src/mcp/server.ts +33 -22
  53. package/src/mcp/tools/debug.ts +21 -24
  54. package/src/mcp/tools/media.ts +27 -27
  55. package/src/mcp/tools/memory.ts +13 -17
  56. package/src/mcp/tools/video.ts +10 -12
  57. package/src/native/c64run.ts +39 -1
  58. package/src/native/decompiler/analyze.ts +1 -1
  59. package/src/native/dxa.ts +2 -2
  60. package/src/native/types.ts +26 -7
  61. package/src/opcodes.ts +5 -0
  62. package/src/program-code.ts +4 -2
  63. package/src/project.ts +224 -71
  64. package/src/protocol/vice.ts +5 -3
  65. package/src/script.ts +60 -15
  66. package/{skills/c64-source/scripts/lib → src}/stage.ts +142 -11
  67. package/tools/c64run.c +18 -5
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) => ({
@@ -1,6 +1,6 @@
1
1
  // Media tools: c64_autostart, c64_program_load, c64_disk_attach and
2
- // c64_snapshot. Paths are relative to the project folder; the host-client
3
- // reads the file and the Host Runtime receives only its bytes.
2
+ // c64_snapshot. Paths are absolute; the host-client reads the file and the
3
+ // Host Runtime receives only its bytes.
4
4
 
5
5
  import { extname } from "node:path";
6
6
 
@@ -8,14 +8,14 @@ import { z } from "zod";
8
8
 
9
9
  import { formatC64Address } from "../../c64.ts";
10
10
  import { refuseNotPrg } from "../../host-client/image.ts";
11
- import { projectFolder, readProjectFile } from "../../host-client/transfer.ts";
11
+ import { readProjectFile, toolFile } from "../../host-client/transfer.ts";
12
12
  import { WireFailure } from "../../protocol/messages.ts";
13
13
  import { AUTOSTART_TYPES, DISK_TYPES, MAX_SNAPSHOTS, RUN_STATES } from "../../protocol/vice.ts";
14
- import { OutInput, ProjectInput, writeOut, WrittenOutput } from "../output.ts";
14
+ import { OutInput, writeOut, WrittenOutput } from "../output.ts";
15
15
  import { AddressInput } from "../inputs.ts";
16
- import { AddressOutput, defineTool, requireFields, requireOut, TransientName } from "../server.ts";
16
+ import { AddressOutput, defineTool, requireFields, TransientName } from "../server.ts";
17
17
 
18
- const ProjectPath = z.string().min(1).describe("path relative to the project folder, for example build/game.prg");
18
+ const FilePath = z.string().min(1).describe("the absolute path of a file in a project folder, for example /home/me/game/build/game.prg");
19
19
 
20
20
  const list = (types: readonly string[]) => types.map((type) => `.${type}`).join(", ");
21
21
 
@@ -34,8 +34,7 @@ const c64Autostart = defineTool({
34
34
  "The c64_timing stopwatch starts again from zero.",
35
35
  inputSchema: z
36
36
  .object({
37
- path: ProjectPath,
38
- project: ProjectInput.optional(),
37
+ path: FilePath,
39
38
  index: z.number().int().min(0).max(0xfffe).optional().describe("directory entry of a disk image, 0 is the first entry. Without it, the first file loads as with LOAD\"*\""),
40
39
  run: z.boolean().default(true).describe("true runs the program after it loads"),
41
40
  })
@@ -51,7 +50,8 @@ const c64Autostart = defineTool({
51
50
  throw new WireFailure("invalid-input", `index selects an entry of a disk image (${list(DISK_TYPES)}). A .${type} file has no directory: leave out index.`);
52
51
  }
53
52
  // VICE numbers the directory entries from 1, and its 0 loads "*".
54
- return session.autostart({ path: input.path, index: input.index === undefined ? 0 : input.index + 1, run: input.run, root: projectFolder(input.project) });
53
+ const { file, root } = toolFile(input.path, "read");
54
+ return session.autostart({ path: file, index: input.index === undefined ? 0 : input.index + 1, run: input.run, root });
55
55
  },
56
56
  });
57
57
 
@@ -64,8 +64,7 @@ const c64ProgramLoad = defineTool({
64
64
  "With address, it goes there instead.",
65
65
  inputSchema: z
66
66
  .object({
67
- path: ProjectPath,
68
- project: ProjectInput.optional(),
67
+ path: FilePath,
69
68
  address: AddressInput.optional().describe("load here instead of at the file's own load address"),
70
69
  })
71
70
  .strict(),
@@ -74,8 +73,8 @@ const c64ProgramLoad = defineTool({
74
73
  async run(input, session) {
75
74
  // The same rule as every PRG reader of the scripts: .prg or no extension.
76
75
  refuseNotPrg(input.path, extname(input.path).slice(1).toLowerCase(), "Use c64_autostart, or c64_disk_attach for a disk image");
77
- const root = projectFolder(input.project);
78
- const result = await session.programLoad(input.address === undefined ? { path: input.path, root } : { path: input.path, address: input.address, root });
76
+ const { file, root } = toolFile(input.path, "read");
77
+ const result = await session.programLoad(input.address === undefined ? { path: file, root } : { path: file, address: input.address, root });
79
78
  return { state: result.state, loadAddress: formatC64Address(result.loadAddress), size: result.size };
80
79
  },
81
80
  });
@@ -87,30 +86,31 @@ const c64DiskAttach = defineTool({
87
86
  `Put a disk image from the project into drive 8 (${list(DISK_TYPES)}). ` +
88
87
  "Nothing loads or runs. To load from the disk, type LOAD on the C64 or use c64_autostart. " +
89
88
  "This does not change the run state of the machine.",
90
- inputSchema: z.object({ path: ProjectPath, project: ProjectInput.optional() }).strict(),
89
+ inputSchema: z.object({ path: FilePath }).strict(),
91
90
  outputSchema: z.object({ attached: z.boolean() }),
92
91
  readOnly: false,
93
92
  async run(input, session) {
94
- return session.diskAttach({ path: input.path, root: projectFolder(input.project) });
93
+ const { file, root } = toolFile(input.path, "read");
94
+ return session.diskAttach({ path: file, root });
95
95
  },
96
96
  });
97
97
 
98
98
  const c64Snapshot = defineTool({
99
+ outActions: ["save"],
99
100
  name: "c64_snapshot",
100
101
  title: "Machine snapshots",
101
102
  description:
102
103
  "Save and restore the whole machine state, attached disks included. Action save keeps a snapshot under a name you choose. " +
103
- "With out, save also writes it to that project file as a snapshot file (.vsf), so a later session can use it. " +
104
- "Action restore puts the machine back in that state and stops the CPU. Give name for a snapshot of this session, or file for a .vsf in the project. " +
104
+ "With out, save also writes it to that file as a snapshot file (.vsf), so a later session can use it. " +
105
+ "Action restore puts the machine back in that state and stops the CPU. Give name for a snapshot of this session, or file for a .vsf file. " +
105
106
  "A file restores only in the emulator version and with the machine settings that saved it. The c64_timing stopwatch keeps its reading. " +
106
107
  `Action list gives the names, and action remove removes one. A session keeps at most ${MAX_SNAPSHOTS} snapshots until it ends.`,
107
108
  inputSchema: z
108
109
  .object({
109
110
  action: z.enum(["save", "restore", "list", "remove"]),
110
111
  name: TransientName.optional().describe("save and remove, and restore without file: 1 to 64 letters, digits, dots, underscores or hyphens"),
111
- out: OutInput.optional().describe("save only: also write the snapshot to this project file, for example snapshots/room0.vsf. An existing file is overwritten. The result then also gives the file, the number of bytes and a SHA-256"),
112
- file: ProjectPath.optional().describe("restore only: a .vsf file in the project, in place of name"),
113
- project: ProjectInput.optional().describe("save with out, and restore with file: the project folder, relative to the folder where the agent started. Give it when that folder is not in a project and has projects below it"),
112
+ out: OutInput.optional().describe("save only: also write the snapshot to this file, the absolute path of a file in a project folder, for example /home/me/game/snapshots/room0.vsf. An existing file is overwritten. The result then also gives the absolute path of the file, the number of bytes and a SHA-256"),
113
+ file: FilePath.optional().describe("restore only: the absolute path of a .vsf file in a project folder, in place of name"),
114
114
  })
115
115
  .strict(),
116
116
  outputSchema: z.object({
@@ -123,7 +123,7 @@ const c64Snapshot = defineTool({
123
123
  ...WrittenOutput,
124
124
  }),
125
125
  readOnly: false,
126
- async run(input, session) {
126
+ async run(input, session, out) {
127
127
  const { action, ...fields } = input;
128
128
  if (action === "list") {
129
129
  requireFields(action, fields, []);
@@ -131,17 +131,17 @@ const c64Snapshot = defineTool({
131
131
  }
132
132
  if (action === "restore") {
133
133
  if (fields.name !== undefined && fields.file !== undefined) throw new WireFailure("invalid-input", "Action restore takes name or file, not both.");
134
- if (fields.name === undefined && fields.file === undefined) throw new WireFailure("invalid-input", "Action restore needs name (a snapshot of this session) or file (a .vsf in the project).");
134
+ if (fields.name === undefined && fields.file === undefined) throw new WireFailure("invalid-input", "Action restore needs name (a snapshot of this session) or file (the absolute path of a .vsf file).");
135
135
  }
136
136
  if (action === "restore" && fields.file !== undefined) {
137
- requireFields(action, fields, ["file", "project"], ["file"]);
138
- return session.snapshotRestore(readProjectFile(fields.file, { root: projectFolder(fields.project), what: "file" }).bytes);
137
+ requireFields(action, fields, ["file"], ["file"]);
138
+ const { file, root } = toolFile(fields.file, "read");
139
+ return session.snapshotRestore(readProjectFile(file, { root, what: "file" }).bytes);
139
140
  }
140
141
  if (action === "save") {
141
- requireOut(fields);
142
- requireFields(action, fields, ["name", "out", "project"], ["name"]);
142
+ requireFields(action, fields, ["name", "out"], ["name"]);
143
143
  const saved = await session.snapshot({ action, name: fields.name! });
144
- return fields.out === undefined ? saved : { ...saved, ...writeOut(fields.out, await session.snapshotExport(fields.name!), fields.project) };
144
+ return out === undefined ? saved : { ...saved, ...writeOut(out, await session.snapshotExport(fields.name!)) };
145
145
  }
146
146
  requireFields(action, fields, ["name"], ["name"]);
147
147
  return session.snapshot({ action, name: fields.name! });