@henols/c64-re-tools 2.6.0-rc.2 → 2.6.0-rc.20

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 (107) hide show
  1. package/package.json +2 -2
  2. package/skills/c64-assembler/SKILL.md +28 -14
  3. package/skills/c64-assembler/scripts/assembler.ts +28 -15
  4. package/skills/c64-development/SKILL.md +4 -4
  5. package/skills/c64-docs/SKILL.md +9 -7
  6. package/skills/c64-docs/scripts/docs.ts +24 -11
  7. package/skills/c64-docs/scripts/lib/reference.ts +119 -33
  8. package/skills/c64-docs/scripts/lib/source-map.ts +23 -4
  9. package/skills/c64-knowledge/SKILL.md +67 -42
  10. package/skills/c64-knowledge/scripts/knowledge.ts +90 -67
  11. package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
  12. package/skills/c64-packer/SKILL.md +1 -1
  13. package/skills/c64-provenance/SKILL.md +11 -10
  14. package/skills/c64-provenance/scripts/lib/library.ts +16 -16
  15. package/skills/c64-provenance/scripts/provenance.ts +33 -23
  16. package/skills/c64-reverse-engineering/SKILL.md +17 -11
  17. package/skills/c64-source/SKILL.md +71 -47
  18. package/skills/c64-source/scripts/lib/export.ts +89 -34
  19. package/skills/c64-source/scripts/lib/loader.ts +79 -36
  20. package/skills/c64-source/scripts/lib/source.ts +38 -32
  21. package/skills/c64-source/scripts/lib/stage.ts +11 -5
  22. package/skills/c64-source/scripts/lib/start-screen.asm +4 -2
  23. package/skills/c64-source/scripts/source.ts +278 -145
  24. package/skills/c64-static-analysis/SKILL.md +29 -25
  25. package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
  26. package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
  27. package/skills/c64-static-analysis/scripts/lib/instructions.ts +26 -24
  28. package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
  29. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -67
  30. package/skills/c64-testing/SKILL.md +15 -5
  31. package/skills/c64-testing/references/recording-format.md +26 -5
  32. package/skills/c64-testing/references/scenario-format.md +11 -8
  33. package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
  34. package/skills/c64-testing/scripts/lib/play.ts +39 -41
  35. package/skills/c64-testing/scripts/lib/recording.ts +220 -46
  36. package/skills/c64-testing/scripts/lib/replay.ts +32 -6
  37. package/skills/c64-testing/scripts/lib/runs.ts +8 -3
  38. package/skills/c64-testing/scripts/lib/scenario.ts +18 -11
  39. package/skills/c64-testing/scripts/testing.ts +23 -2
  40. package/skills/c64-unpacker/SKILL.md +10 -5
  41. package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
  42. package/skills/c64-unpacker/scripts/lib/machine.ts +7 -3
  43. package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
  44. package/skills/c64-unpacker/scripts/unpacker.ts +43 -9
  45. package/skills/emulator/SKILL.md +7 -12
  46. package/src/build-name.ts +55 -0
  47. package/src/c64-keys.ts +98 -0
  48. package/src/c64.ts +22 -2
  49. package/src/cli/main.ts +3 -29
  50. package/src/host/main.ts +3 -3
  51. package/src/host/server.ts +3 -1
  52. package/src/host/tools/index.ts +2 -7
  53. package/src/host/vice/process.ts +34 -17
  54. package/src/host/vice/session.ts +138 -31
  55. package/src/host-client/steps.ts +21 -18
  56. package/src/host-client/tools.ts +2 -7
  57. package/src/host-client/vice-session.ts +7 -1
  58. package/src/knowledge/evidence.ts +66 -0
  59. package/src/knowledge/history.ts +5 -5
  60. package/src/knowledge/import.ts +12 -5
  61. package/src/knowledge/program.ts +123 -32
  62. package/src/knowledge/read.ts +36 -13
  63. package/src/knowledge/schema.ts +43 -17
  64. package/src/knowledge/start-screen.ts +70 -0
  65. package/src/knowledge/text.ts +33 -5
  66. package/src/knowledge/write.ts +75 -36
  67. package/src/mcp/inputs.ts +12 -0
  68. package/src/mcp/server.ts +1 -1
  69. package/src/mcp/tools/debug.ts +23 -21
  70. package/src/mcp/tools/input.ts +38 -5
  71. package/src/mcp/tools/machine.ts +3 -42
  72. package/src/mcp/tools/media.ts +1 -1
  73. package/src/mcp/tools/memory.ts +12 -9
  74. package/src/native/acme.ts +1 -1
  75. package/src/native/c64run.ts +7 -4
  76. package/src/native/decompiler/analyze.ts +98 -0
  77. package/src/native/decompiler/c64rt-wasm.ts +4 -0
  78. package/src/native/decompiler/language/c64rt_6510.sla +0 -0
  79. package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
  80. package/src/native/decompiler/pcode.ts +222 -0
  81. package/src/native/decompiler/walk.ts +205 -0
  82. package/src/native/decompiler/wasm.ts +98 -0
  83. package/src/native/discover.ts +3 -3
  84. package/src/native/dxa.ts +12 -1
  85. package/src/native/processes.ts +4 -4
  86. package/src/native/types.ts +27 -27
  87. package/src/opcodes.ts +1 -1
  88. package/src/platform.ts +30 -1
  89. package/src/project.ts +17 -4
  90. package/src/protocol/tools.ts +1 -45
  91. package/src/protocol/vice.ts +47 -0
  92. package/src/reference-pages.ts +64 -0
  93. package/src/script.ts +4 -4
  94. package/src/vsf.ts +98 -0
  95. package/tools/c64run.c +158 -15
  96. package/tools/install-container.sh +1 -2
  97. package/src/cli/status.ts +0 -127
  98. package/src/host/tools/status.ts +0 -47
  99. package/src/native/ghidra/analyze.ts +0 -87
  100. package/src/native/ghidra/index.ts +0 -170
  101. package/src/native/ghidra/scripts/C64Export.java +0 -274
  102. package/src/native/ghidra/scripts/C64Prepare.java +0 -66
  103. package/src/native/status.ts +0 -135
  104. package/tools/install-ghidra.sh +0 -40
  105. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
  106. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
  107. /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
