c64bridge 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +3 -3
  3. package/data/sound/sidwave.md +113 -36
  4. package/data/sound/sidwave.schema.json +138 -28
  5. package/dist/.tsbuildinfo +1 -1
  6. package/dist/c64Client.js +83 -93
  7. package/dist/chargen.js +0 -4
  8. package/dist/config.js +26 -6
  9. package/dist/device.js +130 -24
  10. package/dist/diagnostics.js +14 -5
  11. package/dist/logger.js +3 -2
  12. package/dist/loggingHttpClient.js +12 -1
  13. package/dist/mcp-server.js +19 -9
  14. package/dist/petscii.js +0 -5
  15. package/dist/redact.js +166 -0
  16. package/dist/sidwave.js +453 -61
  17. package/dist/sidwaveCompiler.js +1424 -269
  18. package/dist/tools/audio.js +70 -12
  19. package/dist/tools/developer.js +17 -9
  20. package/dist/tools/errors.js +7 -0
  21. package/dist/tools/graphics.js +4 -4
  22. package/dist/tools/input.js +10 -13
  23. package/dist/tools/machineControl.js +7 -7
  24. package/dist/tools/memory.js +6 -6
  25. package/dist/tools/meta/audio.js +8 -2
  26. package/dist/tools/meta/config.js +5 -4
  27. package/dist/tools/meta/configInventory.js +25 -2
  28. package/dist/tools/meta/diagnostics.js +2 -1
  29. package/dist/tools/meta/graphics.js +1 -1
  30. package/dist/tools/meta/memory.js +4 -4
  31. package/dist/tools/meta/program.js +12 -8
  32. package/dist/tools/printer.js +4 -4
  33. package/dist/tools/programRunners.js +8 -8
  34. package/dist/tools/registry/batch.js +1 -7
  35. package/dist/tools/registry/disk.js +7 -5
  36. package/dist/tools/storage.js +21 -17
  37. package/dist/tools/streaming.js +2 -2
  38. package/dist/tools/translation/assembler.js +44 -12
  39. package/dist/tools/translation/basicTokenizer.js +5 -1
  40. package/dist/tools/translation/opcodeInventory.js +1 -1
  41. package/dist/tools/vice.js +1 -1
  42. package/dist/vice/mockServer.js +92 -5
  43. package/dist/vice/readiness.js +4 -9
  44. package/dist/vice/viceClient.js +18 -0
  45. package/doc/audit/secret-handling.md +61 -0
  46. package/mcp/schemas/c64_config.schema.json +19 -2
  47. package/mcp/schemas/c64_disk.schema.json +2 -2
  48. package/mcp/schemas/c64_input.schema.json +3 -3
  49. package/mcp/schemas/c64_program.schema.json +2 -2
  50. package/mcp/schemas/c64_vice.schema.json +3 -3
  51. package/mcp/server.json +1 -1
  52. package/mcp/tools.json +33 -12
  53. package/mcp.json +1 -1
  54. package/package.json +5 -2
  55. package/scripts/mockC64Server.mjs +15 -1
  56. package/scripts/run-coverage.mjs +31 -1
  57. package/scripts/update-readme.ts +3 -2
  58. package/server.json +20 -3
@@ -1,5 +1,5 @@
1
1
  import { compileSidwaveToPrg, compileSidwaveToSid } from "../sidwaveCompiler.js";
2
- import { parseSidwave } from "../sidwave.js";
2
+ import { midiToHz, noteNameToMidi, parseSidwave } from "../sidwave.js";
3
3
  import { recordAndAnalyzeAudio } from "../audio/record_and_analyze_audio.js";
4
4
  import { defineToolModule } from "./types.js";
5
5
  import { booleanSchema, numberSchema, objectSchema, optionalSchema, stringSchema, } from "./schema.js";
@@ -318,6 +318,21 @@ function transposeNote(note, semitones) {
318
318
  const newOctave = Math.floor(midi / 12) - 1;
319
319
  return `${names[wrapped]}${newOctave}`;
320
320
  }
