@henols/c64-re-tools 2.4.0-rc.2 → 2.4.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +8 -3
- package/skills/c64-assembler/scripts/assembler.ts +6 -16
- package/skills/c64-basic/SKILL.md +2 -0
- package/skills/c64-disk/SKILL.md +21 -4
- package/skills/c64-disk/scripts/disk.ts +43 -3
- package/skills/c64-docs/SKILL.md +2 -0
- package/skills/c64-docs/scripts/docs.ts +6 -6
- package/skills/c64-knowledge/SKILL.md +2 -0
- package/skills/c64-memory-map/SKILL.md +2 -0
- package/skills/c64-packer/SKILL.md +2 -0
- package/skills/c64-provenance/SKILL.md +11 -4
- package/skills/c64-provenance/scripts/lib/library.ts +99 -19
- package/skills/c64-provenance/scripts/provenance.ts +4 -3
- package/skills/c64-reverse-engineering/SKILL.md +3 -3
- package/skills/c64-source/SKILL.md +10 -2
- package/skills/c64-source/scripts/lib/export.ts +3 -3
- package/skills/c64-source/scripts/lib/source.ts +80 -24
- package/skills/c64-source/scripts/source.ts +49 -8
- package/skills/c64-static-analysis/SKILL.md +3 -1
- package/skills/c64-testing/SKILL.md +13 -1
- package/skills/c64-testing/references/recording-format.md +5 -1
- package/skills/c64-testing/references/scenario-format.md +5 -3
- package/skills/c64-testing/scripts/lib/recording.ts +32 -6
- package/skills/c64-testing/scripts/lib/runs.ts +13 -7
- package/skills/c64-testing/scripts/lib/scenario.ts +13 -6
- package/skills/c64-testing/scripts/testing.ts +6 -3
- package/skills/c64-unpacker/SKILL.md +2 -0
- package/src/host/server.ts +31 -6
- package/src/host/tools/c1541.ts +32 -8
- package/src/host/vice/binary-monitor.ts +19 -7
- package/src/host/vice/session.ts +6 -2
- package/src/host-client/connect.ts +12 -2
- package/src/host-client/tools.ts +9 -4
- package/src/host-client/transfer.ts +58 -4
- package/src/host-client/vice-session.ts +10 -3
- package/src/knowledge/import.ts +28 -5
- package/src/knowledge/write.ts +4 -0
- package/src/mcp/main.ts +4 -66
- package/src/mcp/session-source.ts +76 -0
- package/src/native/acme.ts +45 -12
- package/src/native/c64run.ts +1 -1
- package/src/native/types.ts +5 -2
- package/src/project.ts +58 -1
- package/src/protocol/framing.ts +15 -2
- package/src/protocol/messages.ts +77 -25
- package/src/protocol/tools.ts +33 -4
- package/src/protocol/vice.ts +40 -20
- package/src/script.ts +11 -6
- package/tools/c64run.c +48 -12
|
@@ -16,6 +16,7 @@ import { basename, join, relative, sep } from "node:path";
|
|
|
16
16
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
17
17
|
import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
|
|
18
18
|
import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
|
|
19
|
+
import { IO_RAM } from "#src/host-client/coverage.ts";
|
|
19
20
|
import { readImage, type Image } from "#src/host-client/image.ts";
|
|
20
21
|
import { readProjectFile } from "#src/host-client/transfer.ts";
|
|
21
22
|
import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
|
|
@@ -615,6 +616,27 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
|
|
|
615
616
|
/** The files of the loader. Only a run with --loader writes them, so only such a run removes them. */
|
|
616
617
|
const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", "loader.prg"]);
|
|
617
618
|
|
|
619
|
+
/** The start of the line of loader.asm that gives the knowledge revision of the loader. */
|
|
620
|
+
const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* The loader files of an earlier run that a run without --loader keeps, when
|
|
624
|
+
* the generated loader.asm is of another knowledge revision: the loader can
|
|
625
|
+
* then copy other bytes than the source has. Undefined when there is no
|
|
626
|
+
* generated loader.asm, or it is of this revision.
|
|
627
|
+
*/
|
|
628
|
+
function staleLoader(out: string, revision: string): { files: string[]; revision?: string } | undefined {
|
|
629
|
+
const path = resolveProjectPath(`${out}/loader.asm`);
|
|
630
|
+
if (!existsSync(path)) return undefined;
|
|
631
|
+
const text = readFileSync(path, "utf8");
|
|
632
|
+
if (!text.startsWith(GENERATED_MARK)) return undefined;
|
|
633
|
+
const line = text.split(/\r?\n/).find((row) => row.startsWith(`; ${LOADER_REVISION}`));
|
|
634
|
+
const old = line?.slice(`; ${LOADER_REVISION}`.length).replace(/\.$/, "");
|
|
635
|
+
if (old === revision) return undefined;
|
|
636
|
+
const files = [...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`);
|
|
637
|
+
return { files, ...(old === undefined ? {} : { revision: old }) };
|
|
638
|
+
}
|
|
639
|
+
|
|
618
640
|
/**
|
|
619
641
|
* Removes the generated .asm files of an earlier run that this run does not
|
|
620
642
|
* write, and an earlier not_executed.json and source-map.json. An earlier
|
|
@@ -691,7 +713,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
691
713
|
macroUses: knowledge.macroUses,
|
|
692
714
|
...(coverage === undefined || !options.notExecutedMarks ? {} : { coverage }),
|
|
693
715
|
// The platform names are C64 names: drive code and banks get none. A ROM that the program does not use gives none.
|
|
694
|
-
...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister } : {}),
|
|
716
|
+
...(space === DEFAULT_SPACE ? { platform, platformLeftOut: leftOutNames(platform), describe: describeAddress, decode: decodeRegister, io: IO_RAM } : {}),
|
|
695
717
|
});
|
|
696
718
|
const asBytes = await probe(laid);
|
|
697
719
|
const { header } = options;
|
|
@@ -785,7 +807,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
785
807
|
// Every build that is compared with the program is the build of the base release: each switch at its base value.
|
|
786
808
|
const baseValues = new Map(knowledge.switches.map((row) => [row.name, row.base]));
|
|
787
809
|
const header = [`Generated by c64-source from knowledge revision ${knowledge.revision}${space === DEFAULT_SPACE ? "" : ` in space ${space}`}.`, "Change names, comments, regions and modules in knowledge, then generate again."];
|
|
788
|
-
const loaderHeader = [
|
|
810
|
+
const loaderHeader = [`${LOADER_REVISION}${knowledge.revision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
|
|
789
811
|
const { romUse, dataOnly, laid, rendered, files, built, loader, missingEntry, loaderRefused } = await buildSource(knowledge, {
|
|
790
812
|
space,
|
|
791
813
|
entries,
|
|
@@ -801,6 +823,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
801
823
|
const kept = new Map(laid.switches.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
|
|
802
824
|
const notDefault = laid.switches.flatMap((row) => (kept.has(row.name) && kept.get(row.name) !== row.default ? [{ name: row.name, value: kept.get(row.name)!, default: row.default }] : []));
|
|
803
825
|
const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted).map((name) => `${out}/${name}`);
|
|
826
|
+
const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.revision);
|
|
804
827
|
const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
|
|
805
828
|
written.push(writeReported(`${out}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files), { what: "--out" }));
|
|
806
829
|
const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
@@ -826,6 +849,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
826
849
|
// The values that config.asm keeps and that are not the default: a build of the source is not the default build.
|
|
827
850
|
...(notDefault.length === 0 ? {} : { config: { file: `${out}/${CONFIG_FILE}`, notDefault } }),
|
|
828
851
|
revision: knowledge.revision,
|
|
852
|
+
// A run without --loader keeps the loader of an earlier run: one of another revision is stale.
|
|
853
|
+
...(stale === undefined ? {} : { staleLoader: { ...stale, ...(image.state === undefined || image.entry === undefined ? { noEntryState: true } : {}) } }),
|
|
829
854
|
instructions: rendered.instructions,
|
|
830
855
|
dataBytes: rendered.dataBytes,
|
|
831
856
|
...(rendered.undecodedBytes === 0 ? {} : { undecodedBytes: rendered.undecodedBytes }),
|
|
@@ -923,7 +948,16 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
923
948
|
written.push(writeReported(loaderPath, program, { what: "--out" }));
|
|
924
949
|
// The unpack runs before the copier.
|
|
925
950
|
const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : packed.cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(packed.cycles / PAL_FRAME_CYCLES);
|
|
926
|
-
|
|
951
|
+
let ran: LoaderRun;
|
|
952
|
+
try {
|
|
953
|
+
ran = await runLoader(loaderPath, program, loader, image, state, { jump, copierSource, fileByte, copierFrames }, expected);
|
|
954
|
+
} catch (error) {
|
|
955
|
+
// A loader.prg without its check does not stay: it looks like a checked loader.
|
|
956
|
+
rmSync(resolveProjectPath(loaderPath), { force: true });
|
|
957
|
+
written.splice(written.findIndex((file) => file.out === loaderPath), 1);
|
|
958
|
+
if (!isRefusal(error)) throw error;
|
|
959
|
+
return { output: { ...output, loader: { verified: false, reason: `The check of loader.prg did not run, so the script removed loader.prg. ${error.message}` } }, removed, failed: true };
|
|
960
|
+
}
|
|
927
961
|
output.loader = {
|
|
928
962
|
program: loaderPath,
|
|
929
963
|
...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
|
|
@@ -1224,7 +1258,7 @@ function isCut(list: unknown): boolean {
|
|
|
1224
1258
|
}
|
|
1225
1259
|
|
|
1226
1260
|
/** The same generate command line again, for the run after a change of the knowledge. */
|
|
1227
|
-
function generateAgain(call: Call): string {
|
|
1261
|
+
function generateAgain(call: Call, loader = call.flag("loader")): string {
|
|
1228
1262
|
const max = call.count("max-listed")!;
|
|
1229
1263
|
return call.next(
|
|
1230
1264
|
"generate",
|
|
@@ -1232,7 +1266,7 @@ function generateAgain(call: Call): string {
|
|
|
1232
1266
|
call.string("out")!,
|
|
1233
1267
|
...call.addresses("entry").flatMap((entry) => ["--entry", formatC64Address(entry)]),
|
|
1234
1268
|
...(call.space === DEFAULT_SPACE ? [] : ["--space", call.space]),
|
|
1235
|
-
...(
|
|
1269
|
+
...(loader ? ["--loader"] : []),
|
|
1236
1270
|
...(call.flag("analyzer-names") ? ["--analyzer-names"] : []),
|
|
1237
1271
|
...(max === OPTIONS["max-listed"].default ? [] : ["--max-listed", String(max)]),
|
|
1238
1272
|
);
|
|
@@ -1281,9 +1315,16 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
|
|
|
1281
1315
|
again = true;
|
|
1282
1316
|
}
|
|
1283
1317
|
if ([body.asBytes, body.operandsAsNumbers, body.macrosAsInstructions, body.patchesNotWritten].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
|
|
1284
|
-
|
|
1318
|
+
const staleLoader = body.staleLoader as { noEntryState?: boolean } | undefined;
|
|
1319
|
+
if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: "Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again." });
|
|
1285
1320
|
if (again) steps.push("Then generate again.");
|
|
1286
|
-
|
|
1321
|
+
// The run with --loader writes the loader again, so it is the next action also for the other findings.
|
|
1322
|
+
const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
|
|
1323
|
+
if (staleLoader !== undefined) {
|
|
1324
|
+
steps.push("The loader files in staleLoader.files are of another knowledge revision, and the run kept them.");
|
|
1325
|
+
steps.push(loaderAgain ? "To write the loader of this revision, generate with --loader." : "The knowledge has no entry state, so --loader cannot write them again. Remove them when the build does not use them.");
|
|
1326
|
+
}
|
|
1327
|
+
return reply(body, { hint: steps.join(" "), ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
|
|
1287
1328
|
}
|
|
1288
1329
|
|
|
1289
1330
|
/** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
|
|
@@ -1316,7 +1357,7 @@ await runScript({
|
|
|
1316
1357
|
out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
|
|
1317
1358
|
entry: { ...OPTIONS.entry, multiple: true, help: "an address where code starts. The entry of the program, the routines and the code regions of the knowledge are entry points too" },
|
|
1318
1359
|
space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, or bank0 to bank255. The coverage and --loader are for c64 only" },
|
|
1319
|
-
loader: { kind: "flag", help: "also write loader.asm and loader.prg: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator" },
|
|
1360
|
+
loader: { kind: "flag", help: "also write loader.asm and loader.prg: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator. When the check cannot run, the script removes loader.prg" },
|
|
1320
1361
|
"analyzer-names": { kind: "flag", help: "name an address that has no name of the user or the LLM, and no platform name, with its analyzer name" },
|
|
1321
1362
|
"max-listed": OPTIONS["max-listed"],
|
|
1322
1363
|
},
|
|
@@ -57,6 +57,8 @@ To get the command list, run the script with no arguments.
|
|
|
57
57
|
|
|
58
58
|
- Give each path relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
|
|
59
59
|
- If the working directory is not in a project, give `--project <folder>` to each command. If the working directory has projects below it, the script refuses and lists them.
|
|
60
|
+
- In a group folder, each version of a program is a project. The script refuses the group folder and each folder in it that is not a project. Give `--project` with a project of the group, for example `--project v1`.
|
|
61
|
+
- A path that a command only reads can go into another project of the group, for example `../v1/original/game.prg`. The command writes only in its own project.
|
|
60
62
|
- An address is `$` and 1 to 4 hex digits, for example `'$c000'` or `'$fb'`, or a name. A name is a symbol, else an analyzer name that only one analyzer gives. Put an address in single quotes in a shell.
|
|
61
63
|
- A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
|
|
62
64
|
- Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
|
|
@@ -100,7 +102,7 @@ The script records only structure: code and data regions, analyzer names, and th
|
|
|
100
102
|
- `analyzer`: `dxa` or `ghidra`. `space` is in `body` only for a space that is not `c64`.
|
|
101
103
|
- `revision`: the revision of the findings, or `null` when the knowledge did not change.
|
|
102
104
|
- `coverage`: the ranges that the analyzer examined.
|
|
103
|
-
- `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `symbols.retired` counts the old symbols of the analyzer that became analyzer names.
|
|
105
|
+
- `changes`: for analyzer names (`names`), `regions` and `references`, the counts `added`, `changed`, `retired`, `unchanged` and `suppressed`. `suppressed` counts the findings that the script did not record, because the user or the LLM removed a fact at that place. `references.inData` counts the references that the script did not record, because they start in a data region of the user, the LLM or a heuristic. The analyzer decoded these data bytes as code. `symbols.retired` counts the old symbols of the analyzer that became analyzer names.
|
|
104
106
|
- `conflicts`: each place where the analyzer and the project knowledge disagree. `problem` tells the disagreement.
|
|
105
107
|
- `coverageSeeds`: only with coverage. `entryPoints` and `used` give how many entry points the coverage gave, and how many the analysis used. `romOnlyRanges` and `romOnlyUsed` give the same counts for the data ranges under ROM.
|
|
106
108
|
- `coverageConflicts`: only with coverage. Each analyzer data region where the coverage shows executed code.
|
|
@@ -52,6 +52,8 @@ To get the command list, run the script with no arguments.
|
|
|
52
52
|
|
|
53
53
|
- Give each path relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
|
|
54
54
|
- If the working directory is not in a project, give `--project <folder>` to each command. If the working directory has projects below it, the script refuses and lists them.
|
|
55
|
+
- In a group folder, each version of a program is a project. The script refuses the group folder and each folder in it that is not a project. Give `--project` with a project of the group, for example `--project v1`.
|
|
56
|
+
- A path that a command only reads can go into another project of the group, for example `../v1/original/game.prg`. The command writes only in its own project.
|
|
55
57
|
- An address is `$` and 1 to 4 hex digits, for example `'$c000'` or `'$fb'`, or a name. A name is a symbol, else an analyzer name that only one analyzer gives. Put an address in single quotes in a shell.
|
|
56
58
|
- A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
|
|
57
59
|
- Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
|
|
@@ -136,6 +138,14 @@ Traps:
|
|
|
136
138
|
|
|
137
139
|
The script does the steps of the run file on one program, with no comparison. It writes the files of the steps and `results.json` into `--out`. One run replaces many emulator calls, for example a visit to each room of a game.
|
|
138
140
|
The run starts from a program or from a snapshot file. To continue from the state of the emulator, save that state to a snapshot file in the emulator. Then start the run from that file.
|
|
141
|
+
|
|
142
|
+
A run file must have `name`, `start` and `steps`:
|
|
143
|
+
|
|
144
|
+
```json
|
|
145
|
+
{ "name": "rooms", "start": { "program": "game.prg" }, "steps": [{ "frames": 100 }, { "screen": "title" }] }
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`symbols` and `videoStandard` are optional. The section "Runs" of `references/scenario-format.md` gives each key and step.
|
|
139
149
|
Before the run starts, the script examines the run file, each file that it names and each name of the steps. The section "Checks" of `references/scenario-format.md` gives each refusal.
|
|
140
150
|
|
|
141
151
|
`body` holds:
|
|
@@ -190,6 +200,7 @@ The script does the steps of the record file on the original program. Then it wr
|
|
|
190
200
|
- `out` and `files`: the recording folder and its files.
|
|
191
201
|
- `frames`, `inputSites` and `events`: the length of the session, the number of instructions that read input, and the number of events.
|
|
192
202
|
- `executed`: the number of instructions in the coverage map.
|
|
203
|
+
- `coverageFrom`: the `frame` and the `pc` where the coverage map starts. `null` when the coverage did not start.
|
|
193
204
|
- `reason`: with a FAIL, why the session did not complete.
|
|
194
205
|
|
|
195
206
|
Do this for each result:
|
|
@@ -197,7 +208,7 @@ Do this for each result:
|
|
|
197
208
|
- `PASS`: `hint` tells you to commit the folder and to add its `coverage.bin` to the project knowledge as coverage. `nextAction` replays the recording on the original. Run it to make sure that the recording replays.
|
|
198
209
|
- `FAIL` after a cancel on the page: `hint` tells you to ask the user what to do. Do not record a session from steps in place of the session of the user.
|
|
199
210
|
- Another `FAIL`: `reason` names the step that did not complete. Examples are a `runUntil` step that did not get to its target, and a `type` step with too many keys. Change the step, then run `record` again.
|
|
200
|
-
- `executed` is 0: the
|
|
211
|
+
- `coverageFrom` is `null` and `executed` is 0: the coverage did not start, so the coverage map is empty. The recording can still replay.
|
|
201
212
|
|
|
202
213
|
With `--play`, a person plays the program after the steps. The steps can start the program, for example a key for an intro.
|
|
203
214
|
|
|
@@ -210,6 +221,7 @@ With `--play`, a person plays the program after the steps. The steps can start t
|
|
|
210
221
|
|
|
211
222
|
Traps:
|
|
212
223
|
|
|
224
|
+
- By default, the coverage map starts at the first input read of code in RAM. The start-up code of the program ran before that point, and it has no marks in the map. Do not think that this code did not run. To include it, give `"coverage": "start"` or a `$` address in the record file.
|
|
213
225
|
- Put a `runUntil` step with the checkpoint routine before a `registers` step. A `registers` step that sets the pc during an interrupt stops the program.
|
|
214
226
|
- A record file has no `raster` target and no `condition`. The script refuses them.
|
|
215
227
|
|
|
@@ -26,6 +26,10 @@ A record file is one JSON object in a project file.
|
|
|
26
26
|
- `load`: optional. With `false` (default), the program must load at `$0801` with a BASIC start line, and the C64 types `RUN`. With `true`, the program goes into memory and the C64 stays at READY. Then a `registers` step with `pc` starts the program.
|
|
27
27
|
- `checkpoint`, `state` and `pin`: optional. The comparison that a replay uses when the replay gives none. `checkpoint` is the name or `$` address of a routine. Each entry of the routine is a checkpoint. `state` is 1 to 16 memory items that the checkpoints compare. `pin` is the random state in RAM. An item is a name, a `$` address, or `{ "address", "size" }` with a size from 1 to 4096. Give `checkpoint` and `state` together.
|
|
28
28
|
- `inputs`: optional. The I/O addresses (or ranges such as `$de00-$dfff`) whose reads are input. The default is `$dc00` and `$dc01`: the joystick ports and the keyboard matrix. It also has `$d419` to `$d41c` (the paddles, and the noise and envelope of SID voice 3), and `$de00-$dfff` (no device: the last byte on the bus). Add `$d012` or a CIA timer only for a program that reads a seed there and does not wait in a loop on it.
|
|
29
|
+
- `coverage`: optional. Where the coverage map starts:
|
|
30
|
+
- `input` (default): at the first input read of code in RAM. The start-up code of the program, for example a loader, a relocation or an initialization, is not in the map.
|
|
31
|
+
- `start`: when the program starts, after `RUN` or at the `registers` step of `load` `true`.
|
|
32
|
+
- A `$` address, for example `"$1aed"`: at the first execution of that address.
|
|
29
33
|
- `steps`: the steps.
|
|
30
34
|
|
|
31
35
|
## Steps
|
|
@@ -99,7 +103,7 @@ The page sends input only between Start and End. The input of the page goes into
|
|
|
99
103
|
|---|---|
|
|
100
104
|
| `recording.json` | The program and its SHA-256, the symbols, and the comparison of the record file. Also the inputs, the events, the input sites, the cycles of the session and the state hash at its end. |
|
|
101
105
|
| `reads.txt` | One line `<site> <addr> <from> <value>` for each change of the value at a site. From the read with the index `<from>`, the reads at `<site>` from `<addr>` get `<value>`. One line `end <site> <addr> <count>` for each site gives its number of reads. |
|
|
102
|
-
| `coverage.bin` | The coverage map of the session: 65536 bytes, one for each address, in the format of the coverage maps of the emulator. It starts
|
|
106
|
+
| `coverage.bin` | The coverage map of the session: 65536 bytes, one for each address, in the format of the coverage maps of the emulator. It starts where the key `coverage` of the record file tells. The code before that point has no marks. |
|
|
103
107
|
|
|
104
108
|
A site is the address of the instruction that reads. The values are hex. `<from>` and `<count>` are decimal.
|
|
105
109
|
|
|
@@ -90,11 +90,11 @@ A `pc` value is an address. Compare `pc` only when both programs have the code a
|
|
|
90
90
|
|
|
91
91
|
A run file is one JSON object in a project file. It has:
|
|
92
92
|
|
|
93
|
-
- `name`:
|
|
94
|
-
- `start`: `{ "program": "game.prg" }` to autostart a program with a BASIC start line, `{ "program": "game.prg", "load": true }` to load it with the CPU stopped (set `pc` in a step), or `{ "snapshot": ".c64-re-tools/local/snapshots/room0.vsf" }`.
|
|
93
|
+
- `name`: required. A short name, a non-empty string.
|
|
94
|
+
- `start`: required. `{ "program": "game.prg" }` to autostart a program with a BASIC start line, `{ "program": "game.prg", "load": true }` to load it with the CPU stopped (set `pc` in a step), or `{ "snapshot": ".c64-re-tools/local/snapshots/room0.vsf" }`.
|
|
95
95
|
- `symbols`: optional, `knowledge`, `none` (default), or a JSON file as for a subject. Without `symbols`, a run has no names: give `"symbols": "knowledge"` to use the names of the knowledge.
|
|
96
96
|
- `videoStandard`: optional, `pal` (default) or `ntsc`.
|
|
97
|
-
- `steps`:
|
|
97
|
+
- `steps`: required. At least one step. The steps `write`, `registers`, `joystick`, `type`, `frames` and `runUntil` of a scenario, and the run steps `snapshot`, `save`, `screen`, `coverage`, `trace`, `observe` and `expect`.
|
|
98
98
|
|
|
99
99
|
The run steps have these effects:
|
|
100
100
|
|
|
@@ -173,6 +173,8 @@ Example: visit two rooms from the same start.
|
|
|
173
173
|
|
|
174
174
|
The script checks the scenario before it does a step. A step with an unknown key or a wrong value stops the script with `invalid-input`. The message names the step.
|
|
175
175
|
|
|
176
|
+
A scenario file or a run file with an unknown key also stops the script with `invalid-input`. The message names the key and gives the keys of the file. A missing or wrong `name`, `start` or `steps` gives the form of that key.
|
|
177
|
+
|
|
176
178
|
The script also examines each file before it does a step: the program and the symbols of each side, and each snapshot file. A missing file stops the script with `not-found`. A program that is not a PRG, for example a disk image, stops the script with `invalid-input`. A snapshot file that is not a `.vsf` snapshot file also stops the script with `invalid-input`. The message names the step and the file.
|
|
177
179
|
|
|
178
180
|
A run also examines each name of its steps before it does a step. An unknown name stops the run with `invalid-input`, and the message names the step. In a scenario, a side that does not have a name gives INCONCLUSIVE, and `reason` names the step.
|
|
@@ -12,7 +12,7 @@ import { createHash } from "node:crypto";
|
|
|
12
12
|
import { readFileSync, writeFileSync } from "node:fs";
|
|
13
13
|
|
|
14
14
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
15
|
-
import { formatC64Address, parseC64Address } from "#src/c64.ts";
|
|
15
|
+
import { c64AddressOf, formatC64Address, parseC64Address } from "#src/c64.ts";
|
|
16
16
|
import { READY_FRAMES } from "#src/host-client/entry-state.ts";
|
|
17
17
|
import { ACTION_STEP_KINDS, checkActionStep, isInteger, isObject, keyboardBytes, renamedField, stepKind, type ActionStep, type Location } from "#src/host-client/steps.ts";
|
|
18
18
|
import { readProjectFile, type Written } from "#src/host-client/transfer.ts";
|
|
@@ -57,9 +57,22 @@ export interface RecordFile {
|
|
|
57
57
|
/** The comparison that a replay uses when it gets none: the checkpoint routine and the state. */
|
|
58
58
|
compare?: Comparison;
|
|
59
59
|
inputs: string[];
|
|
60
|
+
/** Where the coverage map starts: "input", "start", or a "$xxxx" address (see COVERAGE_COMMANDS). */
|
|
61
|
+
coverage: string;
|
|
60
62
|
steps: ActionStep[];
|
|
61
63
|
}
|
|
62
64
|
|
|
65
|
+
/**
|
|
66
|
+
* The commands of the replay core that start the coverage map. "input": at the
|
|
67
|
+
* first input read of code in RAM, after a loader or a relocation. "start":
|
|
68
|
+
* when the program starts, with RUN (or the registers step of load true). An
|
|
69
|
+
* address: at the first execution of that address.
|
|
70
|
+
*/
|
|
71
|
+
const COVERAGE_COMMANDS = new Map([
|
|
72
|
+
["input", "coverage on-input"],
|
|
73
|
+
["start", "coverage on"],
|
|
74
|
+
]);
|
|
75
|
+
|
|
63
76
|
/**
|
|
64
77
|
* What a replay compares: the state at each entry of a routine, for example the
|
|
65
78
|
* main loop of a game. `pin` is random state in RAM (a seed, a pointer into a
|
|
@@ -193,7 +206,7 @@ export function readRecordFile(path: string): RecordFile {
|
|
|
193
206
|
return fail((error as Error).message);
|
|
194
207
|
}
|
|
195
208
|
if (!isObject(value)) return fail("it must be a JSON object");
|
|
196
|
-
const known = ["name", "program", "symbols", "load", "checkpoint", "state", "pin", "inputs", "steps"];
|
|
209
|
+
const known = ["name", "program", "symbols", "load", "checkpoint", "state", "pin", "inputs", "coverage", "steps"];
|
|
197
210
|
for (const key of Object.keys(value)) if (!known.includes(key)) fail(`it has the key ${key}; a record file has ${known.join(", ")}`);
|
|
198
211
|
if (typeof value.name !== "string" || value.name === "") fail("name must be a short text");
|
|
199
212
|
if (typeof value.program !== "string" || value.program === "") fail("program must be a PRG file in the project");
|
|
@@ -205,6 +218,10 @@ export function readRecordFile(path: string): RecordFile {
|
|
|
205
218
|
const pin = value.pin === undefined ? undefined : checkState(value.pin, fail, "pin");
|
|
206
219
|
const compare = value.checkpoint === undefined ? undefined : { checkpoint: value.checkpoint as string, state: checkState(value.state, fail), ...(pin === undefined ? {} : { pin }) };
|
|
207
220
|
const inputs = checkInputs(value.inputs, fail);
|
|
221
|
+
const coverage = value.coverage ?? "input";
|
|
222
|
+
if (typeof coverage !== "string" || (!COVERAGE_COMMANDS.has(coverage) && c64AddressOf(coverage) === undefined)) {
|
|
223
|
+
fail(`coverage must be "input" (default), "start" or a $ address such as "$1aed", not ${JSON.stringify(coverage)}`);
|
|
224
|
+
}
|
|
208
225
|
if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
|
|
209
226
|
const steps = (value.steps as unknown[]).map((raw, index) => {
|
|
210
227
|
const at = `step ${index + 1}`;
|
|
@@ -219,6 +236,7 @@ export function readRecordFile(path: string): RecordFile {
|
|
|
219
236
|
load: value.load === true,
|
|
220
237
|
...(compare === undefined ? {} : { compare }),
|
|
221
238
|
inputs,
|
|
239
|
+
coverage: coverage as string,
|
|
222
240
|
steps,
|
|
223
241
|
};
|
|
224
242
|
}
|
|
@@ -444,6 +462,8 @@ export interface RecordOutcome {
|
|
|
444
462
|
recording: Recording;
|
|
445
463
|
reads: Uint8Array;
|
|
446
464
|
coverage: Uint8Array;
|
|
465
|
+
/** The cycle and the instruction at which the coverage map started; none when it never started. */
|
|
466
|
+
coverageFrom?: { tick: number; pc: number };
|
|
447
467
|
/** Why the session did not complete (a runUntil that did not reach its target). */
|
|
448
468
|
reason?: string;
|
|
449
469
|
}
|
|
@@ -471,11 +491,10 @@ export async function record(
|
|
|
471
491
|
const coverage = workspace.path(RECORDING_FILES.coverage);
|
|
472
492
|
await core.init();
|
|
473
493
|
await core.command(`inputs ${inputsArgument(file.inputs)}`);
|
|
474
|
-
// The coverage starts at the first input read of code in RAM: then the program has done its
|
|
475
|
-
// own start (a loader, a relocation), so the map holds the work of the program.
|
|
476
|
-
await core.command("coverage on-input");
|
|
477
494
|
await core.command(`record ${reads}`);
|
|
478
495
|
await startProgram(core, prg, file.load ?? false);
|
|
496
|
+
// From READY on: the start of the C64 itself is never in the map.
|
|
497
|
+
await core.command(COVERAGE_COMMANDS.get(file.coverage) ?? `coverage on-pc ${hex(parseC64Address(file.coverage))}`);
|
|
479
498
|
const events: RecordedEvent[] = [];
|
|
480
499
|
const masks = [0, 0];
|
|
481
500
|
let reason: string | undefined;
|
|
@@ -532,6 +551,7 @@ export async function record(
|
|
|
532
551
|
return { site: `$${site}`, addr: `$${addr}`, reads: Number(reads), rom: kind === "rom" };
|
|
533
552
|
});
|
|
534
553
|
await core.command("record off");
|
|
554
|
+
const from = /from tick=(\d+) pc=([0-9a-f]{4})/.exec(await core.command("coverage status"));
|
|
535
555
|
await core.command(`coverage ${coverage}`);
|
|
536
556
|
const recording: Recording = {
|
|
537
557
|
format: RECORDING_FORMAT,
|
|
@@ -547,7 +567,13 @@ export async function record(
|
|
|
547
567
|
ticks: end.tick,
|
|
548
568
|
hash: end.hash,
|
|
549
569
|
};
|
|
550
|
-
return {
|
|
570
|
+
return {
|
|
571
|
+
recording,
|
|
572
|
+
reads: readFileSync(reads),
|
|
573
|
+
coverage: readFileSync(coverage),
|
|
574
|
+
...(from === null ? {} : { coverageFrom: { tick: Number(from[1]), pc: Number.parseInt(from[2]!, 16) } }),
|
|
575
|
+
...(reason === undefined ? {} : { reason }),
|
|
576
|
+
};
|
|
551
577
|
}
|
|
552
578
|
|
|
553
579
|
/** One side of a replay. */
|
|
@@ -55,6 +55,10 @@ interface Run {
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
const OWN_KINDS = ["snapshot", "save", "screen", "coverage", "observe", "expect", "trace"] as const;
|
|
58
|
+
/** The keys of a run file: name, start and steps are required. */
|
|
59
|
+
const RUN_KEYS = ["name", "start", "steps", "symbols", "videoStandard"];
|
|
60
|
+
const RUN_FIELDS = "A run file has name, start and steps, and optionally symbols and videoStandard";
|
|
61
|
+
const START_FORMS = '{ "program": "<file.prg>" }, { "program": "<file.prg>", "load": true } or { "snapshot": "<file.vsf>" }';
|
|
58
62
|
const TRACE_KEYS = ["trace", "points", "frames", "maxHits"];
|
|
59
63
|
const OBSERVE_KEYS = ["observe", "memory", "registers", "vicii", "sprites"];
|
|
60
64
|
const EXPECT_KEYS = ["expect", "memory", "registers"];
|
|
@@ -111,14 +115,16 @@ function readRun(path: string): Run {
|
|
|
111
115
|
const fail = (message: string): never => {
|
|
112
116
|
throw new Refusal("invalid-input", `run ${path}: ${message}`);
|
|
113
117
|
};
|
|
114
|
-
if (!isObject(value)) return fail(
|
|
115
|
-
|
|
116
|
-
if (
|
|
118
|
+
if (!isObject(value)) return fail(`is not a JSON object. ${RUN_FIELDS}`);
|
|
119
|
+
for (const key of Object.keys(value)) if (!RUN_KEYS.includes(key)) fail(`has the key ${key}. ${RUN_FIELDS}`);
|
|
120
|
+
if (typeof value.name !== "string" || value.name === "") fail('name must be a non-empty string, for example "rooms"');
|
|
121
|
+
if (value.videoStandard !== undefined && value.videoStandard !== "pal" && value.videoStandard !== "ntsc") fail('videoStandard must be "pal" or "ntsc"');
|
|
117
122
|
const start = value.start;
|
|
118
|
-
if (!isObject(start) || (typeof start.program !== "string") === (typeof start.snapshot !== "string")) fail(
|
|
119
|
-
|
|
120
|
-
if (
|
|
121
|
-
if (
|
|
123
|
+
if (!isObject(start) || (typeof start.program !== "string") === (typeof start.snapshot !== "string")) return fail(`start must be ${START_FORMS}`);
|
|
124
|
+
for (const key of Object.keys(start)) if (!(typeof start.program === "string" ? ["program", "load"] : ["snapshot"]).includes(key)) fail(`start has the key ${key}. start must be ${START_FORMS}`);
|
|
125
|
+
if (start.load !== undefined && typeof start.load !== "boolean") fail("start.load must be true or false");
|
|
126
|
+
if (value.symbols !== undefined && typeof value.symbols !== "string") fail('symbols must be "knowledge", "none" or a JSON file');
|
|
127
|
+
if (!Array.isArray(value.steps) || value.steps.length === 0) fail("steps must be a list with at least one step");
|
|
122
128
|
const labels = new Set<string>();
|
|
123
129
|
(value.steps as unknown[]).forEach((step, index) => {
|
|
124
130
|
const at = `step ${index + 1}`;
|
|
@@ -109,6 +109,10 @@ const STEP_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...AC
|
|
|
109
109
|
/** The step kinds that a scenario runs: press is for the replay core only. */
|
|
110
110
|
const SHOWN_KINDS = ["reset", "load", "autostart", "snapshot", "normalize", ...VICE_STEP_KINDS, "observe"];
|
|
111
111
|
|
|
112
|
+
/** The keys of a scenario file: all but videoStandard are required. */
|
|
113
|
+
const SCENARIO_KEYS = ["name", "original", "rebuild", "steps", "videoStandard"];
|
|
114
|
+
const SCENARIO_FIELDS = "A scenario file has name, original, rebuild and steps, and optionally videoStandard";
|
|
115
|
+
|
|
112
116
|
/** The keys each kind of step can have. */
|
|
113
117
|
const STEP_KEYS: Record<string, readonly string[]> = {
|
|
114
118
|
observe: ["observe", "memory", "registers", "screen", "vicii", "sprites"],
|
|
@@ -130,15 +134,18 @@ export function readScenario(path: string): Scenario {
|
|
|
130
134
|
const fail = (message: string): never => {
|
|
131
135
|
throw new Refusal("invalid-input", `scenario ${path}: ${message}`);
|
|
132
136
|
};
|
|
133
|
-
if (!isObject(value)) return fail(
|
|
137
|
+
if (!isObject(value)) return fail(`is not a JSON object. ${SCENARIO_FIELDS}`);
|
|
138
|
+
for (const key of Object.keys(value)) if (!SCENARIO_KEYS.includes(key)) fail(`has the key ${key}. ${SCENARIO_FIELDS}`);
|
|
134
139
|
const scenario = value as unknown as Scenario;
|
|
135
|
-
if (typeof scenario.name !== "string" || scenario.name === "") fail(
|
|
136
|
-
if (scenario.videoStandard !== undefined && scenario.videoStandard !== "pal" && scenario.videoStandard !== "ntsc") fail(
|
|
140
|
+
if (typeof scenario.name !== "string" || scenario.name === "") fail('name must be a non-empty string, for example "player moves left"');
|
|
141
|
+
if (scenario.videoStandard !== undefined && scenario.videoStandard !== "pal" && scenario.videoStandard !== "ntsc") fail('videoStandard must be "pal" or "ntsc"');
|
|
137
142
|
for (const side of SIDES) {
|
|
138
|
-
const subject = scenario[side];
|
|
139
|
-
|
|
143
|
+
const subject: unknown = scenario[side];
|
|
144
|
+
const form = `${side} must be { "program": "<file.prg>", "symbols": "knowledge" }. symbols can also be "none" or a JSON file`;
|
|
145
|
+
if (!isObject(subject) || typeof subject.program !== "string" || typeof subject.symbols !== "string") return fail(form);
|
|
146
|
+
for (const key of Object.keys(subject)) if (key !== "program" && key !== "symbols") fail(`${side} has the key ${key}. ${form}`);
|
|
140
147
|
}
|
|
141
|
-
if (!Array.isArray(scenario.steps) || scenario.steps.length === 0) fail("
|
|
148
|
+
if (!Array.isArray(scenario.steps) || scenario.steps.length === 0) fail("steps must be a list with at least one step");
|
|
142
149
|
const labels = new Set<string>();
|
|
143
150
|
let screens = 0;
|
|
144
151
|
scenario.steps.forEach((step: unknown, index) => {
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// compare the rebuild with it; diff shows what changed between two states;
|
|
5
5
|
// checklist gives the Markdown list for a human tester.
|
|
6
6
|
|
|
7
|
-
import { COVERAGE } from "#src/c64.ts";
|
|
7
|
+
import { COVERAGE, formatC64Address } from "#src/c64.ts";
|
|
8
8
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
9
9
|
import { WireFailure } from "#src/host-client/tools.ts";
|
|
10
10
|
import { readPrg } from "#src/host-client/image.ts";
|
|
@@ -92,8 +92,10 @@ async function recordCommand(call: Call): Promise<Reply> {
|
|
|
92
92
|
frames: Math.round(outcome.recording.ticks / PAL_FRAME_CYCLES),
|
|
93
93
|
inputSites: outcome.recording.sites.length,
|
|
94
94
|
events: outcome.recording.events.length,
|
|
95
|
-
// The instructions in the coverage map: 0 when the
|
|
95
|
+
// The instructions in the coverage map: 0 when the coverage never started.
|
|
96
96
|
executed: outcome.coverage.reduce((count, byte) => count + ((byte & COVERAGE.ramExecute) === 0 ? 0 : 1), 0),
|
|
97
|
+
// The frame and the instruction where the map starts: the code before them has no marks.
|
|
98
|
+
coverageFrom: outcome.coverageFrom === undefined ? null : { frame: Math.floor(outcome.coverageFrom.tick / PAL_FRAME_CYCLES), pc: formatC64Address(outcome.coverageFrom.pc) },
|
|
97
99
|
};
|
|
98
100
|
if (outcome.reason === CANCELLED) return reply({ result: "FAIL", recorded: false, reason: outcome.reason, ...summary }, { hint: "Ask the user what to do. Do not make a scripted recording in place of the session of the user." });
|
|
99
101
|
if (outcome.reason !== undefined) return reply({ result: "FAIL", recorded: false, reason: outcome.reason, ...summary }, { hint: "reason names the step that did not complete. Change that step, then record again." });
|
|
@@ -104,7 +106,7 @@ async function recordCommand(call: Call): Promise<Reply> {
|
|
|
104
106
|
];
|
|
105
107
|
return reply(
|
|
106
108
|
{ result: "PASS", recorded: true, out, ...summary, files },
|
|
107
|
-
{ hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
|
|
109
|
+
{ hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
|
|
108
110
|
);
|
|
109
111
|
} finally {
|
|
110
112
|
await core.close();
|
|
@@ -144,6 +146,7 @@ const COMMANDS: CommandSpec[] = [
|
|
|
144
146
|
summary: "Runs the steps of a run file in its own emulator and writes what they ask for into --out: screens, coverage maps, snapshot files, traces, and results.json with the observations and the expectations. result is FAIL when a step did not run or an expect step found a value that differs.",
|
|
145
147
|
subjects: [{ name: "<run.json>", help: "a run file, relative to the project folder. See references/scenario-format.md, section Runs" }],
|
|
146
148
|
options: { out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the files of the steps and results.json" } },
|
|
149
|
+
notes: 'A run file is one JSON object. It must have name, start and steps. name is a non-empty string. start is { "program": "<file.prg>" }, { "program": "<file.prg>", "load": true } or { "snapshot": "<file.vsf>" }. steps is a list with at least one step. Optional: symbols ("knowledge", "none" (default) or a JSON file) and videoStandard ("pal" (default) or "ntsc"). The script refuses other keys.',
|
|
147
150
|
run: async (call) => {
|
|
148
151
|
const { output, failed } = await runFile(call.subject(0), call.string("out")!);
|
|
149
152
|
if (!failed) return { result: "PASS", ...output };
|
|
@@ -72,6 +72,8 @@ The script refuses a step in an old form. The message gives the step to write.
|
|
|
72
72
|
|
|
73
73
|
- Give each path relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
|
|
74
74
|
- If the working directory is not in a project, give `--project <folder>` to each command. If the working directory has projects below it, the script refuses and lists them.
|
|
75
|
+
- In a group folder, each version of a program is a project. The script refuses the group folder and each folder in it that is not a project. Give `--project` with a project of the group, for example `--project v1`.
|
|
76
|
+
- A path that a command only reads can go into another project of the group, for example `../v1/original/game.prg`. The command writes only in its own project.
|
|
75
77
|
- An address is `$` and 1 to 4 hex digits, for example `'$c000'` or `'$fb'`, or a name. A name is a symbol, else an analyzer name that only one analyzer gives. Put an address in single quotes in a shell.
|
|
76
78
|
- A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
|
|
77
79
|
- Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
|
package/src/host/server.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createServer, type Server, type Socket } from "node:net";
|
|
2
2
|
|
|
3
|
-
import { encodeFrame, MessageReader } from "../protocol/framing.ts";
|
|
3
|
+
import { encodeFrame, FrameTooLarge, MessageReader } from "../protocol/framing.ts";
|
|
4
4
|
import { isRefusal } from "../errors.ts";
|
|
5
|
+
import { PACKAGE } from "../package.ts";
|
|
5
6
|
import { checkHello, isOneOf, HEARTBEAT_TIMEOUT_MS, parseClientMessage, ProtocolError, type HostMessage, type ReceivedRequest, type VideoStandard, type WireError, WireFailure } from "../protocol/messages.ts";
|
|
6
7
|
import { TOOL_OPERATIONS, validateToolParams, type ToolOperation, type ToolOperations } from "../protocol/tools.ts";
|
|
7
8
|
import { attachmentCount, VICE_OPERATIONS, validateViceParams, type ViceOperation, type ViceOperations } from "../protocol/vice.ts";
|
|
@@ -47,6 +48,8 @@ export interface HostServerOptions {
|
|
|
47
48
|
/** How long a ready connection may send nothing (no request, no ping) before it is closed with its session. */
|
|
48
49
|
heartbeatTimeoutMs?: number;
|
|
49
50
|
log?: (line: string) => void;
|
|
51
|
+
/** The package version that the host compares with the client's and gives in ready; PACKAGE.version when not given. */
|
|
52
|
+
release?: string;
|
|
50
53
|
}
|
|
51
54
|
|
|
52
55
|
export interface HostServer {
|
|
@@ -86,6 +89,7 @@ class Connection {
|
|
|
86
89
|
|
|
87
90
|
readonly #socket: Socket;
|
|
88
91
|
readonly #options: HostServerOptions;
|
|
92
|
+
readonly #release: string;
|
|
89
93
|
readonly #log: (line: string) => void;
|
|
90
94
|
readonly #handshakeTimer: NodeJS.Timeout;
|
|
91
95
|
/** Runs from ready on; every received frame restarts it. */
|
|
@@ -96,6 +100,7 @@ class Connection {
|
|
|
96
100
|
constructor(socket: Socket, options: HostServerOptions, log: (line: string) => void) {
|
|
97
101
|
this.#socket = socket;
|
|
98
102
|
this.#options = options;
|
|
103
|
+
this.#release = options.release ?? PACKAGE.version;
|
|
99
104
|
// Every line names its connection, so the console shows which client starts and stops what.
|
|
100
105
|
this.#log = (line) => log(`connection ${this.#id}: ${line}`);
|
|
101
106
|
this.closed = new Promise((resolve) => (this.#resolveClosed = resolve));
|
|
@@ -133,7 +138,27 @@ class Connection {
|
|
|
133
138
|
}
|
|
134
139
|
|
|
135
140
|
#send(message: HostMessage, attachments: readonly Uint8Array[] = []): void {
|
|
136
|
-
|
|
141
|
+
this.#write(encodeFrame(message, attachments));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
#write(frame: Buffer): void {
|
|
145
|
+
if (this.#state !== "closed" && !this.#socket.destroyed) this.#socket.write(frame);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Sends a result. A result too large for the wire is refused with its size and a remedy, and the host log tells it. */
|
|
149
|
+
#reply(request: ReceivedRequest, result: unknown, attachments: readonly Uint8Array[]): void {
|
|
150
|
+
let frame: Buffer;
|
|
151
|
+
try {
|
|
152
|
+
frame = encodeFrame({ type: "reply", id: request.id, result }, attachments);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (!(error instanceof FrameTooLarge)) throw error;
|
|
155
|
+
this.#log(`the reply to ${request.op} is too large to send: ${error.message}`);
|
|
156
|
+
throw new WireFailure(
|
|
157
|
+
"limit-exceeded",
|
|
158
|
+
`The result of this call is ${error.bytes} bytes, more than the ${error.limit} bytes that one reply can hold. Ask for less in one call: a smaller range, count or limit.`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
this.#write(frame);
|
|
137
162
|
}
|
|
138
163
|
|
|
139
164
|
/** Ends the host's side after a refusal; a client that does not close its side in time is cut off. */
|
|
@@ -171,7 +196,7 @@ class Connection {
|
|
|
171
196
|
if (this.#state === "handshake") {
|
|
172
197
|
if (message.type !== "hello") throw new ProtocolError("first message is not hello");
|
|
173
198
|
clearTimeout(this.#handshakeTimer);
|
|
174
|
-
const mismatch = checkHello(message);
|
|
199
|
+
const mismatch = checkHello(message, this.#release);
|
|
175
200
|
if (mismatch !== undefined) {
|
|
176
201
|
this.#log(`refusing a client: ${mismatch.message}`);
|
|
177
202
|
trace().event("connection.refused", { connection: this.#id, role: message.role, ...mismatch });
|
|
@@ -183,7 +208,7 @@ class Connection {
|
|
|
183
208
|
if (message.role === "tool") {
|
|
184
209
|
this.#isTool = true;
|
|
185
210
|
this.#state = "open";
|
|
186
|
-
this.#send({ type: "ready" });
|
|
211
|
+
this.#send({ type: "ready", release: this.#release });
|
|
187
212
|
this.#log("ready for tool requests");
|
|
188
213
|
trace().event("connection.ready", { connection: this.#id, role: "tool" });
|
|
189
214
|
this.#restartHeartbeat();
|
|
@@ -211,7 +236,7 @@ class Connection {
|
|
|
211
236
|
if (session === undefined || this.#state === "closed") return;
|
|
212
237
|
this.#session = session;
|
|
213
238
|
this.#state = "open";
|
|
214
|
-
this.#send({ type: "ready" });
|
|
239
|
+
this.#send({ type: "ready", release: this.#release });
|
|
215
240
|
this.#log(`VICE session ready after ${Math.round(performance.now() - started)} ms`);
|
|
216
241
|
trace().event("connection.ready", { connection: this.#id, role: "vice-session", videoStandard, ms: elapsedMs(started) });
|
|
217
242
|
this.#restartHeartbeat();
|
|
@@ -265,7 +290,7 @@ class Connection {
|
|
|
265
290
|
}
|
|
266
291
|
result = await session.handle(op, params, attachments, replyAttachments);
|
|
267
292
|
}
|
|
268
|
-
this.#
|
|
293
|
+
this.#reply(request, result, replyAttachments);
|
|
269
294
|
record({ ok: true, result });
|
|
270
295
|
} catch (error) {
|
|
271
296
|
if (!isRefusal(error)) {
|