package/tools/c64run.c CHANGED
@@ -27,11 +27,9 @@
27
27
  #include "systems/c1541.h"
28
28
  #include "systems/c64.h"
29
29
 
30
- #define C64RUN_PROTOCOL 3
31
- // Keys that chips has no code for: each SHIFT alone, and the up arrow.
32
- #define C64RUN_KEY_LSHIFT 0x11
33
- #define C64RUN_KEY_RSHIFT 0x12
34
- #define C64RUN_KEY_UPARROW 0x5E
30
+ #define C64RUN_PROTOCOL 7
31
+ // The key code of matrix place 0 (row 0, column 0); place n has code 0x80 + n.
32
+ #define C64RUN_KEY_PLACE 0x80
35
33
  #ifndef CHIPS_COMMIT
36
34
  #define CHIPS_COMMIT "unknown"
37
35
  #endif
@@ -228,6 +226,80 @@ static void sample(void) {
228
226
  if (sample_stop && samples >= sample_stop) halted = 1;
229
227
  }
230
228
 
229
+ // ---- Counts: the opcode fetches at some pcs, from "count-pc" on ----
230
+
231
+ #define MAX_COUNTED 64
232
+ // 0: the pc is not counted; else the index of its count + 1.
233
+ static uint8_t counted_at[0x10000];
234
+ static uint16_t counted_pc[MAX_COUNTED];
235
+ static uint64_t counted[MAX_COUNTED];
236
+ static int counted_pcs;
237
+ // "mark": the counts and the tick at the first opcode fetch at mark_pc, before that fetch counts.
238
+ static uint64_t marked[MAX_COUNTED];
239
+ static uint64_t mark_tick;
240
+ static int mark_pc = -1; // -1: no mark waits
241
+ static int mark_set; // marked and mark_tick hold the mark
242
+
243
+ // The phase of the machine at the mark: the beam position, the timers and interrupt
244
+ // state of both CIAs and the interrupt state of the CPU. It depends on how the
245
+ // program was started, and no program can set all of it. "align" gives it to
246
+ // another run at its own entry, so both runs go on from the same phase.
247
+ typedef struct {
248
+ uint16_t line, cycle;
249
+ m6526_timer_t ta[2], tb[2];
250
+ m6526_int_t intr[2];
251
+ uint16_t irq_pip;
252
+ uint32_t nmi_pip;
253
+ uint8_t brk_flags;
254
+ uint64_t pins, cpu_pins; // only the IRQ and NMI lines
255
+ } phase_t;
256
+ static phase_t mark_phase;
257
+
258
+ static void phase_get(phase_t* p) {
259
+ memset(p, 0, sizeof *p);
260
+ p->line = sys.vic.rs.v_count;
261
+ p->cycle = sys.vic.rs.h_count;
262
+ const m6526_t* cia[2] = { &sys.cia_1, &sys.cia_2 };
263
+ for (int i = 0; i < 2; i++) { p->ta[i] = cia[i]->ta; p->tb[i] = cia[i]->tb; p->intr[i] = cia[i]->intr; }
264
+ p->irq_pip = sys.cpu.irq_pip;
265
+ p->nmi_pip = sys.cpu.nmi_pip;
266
+ p->brk_flags = sys.cpu.brk_flags;
267
+ p->pins = pins & (M6502_IRQ | M6502_NMI);
268
+ p->cpu_pins = sys.cpu.PINS & (M6502_IRQ | M6502_NMI);
269
+ }
270
+
271
+ static void phase_set(const phase_t* p) {
272
+ m6526_t* cia[2] = { &sys.cia_1, &sys.cia_2 };
273
+ for (int i = 0; i < 2; i++) { cia[i]->ta = p->ta[i]; cia[i]->tb = p->tb[i]; cia[i]->intr = p->intr[i]; }
274
+ sys.cpu.irq_pip = p->irq_pip;
275
+ sys.cpu.nmi_pip = p->nmi_pip;
276
+ sys.cpu.brk_flags = p->brk_flags;
277
+ pins = (pins & ~(M6502_IRQ | M6502_NMI)) | p->pins;
278
+ sys.cpu.PINS = (sys.cpu.PINS & ~(M6502_IRQ | M6502_NMI)) | p->cpu_pins;
279
+ }
280
+
281
+ static void clear_counts(void) {
282
+ for (int i = 0; i < counted_pcs; i++) counted_at[counted_pc[i]] = 0;
283
+ counted_pcs = 0;
284
+ mark_pc = -1;
285
+ mark_set = 0;
286
+ }
287
+
288
+ static void count_fetch(uint16_t pc) {
289
+ if (mark_pc == pc) {
290
+ for (int i = 0; i < counted_pcs; i++) marked[i] = counted[i];
291
+ mark_tick = ticks;
292
+ phase_get(&mark_phase);
293
+ mark_pc = -1;
294
+ mark_set = 1;
295
+ }
296
+ if (counted_at[pc]) counted[counted_at[pc] - 1]++;
297
+ }
298
+
299
+ static uint64_t count_of(uint16_t pc) {
300
+ return counted_at[pc] ? counted[counted_at[pc] - 1] : 0;
301
+ }
302
+
231
303
  // ---- The tick ----