321
+ /** Highest frequency the SID's 16-bit frequency register can produce (about 3848 Hz PAL, 3995 Hz NTSC). */
322
+ function maxSidFrequencyHz(system) {
323
+ return (0xffff * (system === "PAL" ? 985248 : 1022727)) / 16777216;
324
+ }
325
+ /** Reject a note or frequency the SID cannot play instead of letting playback clamp or skip it. */
326
+ function assertPlayableFrequency(hz, label, system, path) {
327
+ const max = maxSidFrequencyHz(system);
328
+ if (hz > max + 0.5) {
329
+ throw new ToolValidationError(`${label} (${hz.toFixed(1)} Hz) is above the SID's highest ${system} frequency of ${max.toFixed(1)} Hz`, { path });
330
+ }
331
+ }
332
+ function noteHz(note) {
333
+ const midi = noteNameToMidi(note);
334
+ return midi === undefined ? Number.NaN : midiToHz(midi);
335
+ }
321
336
  function sleep(ms, signal) {
322
337
  return new Promise((resolve) => {
323
338
  if (signal?.aborted) {
@@ -347,6 +362,28 @@ function resolveAnalyzer(ctx) {
347
362
  }
348
363
  return (options) => recordAndAnalyzeAudio(options);
349
364
  }
365
+ /**
366
+ * Measure whether the SID is silent by capturing audio (the Ultimate audio
367
+ * stream on C64U, otherwise the host microphone). The SID's control registers
368
+ * are write-only, so reading them back cannot show whether a voice sounds.
369
+ */
370
+ export async function measureSidSilence(ctx) {
371
+ if (DEFAULT_SILENCE_VERIFY_WAIT_MS > 0) {
372
+ await sleep(DEFAULT_SILENCE_VERIFY_WAIT_MS);
373
+ }
374
+ const analysis = await resolveAnalyzer(ctx)({ durationSeconds: DEFAULT_SILENCE_VERIFY_DURATION_SECONDS });
375
+ const { average, max } = extractRmsMetrics((analysis?.analysis?.global_metrics ?? {}));
376
+ if (average === null && max === null) {
377
+ throw new ToolExecutionError("Audio analysis did not provide RMS metrics for silence verification");
378
+ }
379
+ const maxRms = max ?? average ?? 0;
380
+ return {
381
+ silent: maxRms <= DEFAULT_SILENCE_VERIFY_RMS_THRESHOLD,
382
+ averageRms: average ?? maxRms,
383
+ maxRms,
384
+ threshold: DEFAULT_SILENCE_VERIFY_RMS_THRESHOLD,
385
+ };
386
+ }
350
387
  function extractRmsMetrics(globalMetrics) {
351
388
  const average = typeof globalMetrics.average_rms === "number" ? globalMetrics.average_rms : null;
352
389
  const max = typeof globalMetrics.max_rms === "number" ? globalMetrics.max_rms : null;
@@ -453,7 +490,7 @@ export const audioModule = defineToolModule({
453
490
  });
454
491
  const result = await ctx.client.sidSetVolume(parsed.volume);
455
492
  if (!result.success) {
456
- throw new ToolExecutionError("C64 firmware reported failure while setting SID volume", {
493
+ throw new ToolExecutionError("C64 backend reported failure while setting SID volume", {
457
494
  details: normaliseFailure(result.details),
458
495
  });
459
496
  }
@@ -496,7 +533,7 @@ export const audioModule = defineToolModule({
496
533
  cancelGeneratedSidPlayback(); // Reset is the documented way to stop a generated arpeggio.
497
534
  const result = await ctx.client.sidReset(parsed.hard);
498
535
  if (!result.success) {
499
- throw new ToolExecutionError("C64 firmware reported failure while resetting SID", {
536
+ throw new ToolExecutionError("C64 backend reported failure while resetting SID", {
500
537
  details: normaliseFailure(result.details),
501
538
  });
502
539
  }
@@ -533,6 +570,13 @@ export const audioModule = defineToolModule({
533
570
  try {
534
571
  const parsed = sidNoteOnArgsSchema.parse(args ?? {});
535
572
  const voice = Math.max(1, Math.min(3, Math.floor(parsed.voice ?? 1)));
573
+ const system = (parsed.system ?? "PAL");
574
+ if (parsed.note) {
575
+ assertPlayableFrequency(noteHz(parsed.note), parsed.note, system, "$.note");
576
+ }
577
+ else if (parsed.frequencyHz !== undefined) {
578
+ assertPlayableFrequency(parsed.frequencyHz, `${parsed.frequencyHz} Hz`, system, "$.frequencyHz");
579
+ }
536
580
  ctx.logger.info("Starting SID voice", {
537
581
  voice,
538
582
  note: parsed.note ?? null,
@@ -552,7 +596,7 @@ export const audioModule = defineToolModule({
552
596
  release: parsed.release,
553
597
  });
554
598
  if (!result.success) {
555
- throw new ToolExecutionError("C64 firmware reported failure while starting SID voice", {
599
+ throw new ToolExecutionError("C64 backend reported failure while starting SID voice", {
556
600
  details: normaliseFailure(result.details),
557
601
  });
558
602
  }
@@ -606,7 +650,7 @@ export const audioModule = defineToolModule({
606
650
  ctx.logger.info("Stopping SID voice", { voice });
607
651
  const result = await ctx.client.sidNoteOff(voice);
608
652
  if (!result.success) {
609
- throw new ToolExecutionError("C64 firmware reported failure while stopping SID voice", {
653
+ throw new ToolExecutionError("C64 backend reported failure while stopping SID voice", {
610
654
  details: normaliseFailure(result.details),
611
655
  });
612
656
  }
@@ -646,7 +690,7 @@ export const audioModule = defineToolModule({
646
690
  cancelGeneratedSidPlayback(); // Otherwise its remaining notes would resume writing right after this silences the chip.
647
691
  const result = await ctx.client.sidSilenceAll();
648
692
  if (!result.success) {
649
- throw new ToolExecutionError("C64 firmware reported failure while silencing SID", {
693
+ throw new ToolExecutionError("C64 backend reported failure while silencing SID", {
650
694
  details: normaliseFailure(result.details),
651
695
  });
652
696
  }
@@ -737,7 +781,7 @@ export const audioModule = defineToolModule({
737
781
  ctx.logger.info("Playing SID file", { path: parsed.path, songnr: parsed.songnr ?? null });
738
782
  const result = await ctx.client.sidplayFile(parsed.path, parsed.songnr);
739
783
  if (!result.success) {
740
- throw new ToolExecutionError("C64 firmware reported failure while starting SID playback", {
784
+ throw new ToolExecutionError("C64 backend reported failure while starting SID playback", {
741
785
  details: normaliseFailure(result.details),
742
786
  });
743
787
  }
@@ -777,7 +821,7 @@ export const audioModule = defineToolModule({
777
821
  ctx.logger.info("Playing MOD file", { path: parsed.path });
778
822
  const result = await ctx.client.modplayFile(parsed.path);
779
823
  if (!result.success) {
780
- throw new ToolExecutionError("C64 firmware reported failure while starting MOD playback", {
824
+ throw new ToolExecutionError("C64 backend reported failure while starting MOD playback", {
781
825
  details: normaliseFailure(result.details),
782
826
  });
783
827
  }
@@ -824,6 +868,8 @@ export const audioModule = defineToolModule({
824
868
  const iv = intervals[i % intervals.length];
825
869
  const note = transposeNote(parsed.root, iv);
826
870
  const durationMs = parsed.preset === "expression" ? expressiveDurations[i % expressiveDurations.length] : parsed.tempoMs;
871
+ // Playback runs in the background, so a note the SID cannot play must be rejected here.
872
+ assertPlayableFrequency(noteHz(note), note, "PAL", "$.root");
827
873
  timeline.push({ t: timestamp, note, durationMs });
828
874
  timestamp += durationMs;
829
875
  }
@@ -910,7 +956,15 @@ export const audioModule = defineToolModule({
910
956
  tags: ["sid", "music", "compiler"],
911
957
  prerequisites: [],
912
958
  examples: [
913
- { name: "Compile PRG", description: "Play compiled PRG", arguments: { sidwave: "song: { title: 'Demo' }", output: "prg", dryRun: false } },
959
+ {
960
+ name: "Compile PRG",
961
+ description: "Play compiled PRG",
962
+ arguments: {
963
+ sidwave: "sidwave: 1.0\ntitle: Demo\ntempo: 120\nmode: PAL\nvoices:\n - id: 1\n waveform: triangle\n patterns: { A: { groove: [C4, E4, G4, C5] } }\ntimeline:\n - { bars: 2, layers: { v1: A } }\n",
964
+ output: "prg",
965
+ dryRun: false,
966
+ },
967
+ },
914
968
  ],
915
969
  workflowHints: [
916
970
  "Use when the user provides SIDWAVE/CPG scores or asks for export to PRG/SID; share any generated download URIs in your response.",
@@ -941,7 +995,7 @@ export const audioModule = defineToolModule({
941
995
  const sid = compileSidwaveToSid(document, compiled.prg, { entryAddress: compiled.entryAddress });
942
996
  const result = await ctx.client.sidplayAttachment(sid.sid);
943
997
  if (!result.success) {
944
- throw new ToolExecutionError("C64 firmware reported failure while playing compiled SID", {
998
+ throw new ToolExecutionError("C64 backend reported failure while playing compiled SID", {
945
999
  details: normaliseFailure(result.details),
946
1000
  });
947
1001
  }
@@ -951,7 +1005,7 @@ export const audioModule = defineToolModule({
951
1005
  else {
952
1006
  const result = await ctx.client.runPrg(compiled.prg);
953
1007
  if (!result.success) {
954
- throw new ToolExecutionError("C64 firmware reported failure while running compiled PRG", {
1008
+ throw new ToolExecutionError("C64 backend reported failure while running compiled PRG", {
955
1009
  details: normaliseFailure(result.details),
956
1010
  });
957
1011
  }
@@ -967,13 +1021,17 @@ export const audioModule = defineToolModule({
967
1021
  pulse_width: voice.pulse_width,
968
1022
  adsr: voice.adsr,
969
1023
  }));
970
- return textResult(message, {
1024
+ // Warnings (for example a PRG that leaves no room for BASIC) go into the text that clients show.
1025
+ const warningText = compiled.warnings.length > 0 ? `\nWarning: ${compiled.warnings.join("\nWarning: ")}` : "";
1026
+ return textResult(`${message}${warningText}`, {
971
1027
  success: true,
972
1028
  ranOnC64,
973
1029
  dryRun: parsed.dryRun,
974
1030
  format: outputFormat,
975
1031
  prgSize: compiled.prg.length,
976
1032
  entryAddress: compiled.entryAddress,
1033
+ basicFreeBytes: compiled.basicFreeBytes,
1034
+ warnings: compiled.warnings,
977
1035
  song: document.song,
978
1036
  voices: voiceSummaries,
979
1037
  runDetails,
@@ -1,6 +1,7 @@
1
1
  import { defineToolModule } from "./types.js";
2
- import { objectSchema, optionalSchema, stringSchema, } from "./schema.js";
2
+ import { booleanSchema, objectSchema, optionalSchema, stringSchema, } from "./schema.js";
3
3
  import { jsonResult, textResult } from "./responses.js";
4
+ import { redactConfigValue } from "../redact.js";
4
5
  import { ToolError, ToolExecutionError, ToolValidationError, toolErrorResult, unknownErrorResult, } from "./errors.js";
5
6
  function toRecord(details) {
6
7
  if (details === undefined || details === null) {
@@ -61,6 +62,10 @@ const configGetArgsSchema = objectSchema({
61
62
  properties: {
62
63
  category: categorySchema,
63
64
  item: itemSchema,
65
+ includeSecretValues: optionalSchema(booleanSchema({
66
+ description: "Return credential values (network password, FTP/Telnet passwords, Wi-Fi keys) in plain text. Default false: those values are replaced with ***.",
67
+ default: false,
68
+ }), false),
64
69
  },
65
70
  required: ["category"],
66
71
  additionalProperties: false,
@@ -190,7 +195,10 @@ export const developerModule = defineToolModule({
190
195
  category: parsed.category,
191
196
  item: parsed.item ?? null,
192
197
  });
193
- const details = await ctx.client.configGet(parsed.category, parsed.item);
198
+ const raw = await ctx.client.configGet(parsed.category, parsed.item);
199
+ const details = parsed.includeSecretValues === true
200
+ ? raw
201
+ : redactConfigValue(raw, parsed.category, parsed.item);
194
202
  return withStructuredJson({ value: details }, {
195
203
  success: true,
196
204
  category: parsed.category,
@@ -229,7 +237,7 @@ export const developerModule = defineToolModule({
229
237
  });
230
238
  const result = await ctx.client.configSet(parsed.category, parsed.item, String(parsed.value));
231
239
  if (!result.success) {
232
- throw new ToolExecutionError("C64 firmware reported failure while updating configuration", {
240
+ throw new ToolExecutionError("C64 backend reported failure while updating configuration", {
233
241
  details: toRecord(result.details),
234
242
  });
235
243
  }
@@ -275,7 +283,7 @@ export const developerModule = defineToolModule({
275
283
  ]));
276
284
  const result = await ctx.client.configBatchUpdate(requestPayload);
277
285
  if (!result.success) {
278
- throw new ToolExecutionError("C64 firmware reported failure during batch configuration update", {
286
+ throw new ToolExecutionError("C64 backend reported failure during batch configuration update", {
279
287
  details: toRecord(result.details),
280
288
  });
281
289
  }
@@ -312,7 +320,7 @@ export const developerModule = defineToolModule({
312
320
  ctx.logger.info("Loading configuration from flash");
313
321
  const result = await ctx.client.configLoadFromFlash();
314
322
  if (!result.success) {
315
- throw new ToolExecutionError("C64 firmware reported failure while loading from flash", {
323
+ throw new ToolExecutionError("C64 backend reported failure while loading from flash", {
316
324
  details: toRecord(result.details),
317
325
  });
318
326
  }
@@ -348,7 +356,7 @@ export const developerModule = defineToolModule({
348
356
  ctx.logger.info("Saving configuration to flash");
349
357
  const result = await ctx.client.configSaveToFlash();
350
358
  if (!result.success) {
351
- throw new ToolExecutionError("C64 firmware reported failure while saving to flash", {
359
+ throw new ToolExecutionError("C64 backend reported failure while saving to flash", {
352
360
  details: toRecord(result.details),
353
361
  });
354
362
  }
@@ -384,7 +392,7 @@ export const developerModule = defineToolModule({
384
392
  ctx.logger.info("Resetting configuration to defaults");
385
393
  const result = await ctx.client.configResetToDefault();
386
394
  if (!result.success) {
387
- throw new ToolExecutionError("C64 firmware reported failure while resetting configuration", {
395
+ throw new ToolExecutionError("C64 backend reported failure while resetting configuration", {
388
396
  details: toRecord(result.details),
389
397
  });
390
398
  }
@@ -484,7 +492,7 @@ export const developerModule = defineToolModule({
484
492
  ctx.logger.info("Reading debug register");
485
493
  const result = await ctx.client.debugregRead();
486
494
  if (!result.success) {
487
- throw new ToolExecutionError("C64 firmware reported failure while reading debug register", {
495
+ throw new ToolExecutionError("C64 backend reported failure while reading debug register", {
488
496
  details: toRecord(result.details),
489
497
  });
490
498
  }
@@ -524,7 +532,7 @@ export const developerModule = defineToolModule({
524
532
  ctx.logger.info("Writing debug register", { value });
525
533
  const result = await ctx.client.debugregWrite(value);
526
534
  if (!result.success) {
527
- throw new ToolExecutionError("C64 firmware reported failure while writing debug register", {
535
+ throw new ToolExecutionError("C64 backend reported failure while writing debug register", {
528
536
  details: toRecord(result.details),
529
537
  });
530
538
  }
@@ -63,6 +63,13 @@ export function unknownErrorResult(error) {
63
63
  if (error instanceof ToolError) {
64
64
  return toolErrorResult(error);
65
65
  }
66
+ // Input documents such as SIDWAVE scores are checked outside the tool schemas;
67
+ // their errors carry a path and are input errors, not internal failures.
68
+ if (error instanceof Error && error.name === "SidwaveValidationError") {
69
+ const path = error.path;
70
+ const metadata = { kind: "validation", ...(typeof path === "string" ? { path } : {}) };
71
+ return { ...textResult(error.message, { error: metadata }), isError: true };
72
+ }
66
73
  const metadata = { kind: "unknown" };
67
74
  const message = error instanceof Error ? error.message : String(error);
68
75
  const base = textResult(message, { error: metadata });
@@ -349,7 +349,7 @@ async function executeGenerateSprite(rawArgs, ctx) {
349
349
  multicolour: parsed.multicolour,
350
350
  });
351
351
  if (!result.success) {
352
- throw new ToolExecutionError("C64 firmware reported failure while rendering sprite", {
352
+ throw new ToolExecutionError("C64 backend reported failure while rendering sprite", {
353
353
  details: normaliseFailure(result.details),
354
354
  });
355
355
  }
@@ -383,7 +383,7 @@ async function executeRenderPetscii(rawArgs, ctx) {
383
383
  });
384
384
  const result = await ctx.client.renderPetsciiScreenAndRun(parsed);
385
385
  if (!result.success) {
386
- throw new ToolExecutionError("C64 firmware reported failure while rendering PETSCII text", {
386
+ throw new ToolExecutionError("C64 backend reported failure while rendering PETSCII text", {
387
387
  details: normaliseFailure(result.details),
388
388
  });
389
389
  }
@@ -426,7 +426,7 @@ async function executeGenerateBitmap(rawArgs, ctx) {
426
426
  screenAddress: parsed.screenAddress,
427
427
  });
428
428
  if (!result.success) {
429
- throw new ToolExecutionError("C64 firmware reported failure while displaying bitmap image", {
429
+ throw new ToolExecutionError("C64 backend reported failure while displaying bitmap image", {
430
430
  details: normaliseFailure(result.details),
431
431
  });
432
432
  }
@@ -498,7 +498,7 @@ async function executeCreatePetscii(rawArgs, ctx) {
498
498
  if (!parsed.dryRun) {
499
499
  runResult = await ctx.client.uploadAndRunBasic(art.program);
500
500
  if (!runResult.success) {
501
- throw new ToolExecutionError("C64 firmware reported failure while rendering PETSCII art", {
501
+ throw new ToolExecutionError("C64 backend reported failure while rendering PETSCII art", {
502
502
  details: normaliseFailure(runResult.details),
503
503
  });
504
504
  }
@@ -1,7 +1,7 @@
1
1
  import { createOperationDispatcher, defineToolModule, discriminatedUnionSchema, } from "./types.js";
2
2
  import { arraySchema, literalSchema, numberSchema, objectSchema, optionalSchema, stringSchema, } from "./schema.js";
3
3
  import { jsonResult, textResult } from "./responses.js";
4
- import { ToolValidationError, toolErrorResult, unknownErrorResult, } from "./errors.js";
4
+ import { ToolExecutionError, ToolValidationError, toolErrorResult, unknownErrorResult, } from "./errors.js";
5
5
  function isMissingNativeInputEndpoint(error) {
6
6
  return typeof error === "object"
7
7
  && error !== null
@@ -9,7 +9,7 @@ function isMissingNativeInputEndpoint(error) {
9
9
  && error.response?.status === 404;
10
10
  }
11
11
  function nativeInputUnavailableResult(operation) {
12
- return textResult(`Native physical input is unavailable on this firmware, so ${operation} was not sent. Use c64://platform/status before choosing native input; use key or write_text for ordinary C64 input.`, { success: false, code: "native_input_unavailable", fallback: "key_or_write_text" });
12
+ return toolErrorResult(new ToolExecutionError(`Native physical input is unavailable on this firmware, so ${operation} was not sent. Use c64://platform/status before choosing native input; use key or write_text for ordinary C64 input.`, { code: "native_input_unavailable", details: { fallback: "key_or_write_text" } }));
13
13
  }
14
14
  // ---------------------------------------------------------------------------
15
15
  // PETSCII token expansion table
@@ -57,12 +57,10 @@ const PETSCII_TOKENS = {
57
57
  LIGHT_GREY: 155,
58
58
  REVERSE_ON: 18,
59
59
  REVERSE_OFF: 146,
60
- FLASH_ON: 130,
61
- FLASH_OFF: 148,
60
+ // FLASH ON/OFF, ESC and TAB are C128 codes: on a C64, 148 is INST (inserts a
61
+ // space) and 9 re-enables SHIFT+C= case switching, so they are not offered.
62
62
  LOWERCASE: 14,
63
63
  UPPERCASE: 142,
64
- ESCAPE: 27,
65
- TAB: 9,
66
64
  CURSOR_UP: 145,
67
65
  CURSOR_DOWN: 17,
68
66
  CURSOR_LEFT: 157,
@@ -176,7 +174,7 @@ export const keyArgsSchema = objectSchema({
176
174
  additionalProperties: false,
177
175
  });
178
176
  export const joystickArgsSchema = objectSchema({
179
- description: "Simulate joystick input. On C64U/U64 this uses machine:input; VICE uses Binary Monitor Joyport Set.",
177
+ description: "Simulate joystick input. On C64U/U64 this uses machine:input. On VICE it attaches VICE's I/O simulation joyport device while pressed; that device also pulls CIA lines 5-7 low, so port 1 produces phantom keys (e.g. SHIFT+C=) and port 2 reads $1E for up instead of $7E. Prefer port 2 on VICE and test bits 0-4.",
180
178
  properties: {
181
179
  op: literalSchema("joystick"),
182
180
  port: numberSchema({
@@ -297,7 +295,6 @@ const inputOperationHandlers = {
297
295
  const port = parsed.port;
298
296
  const durationMs = parsed.durationMs ?? 80;
299
297
  const pressedByte = joystickByte(parsed.controls);
300
- const releasedByte = 0xff;
301
298
  const platform = await ctx.client.getActiveBackendType();
302
299
  if (platform === "c64u") {
303
300
  if (parsed.controls.length === 0 && parsed.action === "release") {
@@ -315,19 +312,19 @@ const inputOperationHandlers = {
315
312
  throw new ToolValidationError("VICE joystick supports up, down, left, right, and fire only.", { path: "$.controls" });
316
313
  }
317
314
  if (parsed.action === "release") {
318
- await ctx.client.viceJoyportSet(port, releasedByte);
315
+ await ctx.client.viceJoystickRelease(port);
319
316
  ctx.logger.info("Released joystick", { port });
320
317
  return textResult(`Joystick port ${port} released.`, { success: true, port, action: "release" });
321
318
  }
322
319
  if (parsed.action === "press") {
323
- await ctx.client.viceJoyportSet(port, pressedByte);
320
+ await ctx.client.viceJoystickPress(port, pressedByte);
324
321
  ctx.logger.info("Pressed joystick", { port, controls: parsed.controls, byte: pressedByte });
325
- return textResult(`Joystick port ${port} pressed: ${parsed.controls.join(", ") || "none"}.`, { success: true, port, action: "press", controls: parsed.controls });
322
+ return textResult(`Joystick port ${port} pressed: ${parsed.controls.join(", ") || "none"}.${port === 1 ? " On VICE, port 1 also shows phantom keys while held." : ""}`, { success: true, port, action: "press", controls: parsed.controls });
326
323
  }
327
324
  // tap: press → wait → release
328
- await ctx.client.viceJoyportSet(port, pressedByte);
325
+ await ctx.client.viceJoystickPress(port, pressedByte);
329
326
  await new Promise((res) => setTimeout(res, durationMs));
330
- await ctx.client.viceJoyportSet(port, releasedByte);
327
+ await ctx.client.viceJoystickRelease(port);
331
328
  ctx.logger.info("Tapped joystick", { port, controls: parsed.controls, durationMs });
332
329
  return textResult(`Joystick port ${port} tapped: ${parsed.controls.join(", ") || "none"} for ${durationMs}ms.`, { success: true, port, action: "tap", controls: parsed.controls, durationMs });
333
330
  }
@@ -70,7 +70,7 @@ export const machineControlModule = defineToolModule({
70
70
  ctx.logger.info("Resetting C64");
71
71
  const result = await ctx.client.reset();
72
72
  if (!result.success) {
73
- throw new ToolExecutionError("C64 firmware reported failure while resetting", {
73
+ throw new ToolExecutionError("C64 backend reported failure while resetting", {
74
74
  details: normaliseFailure(result.details),
75
75
  });
76
76
  }
@@ -108,7 +108,7 @@ export const machineControlModule = defineToolModule({
108
108
  ctx.logger.info("Rebooting C64");
109
109
  const result = await ctx.client.reboot();
110
110
  if (!result.success) {
111
- throw new ToolExecutionError("C64 firmware reported failure while rebooting", {
111
+ throw new ToolExecutionError("C64 backend reported failure while rebooting", {
112
112
  details: normaliseFailure(result.details),
113
113
  });
114
114
  }
@@ -146,7 +146,7 @@ export const machineControlModule = defineToolModule({
146
146
  ctx.logger.info("Pausing C64 execution");
147
147
  const result = await ctx.client.pause();
148
148
  if (!result.success) {
149
- throw new ToolExecutionError("C64 firmware reported failure while pausing", {
149
+ throw new ToolExecutionError("C64 backend reported failure while pausing", {
150
150
  details: normaliseFailure(result.details),
151
151
  });
152
152
  }
@@ -184,7 +184,7 @@ export const machineControlModule = defineToolModule({
184
184
  ctx.logger.info("Resuming C64 execution");
185
185
  const result = await ctx.client.resume();
186
186
  if (!result.success) {
187
- throw new ToolExecutionError("C64 firmware reported failure while resuming", {
187
+ throw new ToolExecutionError("C64 backend reported failure while resuming", {
188
188
  details: normaliseFailure(result.details),
189
189
  });
190
190
  }
@@ -222,7 +222,7 @@ export const machineControlModule = defineToolModule({
222
222
  ctx.logger.info("Powering off C64");
223
223
  const result = await ctx.client.poweroff();
224
224
  if (!result.success) {
225
- throw new ToolExecutionError("C64 firmware reported failure while powering off", {
225
+ throw new ToolExecutionError("C64 backend reported failure while powering off", {
226
226
  details: normaliseFailure(result.details),
227
227
  });
228
228
  }
@@ -295,7 +295,7 @@ export const machineControlModule = defineToolModule({
295
295
  ctx.logger.info("Toggling Ultimate menu button");
296
296
  const result = await ctx.client.menuButton();
297
297
  if (!result.success) {
298
- throw new ToolExecutionError("C64 firmware reported failure while toggling menu button", {
298
+ throw new ToolExecutionError("C64 backend reported failure while toggling menu button", {
299
299
  details: normaliseFailure(result.details),
300
300
  });
301
301
  }
@@ -342,7 +342,7 @@ export const machineControlModule = defineToolModule({
342
342
  if (error instanceof ToolError)
343
343
  return toolErrorResult(error);
344
344
  if (isMissingMenuScreenEndpoint(error)) {
345
- return textResult("No menu matrix is available. Open the Ultimate menu and retry; if it remains unavailable, this firmware does not provide machine:menu_screen. Use REST configuration instead of menu navigation where possible.", { success: false, code: "native_menu_screen_unavailable", fallback: "rest_configuration_or_manual_menu" });
345
+ return toolErrorResult(new ToolExecutionError("No menu matrix is available. Open the Ultimate menu and retry; if it remains unavailable, this firmware does not provide machine:menu_screen. Use REST configuration instead of menu navigation where possible.", { code: "native_menu_screen_unavailable", details: { fallback: "rest_configuration_or_manual_menu" }, cause: error }));
346
346
  }
347
347
  return unknownErrorResult(error);
348
348
  }
@@ -186,7 +186,7 @@ async function executeReadMemory(rawArgs, ctx) {
186
186
  ctx.logger.info("Reading C64 memory", { address: parsed.address, length: parsed.length });
187
187
  const result = await ctx.client.readMemory(parsed.address, String(parsed.length));
188
188
  if (!result.success) {
189
- throw new ToolExecutionError("C64 firmware reported failure while reading memory", {
189
+ throw new ToolExecutionError("C64 backend reported failure while reading memory", {
190
190
  details: normaliseFailure(result.details),
191
191
  });
192
192
  }
@@ -229,7 +229,7 @@ async function executeWriteMemory(rawArgs, ctx) {
229
229
  if (!shouldVerify) {
230
230
  const result = await ctx.client.writeMemory(parsed.address, writeInfo.canonical);
231
231
  if (!result.success) {
232
- throw new ToolExecutionError("C64 firmware reported failure while writing memory", {
232
+ throw new ToolExecutionError("C64 backend reported failure while writing memory", {
233
233
  details: normaliseFailure(result.details),
234
234
  });
235
235
  }
@@ -251,7 +251,7 @@ async function executeWriteMemory(rawArgs, ctx) {
251
251
  if (canPause) {
252
252
  const pauseResult = await ctx.client.pause(pinnedFacade);
253
253
  if (!pauseResult.success) {
254
- throw new ToolExecutionError("C64 firmware reported failure while pausing", {
254
+ throw new ToolExecutionError("C64 backend reported failure while pausing", {
255
255
  details: normaliseFailure(pauseResult.details),
256
256
  });
257
257
  }
@@ -262,7 +262,7 @@ async function executeWriteMemory(rawArgs, ctx) {
262
262
  const readLength = Math.max(1, Math.max(writeInfo.bytes.length, expectedBytes.length));
263
263
  const preRead = await ctx.client.readMemory(parsed.address, String(readLength), pinnedFacade);
264
264
  if (!preRead.success) {
265
- throw new ToolExecutionError("C64 firmware reported failure while reading memory", {
265
+ throw new ToolExecutionError("C64 backend reported failure while reading memory", {
266
266
  details: normaliseFailure(preRead.details),
267
267
  });
268
268
  }
@@ -290,13 +290,13 @@ async function executeWriteMemory(rawArgs, ctx) {
290
290
  }
291
291
  const writeResult = await ctx.client.writeMemory(parsed.address, writeInfo.canonical, pinnedFacade);
292
292
  if (!writeResult.success) {
293
- throw new ToolExecutionError("C64 firmware reported failure while writing memory", {
293
+ throw new ToolExecutionError("C64 backend reported failure while writing memory", {
294
294
  details: normaliseFailure(writeResult.details),
295
295
  });
296
296
  }
297
297
  const postRead = await ctx.client.readMemory(parsed.address, String(Math.max(1, writeInfo.bytes.length)), pinnedFacade);
298
298
  if (!postRead.success) {
299
- throw new ToolExecutionError("C64 firmware reported failure while reading back memory", {
299
+ throw new ToolExecutionError("C64 backend reported failure while reading back memory", {
300
300
  details: normaliseFailure(postRead.details),
301
301
  });
302
302
  }
@@ -267,7 +267,7 @@ export const tools = [
267
267
  const results = [];
268
268
  let restoreError;
269
269
  try {
270
- for (const backend of requestedBackends) {
270
+ for (const [backendIndex, backend] of requestedBackends.entries()) {
271
271
  context.client.switchBackend(backend);
272
272
  context.setPlatform(backend);
273
273
  await trySilenceSid(context);
@@ -303,7 +303,11 @@ export const tools = [
303
303
  analysis,
304
304
  };
305
305
  }
306
- await trySilenceSid(context);
306
+ // Stop this backend's playback only before moving on to the next one;
307
+ // the last backend keeps playing so the preset can be heard in full.
308
+ if (backendIndex < requestedBackends.length - 1) {
309
+ await trySilenceSid(context);
310
+ }
307
311
  backendResult.verification = verification;
308
312
  backendResult.success = true;
309
313
  results.push(backendResult);
@@ -493,6 +497,8 @@ export const tools = [
493
497
  entryAddress: compiled.entryAddress,
494
498
  prgBytes: compiled.prg.length,
495
499
  title: document.song?.title ?? null,
500
+ basicFreeBytes: compiled.basicFreeBytes,
501
+ warnings: compiled.warnings,
496
502
  },
497
503
  playback: {
498
504
  method: playbackMethod,
@@ -4,13 +4,14 @@ import { ToolError, ToolUnsupportedPlatformError, ToolExecutionError, ToolValida
4
4
  import { getPlatformStatus } from "../../platform.js";
5
5
  import { promises as fs } from "node:fs";
6
6
  import { dirname, resolve as resolvePath } from "node:path";
7
- import { captureConfigSnapshot, validateSnapshotCategories } from "./configInventory.js";
7
+ import { captureConfigSnapshot, stripRedactedSecrets, validateSnapshotCategories } from "./configInventory.js";
8
8
  import { normalizeErrorDetails } from "./util.js";
9
9
  const configSnapshotAndRestoreArgsSchema = objectSchema({
10
10
  description: "Snapshot or restore full device configuration. Snapshot writes versioned JSON.",
11
11
  properties: {
12
12
  action: stringSchema({ description: "One of: snapshot|restore|diff", enum: ["snapshot", "restore", "diff"] }),
13
13
  path: stringSchema({ description: "Snapshot file path", minLength: 1 }),
14
+ includeSecretValues: optionalSchema(booleanSchema({ description: "Snapshot and diff only: store credential values (network password, FTP/Telnet passwords, Wi-Fi keys) in plain text in the snapshot file. Default false: they are written as ***, and restore skips them.", default: false }), false),
14
15
  applyToFlash: optionalSchema(booleanSchema({ description: "Save configuration to flash after restore (C64U/U64 and U2 only)", default: false }), false),
15
16
  },
16
17
  required: ["action", "path"],
@@ -37,7 +38,7 @@ export const tools = [
37
38
  const [version, info, snapshotData] = await Promise.all([
38
39
  ctx.client.version(),
39
40
  ctx.client.info(),
40
- captureConfigSnapshot(ctx.client),
41
+ captureConfigSnapshot(ctx.client, { includeSecretValues: parsed.includeSecretValues === true }),
41
42
  ]);
42
43
  const snapshot = {
43
44
  createdAt: new Date().toISOString(),
@@ -61,7 +62,7 @@ export const tools = [
61
62
  }
62
63
  let payload;
63
64
  try {
64
- payload = validateSnapshotCategories(snapshot.categories);
65
+ payload = stripRedactedSecrets(validateSnapshotCategories(snapshot.categories));
65
66
  }
66
67
  catch {
67
68
  throw new ToolValidationError("Invalid snapshot file", { path: "$.path" });
@@ -81,7 +82,7 @@ export const tools = [
81
82
  const text = await fs.readFile(path, "utf8");
82
83
  const snapshot = JSON.parse(text);
83
84
  const snapCats = validateSnapshotCategories(snapshot.categories ?? {});
84
- const current = (await captureConfigSnapshot(ctx.client)).categories;
85
+ const current = (await captureConfigSnapshot(ctx.client, { includeSecretValues: parsed.includeSecretValues === true })).categories;
85
86
  const diff = {};
86
87
  for (const [cat, snapVal] of Object.entries(snapCats)) {
87
88
  const curVal = current[cat];