232
304
 
233
305
  static void tick(void) {
@@ -242,6 +314,14 @@ static void tick(void) {
242
314
  last_sync_pc = addr;
243
315
  if (sample_file && addr == sample_pc && decoded) sample();
244
316
  if (coverage_armed_pc && addr == coverage_pc && decoded) { coverage_armed_pc = 0; coverage_start(addr); }
317
+ if (decoded) count_fetch(addr);
318
+ }
319
+ if (read && !sync && decoded && sys.io_mapped && (addr & 0xFF0F) == 0xDC00) {
320
+ // chips gives port A of CIA 1 only joystick 2. A key also pulls its line of port A
321
+ // low while port B drives its column low: the scan from port B that some games use.
322
+ const m6526_port_t* pb = &sys.cia_1.pb;
323
+ const uint8_t low_columns = (uint8_t)~(pb->reg | ~pb->ddr);
324
+ if (low_columns) M6502_SET_DATA(pins, M6502_GET_DATA(pins) & (uint8_t)~kbd_test_lines(&sys.kbd, low_columns));
245
325
  }
246
326
  if (read && !sync && decoded && sys.io_mapped && (addr & 0xF000) == 0xD000 && input_addr[addr & 0x0FFF]) {
247
327
  input_read(last_sync_pc, addr);
@@ -335,10 +415,9 @@ static const char* init(const char* romdir) {
335
415
  .chars = { .ptr = rom[2], .size = 0x1000 },
336
416
  },
337
417
  });
338
- // The matrix positions (column, line) of the keys that chips has no code for.
339
- kbd_register_key(&sys.kbd, C64RUN_KEY_LSHIFT, 7, 1, 0);
340
- kbd_register_key(&sys.kbd, C64RUN_KEY_RSHIFT, 4, 6, 0);
341
- kbd_register_key(&sys.kbd, C64RUN_KEY_UPARROW, 6, 6, 0);
418
+ // One code for each place of the matrix: place row * 8 + column, where the row is the
419
+ // line of CIA 1 port A and the column the bit of port B (chips: column, line).
420
+ for (int place = 0; place < 64; place++) kbd_register_key(&sys.kbd, C64RUN_KEY_PLACE + place, place & 7, place >> 3, 0);
342
421
  const uint16_t vector = rom[0][0x1FFC] | (rom[0][0x1FFD] << 8);
343
422
  for (int i = 0; i < 3; i++) free(rom[i]);
344
423
  pins = sys.pins;
@@ -440,6 +519,7 @@ int main(int argc, char** argv) {
440
519
  halted = 0;
441
520
  sample_stop = 0;
442
521
  maps = 0;
522
+ clear_counts();
443
523
  coverage_reset();
444
524
  if (pin_file) { fclose(pin_file); pin_file = NULL; }
445
525
  if (record_file) { fclose(record_file); record_file = NULL; }
@@ -489,6 +569,7 @@ int main(int argc, char** argv) {
489
569
  last_sync_pc = pc;
490
570
  // The prefetch is the opcode fetch at pc: it does not pass through tick.
491
571
  if (coverage_armed_pc && pc == coverage_pc) { coverage_armed_pc = 0; coverage_start(pc); }
572
+ count_fetch((uint16_t)pc);
492
573
  if (coverage_on) cover(pc, 1, 1);
493
574
  status("ok");
494
575
  } else if (!strcmp(cmd, "run")) {
@@ -501,12 +582,74 @@ int main(int argc, char** argv) {
501
582
  do tick(); while (!(pins & M6502_SYNC) && !halted);
502
583
  status("ok");
503
584
  } else if (!strcmp(cmd, "run-pc")) {
504
- // run-pc <pc hex> <until tick>: run to the next opcode fetch at pc
585
+ // run-pc <pc hex> <until tick> [<n>]: run to the next opcode fetch at pc; with n, run
586
+ // until the count of pc ("count-pc") is n
505
587
  unsigned pc;
506
- const unsigned long long until = strtoull(a2, NULL, 10);
507
- if (sscanf(a1, "%x", &pc) != 1) { printf("err run-pc: give a pc and a tick\n"); continue; }
588
+ unsigned long long until, n;
589
+ const int fields = sscanf(line, "%*s %x %llu %llu", &pc, &until, &n);
590
+ if (fields < 2 || pc > 0xFFFF) { printf("err run-pc: give a pc and a tick\n"); continue; }
591
+ if (fields == 3) {
592
+ if (!counted_at[pc]) { printf("err run-pc: give count-pc with %04x first\n", pc); continue; }
593
+ while (count_of((uint16_t)pc) < n && ticks < until && !halted) tick();
594
+ status(count_of((uint16_t)pc) >= n ? "ok reached" : "ok not-reached");
595
+ continue;
596
+ }
508
597
  do tick(); while (!((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc) && ticks < until && !halted);
509
598
  status((pins & M6502_SYNC) && M6502_GET_ADDR(pins) == pc ? "ok reached" : "ok not-reached");
599
+ } else if (!strcmp(cmd, "count-pc")) {
600
+ // count-pc <pc hex,...> | off: count the opcode fetches at each pc from 0
601
+ clear_counts();
602
+ if (!strcmp(a1, "off")) { printf("ok counted=0\n"); continue; }
603
+ int bad = 0;
604
+ for (char* part = strtok(a1, ","); part; part = strtok(NULL, ",")) {
605
+ unsigned pc;
606
+ if (sscanf(part, "%x", &pc) != 1 || pc > 0xFFFF || counted_pcs == MAX_COUNTED) { bad = 1; break; }
607
+ if (counted_at[pc]) continue;
608
+ counted_pc[counted_pcs] = (uint16_t)pc;
609
+ counted[counted_pcs] = 0;
610
+ counted_at[pc] = (uint8_t)++counted_pcs;
611
+ }
612
+ if (bad) { clear_counts(); printf("err count-pc: give 1 to %d pcs in hex\n", MAX_COUNTED); } else printf("ok counted=%d\n", counted_pcs);
613
+ } else if (!strcmp(cmd, "mark")) {
614
+ // mark <pc hex>: keep the counts of count-pc at the next opcode fetch at pc, before it counts
615
+ unsigned pc;
616
+ if (sscanf(a1, "%x", &pc) != 1 || pc > 0xFFFF) { printf("err mark: give a pc\n"); continue; }
617
+ mark_pc = (int)pc;
618
+ mark_set = 0;
619
+ printf("ok\n");
620
+ } else if (!strcmp(cmd, "marked")) {
621
+ // marked: the tick and the phase (hex) of the mark when it came, else none
622
+ if (mark_set) {
623
+ printf("ok tick=%llu phase=", (unsigned long long)mark_tick);
624
+ for (size_t i = 0; i < sizeof mark_phase; i++) printf("%02x", ((const uint8_t*)&mark_phase)[i]);
625
+ printf("\n");
626
+ }
627
+ else printf("ok none\n");
628
+ } else if (!strcmp(cmd, "align")) {
629
+ // align <phase hex>: at an opcode fetch, hold the CPU on the fetch (RDY, as the VIC-II
630
+ // does on a bad line) until the beam is at the position of the phase, then give the
631
+ // CIAs and the CPU the timers and interrupt state of the phase (from "marked")
632
+ phase_t p;
633
+ if (strlen(a1) != 2 * sizeof p || !(pins & M6502_SYNC)) { printf("err align: give the phase of marked, at an opcode fetch\n"); continue; }
634
+ for (size_t i = 0; i < sizeof p; i++) ((uint8_t*)&p)[i] = (uint8_t)hexbyte(a1 + 2 * i);
635
+ // A PAL frame holds each beam position one time.
636
+ uint64_t held = 0;
637
+ while ((sys.vic.rs.v_count != p.line || sys.vic.rs.h_count != p.cycle) && held <= 312 * 63) {
638
+ pins = _c64_tick(&sys, pins | M6502_RDY);
639
+ ticks++;
640
+ held++;
641
+ }
642
+ if (sys.vic.rs.v_count != p.line || sys.vic.rs.h_count != p.cycle) { printf("err align: the beam never came to line %u cycle %u\n", p.line, p.cycle); continue; }
643
+ phase_set(&p);
644
+ char prefix[64];
645
+ snprintf(prefix, sizeof prefix, "ok held=%llu", (unsigned long long)held);
646
+ status(prefix);
647
+ } else if (!strcmp(cmd, "hits")) {
648
+ // hits <pc hex>: the count of a pc of count-pc, and its count at the mark when the mark came
649
+ unsigned pc;
650
+ if (sscanf(a1, "%x", &pc) != 1 || pc > 0xFFFF) { printf("err hits: give a pc\n"); continue; }
651
+ if (mark_set && counted_at[pc]) printf("ok count=%llu marked=%llu\n", (unsigned long long)count_of((uint16_t)pc), (unsigned long long)marked[counted_at[pc] - 1]);
652
+ else printf("ok count=%llu\n", (unsigned long long)count_of((uint16_t)pc));
510
653
  } else if (!strcmp(cmd, "run-reads")) {
511
654
  // run-reads <pc hex> <addr hex> <n> <until tick>: run until the site has n reads
512
655
  unsigned pc, addr;
@@ -536,11 +679,11 @@ int main(int argc, char** argv) {
536
679
  c64_joystick(&sys, (uint8_t)j1, (uint8_t)j2);
537
680
  printf("ok\n");
538
681
  } else if (!strcmp(cmd, "key")) {
539
- // key <code hex> down|up: a key of the keyboard matrix; the code is ASCII as
540
- // chips maps it (A-Z, 0-9, space 20, return 0d, ...); shifted keys press SHIFT.
541
- // 11 and 12 are the left and right SHIFT alone, 5e the up arrow, ff RESTORE (NMI).
682
+ // key <code hex> down|up: 80 + place is the key at matrix place row * 8 + column
683
+ // (80-bf), ff is RESTORE (NMI). chips holds at most 4 keys at once.
542
684
  unsigned code;
543
685
  if (sscanf(a1, "%x", &code) != 1 || (strcmp(a2, "down") && strcmp(a2, "up"))) { printf("err key: give a code and down or up\n"); continue; }
686
+ if ((code < C64RUN_KEY_PLACE || code >= C64RUN_KEY_PLACE + 64) && code != C64_KEY_RESTORE) { printf("err key: give 80-bf (a matrix place) or ff (RESTORE)\n"); continue; }
544
687
  if (!strcmp(a2, "down")) c64_key_down(&sys, (int)code);
545
688
  else {
546
689
  // chips releases a key in kbd_update, after its sticky time: one call
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bash
2
2
  # The native tools of the skill scripts in a Debian or Ubuntu dev container,
3
- # as root: ACME, dxa, Exomizer, c64run with its C64 ROMs, and Ghidra. The dev container
3
+ # as root: ACME, dxa, Exomizer, and c64run with its C64 ROMs. The dev container
4
4
  # Feature runs the copy of this script that comes with the toolkit version it
5
5
  # installs, so the tools and the skills are always of the same version.
6
6
  # A tool is installed again only when its install files changed: a stamp in
@@ -57,6 +57,5 @@ packages acme unzip curl ca-certificates build-essential
57
57
  tool dxa install-dxa.sh
58
58
  tool exomizer install-exomizer.sh
59
59
  tool c64run install-chips.sh c64run.c
60
- tool ghidra install-ghidra.sh
61
60
 
62
61
  [[ -z "${APT_UPDATED}" ]] || rm -rf /var/lib/apt/lists/*
package/src/cli/status.ts DELETED
@@ -1,127 +0,0 @@
1
- // The status report of the CLI: the installed skills and MCP declarations,
2
- // the tools on this machine and the Host Runtime with its tools.
3
-
4
- import { readFileSync } from "node:fs";
5
- import { isAbsolute, join } from "node:path";
6
-
7
- import { installedItems, scopeRoot, type InstallItem, type Scope } from "./cleanup.ts";
8
- import { hostTools, type ToolCallOptions } from "../host-client/tools.ts";
9
- import { viceVersionOf } from "../native/discover.ts";
10
- import { PACKAGE } from "../package.ts";
11
- import { STOP_AND_ASK } from "../protocol/messages.ts";
12
- import type { HostInfo, ToolStatus } from "../protocol/tools.ts";
13
-
14
- /** One line per tool under `heading`: its version, or why it does not run; then each known flaw of it. */
15
- export function toolLines(heading: string, tools: readonly ToolStatus[]): string[] {
16
- return [
17
- heading,
18
- ...tools.flatMap((tool) => [
19
- tool.runs
20
- ? ` ${tool.name}: ${tool.version} (${tool.path})`
21
- : tool.found
22
- ? ` ${tool.name}: found at ${tool.path} but it does not run. ${tool.problem}`
23
- : ` ${tool.name}: missing. ${tool.problem}`,
24
- ...(tool.flaws ?? []).map((flaw) => ` Known flaw: ${flaw}`),
25
- ]),
26
- ];
27
- }
28
-
29
- /**
30
- * Whether the Host Runtime answers, and the tools it has. VICE and its tools
31
- * live on the host; it finds and runs each one. One request shows both that
32
- * the host answers and what it has. `ready` is true when the host answers and
33
- * every tool on it runs.
34
- */
35
- export async function hostStatusLines(options: ToolCallOptions = {}): Promise<{ lines: string[]; ready: boolean }> {
36
- let host: HostInfo;
37
- let tools: ToolStatus[];
38
- try {
39
- ({ host, tools } = await hostTools(options));
40
- } catch (error) {
41
- // status is read by a person: the instruction for an agent stays out.
42
- return { lines: [`Host Runtime: not reachable. ${(error as Error).message.replace(` ${STOP_AND_ASK}`, "")}`], ready: false };
43
- }
44
- const mixed = mixedViceBuilds(tools);
45
- return {
46
- lines: [
47
- `Host Runtime: reachable, c64-re-tools ${host.version} on ${host.platform} ${host.release} (${host.arch})`,
48
- ...(host.version === PACKAGE.version ? [] : [` Warning: the Host Runtime is c64-re-tools ${host.version} and this is ${PACKAGE.version}. Start the host again so that both are the same version.`]),
49
- ...toolLines("Tools on the host:", tools),
50
- ...(mixed === undefined ? [] : [` Warning: ${mixed}`]),
51
- ],
52
- ready: tools.every((tool) => tool.runs),
53
- };
54
- }
55
-
56
- /** A warning when x64sc, c1541 and petcat that run come from different VICE versions or builds. */
57
- export function mixedViceBuilds(tools: readonly ToolStatus[]): string | undefined {
58
- const running = tools.filter((tool) => tool.runs && tool.version !== undefined);
59
- const builds = running.map((tool) => {
60
- const version = viceVersionOf(tool.version!);
61
- return version === undefined ? tool.version! : `VICE ${version.major}.${version.minor}${version.revision === undefined ? "" : ` SVN r${version.revision}`}`;
62
- });
63
- if (new Set(builds).size <= 1) return undefined;
64
- return `the VICE tools come from different VICE builds: ${running.map((tool) => `${tool.version} (${tool.path})`).join(", ")}. Put x64sc, c1541 and petcat of one VICE first on PATH, or set C64RT_VICE, C64RT_C1541 and C64RT_PETCAT.`;
65
- }
66
-
67
- /**
68
- * The skills and MCP declarations that install wrote for this project and
69
- * globally: the c64-re-tools version of each harness's skills,
70
- * from their package.json, and the command that starts the MCP server. A
71
- * warning names skills of another version than this one.
72
- */
73
- export function installedLines(cwd = process.cwd()): string[] {
74
- const lines: string[] = [];
75
- for (const scope of ["project", "global"] as const satisfies readonly Scope[]) {
76
- const items = installedItems(scope, undefined, cwd);
77
- if (items.length === 0) continue;
78
- const root = scopeRoot(scope, cwd);
79
- lines.push(`Installed ${scope === "project" ? `in this project (${root})` : "globally"}:`);
80
- for (const harness of [...new Set(items.map((item) => item.harness))]) {
81
- const skills = items.filter((item) => item.harness === harness && item.kind === "skill");
82
- const versions = [...new Set(skills.map((item) => skillVersion(item, root)).filter((version) => version !== undefined))];
83
- if (skills.length > 0) {
84
- lines.push(` ${harness}: ${skills.length} skills, c64-re-tools ${versions.length === 0 ? "of an unknown version" : versions.join(" and ")}`);
85
- const other = versions.filter((version) => version !== PACKAGE.version);
86
- if (other.length > 0) lines.push(` Warning: the ${harness} skills are c64-re-tools ${other.join(" and ")} and this is ${PACKAGE.version}. Run npx -y ${PACKAGE.name}@${PACKAGE.tag} update${scope === "global" ? " --global" : ""} to install this version.`);
87
- }
88
- for (const item of items.filter((candidate) => candidate.harness === harness && candidate.kind === "mcp")) {
89
- lines.push(` ${harness} MCP server: ${mcpCommand(item, root) ?? `declared in ${item.files.join(", ")}`}`);
90
- }
91
- }
92
- }
93
- if (lines.length === 0) return ["Installed: nothing in this project or globally."];
94
- return lines;
95
- }
96
-
97
- function itemPath(file: string, root: string): string {
98
- return isAbsolute(file) ? file : join(root, file);
99
- }
100
-
101
- /** The version in the package.json of an installed skill; a skill without scripts has none. */
102
- function skillVersion(item: InstallItem, root: string): string | undefined {
103
- const file = item.files.find((candidate) => candidate.endsWith("/package.json") || candidate.endsWith("\\package.json"));
104
- if (file === undefined) return undefined;
105
- try {
106
- const { version } = JSON.parse(readFileSync(itemPath(file, root), "utf8")) as { version?: unknown };
107
- return typeof version === "string" ? version : undefined;
108
- } catch {
109
- return undefined;
110
- }
111
- }
112
-
113
- /** The command of the MCP server in a JSON configuration file, or undefined for another format. */
114
- function mcpCommand(item: InstallItem, root: string): string | undefined {
115
- const key = item.detail?.mergeKey;
116
- const [file] = item.files;
117
- if (key === undefined || file === undefined) return undefined;
118
- try {
119
- const servers = (JSON.parse(readFileSync(itemPath(file, root), "utf8")) as Record<string, unknown>)[key] as Record<string, { command?: unknown; args?: unknown }> | undefined;
120
- const server = servers?.[item.name];
121
- if (typeof server?.command !== "string") return undefined;
122
- const args = Array.isArray(server.args) ? server.args.filter((arg): arg is string => typeof arg === "string") : [];
123
- return [server.command, ...args].join(" ");
124
- } catch {
125
- return undefined;
126
- }
127
- }
@@ -1,47 +0,0 @@
1
- // host.status: VICE and the tools that come with it, each found the way its
2
- // operations find it and run once with a version option. A tool from a
3
- // VICE older than MIN_VICE is reported as not working, as its operations refuse it.
4
- // VICE itself is reported with the version that the host read from the
5
- // running emulator at start: the Homebrew x64sc of VICE 3.10 on macOS stops
6
- // on -version ("argv[0] is NULL") although the emulator runs.
7
-
8
- import { arch, platform, release } from "node:os";
9
-
10
- import { PACKAGE } from "../../package.ts";
11
- import type { HostInfo, ToolStatus } from "../../protocol/tools.ts";
12
- import { C1541, findTool, isOlderThanMinimum, MIN_VICE, PETCAT, VICE, viceFlaws, viceVersionOf, type ToolSpec, type ViceVersion } from "../../native/discover.ts";
13
- import type { ToolContext } from "../../native/run.ts";
14
- import { probeTools } from "../../native/status.ts";
15
- import { findVice } from "../vice/process.ts";
16
-
17
- function requireMinimum(status: ToolStatus, tool: ToolSpec): ToolStatus {
18
- if (!status.runs) return status;
19
- const version = viceVersionOf(status.version ?? "");
20
- if (version !== undefined && !isOlderThanMinimum(version)) return status;
21
- const found = version === undefined ? "It does not tell its VICE version" : `It comes from VICE ${version.major}.${version.minor}`;
22
- return { ...status, runs: false, problem: `${found}, and c64-re-tools needs VICE ${MIN_VICE.major}.${MIN_VICE.minor} or later. ${tool.remedy}` };
23
- }
24
-
25
- /** The version text of a VICE version, as x64sc -version prints it. */
26
- const versionText = (version: ViceVersion) => `x64sc (VICE ${version.major}.${version.minor}${version.revision === undefined ? "" : ` SVN r${version.revision}`})`;
27
-
28
- /** `started`: the version that the host read from the emulator at start; without it, VICE is probed with -version too. */
29
- export async function hostStatus(context: ToolContext, started?: ViceVersion): Promise<{ result: { host: HostInfo; tools: ToolStatus[] } }> {
30
- const specs = [VICE, C1541, PETCAT];
31
- const probed = await probeTools(
32
- [
33
- ...(started === undefined ? [{ name: VICE.name, find: findVice, args: ["-version"], pattern: /^x64sc \(VICE \d/ }] : []),
34
- { name: C1541.name, find: (env) => findTool(C1541, env), args: ["-version"], pattern: /^c1541 \(VICE \d/ },
35
- { name: PETCAT.name, find: (env) => findTool(PETCAT, env), args: ["-version"], pattern: /^petcat \(VICE \d/ },
36
- ],
37
- context,
38
- );
39
- const tools = started === undefined ? probed : [{ name: VICE.name, found: true, path: findVice(context.env ?? process.env), version: versionText(started), runs: true }, ...probed];
40
- const checked = tools.map((status, index) => requireMinimum(status, specs[index]!));
41
- // VICE runs with its known flaws; status names them.
42
- const vice = checked[0]!;
43
- const version = vice.runs ? viceVersionOf(vice.version ?? "") : undefined;
44
- const flaws = version === undefined ? [] : viceFlaws(version).map((flaw) => flaw.text);
45
- if (flaws.length > 0) checked[0] = { ...vice, flaws };
46
- return { result: { host: { version: PACKAGE.version, platform: platform(), release: release(), arch: arch() }, tools: checked } };
47
- }
@@ -1,87 +0,0 @@
1
- // The Ghidra analysis: one disposable headless run with the NMOS
2
- // 6510 language, knowledge seeds before analysis, and the structural export
3
- // after it. The result is checked completely before the script imports it.
4
-
5
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
-
7
- import { Refusal } from "../../errors.ts";
8
- import { describeError, isObject, WireFailure } from "../../protocol/messages.ts";
9
- import { checkGhidraResult, checkRequestBounds, GHIDRA_LIMITS, imageRange, seedsInside, type GhidraParams, type GhidraResult } from "../types.ts";
10
- import { outputTail, type ToolContext } from "../run.ts";
11
- import { Workspace } from "../staging.ts";
12
- import { findGhidra, ghidraVersion, runHeadless, SCRIPT_DIRECTORY } from "./index.ts";
13
-
14
- const TIMEOUT_MS = 600_000;
15
- /** The part of the run that the decompilations leave for the export, the project removal and the end of Ghidra. */
16
- const AFTER_DECOMPILE_MS = 30_000;
17
-
18
- export async function analyze(
19
- params: GhidraParams,
20
- image: Buffer,
21
- context: ToolContext,
22
- ): Promise<{ result: GhidraResult }> {
23
- checkRequestBounds(params);
24
- const ghidra = findGhidra(context.env);
25
- const { start, end, body } = imageRange(params.imageKind, image);
26
- const base = start;
27
-
28
- // Ghidra disassembles and defines data only in the loaded bytes; labels may name any address.
29
- const { entryPoints, codeStarts, dataRanges } = seedsInside(params, start, end);
30
- if (entryPoints.length === 0) {
31
- throw new WireFailure("invalid-input", "Give at least one entry point inside the program, for example the SYS address of its BASIC loader.");
32
- }
33
-
34
- const workspace = Workspace.create(context.supervisor);
35
- try {
36
- workspace.materialize("input", [{ path: "image.bin", size: body.length }], [body]);
37
- writeFileSync(workspace.path("seeds.json"), JSON.stringify({ start, end, entryPoints, codeStarts, dataRanges, labels: params.labels }));
38
- writeFileSync(
39
- workspace.path("request.json"),
40
- JSON.stringify({
41
- start,
42
- end,
43
- decompile: params.decompile,
44
- maxChars: GHIDRA_LIMITS.decompiledChars,
45
- maxTotalChars: GHIDRA_LIMITS.decompiledTotalChars,
46
- decompileDeadline: Date.now() + TIMEOUT_MS - AFTER_DECOMPILE_MS,
47
- }),
48
- );
49
- const run = await runHeadless({
50
- ghidra,
51
- workspace,
52
- file: "input/image.bin",
53
- baseAddress: base,
54
- scriptDirectories: [SCRIPT_DIRECTORY],
55
- preScripts: [{ name: "C64Prepare.java", args: [workspace.path("seeds.json")] }],
56
- postScripts: [{ name: "C64Export.java", args: [workspace.path("request.json"), workspace.path("out.json")] }],
57
- analyze: true,
58
- timeoutMs: TIMEOUT_MS,
59
- supervisor: context.supervisor,
60
- signal: context.signal,
61
- ...(context.env === undefined ? {} : { env: context.env }),
62
- }).catch((error: unknown) => {
63
- context.log?.(`Ghidra failed: ${describeError(error)}`);
64
- throw error;
65
- });
66
- const outPath = workspace.path("out.json");
67
- if (!existsSync(outPath)) {
68
- context.log?.(`Ghidra wrote no result:\n${run.stdout.slice(-4000)}\n${run.stderr.slice(-4000)}`);
69
- // Ghidra's own warnings and errors say why its export script wrote nothing.
70
- throw new WireFailure("operation-failed", `Ghidra finished without a result.${outputTail("Ghidra", run, workspace.root, /ERROR|WARN|Exception|Error:|SCRIPT/)}`);
71
- }
72
- let result: GhidraResult;
73
- try {
74
- const exported: unknown = JSON.parse(readFileSync(outPath, "utf8"));
75
- // The version comes from the installation's application.properties, which findGhidra read.
76
- result = checkGhidraResult(isObject(exported) ? { ...exported, toolVersion: ghidraVersion(ghidra) } : exported);
77
- const [range] = result.coverage;
78
- if (result.coverage.length !== 1 || range === undefined || range.start !== start || range.end !== end) throw new Refusal("operation-failed", "the coverage is not the loaded program");
79
- } catch (error) {
80
- context.log?.(`Ghidra result rejected: ${describeError(error)}`);
81
- throw new WireFailure("operation-failed", `Ghidra returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
82
- }
83
- return { result };
84
- } finally {
85
- workspace.remove();
86
- }
87
- }