Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import <Foundation/Foundation.h>
static NSDictionary *MCPGuestKeySchema(BOOL includeProbe) {
NSString *alphabet = @" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
NSMutableArray *values = [NSMutableArray array];
for (NSUInteger i = 0; i < alphabet.length; ++i)
[values addObject:[alphabet substringWithRange:NSMakeRange(i, 1)]];
if (includeProbe) [values addObject:@"PRINT 7\n"];
return @{@"type": @"string", @"enum": values};
}
static NSArray<NSDictionary *> *MCPGuestTools(BOOL interactive) {
NSDictionary *identifier = @{@"type": @"string", @"minLength": @1, @"maxLength": @64};
NSDictionary *keys = interactive ? MCPGuestKeySchema(YES) : @{@"type": @"string", @"enum": @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"PRINT 7\n"]};
NSDictionary *(^tool)(NSString *, NSString *, NSDictionary *, BOOL) =
^NSDictionary *(NSString *name, NSString *description, NSDictionary *properties, BOOL readOnly) {
return @{@"name":name, @"description":description,
@"annotations":@{@"readOnlyHint":@(readOnly), @"openWorldHint":@NO},
@"inputSchema":@{@"type":@"object", @"properties":properties,
@"additionalProperties":@NO, @"required":[properties.allKeys sortedArrayUsingSelector:@selector(compare:)]}};
};
return @[tool(@"get_run", @"Inspect the run started by the user for this reviewed BASIC revision.",
@{@"document_id":identifier, @"revision":@{@"type":@"integer", @"minimum":@0}}, YES),
tool(@"read_screen_text", @"Observe this run's guest text, frame, display signal and sampled RGB text backgrounds.", @{@"run_id":identifier}, YES),
tool(@"send_keys", interactive ? @"Send one ASCII letter, digit or space to the running BASIC program, or PRINT 7\n at the BASIC prompt. Use a fresh request_id per key and reuse it on retry. Up to 64 keys per run." : @"Send a single menu digit, or a fixed PRINT 7 command after BASIC returns. Reuse request_id when retrying.",
@{@"run_id":identifier, @"request_id":identifier, @"keys":keys}, NO)];
}
+216
View File
@@ -0,0 +1,216 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#import "MCPGuestTools.h"
static NSArray<NSDictionary *> *MCPProjectTools(BOOL assembly, BOOL interactive, BOOL customMake) {
NSDictionary *identifier = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
NSDictionary *requestID = @{@"type":@"string", @"minLength":@1, @"maxLength":assembly ? @64 : @128,
@"description":assembly ? @"Unique request ID, up to 64 UTF-8 bytes." : @"Unique request ID, up to 128 UTF-8 bytes."};
NSDictionary *replacement = @{@"type":@"string", @"minLength":assembly ? @0 : @1, @"maxLength":assembly ? @1024 : @512,
@"description":assembly ? @"One assembly line of up to 1024 UTF-8 bytes." : @"One ASCII C source line of up to 512 bytes, with printable characters or tabs."};
NSDictionary *path = @{@"type":@"string", @"minLength":@1, @"maxLength":@512};
NSDictionary *revision = @{@"type":@"integer", @"minimum":@0};
NSDictionary *scope = @{@"project_id":identifier, @"revision":revision};
NSDictionary *(^tool)(NSString *, NSString *, NSDictionary *, BOOL) =
^NSDictionary *(NSString *name, NSString *description, NSDictionary *fields, BOOL readOnly) {
return @{@"name":name, @"description":description,
@"inputSchema":@{@"type":@"object", @"properties":fields,
@"required":[fields.allKeys sortedArrayUsingSelector:@selector(compare:)], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@(readOnly), @"openWorldHint":@NO}};
};
NSDictionary *build = tool(@"build_project", @"Start a build of the selected revision. Reuse the request ID on retry. Poll get_build with the returned build ID.",
@{@"project_id":identifier, @"revision":revision, @"request_id":requestID}, NO);
if (customMake) {
NSMutableDictionary *fields = [build[@"inputSchema"][@"properties"] mutableCopy];
fields[@"action"] = @{@"type":@"string", @"enum":@[@"build", @"disk"],
@"description":@"Optional declared project action. Defaults to build. Arbitrary Make targets are not accepted."};
fields[@"configuration"] = @{@"type":@"string", @"minLength":@1, @"maxLength":@128,
@"description":@"Optional configuration name from get_capabilities. Defaults to the selected workspace configuration."};
NSMutableDictionary *schema = [build[@"inputSchema"] mutableCopy];
schema[@"properties"] = fields; // Preserve the three original required arguments.
NSMutableDictionary *customBuild = [build mutableCopy];
customBuild[@"inputSchema"] = schema;
customBuild[@"description"] = @"Build the selected revision with the explicitly approved project Make recipe. Use only advertised actions and configurations. Reuse request_id only for the identical revision, action and configuration; poll get_build.";
build = customBuild;
}
NSString *capabilities = assembly ? @"Identify the shared assembly project, target processor, files and revision."
: customMake ? @"Identify the shared CMOC project, files, revision, approved Make recipe identity, declared actions, targets and configurations."
: @"Identify the shared CMOC project, files and revision.";
NSArray *tools = @[tool(@"get_capabilities", capabilities, @{}, YES),
tool(@"read_project_file", @"Read one file named in the shared project manifest.", @{@"project_id":identifier, @"path":path}, YES),
build,
tool(@"get_build", @"Read the build state, compiler or assembler diagnostics and linked result.", @{@"build_id":identifier}, YES),
tool(@"propose_fix", @"Submit one full replacement line for native review. Use the current revision and 1-based file line. Reuse the request ID on retry.",
@{@"project_id":identifier, @"revision":revision, @"path":path, @"line_number":@{@"type":@"integer",@"minimum":@1},
@"replacement":replacement, @"request_id":requestID}, NO),
tool(@"get_proposal", @"Read the user's decision on this proposed edit.", @{@"proposal_id":identifier}, YES),
tool(@"get_run", @"Read guest execution or poll an accepted asynchronous playtest startup. A starting/cancelling result includes phase and busy; ready includes its receipt; failed includes phase and error. Use the project_id/revision from start_playtest.", scope, YES)];
if (!interactive) return tools;
NSDictionary *keyRequestID = @{@"type":@"string", @"minLength":@1, @"maxLength":@64};
return [tools arrayByAddingObjectsFromArray:@[
tool(@"read_screen_text", @"Read the hardware text screen of the locally started, active compiled game. Live access ends on return to BASIC.",
@{@"run_id":identifier}, YES),
tool(@"send_keys", @"Send one letter, digit or space to the running game. Reuse request_id on retry. Up to 64 inputs per run.",
@{@"run_id":identifier, @"request_id":keyRequestID, @"keys":MCPGuestKeySchema(NO)}, NO)]];
}
// Added only when the running app explicitly advertises project refresh.
static NSArray<NSDictionary *> *MCPProjectRefreshTools() {
NSDictionary *identifier = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
NSDictionary *(^tool)(NSString *, NSString *, NSDictionary *, NSArray *, BOOL) =
^NSDictionary *(NSString *name, NSString *description, NSDictionary *fields, NSArray *required, BOOL readOnly) {
return @{@"name":name, @"description":description,
@"inputSchema":@{@"type":@"object", @"properties":fields, @"required":required, @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@(readOnly), @"openWorldHint":@NO}};
};
return @[
tool(@"refresh_project", @"Refresh captured project inputs after external edits. Existing authorized source changes can be accepted automatically; recipe, permissions, support scope or newly shared files require native review. Reuse request_id only for the identical request. Returns refresh_id and pending, approved, rejected or unchanged status; never executes a recipe.",
@{@"project_id":identifier, @"request_id":identifier, @"revision":@{@"type":@"integer", @"minimum":@0}},
@[@"project_id", @"request_id", @"revision"], NO),
tool(@"get_project_refresh", @"Poll a project refresh and its native review decision. Remains available while changed inputs block builds and runs.",
@{@"project_id":identifier, @"refresh_id":identifier}, @[@"project_id", @"refresh_id"], YES),
tool(@"read_project_inputs", @"Read the approved canonical input manifest: relative paths, roles, SHA-256 and permissions, plus current refresh status. This does not expose unapproved file contents or host paths. Page using offset and limit.",
@{@"project_id":identifier, @"offset":@{@"type":@"integer", @"minimum":@0},
@"limit":@{@"type":@"integer", @"minimum":@1, @"maximum":@256}}, @[@"project_id"], YES)
];
}
// Added only by a freshly exported diagnostics-aware C grant.
static NSArray<NSDictionary *> *MCPBuildDiagnosticTools() {
return @[@{@"name":@"get_build_log", @"description":@"Read a retained, redacted build log in bounded UTF-8 byte pages. Use next_offset for the next page; logs disclose original process/retention truncation. This reads only a build belonging to this connection, never a host path.",
@"inputSchema":@{@"type":@"object", @"properties":@{
@"build_id":@{@"type":@"string",@"minLength":@1,@"maxLength":@128},
@"offset":@{@"type":@"integer",@"minimum":@0},
@"limit":@{@"type":@"integer",@"minimum":@1,@"maximum":@32768}},
@"required":@[@"build_id"],@"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@YES,@"openWorldHint":@NO}}];
}
static NSArray<NSDictionary *> *MCPPlaytestAudioTools() {
return @[@{@"name":@"capture_playtest_audio", @"description":@"Advance an owned disposable guest for 1 to 120 emulated fields and return its direct audio as PCM16 stereo WAV. Leaves the guest paused; verified stops can shorten the interval. Uses no microphone or personal emulator audio. Reuse request_id on retry to return the same clip without execution. Maximum 16 clips and 4 MiB retained WAV per run across boots; a maximum-clip allowance must remain before capture. Receipts include actual field interval, boot/run/artifact identity, sample count and SHA-256.",
@"inputSchema":@{@"type":@"object", @"properties":@{
@"run_id":@{@"type":@"string",@"minLength":@1,@"maxLength":@64},
@"request_id":@{@"type":@"string",@"minLength":@1,@"maxLength":@64},
@"fields":@{@"type":@"integer",@"minimum":@1,@"maximum":@120}},
@"required":@[@"run_id",@"request_id",@"fields"],@"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@NO,@"openWorldHint":@NO}}];
}
// Fresh C owned-playtest grants only; never an arbitrary memory-read interface.
static NSArray<NSDictionary *> *MCPPlaytestCallContextTools() {
NSDictionary *identifier = @{@"type":@"string", @"minLength":@1, @"maxLength":@64};
return @[@{@"name":@"get_call_context", @"description":@"Read bounded call context for a verified stopped owned disposable C run using its current snapshot. Returns only verified caller evidence; unsupported or ambiguous context is reported unavailable. Does not execute the guest or accept memory addresses.",
@"inputSchema":@{@"type":@"object", @"properties":@{@"run_id":identifier, @"snapshot_id":identifier},
@"required":@[@"run_id", @"snapshot_id"], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@YES, @"openWorldHint":@NO}}];
}
// Fresh reviewed media-aware C playtest grants only. The two insertion fields
// are action-specific in discovery as well as helper/host validation.
static NSArray<NSDictionary *> *MCPPlaytestMediaTools() {
NSDictionary *identifier = @{ @"type":@"string", @"minLength":@1, @"maxLength":@64 };
NSDictionary *mediaID = @{ @"type":@"string", @"minLength":@1, @"maxLength":@64,
@"pattern":@"^[A-Za-z0-9_-]{1,64}$", @"description":@"Opaque ID from list_playtest_media; never a host path." };
NSDictionary *sha = @{ @"type":@"string", @"minLength":@64, @"maxLength":@64,
@"pattern":@"^[0-9a-f]{64}$", @"description":@"Exact current lowercase SHA-256 from the selected media listing." };
NSDictionary *listProperties = @{ @"project_id":identifier, @"revision":@{ @"type":@"integer", @"minimum":@0 },
@"artifact_id":identifier, @"run_id":identifier };
NSDictionary *insertProperties = @{ @"run_id":identifier, @"request_id":identifier,
@"action":@{ @"type":@"string", @"enum":@[ @"insert" ] }, @"media_id":mediaID, @"media_sha256":sha };
NSDictionary *ejectProperties = @{ @"run_id":identifier, @"request_id":identifier,
@"action":@{ @"type":@"string", @"enum":@[ @"eject" ] } };
NSMutableDictionary *exchangeProperties = [insertProperties mutableCopy];
exchangeProperties[@"action"] = @{ @"type":@"string", @"enum":@[ @"insert", @"eject" ] };
return @[
@{ @"name":@"list_playtest_media", @"description":@"List reviewed, hash-bound floppy media and compatible retained choices for the exact current project revision and build artifact. Optional run_id selects the current owned run's writable copies and their current hashes, mounted state and retention status. Listing does not advance or modify a guest. IDs are opaque; no host paths are exposed or accepted. Additional disk products must be declared in the reviewed project.",
@"inputSchema":@{ @"type":@"object", @"properties":listProperties,
@"required":@[ @"project_id", @"revision", @"artifact_id" ], @"additionalProperties":@NO },
@"annotations":@{ @"readOnlyHint":@YES, @"openWorldHint":@NO } },
@{ @"name":@"exchange_playtest_media", @"description":@"Insert or eject FD0 in a paused owned disposable run while its floppy controller is idle. Insert requires media_id and exact media_sha256 from that run's listing; eject forbids both. Uses only reviewed artifact-bound private writable disks, preserving every disk across swaps and restart and retaining all disks when the run stops. A successful exchange neither resets nor advances the guest; receipts identify old/new media, hashes, dirty/retained state and clock. Failed exchange preserves the mounted disk and data. Reuse request_id only for the identical action and selection; changed plans conflict. No arbitrary paths, personal media, memory or register writes.",
@"inputSchema":@{ @"type":@"object", @"properties":exchangeProperties,
@"required":@[ @"run_id", @"request_id", @"action" ], @"additionalProperties":@NO,
@"oneOf":@[
@{ @"type":@"object", @"properties":insertProperties,
@"required":@[ @"run_id", @"request_id", @"action", @"media_id", @"media_sha256" ], @"additionalProperties":@NO },
@{ @"type":@"object", @"properties":ejectProperties,
@"required":@[ @"run_id", @"request_id", @"action" ], @"additionalProperties":@NO } ] },
@"annotations":@{ @"readOnlyHint":@NO, @"idempotentHint":@YES, @"openWorldHint":@NO } }
];
}
// Available only through an explicit native owned-playtest connection grant.
static NSArray<NSDictionary *> *MCPPlaytestTools(BOOL processorSelection = NO, BOOL joystickInput = NO, BOOL mediaExchange = NO) {
NSDictionary *id = @{@"type":@"string",@"minLength":@1,@"maxLength":@64};
NSDictionary *functionName = @{@"type":@"string",@"minLength":@1,@"maxLength":@1023};
NSDictionary *sha256 = @{@"type":@"string",@"minLength":@64,@"maxLength":@64,@"pattern":@"^[0-9a-f]{64}$",
@"description":@"Exact lowercase SHA-256 from the retained test-disk receipt."};
NSDictionary *(^tool)(NSString *, NSString *, NSDictionary *, NSArray *, BOOL) =
^NSDictionary *(NSString *name, NSString *description, NSDictionary *fields, NSArray *required, BOOL readOnly) {
return @{@"name":name,@"description":description,@"inputSchema":@{@"type":@"object",@"properties":fields,
@"required":required,@"additionalProperties":@NO},@"annotations":@{@"readOnlyHint":@(readOnly),@"openWorldHint":@NO}};
};
NSDictionary *stopKind = @{@"type":@"string", @"enum":@[@"c_line", @"function_entry"], @"default":@"c_line",
@"description":@"Optional stop mode. c_line requires a compiler-verified C statement; function_entry uses a verified object/linker function entry and may have no C source line."};
NSDictionary *step = @{@"type":@"object",@"properties":@{
@"keys":@{@"type":@"array",@"items":@{@"type":@"string",@"enum":@[@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"up",@"down",@"left",@"backspace",@"right",@"space",@"period",@"enter",@"clear",@"break",@"alt",@"control",@"f1",@"f2",@"shift"]},@"maxItems":@8,@"uniqueItems":@YES},
@"fields":@{@"type":@"integer",@"minimum":@1,@"maximum":@600}},
@"required":@[@"keys",@"fields"],@"additionalProperties":@NO};
if (joystickInput) {
NSMutableDictionary *properties = [step[@"properties"] mutableCopy];
NSDictionary *axis = @{@"type":@"integer",@"minimum":@0,@"maximum":@16383};
NSDictionary *joystick = @{@"type":@"object",@"properties":@{
@"port":@{@"type":@"string",@"enum":@[@"right",@"left"]}, @"x":axis, @"y":axis,
@"buttons":@{@"type":@"array",@"items":@{@"type":@"string",@"enum":@[@"fire1",@"fire2"]},@"maxItems":@2,@"uniqueItems":@YES}},
@"required":@[@"port",@"x",@"y",@"buttons"],@"additionalProperties":@NO};
properties[@"joysticks"] = @{@"type":@"array",@"items":joystick,@"maxItems":@2,@"uniqueItems":@YES,
@"description":@"Complete standard analog port states for this step. At most one entry per named port. Axes 0..16383, center 8191; X increases right, Y down. Missing ports center and release; omitted joysticks is keyboard-only with neutral ports."};
NSMutableDictionary *updatedStep = [step mutableCopy]; updatedStep[@"properties"] = properties; step = updatedStep;
}
NSMutableArray *tools = [@[
tool(@"start_playtest",@"Accept asynchronous startup of a disposable 512 KB MC6809 disk run of the exact current artifact. Returns a reserved run_id and starting status immediately; poll get_run(project_id, revision) until ready or failed, then use capture_playtest for an image. stop_playtest can cancel the reserved run_id during preparation or boot. No transport request waits for full startup. Personal session and media are preserved. Optional stop_function names a verified function. stop_kind defaults to c_line; function_entry stops at its verified object/linker entry without inventing a C line. stop_kind requires stop_function. To resume a retained writable test disk, supply both retained_disk_id and its exact prior receipt retained_disk_sha256; no host paths are accepted. Omit both for a fresh artifact disk. Reuse request_id on retry.",
@{@"project_id":id,@"revision":@{@"type":@"integer",@"minimum":@0},@"artifact_id":id,@"request_id":id,@"stop_function":functionName,@"stop_kind":stopKind,@"retained_disk_id":id,@"retained_disk_sha256":sha256},
@[@"project_id",@"revision",@"artifact_id",@"request_id"],NO),
tool(@"list_playtest_disks",@"List retained writable test disks recorded for the current shared project. Use a returned retained_disk_id and exact SHA-256 receipt with start_playtest. Older unscoped disks are not listed; a legacy resume requires its prior run ID and exact disk hash and reports legacy provenance. No host paths are exposed or accepted.",
@{@"project_id":id},@[@"project_id"],YES),
tool(@"playtest_input",@"Send held physical-key chords for bounded emulated video fields in the owned run (600 per step, 3600 per request, 216000 per run, 16 boots). Empty keys releases all keys. Resumes a verified stop. Reuse request_id only for an identical plan.",
@{@"run_id":id,@"request_id":id,@"steps":@{@"type":@"array",@"items":step,@"minItems":@1,@"maxItems":@64}},@[@"run_id",@"request_id",@"steps"],NO),
tool(@"playtest_debug",@"Pause, continue, instruction-step, or arm a verified named function in the owned run. stop_at requires function; optional stop_kind defaults to c_line, or function_entry uses its verified object/linker entry without claiming a C statement. Other actions do not accept function or stop_kind. No registers or guest memory can be written.",
@{@"run_id":id,@"request_id":id,@"action":@{@"type":@"string",@"enum":@[@"pause",@"continue",@"step",@"stop_at"]},@"function":functionName,@"stop_kind":stopKind},@[@"run_id",@"request_id",@"action"],NO),
tool(@"capture_playtest",@"Capture the owned run's framebuffer, field clock and disk identity without advancing it.",@{@"run_id":id},@[@"run_id"],YES),
tool(@"capture_playtest_graphics",@"Capture a read-only graphics preview at one paused owned-machine state. Returns current display-buffer physical identity and its PNG; optional buffer_id selects one framebuffer declared by this artifact's verified manifest for a second PNG, including a bounded current_gime canvas. Uses current video registers, not a historical presented frame. Accepts no addresses and never advances or edits the guest.",
@{@"run_id":id,@"buffer_id":@{@"type":@"string",@"minLength":@1,@"maxLength":@64,@"pattern":@"^[A-Za-z0-9_-]{1,64}$"}},@[@"run_id"],YES),
tool(@"restart_playtest",@"Cold restart only the owned run, retaining its writable test disk and repeating its declared boot commands. Reuse request_id on retry.",@{@"run_id":id,@"request_id":id},@[@"run_id",@"request_id"],NO),
tool(@"stop_playtest",@"Cancel a pending startup by its reserved run_id, or stop the owned worker and retain its test disk in VCC Plus development results. Pending cancellation is polled with get_run until busy is false; a late worker is cleaned up before replacement. Personal media remain untouched.",@{@"run_id":id,@"request_id":id},@[@"run_id",@"request_id"],NO)
] mutableCopy];
if (joystickInput) {
NSMutableDictionary *input = [tools[2] mutableCopy];
input[@"description"] = @"Apply complete keyboard and standard analog joystick states for bounded emulated fields in this owned run. At most two distinct ports, axis range 0..16383, center 8191, fire1/fire2. Missing ports center/release. Inputs release after the plan, interrupted stops or errors. Limits: 64 steps, 600 fields per step, 3600 per request; budgets/ownership remain enforced. Reuse request_id only for an identical plan. Receipts include actual input and bounded per-step input_trace; no guest memory/register writes.";
tools[2] = input;
[tools addObject:tool(@"get_playtest_input", @"Read the owned worker's actual current keyboard-held flag and two standard analog port snapshots without advancing, changing input or consuming execution budget. Completed plans report neutral released input; input_trace in the input receipt describes applied step states.", @{@"run_id":id}, @[@"run_id"], YES)];
}
if (mediaExchange) {
NSMutableDictionary *start = [tools[0] mutableCopy];
NSMutableDictionary *schema = [start[@"inputSchema"] mutableCopy];
NSMutableDictionary *properties = [schema[@"properties"] mutableCopy];
properties[@"retained_media"] = @{ @"type":@"array", @"minItems":@1, @"maxItems":@8, @"uniqueItems":@YES,
@"description":@"Optional retained writable copies for distinct additional media_id values from the current artifact listing. Omit for fresh additional disks; primary disk resumption still uses retained_disk_id and retained_disk_sha256. Exact per-disk provenance and hashes are rechecked before startup.",
@"items":@{ @"type":@"object", @"properties":@{
@"media_id":@{ @"type":@"string", @"minLength":@1, @"maxLength":@64, @"pattern":@"^[A-Za-z0-9_-]{1,64}$" },
@"retained_disk_id":id, @"retained_disk_sha256":sha256 },
@"required":@[ @"media_id", @"retained_disk_id", @"retained_disk_sha256" ], @"additionalProperties":@NO } };
schema[@"properties"] = properties; start[@"inputSchema"] = schema;
start[@"description"] = [start[@"description"] stringByAppendingString:@" Fresh media-aware grants may additionally resume declared disks through retained_media; each run keeps independent writable copies. stop_playtest retains all of those copies, including unmounted media."];
tools[0] = start;
}
if (!processorSelection) return tools;
NSMutableArray *updated = [tools mutableCopy];
NSMutableDictionary *start = [tools[0] mutableCopy];
NSMutableDictionary *schema = [start[@"inputSchema"] mutableCopy];
NSMutableDictionary *properties = [schema[@"properties"] mutableCopy];
properties[@"processor"] = @{@"type":@"string",@"enum":@[@"MC6809",@"HD6309"],@"default":@"MC6809",
@"description":@"Guest CPU, independent of host architecture. Omission selects MC6809. HD6309 starts in reset emulation mode; the guest controls MD/native mode. Restart retains this CPU. A changed CPU requires a new start request_id."};
schema[@"properties"] = properties; start[@"inputSchema"] = schema;
start[@"description"] = [start[@"description"] stringByReplacingOccurrencesOfString:@"512 KB MC6809 disk run"
withString:@"512 KB disk run using processor MC6809 (default) or HD6309"];
updated[0] = start;
return updated;
}
+557
View File
@@ -0,0 +1,557 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// VCC Plus MCP server, standard input/output transport.
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import "MCPGuestTools.h"
#import "MCPProjectTools.h"
#include <arpa/inet.h>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <string>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
namespace {
using Clock = std::chrono::steady_clock;
constexpr size_t maxClientFrame = 64 * 1024;
constexpr size_t maxHostRequest = 48 * 1024;
constexpr size_t maxHostFrame = 1024 * 1024;
struct Descriptor {
int fd;
explicit Descriptor(int fd) : fd(fd) {}
~Descriptor() { if (fd >= 0) close(fd); }
Descriptor(const Descriptor&) = delete;
Descriptor& operator=(const Descriptor&) = delete;
};
bool object(id value) { return [value isKindOfClass:NSDictionary.class]; }
bool string(id value) { return [value isKindOfClass:NSString.class]; }
bool integer(id value) {
if (![value isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID())
return false;
return !CFNumberIsFloatType((__bridge CFNumberRef)value);
}
NSData *jsonBytes(id value) {
return [NSJSONSerialization dataWithJSONObject:value options:0 error:nil];
}
id parse(const void *bytes, size_t length) {
// NSJSONSerialization also accepts UTF-16/32. MCP frames are UTF-8.
if (!length || memchr(bytes, 0, length)) return nil;
NSData *data = [NSData dataWithBytes:bytes length:length];
if (![[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]) return nil;
return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingFragmentsAllowed error:nil];
}
NSDictionary *loadGrant(const char *path) {
Descriptor file(open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK));
struct stat st{};
if (file.fd < 0 || fstat(file.fd, &st) || !S_ISREG(st.st_mode) || st.st_uid != geteuid() ||
(st.st_mode & 0077) || st.st_size < 1 || st.st_size > 4096) return nil;
char bytes[4097];
size_t size = 0;
while (size < sizeof(bytes)) {
ssize_t count = read(file.fd, bytes + size, sizeof(bytes) - size);
if (count < 0 && errno == EINTR) continue;
if (count < 0) return nil;
if (count == 0) break;
size += static_cast<size_t>(count);
}
if (size != static_cast<size_t>(st.st_size)) return nil;
id grant = parse(bytes, size);
if (!object(grant) || !integer(grant[@"version"]) || !string(grant[@"token"]) || [grant[@"token"] length] == 0)
return nil;
// Older helpers reject a version-2 archive grant instead of treating it as a BASIC grant.
if (![grant[@"version"] isEqual:([grant[@"kind"] isEqual:@"archive"] ? @2 : @1)]) return nil;
return grant;
}
bool ready(int fd, short events, Clock::time_point deadline) {
pollfd p{fd, events, 0};
for (;;) {
const auto now = Clock::now();
if (now >= deadline) return false;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count();
if (ms < 1) ms = 1;
int n = poll(&p, 1, static_cast<int>(ms));
if (n < 0 && errno == EINTR) continue;
if (n == 0) continue;
return n > 0 && (p.revents & events);
}
}
NSDictionary *hostCall(NSDictionary *grant, bool loopback, NSString *tool, NSDictionary *args) {
sockaddr_storage storage{};
sockaddr *address = reinterpret_cast<sockaddr *>(&storage);
if (loopback || !grant[@"socket"]) {
NSNumber *port = grant[@"port"];
if (!integer(port) || port.longLongValue < 1 || port.longLongValue > 65535) return @{@"error":@"invalid_endpoint"};
sockaddr_in *tcp = reinterpret_cast<sockaddr_in *>(&storage);
tcp->sin_family = AF_INET;
tcp->sin_len = sizeof(*tcp);
tcp->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
tcp->sin_port = htons(port.unsignedShortValue);
} else {
NSString *path = grant[@"socket"];
sockaddr_un *local = reinterpret_cast<sockaddr_un *>(&storage);
if (!string(path) || ![path hasPrefix:@"/"] || [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding] >= sizeof(local->sun_path) ||
strlen(path.UTF8String) != [path lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) return @{@"error":@"invalid_endpoint"};
local->sun_family = AF_UNIX;
local->sun_len = sizeof(*local);
strlcpy(local->sun_path, path.UTF8String, sizeof(local->sun_path));
}
NSData *payload = jsonBytes(@{@"version":@1, @"token":grant[@"token"], @"tool":tool, @"arguments":args});
if (!payload || payload.length + 1 > maxHostRequest) return @{@"error":@"request_too_large"};
std::string request(static_cast<const char *>(payload.bytes), payload.length);
request.push_back('\n');
Descriptor peer(socket(address->sa_family, SOCK_STREAM, 0));
const bool playtestCall = [@[@"start_playtest", @"playtest_input", @"playtest_debug", @"capture_playtest",
@"restart_playtest", @"stop_playtest", @"get_debug_snapshot", @"capture_playtest_graphics",
@"exchange_playtest_media"] containsObject:tool];
const auto deadline = Clock::now() + std::chrono::seconds(playtestCall ? 55 : 5);
if (peer.fd < 0 || fcntl(peer.fd, F_SETFL, O_NONBLOCK) < 0) return @{@"error":@"host_unavailable"};
if (connect(peer.fd, address, address->sa_len) != 0) {
int error = 0;
socklen_t size = sizeof(error);
if (errno != EINPROGRESS) return @{@"error":@"host_unavailable"};
if (!ready(peer.fd, POLLOUT, deadline))
return @{@"error":Clock::now() >= deadline ? @"transport_timeout" : @"host_unavailable"};
if (getsockopt(peer.fd, SOL_SOCKET, SO_ERROR, &error, &size) || error) return @{@"error":@"host_unavailable"};
}
if (address->sa_family == AF_UNIX) {
uid_t uid;
gid_t gid;
if (getpeereid(peer.fd, &uid, &gid) || uid != geteuid()) return @{@"error":@"host_identity_mismatch"};
}
size_t offset = 0;
while (offset < request.size()) {
if (!ready(peer.fd, POLLOUT, deadline))
return @{@"error":Clock::now() >= deadline ? @"transport_timeout" : @"host_unavailable"};
ssize_t n = write(peer.fd, request.data() + offset, request.size() - offset);
if (n < 0 && (errno == EINTR || errno == EAGAIN)) continue;
if (n <= 0) return @{@"error":@"host_unavailable"};
offset += static_cast<size_t>(n);
}
std::string response;
while (response.size() < maxHostFrame && ready(peer.fd, POLLIN, deadline)) {
char buffer[8192];
ssize_t n = read(peer.fd, buffer, sizeof(buffer));
if (n < 0 && (errno == EAGAIN || errno == EINTR)) continue;
if (n <= 0) break;
const char *end = static_cast<const char *>(memchr(buffer, '\n', n));
response.append(buffer, end ? static_cast<size_t>(end-buffer) : static_cast<size_t>(n));
if (end && response.size() < maxHostFrame) {
id reply = parse(response.data(), response.size());
if (object(reply) && ((object(reply[@"result"]) && !reply[@"error"]) ||
(string(reply[@"error"]) && !reply[@"result"]))) return reply;
break;
}
}
if (Clock::now() >= deadline) return @{@"error":@"transport_timeout"};
return @{@"error":@"invalid_or_incomplete_host_reply"};
}
NSDictionary *tool(NSString *name, NSString *description, NSString *argument) {
NSDictionary *properties = argument ? @{argument:@{@"type":@"string", @"minLength":@1}} : @{};
return @{@"name":name, @"description":description,
@"inputSchema":@{@"type":@"object", @"properties":properties,
@"required":argument ? @[argument] : @[], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@YES, @"openWorldHint":@NO}};
}
NSDictionary *proposalTool(bool listing) {
NSDictionary *str = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
if (listing) {
NSDictionary *fields = @{@"document_id":str, @"request_id":str,
@"revision":@{@"type":@"integer", @"minimum":@0},
@"source":@{@"type":@"string", @"minLength":@1, @"maxLength":@12288}};
return @{@"name":@"propose_listing",
@"description":@"Propose a complete numbered ASCII BASIC listing (up to 12 KiB) to create or revise the shared draft. Read its document_id and revision first. The user reviews before applying or running it. Reuse request_id (up to 128 UTF-8 bytes) only for an identical proposal.",
@"inputSchema":@{@"type":@"object", @"properties":fields, @"required":@[@"document_id", @"revision", @"source", @"request_id"], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@NO, @"destructiveHint":@NO, @"idempotentHint":@YES, @"openWorldHint":@NO}};
}
NSDictionary *props = @{@"document_id":str, @"request_id":str, @"revision":@{@"type":@"integer", @"minimum":@0},
@"line_number":@{@"type":@"integer", @"minimum":@0, @"maximum":@63999},
@"replacement":@{@"type":@"string", @"minLength":@1, @"maxLength":@249}};
return @{@"name":@"propose_edit", @"description":@"Propose replacing exactly one existing numbered BASIC line for native review. Read the current source revision first. Include the number in the replacement. Reuse request_id only for the same proposal.",
@"inputSchema":@{@"type":@"object", @"properties":props, @"required":@[@"document_id", @"revision", @"line_number", @"replacement", @"request_id"], @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@NO, @"destructiveHint":@NO, @"idempotentHint":@YES, @"openWorldHint":@NO}};
}
NSArray *archiveTools() {
NSDictionary *readOnly = @{@"readOnlyHint":@YES, @"openWorldHint":@NO};
NSDictionary *fields = @{
@"query":@{@"type":@"string", @"minLength":@1, @"maxLength":@256},
@"category":@{@"type":@"string", @"minLength":@1, @"maxLength":@512,
@"description":@"An optional Archive collection path such as Books or Magazines."},
@"limit":@{@"type":@"integer", @"minimum":@1, @"maximum":@50, @"default":@10},
@"offset":@{@"type":@"integer", @"minimum":@0, @"maximum":@250000, @"default":@0}
};
return @[
@{@"name":@"search_archive", @"description":@"Search the installed Color Computer Archive index by terms or title. Returns public citations and upstream source links. Inspect the original source to verify a passage.",
@"inputSchema":@{@"type":@"object", @"properties":fields, @"required":@[@"query"], @"additionalProperties":@NO},
@"annotations":readOnly},
@{@"name":@"get_archive_citation", @"description":@"Resolve a citation_id returned by search_archive to its original Archive source and location. This lookup does not fetch the source or return page text.",
@"inputSchema":@{@"type":@"object", @"properties":@{@"citation_id":@{@"type":@"string", @"minLength":@1, @"maxLength":@128}},
@"required":@[@"citation_id"], @"additionalProperties":@NO},
@"annotations":readOnly}
];
}
NSDictionary *inspectionTool(NSString *name, NSString *description, NSDictionary *properties, BOOL readOnly) {
NSArray *required = [properties.allKeys sortedArrayUsingSelector:@selector(compare:)];
return @{@"name":name, @"description":description,
@"inputSchema":@{@"type":@"object", @"properties":properties, @"required":required, @"additionalProperties":@NO},
@"annotations":@{@"readOnlyHint":@(readOnly), @"openWorldHint":@NO}};
}
NSArray *debuggerTools() {
NSDictionary *identifier = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
return @[
inspectionTool(@"get_debug_snapshot", @"Inspect a verified stopped run. Returns registers, available source or function information, watches, readable ranges and an opaque snapshot ID.",
@{@"run_id":identifier}, YES),
inspectionTool(@"read_debug_memory", @"Read 1–256 bytes from an advertised range of the same stopped program using its run and snapshot IDs.",
@{@"run_id":identifier, @"snapshot_id":identifier, @"address":@{@"type":@"integer", @"minimum":@0, @"maximum":@65535},
@"count":@{@"type":@"integer", @"minimum":@1, @"maximum":@256}}, YES)
];
}
NSDictionary *projectEditsTool(bool assembly) {
NSDictionary *identifier = @{@"type":@"string", @"minLength":@1, @"maxLength":@128};
NSDictionary *file = @{@"type":@"object", @"required":@[@"path", @"source"], @"additionalProperties":@NO,
@"properties":@{@"path":@{@"type":@"string", @"minLength":@1, @"maxLength":@512},
@"source":@{@"type":@"string", @"maxLength":@16384}}};
NSString *description = [NSString stringWithFormat:@"Propose one reviewed change to 1–8 existing %@ files. Each entry contains a shared relative path and complete replacement text. All replacements together must fit 16 KiB UTF-8. Use the current revision. Reuse request_id only for the identical request.", assembly ? @"assembly or include" : @"C or header"];
return inspectionTool(@"propose_project_edits", description,
@{@"project_id":identifier, @"revision":@{@"type":@"integer", @"minimum":@0}, @"request_id":identifier,
@"edits":@{@"type":@"array", @"minItems":@1, @"maxItems":@8, @"items":file}}, NO);
}
NSDictionary *rpcError(id rid, NSInteger code, NSString *message) {
return @{@"jsonrpc":@"2.0", @"id":rid ?: NSNull.null, @"error":@{@"code":@(code), @"message":message}};
}
NSDictionary *toolError(id rid, NSString *message) {
return @{@"jsonrpc":@"2.0", @"id":rid, @"result":@{@"isError":@YES,
@"content":@[@{@"type":@"text", @"text":message}]}};
}
// Validate schema values recursively: array items can themselves be scalars,
// arrays or objects. Bounds apply only when declared in the tool's schema.
NSString *schemaValueError(id value, NSDictionary *schema, unsigned depth, unsigned& nodes) {
if (depth > 16 || ++nodes > 8192) return @"Tool argument nesting or item limit exceeded";
if (!object(schema)) return @"Invalid tool schema";
NSString *type = schema[@"type"];
if ([type isEqual:@"object"]) {
if (!object(value)) return @"arguments must be an object";
NSDictionary *properties = schema[@"properties"] ?: @{};
for (NSString *key in schema[@"required"])
if (!value[key]) return [NSString stringWithFormat:@"Missing required argument: %@", key];
for (NSString *key in value) {
NSDictionary *field = properties[key];
if (!field) {
if ([schema[@"additionalProperties"] isEqual:@YES]) continue;
return @"Unexpected tool argument. Use the properties in tools/list.";
}
NSString *problem = schemaValueError(value[key], field, depth + 1, nodes);
if (problem) return [NSString stringWithFormat:@"%@: %@", key, problem];
}
} else if ([type isEqual:@"array"]) {
if (![value isKindOfClass:NSArray.class]) return @"must be an array";
if ((schema[@"minItems"] && [value count] < [schema[@"minItems"] unsignedIntegerValue]) ||
(schema[@"maxItems"] && [value count] > [schema[@"maxItems"] unsignedIntegerValue]))
return @"must be an array within its allowed size";
if ([schema[@"uniqueItems"] isEqual:@YES] && [NSSet setWithArray:value].count != [value count])
return @"array items must be unique";
NSUInteger index = 0;
for (id member in value) {
NSString *problem = schemaValueError(member, schema[@"items"], depth + 1, nodes);
if (problem) return [NSString stringWithFormat:@"item %lu: %@", (unsigned long)index, problem];
++index;
}
} else if ([type isEqual:@"integer"]) {
if (!integer(value)) return @"must be an integer";
if ((schema[@"minimum"] && [value compare:schema[@"minimum"]] == NSOrderedAscending) ||
(schema[@"maximum"] && [value compare:schema[@"maximum"]] == NSOrderedDescending))
return @"is outside the allowed numeric range";
} else if ([type isEqual:@"boolean"]) {
if (![value isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID())
return @"must be a boolean";
} else if ([type isEqual:@"string"]) {
if (!string(value)) return @"must be a string";
NSUInteger length = [value lengthOfBytesUsingEncoding:NSUTF32LittleEndianStringEncoding] / 4;
if ((schema[@"minLength"] && length < [schema[@"minLength"] unsignedIntegerValue]) ||
(schema[@"maxLength"] && length > [schema[@"maxLength"] unsignedIntegerValue]))
return @"is outside the allowed string length";
if (NSString *pattern = schema[@"pattern"]) {
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
if (!expression) return @"Invalid tool schema pattern";
NSTextCheckingResult *match = [expression firstMatchInString:value options:0 range:NSMakeRange(0, [value length])];
if (!match || !NSEqualRanges(match.range, NSMakeRange(0, [value length])))
return @"does not match the required string pattern";
}
} else return @"Unsupported tool schema type";
NSArray *choices = schema[@"enum"];
if (choices && ![choices containsObject:value]) return @"must be one of the listed values";
if (id alternatives = schema[@"oneOf"]) {
if (![alternatives isKindOfClass:NSArray.class] || ![alternatives count]) return @"Invalid tool schema alternatives";
unsigned matches = 0;
for (id alternative in alternatives) {
if (!object(alternative)) return @"Invalid tool schema alternative";
if (!schemaValueError(value, alternative, depth + 1, nodes)) ++matches;
if (nodes > 8192) return @"Tool argument nesting or item limit exceeded";
}
if (matches != 1) return @"arguments must match exactly one advertised action schema";
}
return nil;
}
NSString *argumentError(NSDictionary *args, NSDictionary *schema) {
unsigned nodes = 0;
return schemaValueError(args, schema, 0, nodes);
}
NSDictionary *success(id rid, NSDictionary *result) {
return @{@"jsonrpc":@"2.0", @"id":rid, @"result":result};
}
enum class Phase { fresh, initializing, active };
NSDictionary *handle(id message, NSDictionary *grant, bool loopback, NSArray *tools, Phase& phase, NSString *__strong& version) {
if (!object(message)) return rpcError(nil, -32600, @"Expected a JSON-RPC request");
id rid = message[@"id"];
NSString *method = message[@"method"];
// This server never calls client methods. A stray response does not need a reply.
if (!method && [message[@"jsonrpc"] isEqual:@"2.0"] && (integer(rid) || string(rid))) {
if ((object(message[@"result"]) && !message[@"error"]) ||
(object(message[@"error"]) && !message[@"result"])) return nil;
}
const bool validID = integer(rid) || string(rid);
if ((rid && !validID) || !string(method) || ![message[@"jsonrpc"] isEqual:@"2.0"])
return rpcError(validID ? rid : nil, -32600, @"Invalid JSON-RPC request");
NSDictionary *params = message[@"params"] ?: @{};
if (!rid) {
if (phase == Phase::initializing && [method isEqual:@"notifications/initialized"] && object(params)) phase = Phase::active;
return nil;
}
if (!object(params)) return rpcError(rid, -32602, @"Expected object parameters");
if ([method isEqual:@"ping"]) return success(rid, @{});
if ([method isEqual:@"initialize"]) {
if (phase != Phase::fresh) return rpcError(rid, -32600, @"Already initialized");
id info = params[@"clientInfo"];
if (!string(params[@"protocolVersion"]) || !object(params[@"capabilities"]) || !object(info) ||
!string(info[@"name"]) || !string(info[@"version"])) return rpcError(rid, -32602, @"Invalid initialization parameters");
NSArray *supported = @[@"2025-11-25", @"2025-06-18", @"2025-03-26"];
version = [supported containsObject:params[@"protocolVersion"]] ? params[@"protocolVersion"] : supported.firstObject;
phase = Phase::initializing;
return success(rid, @{@"protocolVersion":version, @"capabilities":@{@"tools":@{}},
@"serverInfo":@{@"name":@"vcc-plus", @"version":@"1.0"}});
}
if (phase != Phase::active) return rpcError(rid, -32002, @"Initialize the MCP session first");
if ([method isEqual:@"tools/list"]) {
if (params[@"cursor"]) return rpcError(rid, -32602, @"Unknown cursor");
return success(rid, @{@"tools":tools});
}
if (![method isEqual:@"tools/call"]) return rpcError(rid, -32601, @"Unknown method");
NSString *name = params[@"name"];
NSDictionary *args = params[@"arguments"] ?: @{};
if (!string(name) || !object(args)) return rpcError(rid, -32602, @"tools/call needs a tool name and object arguments");
for (NSDictionary *item in tools) {
if (![item[@"name"] isEqual:name]) continue;
NSString *problem = argumentError(args, item[@"inputSchema"]);
if (problem) {
if ([version isEqual:@"2025-11-25"]) return toolError(rid, problem);
return rpcError(rid, -32602, problem);
}
NSDictionary *reply = hostCall(grant, loopback, name, args);
if (reply[@"error"]) {
if (object(reply[@"error_details"])) {
NSMutableDictionary *failure = [toolError(rid, reply[@"error"]) mutableCopy];
NSMutableDictionary *result = [failure[@"result"] mutableCopy];
result[@"structuredContent"] = reply[@"error_details"];
failure[@"result"] = result;
return failure;
}
return toolError(rid, reply[@"error"]);
}
NSMutableDictionary *data = [reply[@"result"] mutableCopy];
NSMutableArray *content = [NSMutableArray array];
if ([name isEqual:@"capture_playtest_audio"]) {
NSString *encoded = data[@"audio_wav_base64"];
if (!string(encoded) || !object(data[@"audio"])) return toolError(rid, @"invalid_playtest_audio");
NSData *wav = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
if (!wav || wav.length < 44 || wav.length > 524332) return toolError(rid, @"invalid_playtest_audio");
const auto *p = static_cast<const unsigned char *>(wav.bytes);
auto u16 = [&](unsigned at) -> uint32_t { return p[at] | (uint32_t(p[at+1]) << 8); };
auto u32 = [&](unsigned at) -> uint32_t { return u16(at) | (u16(at+2) << 16); };
if (memcmp(p,"RIFF",4) || memcmp(p+8,"WAVEfmt ",8) || memcmp(p+36,"data",4) ||
u32(4) != wav.length-8 || u32(16) != 16 || u16(20) != 1 || u16(22) != 2 ||
u32(24) != 44100 || u32(28) != 176400 || u16(32) != 4 || u16(34) != 16 ||
u32(40) != wav.length-44 || (wav.length-44)%4) return toolError(rid, @"invalid_playtest_audio");
NSDictionary *audio = data[@"audio"];
const NSUInteger frames = (wav.length-44)/4;
if (!integer(audio[@"sample_rate"]) || [audio[@"sample_rate"] unsignedIntegerValue] != 44100 ||
!integer(audio[@"channels"]) || [audio[@"channels"] unsignedIntegerValue] != 2 ||
![audio[@"encoding"] isEqual:@"pcm_s16le"] ||
!integer(audio[@"sample_frames"]) || [audio[@"sample_frames"] unsignedIntegerValue] != frames ||
!integer(audio[@"sample_count"]) || [audio[@"sample_count"] unsignedIntegerValue] != frames*2 ||
!integer(audio[@"byte_count"]) || [audio[@"byte_count"] unsignedIntegerValue] != wav.length)
return toolError(rid, @"invalid_playtest_audio");
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(wav.bytes, static_cast<CC_LONG>(wav.length), digest);
NSMutableString *hash = [NSMutableString string];
for (auto byte : digest) [hash appendFormat:@"%02x",byte];
if (![audio[@"sha256"] isEqual:hash]) return toolError(rid, @"invalid_playtest_audio");
[data removeObjectForKey:@"audio_wav_base64"];
data[@"audio_content"] = @YES;
[content addObject:@{@"type":@"audio", @"mimeType":@"audio/wav", @"data":encoded}];
}
if ([name isEqual:@"capture_playtest_graphics"]) {
NSArray *buffers = data[@"buffers"];
if (![buffers isKindOfClass:NSArray.class] || buffers.count < 1 || buffers.count > 2)
return toolError(rid, @"invalid_playtest_capture");
NSMutableArray *metadata = [NSMutableArray array];
NSUInteger total = 0;
for (id row in buffers) {
if (!object(row) || !string(row[@"png_base64"])) return toolError(rid, @"invalid_playtest_capture");
NSString *encoded = row[@"png_base64"];
NSData *png = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
const unsigned char signature[] = {137,80,78,71,13,10,26,10};
if (!png || png.length < 33 || png.length > 350000 || memcmp(png.bytes, signature, 8))
return toolError(rid, @"invalid_playtest_capture");
total += png.length;
if (total > 700000) return toolError(rid, @"invalid_playtest_capture");
NSMutableDictionary *fields = [row mutableCopy];
[fields removeObjectForKey:@"png_base64"]; fields[@"image_content"] = @YES;
[metadata addObject:fields];
[content addObject:@{@"type":@"image", @"mimeType":@"image/png", @"data":encoded}];
}
data[@"buffers"] = metadata;
}
if ([@[@"capture_playtest", @"start_playtest"] containsObject:name] && string(data[@"png_base64"])) {
NSString *encoded = data[@"png_base64"];
NSData *png = [[NSData alloc] initWithBase64EncodedString:encoded options:0];
const unsigned char signature[] = {137,80,78,71,13,10,26,10};
if (!png || png.length < 8 || png.length > 650000 || memcmp(png.bytes, signature, 8))
return toolError(rid, @"invalid_playtest_capture");
[data removeObjectForKey:@"png_base64"];
data[@"image_content"] = @YES;
[content addObject:@{@"type":@"image", @"mimeType":@"image/png", @"data":encoded}];
}
NSString *text = [[NSString alloc] initWithData:jsonBytes(data) encoding:NSUTF8StringEncoding];
[content insertObject:@{@"type":@"text", @"text":text} atIndex:0];
NSMutableDictionary *result = [@{@"content":content} mutableCopy];
if (![version isEqual:@"2025-03-26"]) result[@"structuredContent"] = data;
return success(rid, result);
}
return rpcError(rid, -32602, @"Unknown tool name");
}
} // namespace
int main(int argc, char **argv) {
@autoreleasepool {
const char *usage = "Usage: vcc-mcp --grant FILE [--loopback]\n"
"Select a private grant file exported by VCC Plus. Use --loopback for local TCP instead of the Unix socket.\n";
if (argc == 2 && !strcmp(argv[1], "--help")) { fputs(usage, stdout); return 0; }
bool loopback = argc == 4 && !strcmp(argv[3], "--loopback");
if ((argc != 3 && !loopback) || strcmp(argv[1], "--grant")) { fputs(usage, stderr); return 2; }
NSDictionary *grant = loadGrant(argv[2]); // Pin the original capability for this helper's lifetime.
if (!grant) { fputs("Invalid grant. Select an owner-only grant file exported by VCC Plus.\n", stderr); return 1; }
signal(SIGPIPE, SIG_IGN);
NSArray *manualTools = @[
tool(@"search_help", @"Find matching sections of the installed VCC Plus manuals. Supply 1 to 160 UTF-8 bytes of search terms.", @"query"),
tool(@"read_topic", @"Read a manual section using its topic_id from search_help (up to 512 UTF-8 bytes).", @"topic_id")
];
NSArray *tools;
const bool archive = [grant[@"kind"] isEqual:@"archive"];
const NSInteger toolset = integer(grant[@"toolset"]) ? [grant[@"toolset"] integerValue] : 0;
if (archive) {
tools = archiveTools();
} else if ([grant[@"kind"] isEqual:@"cmoc"] || [grant[@"kind"] isEqual:@"assembly"]) {
const bool customMake = [grant[@"kind"] isEqual:@"cmoc"] &&
toolset >= 4 && [grant[@"customMake"] isEqual:@YES];
const bool mediaExchange = [grant[@"kind"] isEqual:@"cmoc"] && toolset >= 11 &&
[grant[@"playtest"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
[grant[@"playtestMedia"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtestMedia"]) == CFBooleanGetTypeID();
tools = [MCPProjectTools([grant[@"kind"] isEqual:@"assembly"], toolset >= 3,
customMake) arrayByAddingObjectsFromArray:manualTools];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 6 && [grant[@"projectRefresh"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPProjectRefreshTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 7 && [grant[@"projectDiagnostics"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPBuildDiagnosticTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 5 && [grant[@"playtest"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestTools(
toolset >= 8 && [grant[@"playtestProcessors"] isEqual:@YES],
toolset >= 9 && [grant[@"playtestJoysticks"] isEqual:@YES] &&
CFGetTypeID((__bridge CFTypeRef)grant[@"playtestJoysticks"]) == CFBooleanGetTypeID(), mediaExchange)];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 7 &&
[grant[@"playtest"] isEqual:@YES] && [grant[@"playtestAudio"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestAudioTools()];
if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 10 && [grant[@"playtest"] isEqual:@YES] &&
CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() &&
[grant[@"playtestCallContext"] isEqual:@YES] &&
CFGetTypeID((__bridge CFTypeRef)grant[@"playtestCallContext"]) == CFBooleanGetTypeID())
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestCallContextTools()];
if (mediaExchange)
tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestMediaTools()];
} else {
tools = [@[tool(@"get_capabilities", @"Identify the connected VCC Plus session and selected BASIC document.", nil),
tool(@"read_source", @"Read the selected BASIC draft using its document_id from get_capabilities.", @"document_id")]
arrayByAddingObjectsFromArray:manualTools];
if ([grant[@"canPropose"] isEqual:@YES]) {
tools = [tools arrayByAddingObjectsFromArray:@[proposalTool(false), proposalTool(true),
tool(@"get_proposal", @"Check the status of a proposal in this session.", @"proposal_id")]];
tools = [tools arrayByAddingObjectsFromArray:MCPGuestTools(toolset >= 3)];
}
}
// A newly installed helper may be used with a connection from an older running app.
if (!archive && toolset >= 2) {
tools = [tools arrayByAddingObject:tool(@"get_machine_status", @"Read the active guest CPU, media status, and build and run blockers for the shared workspace.", nil)];
const bool cmoc = [grant[@"kind"] isEqual:@"cmoc"];
if (cmoc || [grant[@"kind"] isEqual:@"assembly"] || [grant[@"canPropose"] isEqual:@YES])
tools = [tools arrayByAddingObjectsFromArray:debuggerTools()];
if (cmoc || [grant[@"kind"] isEqual:@"assembly"]) tools = [tools arrayByAddingObject:projectEditsTool(!cmoc)];
}
Phase phase = Phase::fresh;
NSString *version = nil;
for (;;) {
@autoreleasepool {
std::string line;
int ch;
while ((ch = getchar()) != EOF && ch != '\n')
if (line.size() <= maxClientFrame) line.push_back(static_cast<char>(ch));
if (ch == EOF) return ferror(stdin) ? 1 : 0;
id record = line.size() <= maxClientFrame ? parse(line.data(), line.size()) : nil;
if ([record isKindOfClass:NSArray.class] && [record count] && [version isEqual:@"2025-03-26"]) {
// March requires batch reception. Stream one result at a time so a batch of
// large tool responses cannot exhaust the helper's memory.
bool emitted = false;
for (id item in record) {
@autoreleasepool {
NSDictionary *reply = handle(item, grant, loopback, tools, phase, version);
if (!reply) continue;
NSData *out = jsonBytes(reply);
if (!out || putchar(emitted ? ',' : '[') == EOF ||
fwrite(out.bytes, 1, out.length, stdout) != out.length) return 1;
emitted = true;
}
}
if (emitted && (fputs("]\n", stdout) == EOF || fflush(stdout))) return 1;
continue;
}
NSDictionary *reply;
if (line.size() > maxClientFrame) reply = rpcError(nil, -32600, @"Request exceeds 64 KiB");
else reply = record ? handle(record, grant, loopback, tools, phase, version) : rpcError(nil, -32700, @"Invalid JSON");
if (reply) {
NSData *out = jsonBytes(reply);
if (!out || fwrite(out.bytes, 1, out.length, stdout) != out.length || putchar('\n') == EOF || fflush(stdout)) return 1;
}
}
}
}
}
+886
View File
@@ -0,0 +1,886 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Exercise a built stdio helper against a disposable host, without emulator or model access."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import select
import socketserver
import subprocess
import struct
import zlib
import tempfile
import threading
import time
class Client:
def __init__(self, helper, grant):
self.proc = subprocess.Popen([helper, "--grant", str(grant)], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, bufsize=0)
def __enter__(self):
return self
def __exit__(self, *exc):
self.proc.stdin.close()
try:
self.proc.wait(timeout=5)
finally:
self.proc.kill()
self.proc.wait()
self.proc.stdout.close()
def send(self, obj):
self.raw(json.dumps(obj).encode())
def raw(self, data):
self.proc.stdin.write(data + b"\n")
self.proc.stdin.flush()
def response(self):
assert select.select([self.proc.stdout], [], [], 7)[0], "Timed out waiting for stdio reply"
line = self.proc.stdout.readline()
assert line, f"Helper exited with {self.proc.poll()}"
return json.loads(line)
def request(self, method, params=None, rid=1):
obj = {"jsonrpc": "2.0", "id": rid, "method": method}
if params is not None:
obj["params"] = params
self.send(obj)
reply = self.response()
assert reply["id"] == rid
return reply
def handshake(self, protocol):
params = {"protocolVersion": protocol, "capabilities": {}, "clientInfo": {"name": "fixture", "version": "1"}}
offer = self.request("initialize", params)["result"]["protocolVersion"]
assert self.request("tools/list")["error"]["code"] == -32002
self.send({"jsonrpc": "2.0", "method": "notifications/initialized"})
return offer
def call(self, name, **arguments):
return self.request("tools/call", {"name": name, "arguments": arguments})
def check(helper):
with tempfile.TemporaryDirectory(dir="/tmp", prefix="vcc-mcp-check-") as work:
socket_path = str(Path(work) / "host")
grant_file = Path(work) / "access"
grant = {"version": 1, "token": "first-grant", "socket": socket_path}
def write_grant(**extra):
grant_file.write_text(json.dumps({**grant, **extra}))
grant_file.chmod(0o600)
write_grant()
active = {"token": grant["token"], "requests": []}
class MockHost(socketserver.StreamRequestHandler):
def handle(self):
request = json.loads(self.rfile.readline(48 * 1024))
active["requests"].append(request)
result = {"result": {"document_id": "selected-draft"}}
if request["tool"] == "get_capabilities" and "project_capabilities" in active:
result = {"result": active["project_capabilities"]}
if request["tool"] == "capture_playtest" and "playtest_capture" in active:
result = {"result": active["playtest_capture"]}
if request["tool"] == "capture_playtest_graphics" and "playtest_graphics" in active:
result = {"result": active["playtest_graphics"]}
if request["tool"] == "capture_playtest_audio" and "playtest_audio" in active:
result = {"result": active["playtest_audio"]}
if request["tool"] == "get_build_log" and "build_log" in active:
result = {"result": active["build_log"]}
if request["tool"] == "get_debug_snapshot" and "debug_snapshot" in active:
result = {"result": active["debug_snapshot"]}
if request["tool"] == "get_call_context" and "call_context" in active:
result = {"result": active["call_context"]}
if request["tool"] == "list_playtest_disks" and "retained_disks" in active:
result = {"result": active["retained_disks"]}
if request["tool"] == "list_playtest_media" and "playtest_media" in active:
result = {"result": active["playtest_media"]}
if request["tool"] == "exchange_playtest_media" and "media_exchange" in active:
if active.get("slow_media_retention"):
time.sleep(5.15)
result = active["media_exchange"]
if request["tool"] in ("refresh_project", "get_project_refresh", "read_project_inputs") and "refresh_reply" in active:
result = active["refresh_reply"]
if request["tool"] in ("start_playtest", "get_run", "stop_playtest") and "startup_receipt" in active:
result = {"result": active["startup_receipt"]}
if request["token"] != active["token"]:
result = {"error": "access_denied"}
if request["arguments"].get("query") == "mixed-envelope":
result["error"] = 42
if request["arguments"].get("query") == "truncated-reply":
self.wfile.write(b'{"result":{}')
return
if request["arguments"].get("query") == "delayed-reply":
# Exercise the real bounded five-second host deadline,
# without changing production timeout settings for tests.
time.sleep(5.15)
return
self.wfile.write(json.dumps(result).encode() + b"\n")
with socketserver.UnixStreamServer(socket_path, MockHost) as host:
thread = threading.Thread(target=host.serve_forever, daemon=True)
thread.start()
try:
with Client(helper, grant_file) as c:
assert c.request("tools/list")["error"]["code"] == -32002
assert c.request("initialize", {})["error"]["code"] == -32602
assert c.handshake("2099-01-01") == "2025-11-25"
assert c.request("initialize", {})["error"]["code"] == -32600
for bad in (b"{", b'{"bad":"\xff"}', '{"jsonrpc":"2.0","id":2,"method":"ping"}'.encode("utf-16")):
c.raw(bad)
assert c.response()["error"]["code"] == -32700
c.raw(b"x" * (64 * 1024 + 1))
assert c.response()["error"]["code"] == -32600
c.send([{"jsonrpc": "2.0", "method": "ping", "id": 1}])
assert c.response()["error"]["code"] == -32600
c.send({"jsonrpc": "2.0", "id": 7, "result": {}})
c.send({"jsonrpc": "2.0", "method": "notifications/ignored"})
assert c.request("ping", rid="after-silent-messages")["result"] == {}
assert c.request("unknown")["error"]["code"] == -32601
assert c.request(42, rid="malformed")["error"]["code"] == -32600
listed = {t["name"] for t in c.request("tools/list")["result"]["tools"]}
assert listed == {"get_capabilities", "search_help", "read_source", "read_topic"}
assert c.call("propose_listing")["error"]["code"] == -32602
assert c.request("tools/call", {"name":"read_source", "arguments":[]})["error"]["code"] == -32602
for args in ({"document_id": []}, {"other": "x"}, {"document_id": ""}, {"document_id":"x","extra":1}):
assert c.call("read_source", **args)["result"]["isError"]
assert not active["requests"]
assert c.call("get_capabilities")["result"]["structuredContent"]["document_id"] == "selected-draft"
for query in ("truncated-reply", "mixed-envelope"):
result = c.call("search_help", query=query)["result"]
assert result["isError"] and result["content"][0]["text"] == "invalid_or_incomplete_host_reply"
delayed = c.call("search_help", query="delayed-reply")["result"]
assert delayed["isError"] and delayed["content"][0]["text"] == "transport_timeout"
assert c.call("get_capabilities")["result"]["structuredContent"]["document_id"] == "selected-draft"
active["token"] = "second-grant"
write_grant(token=active["token"])
denied = c.call("get_capabilities")["result"]
assert denied["isError"] and denied["content"][0]["text"] == "access_denied"
write_grant(token=active["token"], canPropose=True)
with Client(helper, grant_file) as c:
assert c.handshake("2025-11-25") == "2025-11-25"
tools = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
assert {"propose_edit", "propose_listing", "send_keys"} <= tools.keys()
args = {"document_id":"draft", "revision":0, "request_id":"once", "source":"10 ?" + "A" * (12288-4)}
assert c.call("propose_listing", **args)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == args
count = len(active["requests"])
for update in ({"source": args["source"]+"x"}, {"revision": True}, {"revision": -1}, {"request_id":"x"*129}):
assert c.call("propose_listing", **{**args, **update})["result"]["isError"]
assert c.call("send_keys", run_id="r", request_id="i", keys="RUN")["result"]["isError"]
assert len(active["requests"]) == count
for kind, limit in (("cmoc", 128), ("assembly", 64)):
write_grant(kind=kind, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = {t["name"]:t for t in c.request("tools/list")["result"]["tools"]}
assert len(listed) == 9 and {"build_project", "search_help", "read_topic"} <= listed.keys()
assert c.call("search_help", query="WIDTH")["result"]["structuredContent"]
assert c.call("read_topic", topic_id="reference")["result"]["structuredContent"]
fields = listed["propose_fix"]["inputSchema"]["properties"]
assert fields["request_id"]["maxLength"] == limit
args = dict(project_id="project", revision=0, request_id="q"*(limit+1))
assert c.call("build_project", **args)["result"]["isError"]
for kind, toolset, custom, supported in (("cmoc", 3, True, False),
("cmoc", 4, False, False),
("cmoc", 4, "yes", False),
("assembly", 4, True, False),
("cmoc", 4, True, True)):
write_grant(kind=kind, toolset=toolset, customMake=custom, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
schema = listed["build_project"]["inputSchema"]
assert set(schema["required"]) == {"project_id", "revision", "request_id"}
assert ("action" in schema["properties"]) == supported
assert ("configuration" in schema["properties"]) == supported
args = dict(project_id="project", revision=7, request_id="custom-build")
assert c.call("build_project", **args)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == args
count = len(active["requests"])
selection = dict(action="disk", configuration="Release")
result = c.call("build_project", **args, **selection)["result"]
assert ("structuredContent" in result) == supported
if not supported:
assert len(active["requests"]) == count
continue
assert active["requests"][-1]["arguments"] == {**args, **selection}
for action in ("build", "disk"):
for configuration in ("Debug", "Release"):
chosen = {**args, "action": action, "configuration": configuration}
assert c.call("build_project", **chosen)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == chosen
count = len(active["requests"])
for invalid in ({"action": "clean"}, {"action": "custom-target"}, {"action": 1},
{"configuration": ""}, {"configuration": "x" * 129},
{"configuration": ["Debug"]}, {"target": "disk"},
{"make_arguments": "-f other.mk"}):
assert c.call("build_project", **{**args, **invalid})["result"]["isError"]
assert len(active["requests"]) == count
capabilities = dict(project_id="project", revision=7, build_recipe="approved_make",
build_actions=["build", "disk"], configurations=["Debug", "Release"],
configuration="Debug", targets={"build": "build", "disk": "disk"},
recipe_id="observed-recipe")
active["project_capabilities"] = capabilities
assert c.call("get_capabilities")["result"]["structuredContent"] == capabilities
del active["project_capabilities"]
refresh_tools = {"refresh_project", "get_project_refresh", "read_project_inputs"}
for kind, toolset, permission in (("cmoc", 5, True), ("cmoc", 6, False),
("cmoc", 6, "yes"), ("assembly", 6, True), ("cmoc", 6, True)):
write_grant(kind=kind, toolset=toolset, projectRefresh=permission, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
supported = kind == "cmoc" and toolset >= 6 and permission is True
assert bool(refresh_tools & listed.keys()) == supported
if not supported:
continue
assert refresh_tools <= listed.keys()
for status in ("pending", "approved", "rejected", "unchanged"):
payload = dict(project_id="project", refresh_id="refresh", status=status, revision=8)
active["refresh_reply"] = {"result": payload}
for tool, arguments in (("refresh_project", dict(project_id="project", request_id="refresh", revision=7)),
("get_project_refresh", dict(project_id="project", refresh_id="refresh")),
("read_project_inputs", dict(project_id="project", offset=0, limit=256))):
assert c.call(tool, **arguments)["result"]["structuredContent"] == payload
assert active["requests"][-1]["arguments"] == arguments
count = len(active["requests"])
for invalid in ({"offset": -1}, {"limit": 0}, {"limit": 257}, {"path": "secret"}):
assert c.call("read_project_inputs", project_id="project", **invalid)["result"]["isError"]
assert len(active["requests"]) == count
details = dict(error="stale_revision", expected_revision=7, current_revision=8,
expected_artifact_id="old", current_artifact_id=None, changed_input_paths=["src/game.c"])
active["refresh_reply"] = {"error": "stale_revision", "error_details": details}
failure = c.call("refresh_project", project_id="project", request_id="stale", revision=7)["result"]
assert failure["isError"] and failure["structuredContent"] == details
del active["refresh_reply"]
# A new helper must not expand an old/forged grant. The one
# discovery list also controls dispatch before contacting host.
for kind, toolset, playtest, permission in (
("cmoc", None, True, True), ("cmoc", 5, True, True), ("cmoc", 9, True, True),
("cmoc", 10, False, True), ("cmoc", 10, None, True), ("cmoc", 10, 1, True),
("cmoc", 10, True, None), ("cmoc", 10, True, False), ("cmoc", 10, True, "yes"),
("cmoc", 10, True, 1), ("cmoc", 10, True, []), ("cmoc", 10, True, {}),
("cmoc", 10, True, "missing"), ("cmoc", 10.0, True, True),
("cmoc", True, True, True), ("cmoc", "10", True, True),
("cmoc", [], True, True), ("cmoc", {}, True, True),
("basic", 10, True, True), ("assembly", 10, True, True), ("archive", 10, True, True),
("cmoc", 10, True, True), ("cmoc", 11, True, True)):
options = dict(kind=kind, version=2 if kind == "archive" else 1, toolset=toolset,
playtest=playtest, playtestCallContext=permission, token=active["token"])
if permission == "missing":
del options["playtestCallContext"]
write_grant(**options)
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
catalog = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
enabled = kind == "cmoc" and type(toolset) is int and toolset >= 10 and playtest is True and permission is True
assert ("get_call_context" in catalog) == enabled, (kind, toolset, playtest, permission)
count = len(active["requests"])
args = dict(run_id="owned-run", snapshot_id="current-snapshot")
if not enabled:
assert c.call("get_call_context", **args)["error"]["code"] == -32602
assert len(active["requests"]) == count
continue
tool = catalog["get_call_context"]; schema = tool["inputSchema"]
assert schema["type"] == "object" and schema["additionalProperties"] is False
assert set(schema["properties"]) == set(schema["required"]) == {"run_id", "snapshot_id"}
assert all(value == dict(type="string", minLength=1, maxLength=64) for value in schema["properties"].values())
assert tool["annotations"] == dict(readOnlyHint=True, openWorldHint=False)
for payload in (dict(run_id="owned-run", snapshot_id="current-snapshot", status="unavailable", reason="unverified_frame"),
dict(run_id="owned-run", snapshot_id="current-snapshot", status="verified", frames=[])):
active["call_context"] = payload
assert c.call("get_call_context", **args)["result"]["structuredContent"] == payload
assert active["requests"][-1]["tool"] == "get_call_context"
assert active["requests"][-1]["arguments"] == args
del active["call_context"]
count = len(active["requests"])
invalid = ({}, {"run_id":"owned-run"}, {"snapshot_id":"current-snapshot"},
dict(args, run_id=""), dict(args, snapshot_id="x"*65), dict(args, run_id=True),
dict(args, snapshot_id=[]), dict(args, address=0), dict(args, offset=0),
dict(args, count=1), dict(args, registers={}), dict(args, memory=[]),
dict(args, caller="guess"), dict(args, max_frames=1), dict(args, request_id="read"))
for arguments in invalid:
assert c.call("get_call_context", **arguments)["result"]["isError"], arguments
assert len(active["requests"]) == count
# Media exchange is a separate, strict Boolean opt-in on fresh
# reviewed grants. Older grants never acquire it on restart.
media_tools = {"list_playtest_media", "exchange_playtest_media"}
for kind, toolset, playtest, permission in (
("cmoc", None, True, True), ("cmoc", 10, True, True), ("cmoc", 11.0, True, True),
("cmoc", True, True, True), ("cmoc", "11", True, True), ("cmoc", [], True, True),
("cmoc", {}, True, True), ("cmoc", 11, False, True), ("cmoc", 11, 1, True),
("cmoc", 11, "yes", True), ("cmoc", 11, None, True), ("cmoc", 11, True, False),
("cmoc", 11, True, 1), ("cmoc", 11, True, "yes"), ("cmoc", 11, True, []),
("cmoc", 11, True, {}), ("cmoc", 11, True, None), ("cmoc", 11, True, "missing"),
("basic", 11, True, True), ("assembly", 11, True, True), ("archive", 11, True, True),
("cmoc", 11, True, True), ("cmoc", 12, True, True)):
options = dict(kind=kind, version=2 if kind == "archive" else 1, toolset=toolset,
playtest=playtest, playtestMedia=permission, token=active["token"])
if permission == "missing":
del options["playtestMedia"]
write_grant(**options)
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
catalog = {t["name"]:t for t in c.request("tools/list")["result"]["tools"]}
enabled = kind == "cmoc" and type(toolset) is int and toolset >= 11 and playtest is True and permission is True
assert (media_tools & set(catalog)) == (media_tools if enabled else set()), options
listing = dict(project_id="project", revision=3, artifact_id="artifact")
insert = dict(run_id="run", request_id="swap-1", action="insert",
media_id="opaque-media-1", media_sha256="0123456789abcdef"*4)
eject = dict(run_id="run", request_id="swap-2", action="eject")
count = len(active["requests"])
if not enabled:
assert c.call("list_playtest_media", **listing)["error"]["code"] == -32602
assert c.call("exchange_playtest_media", **insert)["error"]["code"] == -32602
if "start_playtest" in catalog:
assert "retained_media" not in catalog["start_playtest"]["inputSchema"]["properties"]
assert c.call("start_playtest", project_id="project", revision=3, artifact_id="artifact",
request_id="start", retained_media=[])["result"]["isError"]
assert len(active["requests"]) == count
continue
assert catalog["list_playtest_media"]["annotations"] == dict(readOnlyHint=True, openWorldHint=False)
assert catalog["exchange_playtest_media"]["annotations"] == dict(readOnlyHint=False, idempotentHint=True, openWorldHint=False)
schema = catalog["exchange_playtest_media"]["inputSchema"]
assert schema["properties"]["action"]["enum"] == ["insert", "eject"]
assert len(schema["oneOf"]) == 2
assert all(branch["additionalProperties"] is False for branch in schema["oneOf"])
assert schema["oneOf"][0]["required"] == ["run_id", "request_id", "action", "media_id", "media_sha256"]
assert set(schema["oneOf"][1]["properties"]) == {"run_id", "request_id", "action"}
assert schema["properties"]["media_sha256"]["pattern"] == "^[0-9a-f]{64}$"
assert schema["properties"]["media_id"]["pattern"] == "^[A-Za-z0-9_-]{1,64}$"
resume_schema = catalog["start_playtest"]["inputSchema"]["properties"]["retained_media"]
assert resume_schema["minItems"] == 1 and resume_schema["maxItems"] == 8 and resume_schema["uniqueItems"] is True
assert set(resume_schema["items"]["properties"]) == {"media_id", "retained_disk_id", "retained_disk_sha256"}
resume_disk = dict(media_id="opaque-media-1", retained_disk_id="00000000-0000-4000-8000-000000000001",
retained_disk_sha256="a"*64)
resume = dict(project_id="project", revision=3, artifact_id="artifact", request_id="resume-media",
retained_media=[resume_disk])
assert c.call("start_playtest", **resume)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == resume
count = len(active["requests"])
for invalid in ([], [resume_disk]*2, [dict(resume_disk, media_id="m"+str(i)) for i in range(9)],
[dict(resume_disk, media_id="/tmp/world.dsk")], [dict(resume_disk, media_id="")],
[dict(resume_disk, retained_disk_sha256="A"*64)],
[{k:v for k,v in resume_disk.items() if k != "retained_disk_id"}],
[dict(resume_disk, path="world.dsk")], "media", None):
assert c.call("start_playtest", **dict(resume, retained_media=invalid))["result"]["isError"], invalid
assert len(active["requests"]) == count, "Invalid additional media resume selections reached the host"
payload = dict(project_id="project", revision=3, artifact_id="artifact",
media=[dict(media_id="opaque-media-1", media_sha256=insert["media_sha256"])])
active["playtest_media"] = payload
for args in (listing, dict(listing, run_id="run")):
assert c.call("list_playtest_media", **args)["result"]["structuredContent"] == payload
assert active["requests"][-1]["arguments"] == args
del active["playtest_media"]
# Preserve the exact request plan on retry. A changed
# selection reaches the host, whose ownership ledger
# decides conflicts; this adapter invents no media state.
receipt = dict(run_id="run", old_media_id="home", media_id="opaque-media-1", fields=42)
active["media_exchange"] = {"result": receipt}
for args in (insert, dict(insert), dict(insert, media_sha256="a"*64), eject):
assert c.call("exchange_playtest_media", **args)["result"]["structuredContent"] == receipt
assert active["requests"][-1]["arguments"] == args
if toolset == 11:
# Durable retention gets the bounded playtest
# deadline, not the five-second metadata deadline.
active["slow_media_retention"] = True
try:
assert c.call("exchange_playtest_media", **insert)["result"]["structuredContent"] == receipt
finally:
del active["slow_media_retention"]
active["media_exchange"] = {"error":"request_id_conflict"}
declined = c.call("exchange_playtest_media", **insert)["result"]
assert declined["isError"] and declined["content"][0]["text"] == "request_id_conflict"
del active["media_exchange"]
count = len(active["requests"])
for args in ({}, {"project_id":"project"}, dict(listing, revision=True), dict(listing, revision=-1),
dict(listing, revision=1.5), dict(listing, run_id=""), dict(listing, artifact_id=[]),
dict(listing, project_id="p"*65), dict(listing, path="/tmp/world.dsk"),
dict(listing, run_id="r"*65), dict(listing, request_id="listing")):
assert c.call("list_playtest_media", **args)["result"]["isError"], args
for args in ({}, {k:v for k,v in insert.items() if k != "media_id"},
{k:v for k,v in insert.items() if k != "media_sha256"},
dict(eject, media_id="opaque-media-1"), dict(eject, media_sha256="a"*64),
dict(insert, action="eject"), dict(insert, action="replace"), dict(insert, action=True),
dict(insert, media_sha256="A"*64), dict(insert, media_sha256="a"*63),
dict(insert, media_sha256="a"*65), dict(insert, media_sha256="a"*63+"\n"),
dict(insert, media_sha256=True), dict(insert, media_sha256=None),
dict(insert, media_id=""), dict(insert, media_id="m"*65),
dict(insert, media_id="../world.dsk"), dict(insert, media_id="/tmp/world.dsk"),
dict(insert, media_id=[]), dict(insert, request_id="r"*65), dict(insert, run_id=""),
dict(insert, path="world.dsk"), dict(insert, drive=0), dict(insert, fields=1),
dict(eject, media_id=None), dict(eject, media_sha256=None)):
assert c.call("exchange_playtest_media", **args)["result"]["isError"], args
assert len(active["requests"]) == count, "Invalid media selections reached the host"
write_grant(kind="cmoc", toolset=11, playtest=True, customMake=True, projectRefresh=True,
projectDiagnostics=True, playtestAudio=True, playtestProcessors=True, playtestJoysticks=True,
playtestCallContext=True, playtestMedia=True, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
catalog = {t["name"]:t for t in c.request("tools/list")["result"]["tools"]}
assert len(catalog) == 32 and media_tools <= set(catalog)
assert "single letter, digit or space" in catalog["send_keys"]["description"] or "one letter, digit or space" in catalog["send_keys"]["description"]
# CPU selection is opt-in; legacy exported schemas retain the
# 6809-only contract even when handled by this newer helper.
for toolset, permission in ((5,True),(7,True),(8,False),(8,"yes"),(8,True)):
write_grant(kind="cmoc",toolset=toolset,playtest=True,playtestProcessors=permission,token=active["token"])
with Client(helper,grant_file) as c:
c.handshake("2025-11-25")
catalog={t["name"]:t for t in c.request("tools/list")["result"]["tools"]}
schema=catalog["start_playtest"]["inputSchema"]
enabled=toolset>=8 and permission is True
assert ("processor" in schema["properties"])==enabled
args=dict(project_id="project",revision=1,artifact_id="artifact",request_id="start")
c.call("start_playtest",**args)
assert "processor" not in active["requests"][-1]["arguments"]
if enabled:
assert schema["properties"]["processor"]["enum"]==["MC6809","HD6309"]
assert schema["properties"]["processor"]["default"]=="MC6809"
assert "processor" not in schema["required"]
for processor in ("MC6809","HD6309"):
c.call("start_playtest",**args,processor=processor)
assert active["requests"][-1]["arguments"]["processor"]==processor
count=len(active["requests"])
for processor in (["6809","6309","hd6309","",None,True,9,[],{}] if enabled else ["HD6309"]):
assert c.call("start_playtest",**args,processor=processor)["result"]["isError"]
assert c.call("start_playtest",**args,cpu="6309")["result"]["isError"]
assert len(active["requests"])==count
# Standard analog ports are an explicit fresh-grant capability.
for toolset, permission in ((8, True), (9, False), (9, "yes"), (9, 1), (9, None), (9, True)):
write_grant(kind="cmoc", toolset=toolset, playtest=True, playtestProcessors=True,
playtestJoysticks=permission, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
catalog = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
step = catalog["playtest_input"]["inputSchema"]["properties"]["steps"]["items"]
enabled = toolset >= 9 and permission is True
assert ("joysticks" in step["properties"]) == enabled
assert ("get_playtest_input" in catalog) == enabled
assert step["required"] == ["keys", "fields"]
joystick = {"port": "right", "x": 0, "y": 8191, "buttons": ["fire1"]}
plan = dict(run_id="run", request_id="joy", steps=[dict(keys=[], fields=6, joysticks=[joystick])])
count = len(active["requests"])
if enabled:
assert catalog["get_playtest_input"]["annotations"]["readOnlyHint"]
c.call("get_playtest_input", run_id="run")
c.call("playtest_input", **plan)
assert active["requests"][-1]["arguments"] == plan
count = len(active["requests"])
for bad in (dict(joystick, x=True), dict(joystick, x=-1), dict(joystick, y=16384),
dict(joystick, x=1.5), dict(joystick, port="0"), dict(joystick, buttons=["fire3"]),
dict(joystick, buttons=["fire1", "fire1"]), dict(joystick, interface="standard")):
invalid = dict(plan, steps=[dict(keys=[], fields=6, joysticks=[bad])])
assert c.call("playtest_input", **invalid)["result"]["isError"], bad
assert len(active["requests"]) == count
else:
assert c.call("playtest_input", **plan)["result"]["isError"]
assert c.call("get_playtest_input", run_id="run")["error"]["code"] == -32602
assert len(active["requests"]) == count
playtest_tools = {"start_playtest", "list_playtest_disks", "playtest_input", "playtest_debug", "capture_playtest",
"capture_playtest_graphics", "restart_playtest", "stop_playtest"}
for kind, toolset, permission in (("cmoc", 4, True), ("cmoc", 5, False),
("cmoc", 5, "yes"), ("assembly", 5, True)):
write_grant(kind=kind, toolset=toolset, playtest=permission, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = {t["name"] for t in c.request("tools/list")["result"]["tools"]}
assert not playtest_tools & listed
count = len(active["requests"])
assert c.call("playtest_input", run_id="r", request_id="i", steps=[])["error"]["code"] == -32602
assert c.call("start_playtest", project_id="p", revision=1, artifact_id="a", request_id="entry",
stop_function="render_frame", stop_kind="function_entry")["error"]["code"] == -32602
assert c.call("list_playtest_disks", project_id="project")["error"]["code"] == -32602
assert c.call("capture_playtest_graphics", run_id="r")["error"]["code"] == -32602
assert len(active["requests"]) == count
write_grant(kind="cmoc", toolset=5, playtest=True, customMake=True, token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = {t["name"] for t in c.request("tools/list")["result"]["tools"]}
assert playtest_tools <= listed and len(listed) == 23
assert {"get_capabilities", "build_project", "get_build", "get_debug_snapshot", "read_debug_memory"} <= listed
detailed = {t["name"]:t for t in c.request("tools/list")["result"]["tools"]}
key_schema = detailed["playtest_input"]["inputSchema"]["properties"]["steps"]["items"]["properties"]["keys"]
assert {"period", "backspace", "shift"} <= set(key_schema["items"]["enum"])
assert "." not in key_schema["items"]["enum"]
graphics_schema = detailed["capture_playtest_graphics"]["inputSchema"]
assert "poll get_run" in detailed["start_playtest"]["description"]
assert "reserved run_id" in detailed["stop_playtest"]["description"]
assert detailed["capture_playtest_graphics"]["annotations"]["readOnlyHint"] is True
assert graphics_schema["required"] == ["run_id"]
assert set(graphics_schema["properties"]) == {"run_id", "buffer_id"}
assert graphics_schema["properties"]["buffer_id"]["pattern"] == "^[A-Za-z0-9_-]{1,64}$"
for name in ("start_playtest", "playtest_debug"):
schema = detailed[name]["inputSchema"]
assert "stop_kind" not in schema["required"]
assert schema["properties"]["stop_kind"]["enum"] == ["c_line", "function_entry"]
assert schema["properties"]["stop_kind"]["default"] == "c_line"
field = "stop_function" if name == "start_playtest" else "function"
assert schema["properties"][field]["maxLength"] == 1023
assert schema["properties"]["request_id"]["maxLength"] == 64
starts = dict(project_id="project", revision=1, artifact_id="artifact", request_id="entry",
stop_function="render_frame")
# Startup is accepted before preparation/boot finishes.
# Preserve polling/cancellation receipts exactly, without
# synthesizing a ready run or hiding the failed phase.
pending = dict(project_id="project", revision=1, artifact_id="artifact", request_id="entry",
run_id="reserved", owned_playtest=True, status="starting",
phase="preparing_debug_metadata", busy=True, poll_tool="get_run")
active["startup_receipt"] = pending
assert c.call("start_playtest", **starts)["result"]["structuredContent"] == pending
assert c.call("start_playtest", **starts)["result"]["structuredContent"] == pending
assert c.call("get_run", project_id="project", revision=1)["result"]["structuredContent"] == pending
for state in ({**pending, "status":"cancelling", "phase":"booting"},
{**pending, "status":"cancelled", "phase":"booting", "busy":False},
{**pending, "status":"failed", "phase":"reading_artifact", "busy":False,
"error":"artifact_disk_changed"}):
active["startup_receipt"] = state
assert c.call("get_run", project_id="project", revision=1)["result"]["structuredContent"] == state
active["startup_receipt"] = {**pending, "status":"cancelling", "phase":"booting"}
assert c.call("stop_playtest", run_id="reserved", request_id="cancel-start")["result"]["structuredContent"]["status"] == "cancelling"
assert active["requests"][-1]["arguments"] == {"run_id":"reserved", "request_id":"cancel-start"}
del active["startup_receipt"]
stops = dict(run_id="owned", request_id="entry-stop", action="stop_at", function="render_frame")
for tool, arguments in (("start_playtest", starts), ("playtest_debug", stops)):
for index, selection in enumerate(({}, {"stop_kind":"c_line"}, {"stop_kind":"function_entry"})):
expected = {**arguments, **selection, "request_id":arguments["request_id"] + "-" + str(index)}
assert c.call(tool, **expected)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == expected
count = len(active["requests"])
for invalid_kind in ("assembly", "", "FUNCTION_ENTRY", True, 1, None, [], {}):
assert c.call(tool, **arguments, stop_kind=invalid_kind)["result"]["isError"]
assert len(active["requests"]) == count, "Invalid stop kinds reached the host"
name_field = "stop_function" if tool == "start_playtest" else "function"
# Function identifiers have the same supported size as
# verified compiler metadata, independently of run IDs.
for length in (65, 1023):
expected = {**arguments, name_field:"f"*length, "stop_kind":"function_entry",
"request_id":arguments["request_id"] + "-long-" + str(length)}
assert c.call(tool, **expected)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == expected
count = len(active["requests"])
too_long = {**arguments, name_field:"f"*1024, "stop_kind":"function_entry"}
assert c.call(tool, **too_long)["result"]["isError"]
long_id = {**arguments, name_field:"f"*65, "request_id":"r"*65}
assert c.call(tool, **long_id)["result"]["isError"]
assert len(active["requests"]) == count, "Oversized names or IDs reached the host"
# Resuming a saved test disk carries an opaque record ID
# and the exact receipt hash, never an arbitrary host path.
disk_id = "00000000-0000-4000-8000-000000000001"
digest = "0123456789abcdef"*4
schema = detailed["start_playtest"]["inputSchema"]
assert not {"retained_disk_id", "retained_disk_sha256"} & set(schema["required"])
assert schema["properties"]["retained_disk_sha256"]["pattern"] == "^[0-9a-f]{64}$"
resumed = {**starts, "request_id":"resume", "retained_disk_id":disk_id, "retained_disk_sha256":digest}
assert c.call("start_playtest", **resumed)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == resumed
count = len(active["requests"])
for update in ({"retained_disk_id":[]}, {"retained_disk_id":True}, {"retained_disk_id":None},
{"retained_disk_id":""}, {"retained_disk_id":"x"*65},
{"retained_disk_sha256":[]}, {"retained_disk_sha256":64}, {"retained_disk_sha256":True},
{"retained_disk_sha256":None}, {"retained_disk_sha256":"a"*63},
{"retained_disk_sha256":"a"*65}, {"retained_disk_sha256":"A"*64},
{"retained_disk_sha256":"g"*64}, {"retained_disk_sha256":"a"*63+"\n"},
{"disk_path":"/tmp/not-an-authorized-disk.dsk"}):
assert c.call("start_playtest", **{**resumed, **update})["result"]["isError"], update
assert len(active["requests"]) == count, "Invalid retained disk fields reached the host"
assert detailed["list_playtest_disks"]["annotations"]["readOnlyHint"] is True
records = dict(project_id="project", disks=[dict(retained_disk_id=disk_id, sha256=digest,
provenance="project_record")])
active["retained_disks"] = records
listed_disks = c.call("list_playtest_disks", project_id="project")["result"]["structuredContent"]
assert listed_disks == records
assert active["requests"][-1]["arguments"] == {"project_id":"project"}
count = len(active["requests"])
for invalid in ({}, {"project_id":[]}, {"project_id":""}, {"project_id":"project", "path":"/tmp"}):
assert c.call("list_playtest_disks", **invalid)["result"]["isError"]
assert len(active["requests"]) == count
del active["retained_disks"]
# An assembly entry observation is distinct from a C line.
# The public adapter preserves that distinction exactly.
snapshot = dict(run_id="owned", snapshot_id="assembly-stop", source_stop=None,
function_stop=dict(name="render_frame", kind="function_entry", address=0x4000,
module_id="render-overlay", physical_address=12*8192),
registers={"PC":0x4000}, watches=[], memory_ranges=[])
active["debug_snapshot"] = snapshot
observed = c.call("get_debug_snapshot", run_id="owned")["result"]
assert observed["structuredContent"] == snapshot
assert json.loads(observed["content"][0]["text"]) == snapshot
assert observed["structuredContent"]["source_stop"] is None
assert "line" not in observed["structuredContent"]["function_stop"]
del active["debug_snapshot"]
# Nested scalar arrays and an empty release chord are both
# valid. Forward the plan byte-for-byte in JSON semantics.
plan = dict(run_id="owned", request_id="held-keys", steps=[
{"keys":["right", "x", "z"], "fields":60}, {"keys":[], "fields":1}])
assert c.call("playtest_input", **plan)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == plan
for step in ({"keys":["left"], "fields":600}, {"keys":[], "fields":1},
{"keys":["period"], "fields":1}, {"keys":["shift", "period"], "fields":1},
{"keys":["backspace"], "fields":1}, {"keys":["shift", "backspace"], "fields":1}):
args = {**plan, "steps":[step]}
assert c.call("playtest_input", **args)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == args
count = len(active["requests"])
invalid_steps = [
{}, "right", {"keys":"right", "fields":1}, {"keys":[{}], "fields":1},
{"keys":[1], "fields":1}, {"keys":[True], "fields":1}, {"keys":[["right"]], "fields":1},
{"keys":["right","right"], "fields":1}, {"keys":["unknown"], "fields":1},
{"keys":["."], "fields":1}, {"keys":["PERIOD"], "fields":1},
{"keys":["period", "period"], "fields":1},
{"keys":["right"], "fields":True}, {"keys":["right"], "fields":1.5},
{"keys":["right"], "fields":0}, {"keys":["right"], "fields":601},
{"keys":["right"], "fields":1, "extra":True},
{"keys":list("abcdefghi"), "fields":1}, {"keys":[], "fields":None},
]
for step in invalid_steps:
assert c.call("playtest_input", **{**plan, "steps":[step]})["result"]["isError"], step
for steps in ([], [{}]*65, "right", [None]):
assert c.call("playtest_input", **{**plan, "steps":steps})["result"]["isError"]
assert len(active["requests"]) == count, "Invalid nested arguments reached the host"
# The transport returns a standard image block, keeping
# base64 out of both human-readable and structured metadata.
def png_chunk(kind, payload):
return (struct.pack(">I", len(payload)) + kind + payload +
struct.pack(">I", zlib.crc32(kind + payload) & 0xffffffff))
authored_png = (b"\x89PNG\r\n\x1a\n" +
png_chunk(b"IHDR", struct.pack(">2I5B", 1, 1, 8, 2, 0, 0, 0)) +
png_chunk(b"IDAT", zlib.compress(b"\0\0\0\0")) + png_chunk(b"IEND", b""))
png = base64.b64encode(authored_png).decode()
active["playtest_capture"] = dict(run_id="owned", field_clock=61, width=1, height=1, png_base64=png)
result = c.call("capture_playtest", run_id="owned")["result"]
image = [item for item in result["content"] if item["type"] == "image"]
assert len(image) == 1 and image[0]["mimeType"] == "image/png" and image[0]["data"] == png
assert base64.b64decode(image[0]["data"]).startswith(b"\x89PNG\r\n\x1a\n")
metadata = json.loads(result["content"][0]["text"])
assert metadata == result["structuredContent"]
assert metadata["field_clock"] == 61 and metadata["image_content"] is True
assert "png_base64" not in metadata and png not in result["content"][0]["text"]
del active["playtest_capture"]
# Paired read-only previews share one paused observation.
# Preserve image order and all physical identity metadata,
# with image bytes occurring only in MCP image blocks.
second_png_bytes = (b"\x89PNG\r\n\x1a\n" +
png_chunk(b"IHDR", struct.pack(">2I5B", 1, 1, 8, 2, 0, 0, 0)) +
png_chunk(b"IDAT", zlib.compress(b"\0\xff\0\0")) + png_chunk(b"IEND", b""))
second_png = base64.b64encode(second_png_bytes).decode()
displayed = dict(role="display", physical_address=0x60000, width=1, height=1, png_base64=png)
declared = dict(role="declared", buffer_id="page_B-2", physical_address=0x62000,
width=1, height=1, png_base64=second_png)
for args, rows in (({"run_id":"owned"}, [displayed]),
({"run_id":"owned", "buffer_id":"page_B-2"}, [displayed, declared]),
({"run_id":"owned", "buffer_id":"A"*64}, [displayed, declared])):
payload = dict(run_id="owned", snapshot_id="paused-graphics", field_clock=61, paused=True, buffers=rows)
active["playtest_graphics"] = payload
result = c.call("capture_playtest_graphics", **args)["result"]
assert active["requests"][-1]["arguments"] == args
images = [item for item in result["content"] if item["type"] == "image"]
assert [item["data"] for item in images] == [row["png_base64"] for row in rows]
assert all(item["mimeType"] == "image/png" for item in images)
expected_rows = [{**{k:v for k,v in row.items() if k != "png_base64"}, "image_content":True} for row in rows]
expected = {**payload, "buffers":expected_rows}
assert result["structuredContent"] == expected
assert json.loads(result["content"][0]["text"]) == expected
metadata_text = json.dumps(result["structuredContent"])
assert "png_base64" not in metadata_text and png not in metadata_text and second_png not in metadata_text
assert png not in result["content"][0]["text"] and second_png not in result["content"][0]["text"]
count = len(active["requests"])
for args in ({}, {"run_id":[]}, {"run_id":"owned", "buffer_id":True},
{"run_id":"owned", "buffer_id":[]}, {"run_id":"owned", "buffer_id":None},
{"run_id":"owned", "buffer_id":""}, {"run_id":"owned", "buffer_id":"A"*65},
{"run_id":"owned", "buffer_id":"page\n"}, {"run_id":"owned", "buffer_id":"../page"},
{"run_id":"owned", "buffer_id":"/tmp/page"}, {"run_id":"owned", "buffer_id":"page.bin"},
{"run_id":"owned", "address":0x60000}, {"run_id":"owned", "path":"/tmp/page"}):
assert c.call("capture_playtest_graphics", **args)["result"]["isError"], args
assert len(active["requests"]) == count, "Invalid graphics selections reached the host"
too_large_png = base64.b64encode(b"\x89PNG\r\n\x1a\n" + b"x"*(350001-8)).decode()
malformed = [None, {}, [], [displayed]*3, [None], ["image"], [{}],
[{"png_base64":None}], [{"png_base64":[]}], [{"png_base64":True}],
[{"png_base64":"not base64!"}], [{"png_base64":base64.b64encode(b"not a PNG").decode()}],
[{"png_base64":base64.b64encode(b"\x89PNG\r\n\x1a").decode()}],
[{"png_base64":too_large_png}], [displayed, {"png_base64":"!"}]]
for rows in malformed:
active["playtest_graphics"] = dict(run_id="owned", buffers=rows)
result = c.call("capture_playtest_graphics", run_id="owned")["result"]
assert result["isError"], rows if not isinstance(rows, list) else len(rows)
assert not any(item["type"] == "image" for item in result["content"])
assert "structuredContent" not in result
active["playtest_graphics"] = dict(run_id="owned")
assert c.call("capture_playtest_graphics", run_id="owned")["result"]["isError"]
del active["playtest_graphics"]
# New diagnostics/audio grants opt in without changing older
# discovery. Audio is execution, not a read-only observation.
for kind, toolset, play, audio, diagnostic in (
("cmoc", 6, True, True, True), ("assembly", 7, True, True, True),
("cmoc", 7, False, True, True), ("cmoc", 7, True, "yes", False),
("cmoc", 7, True, True, True)):
write_grant(kind=kind, toolset=toolset, playtest=play, playtestAudio=audio,
projectDiagnostics=diagnostic, projectRefresh=True, customMake=True,
token=active["token"])
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
catalog = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]}
has_audio = kind == "cmoc" and toolset >= 7 and play is True and audio is True
has_log = kind == "cmoc" and toolset >= 7 and diagnostic is True
assert ("capture_playtest_audio" in catalog) == has_audio
assert ("get_build_log" in catalog) == has_log
if has_log:
active["build_log"] = dict(build_id="build", text="warning: first\nerror: actual failure\n",
offset=0, next_offset=None, process_output_truncated=False)
assert c.call("get_build_log", build_id="build", offset=0, limit=32768)["result"]["structuredContent"] == active["build_log"]
count = len(active["requests"])
for args in ({"build_id":"build", "limit":32769}, {"build_id":"build", "limit":0},
{"build_id":"build", "offset":-1}, {"build_id":"build", "path":"/tmp/private"}):
assert c.call("get_build_log", **args)["result"]["isError"]
assert count == len(active["requests"])
del active["build_log"]
if not has_audio:
continue
assert catalog["capture_playtest_audio"]["annotations"]["readOnlyHint"] is False
payload = struct.pack("<8h", 0,0,100,100,-100,-100,0,0)
wav = (b"RIFF" + struct.pack("<I", 36+len(payload)) + b"WAVEfmt " +
struct.pack("<IHHIIHH",16,1,2,44100,176400,4,16) + b"data" + struct.pack("<I",len(payload)) + payload)
encoded = base64.b64encode(wav).decode()
audio_fields = dict(sample_rate=44100,channels=2,encoding="pcm_s16le",sample_frames=4,
sample_count=8,byte_count=len(wav),sha256=hashlib.sha256(wav).hexdigest(),
field_start=10,field_end=11,fields_requested=1,fields_advanced=1,
advances_execution=True,completed=True,truncated=False)
active["playtest_audio"] = dict(run_id="owned",boot=2,artifact_id="artifact",
audio_wav_base64=encoded,audio=audio_fields)
result = c.call("capture_playtest_audio",run_id="owned",request_id="tone",fields=1)["result"]
clips = [item for item in result["content"] if item["type"] == "audio"]
assert clips == [dict(type="audio",mimeType="audio/wav",data=encoded)]
metadata = result["structuredContent"]
assert metadata["audio_content"] is True and metadata["boot"] == 2
assert "audio_wav_base64" not in metadata and encoded not in result["content"][0]["text"]
assert json.loads(result["content"][0]["text"]) == metadata
count = len(active["requests"])
for fields in (0,121,-1,True,1.5):
assert c.call("capture_playtest_audio",run_id="owned",request_id="bad",fields=fields)["result"]["isError"]
assert c.call("capture_playtest_audio",run_id="owned",request_id="bad",fields=1,path="/tmp/private")["result"]["isError"]
assert count == len(active["requests"])
for update in ({"audio_wav_base64":"!"}, {"audio_wav_base64":base64.b64encode(b"not WAV").decode()},
{"audio":{**audio_fields,"sha256":"0"*64}},
{"audio":{**audio_fields,"sample_count":9}},
{"audio":{**audio_fields,"channels":1}}):
active["playtest_audio"] = dict(run_id="owned",boot=2,audio_wav_base64=encoded,audio=audio_fields,**{})
active["playtest_audio"].update(update)
refused = c.call("capture_playtest_audio",run_id="owned",request_id="malformed",fields=1)["result"]
assert refused["isError"] and not any(x["type"] == "audio" for x in refused["content"])
del active["playtest_audio"]
write_grant(version=2, kind="archive", token=active["token"], canPropose=True, toolset=3)
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = c.request("tools/list")["result"]["tools"]
assert {item["name"] for item in listed} == {"search_archive", "get_archive_citation"}
assert all(item["annotations"]["readOnlyHint"] for item in listed)
before = len(active["requests"])
for name in ("read_source", "get_machine_status", "build_project", "get_debug_snapshot"):
assert c.call(name)["error"]["code"] == -32602
for query in ({"query":""}, {"query":"q"*257}, {"query":"6809", "limit":51},
{"query":"6809", "offset":True}, {"query":"6809", "url":"https://example.org"}):
assert c.call("search_archive", **query)["result"]["isError"]
assert len(active["requests"]) == before
args = {"query":"JOYSTK", "category":"Books", "limit":7, "offset":1}
assert c.call("search_archive", **args)["result"]["structuredContent"]
assert active["requests"][-1]["arguments"] == args
assert c.call("get_archive_citation", citation_id="selected")["result"]["structuredContent"]
active["token"] = "rotated"
assert c.call("search_archive", query="JOYSTK")["result"]["isError"]
for version, kind in ((2, "basic"), (2, "cmoc"), (1, "archive")):
write_grant(version=version, kind=kind)
rejected = subprocess.run([helper, "--grant", str(grant_file)], input=b"", capture_output=True, timeout=5)
assert rejected.returncode != 0 and not rejected.stdout
for toolset in (2, 3):
write_grant(token=active["token"], canPropose=True, toolset=toolset)
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
for key in (" ", "y", "A", "1", "PRINT 7\n", "RUN\n", "\n", "é", ".", "period", "backspace"):
result = c.call("send_keys", run_id="r", request_id="key", keys=key)["result"]
valid = key in ("1", "PRINT 7\n") or toolset == 3 and key in (" ", "y", "A")
assert ("structuredContent" in result) == valid, (toolset, key, result)
for kind, review in (("basic", False), ("basic", True), ("assembly", True), ("cmoc", True)):
write_grant(token=active["token"], kind=kind, canPropose=review, toolset=2)
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = {t["name"] for t in c.request("tools/list")["result"]["tools"]}
assert "get_machine_status" in listed
assert ("get_debug_snapshot" in listed) == review
assert ("read_debug_memory" in listed) == review
assert ("propose_project_edits" in listed) == (kind in ("cmoc", "assembly"))
if kind == "cmoc":
args = dict(project_id="project", revision=0, request_id="patch")
for edits in ([], [{}], ["file.c"], [{"path":"file.c","source":1}],
[{"path":"file.c","source":"", "extra":"x"}]):
assert c.call("propose_project_edits", edits=edits, **args)["result"]["isError"]
edits = [{"path":"src/one.c", "source":"int one;"}, {"path":"inc/two.h", "source":"int two;"}]
assert c.call("propose_project_edits", edits=edits, **args)["result"]["structuredContent"]
if review:
assert c.call("read_debug_memory", run_id="r", snapshot_id="s", address=0, count=257)["result"]["isError"]
for kind in ("cmoc", "assembly"):
for version in (2, 3):
write_grant(token=active["token"], kind=kind, canPropose=True, toolset=version)
with Client(helper, grant_file) as c:
c.handshake("2025-11-25")
listed = {t["name"] for t in c.request("tools/list")["result"]["tools"]}
assert ("send_keys" in listed) == (version == 3)
assert ("read_screen_text" in listed) == (version == 3)
if version == 3:
for key in (" ", "1", "N", "\n", "NEW\n", "PRINT 7\n", ".", "period", "backspace"):
result = c.call("send_keys", run_id="r", request_id="key", keys=key)["result"]
assert ("structuredContent" in result) == (key in (" ", "1", "N")), (kind, key, result)
write_grant(token=active["token"], canPropose=True)
for protocol in ("2025-03-26", "2025-06-18"):
with Client(helper, grant_file) as c:
assert c.handshake(protocol) == protocol
assert c.call("read_source", document_id=[])["error"]["code"] == -32602
result = c.call("get_capabilities")["result"]
assert json.loads(result["content"][0]["text"])["document_id"] == "selected-draft"
assert ("structuredContent" in result) == (protocol == "2025-06-18")
if protocol == "2025-03-26":
note = {"jsonrpc":"2.0", "method":"notifications/ignored"}
c.send([note, note])
c.send([note, {"jsonrpc":"2.0","method":"ping","id":"one"},
{"jsonrpc":"2.0","method":"unknown","id":2}, None])
first, second, invalid = c.response()
assert first["id"] == "one" and first["result"] == {}
assert second["id"] == 2 and second["error"]["code"] == -32601
assert invalid["id"] is None and invalid["error"]["code"] == -32600
finally:
host.shutdown()
thread.join()
grant_file.chmod(0o644)
rejected = subprocess.run([helper, "--grant", str(grant_file)], input=b"", capture_output=True, timeout=5)
assert rejected.returncode != 0 and not rejected.stdout
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("helper", type=Path)
check(os.fspath(parser.parse_args().helper.resolve(strict=True)))
print("PASS: protocol lifecycle, three revisions, UTF-8 framing, March batches, validation, large listing, host envelopes and grants")
+724
View File
@@ -0,0 +1,724 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// App-owned disposable machine. STDIO is private to the parent app; no sockets,
// credentials, user settings, host paths, or externally mounted media are read.
#import <AppKit/AppKit.h>
#import <CommonCrypto/CommonDigest.h>
#include "../../../../src/core/MachineSession.h"
#include "../../../../src/devices/FD502/Fd502Device.h"
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cctype>
#include <cstdint>
using namespace VCC::Mac;
namespace {
constexpr size_t wireLimit = 1024 * 1024;
constexpr uint64_t fieldBudget = 216000;
constexpr size_t maximumDiskBytes = 512 * 1024;
constexpr unsigned audioFieldLimit = 120;
constexpr size_t audioSampleFrameLimit = 131072;
void little16(std::vector<uint8_t>& bytes, uint16_t value) {
bytes.push_back(value & 255); bytes.push_back(value >> 8);
}
void little32(std::vector<uint8_t>& bytes, uint32_t value) {
little16(bytes, value & 65535); little16(bytes, value >> 16);
}
NSString *sha256(const std::vector<uint8_t>& bytes) {
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(bytes.data(), static_cast<CC_LONG>(bytes.size()), digest);
NSMutableString *text = [NSMutableString string];
for (auto byte : digest) [text appendFormat:@"%02x",byte];
return text;
}
std::vector<uint8_t> wave(const std::vector<StereoSample>& samples) {
// No host gain or device/microphone path is involved. Preserve both guest
// channels, quantized to standard signed 16-bit little-endian PCM.
if (samples.size() > audioSampleFrameLimit) throw std::runtime_error("playtest_audio_limit");
const uint32_t dataBytes = uint32_t(samples.size() * 4);
std::vector<uint8_t> bytes; bytes.reserve(44 + dataBytes);
bytes.insert(bytes.end(), {'R','I','F','F'}); little32(bytes, 36 + dataBytes);
bytes.insert(bytes.end(), {'W','A','V','E','f','m','t',' '}); little32(bytes, 16);
little16(bytes, 1); little16(bytes, 2); little32(bytes, CassetteDeck::rate);
little32(bytes, CassetteDeck::rate * 4); little16(bytes, 4); little16(bytes, 16);
bytes.insert(bytes.end(), {'d','a','t','a'}); little32(bytes, dataBytes);
for (const auto& sample : samples) {
for (float value : {sample.left, sample.right}) {
if (!std::isfinite(value)) throw std::runtime_error("playtest_audio_invalid_sample");
const long quantized = std::lround(std::clamp(value, -1.0f, 1.0f) * 32768.0f);
little16(bytes, uint16_t(int16_t(std::clamp(quantized, -32768L, 32767L))));
}
}
return bytes;
}
int number(id value, int low, int high) {
if (![value isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID())
throw std::invalid_argument("invalid_arguments");
double n = [value doubleValue];
if (!std::isfinite(n) || n < low || n > high || std::floor(n) != n) throw std::invalid_argument("invalid_arguments");
return int(n);
}
NSString *mediaIdentifier(id value) {
if (![value isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_media_id");
const auto count = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
if (!count || count > 64 || count != [value length]) throw std::invalid_argument("invalid_media_id");
const char *text = [value UTF8String];
for (NSUInteger i = 0; i < count; ++i) {
const auto c = static_cast<unsigned char>(text[i]);
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_')) throw std::invalid_argument("invalid_media_id");
}
return value;
}
struct InputStep {
uint64_t keys = 0;
unsigned fields = 0;
std::array<JoystickInputSnapshot, 2> joysticks{};
};
std::vector<InputStep> inputPlan(id value, unsigned& total) {
if (![value isKindOfClass:NSArray.class] || [value count] == 0 || [value count] > 64)
throw std::invalid_argument("invalid_arguments");
std::vector<InputStep> plan;
total = 0;
for (id raw in (NSArray *)value) {
if (![raw isKindOfClass:NSDictionary.class]) throw std::invalid_argument("invalid_arguments");
NSDictionary *step = raw;
for (NSString *key in step)
if (![@[@"mask", @"fields", @"joysticks"] containsObject:key]) throw std::invalid_argument("invalid_arguments");
NSNumber *mask = step[@"mask"];
if (![mask isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)mask) == CFBooleanGetTypeID() ||
!std::isfinite(mask.doubleValue) || mask.doubleValue < 0 || std::floor(mask.doubleValue) != mask.doubleValue ||
mask.unsignedLongLongValue >> 56) throw std::invalid_argument("invalid_arguments");
InputStep item;
item.keys = mask.unsignedLongLongValue;
item.fields = number(step[@"fields"], 1, 600);
total += item.fields;
if (total > 3600) throw std::invalid_argument("invalid_arguments");
if (step[@"joysticks"]) {
id ports = step[@"joysticks"];
if (![ports isKindOfClass:NSArray.class] || [ports count] > 2) throw std::invalid_argument("invalid_arguments");
bool seen[2] = {};
for (id rawPort in (NSArray *)ports) {
if (![rawPort isKindOfClass:NSDictionary.class] || [rawPort count] != 4)
throw std::invalid_argument("invalid_arguments");
NSDictionary *port = rawPort;
for (NSString *key in port)
if (![@[@"port", @"x", @"y", @"buttons"] containsObject:key]) throw std::invalid_argument("invalid_arguments");
unsigned index;
if ([port[@"port"] isEqual:@"right"]) index = 0;
else if ([port[@"port"] isEqual:@"left"]) index = 1;
else throw std::invalid_argument("invalid_arguments");
if (seen[index]) throw std::invalid_argument("invalid_arguments");
seen[index] = true;
auto& input = item.joysticks[index];
input.x = number(port[@"x"], 0, 16383);
input.y = number(port[@"y"], 0, 16383);
id buttons = port[@"buttons"];
if (![buttons isKindOfClass:NSArray.class] || [buttons count] > 2) throw std::invalid_argument("invalid_arguments");
for (id button in (NSArray *)buttons) {
unsigned bit;
if ([button isEqual:@"fire1"]) bit = 1;
else if ([button isEqual:@"fire2"]) bit = 2;
else throw std::invalid_argument("invalid_arguments");
if (input.buttons & bit) throw std::invalid_argument("invalid_arguments");
input.buttons |= bit;
}
}
}
plan.push_back(item);
}
return plan;
}
struct ReleaseInput {
MachineSession *machine;
~ReleaseInput() { machine->releaseInputs(); }
};
NSDictionary *inputMetadata(const Snapshot& snapshot) {
NSMutableArray *ports = [NSMutableArray arrayWithCapacity:2];
bool neutral = !snapshot.keyboardHeld;
for (unsigned index = 0; index < snapshot.joysticks.size(); ++index) {
const auto& port = snapshot.joysticks[index];
NSMutableArray *buttons = [NSMutableArray array];
if (port.buttons & 1) [buttons addObject:@"fire1"];
if (port.buttons & 2) [buttons addObject:@"fire2"];
neutral = neutral && port.x == 8191 && port.y == 8191 && port.buttons == 0;
[ports addObject:@{@"port":index == 0 ? @"right" : @"left", @"x":@(port.x), @"y":@(port.y),
@"buttons":buttons, @"interface":@[@"standard",@"software",@"tandy",@"coco_max"][std::min(port.mode, 3u)]}];
}
return @{@"source":@"owned_playtest", @"interface":@"standard", @"axis_min":@0, @"axis_max":@16383,
@"axis_center":@8191, @"x_direction":@"increases_right", @"y_direction":@"increases_down",
@"ports":ports, @"keyboard_held":@(snapshot.keyboardHeld), @"neutral":@(neutral)};
}
std::vector<uint8_t> bytes(id value, size_t maximum, size_t exact = 0) {
if (![value isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_arguments");
NSData *data = [[NSData alloc] initWithBase64EncodedString:value options:0];
if (!data || !data.length || data.length > maximum || (exact && data.length != exact))
throw std::invalid_argument("invalid_bytes");
auto p = static_cast<const uint8_t *>(data.bytes);
return {p, p + data.length};
}
NSArray *array(const std::vector<uint8_t>& data) {
NSMutableArray *out = [NSMutableArray arrayWithCapacity:data.size()];
for (auto b : data) [out addObject:@(b)];
return out;
}
DebugGraphicsMode graphicsMode(NSString *name) {
if (![name isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_graphics_buffer_mode");
const std::pair<const char*, DebugGraphicsMode> modes[] = {
{"sg4", DebugGraphicsMode::SG4}, {"pmode0", DebugGraphicsMode::PMODE0},
{"pmode1", DebugGraphicsMode::PMODE1}, {"pmode2", DebugGraphicsMode::PMODE2},
{"pmode3", DebugGraphicsMode::PMODE3}, {"pmode4", DebugGraphicsMode::PMODE4},
{"hscreen1", DebugGraphicsMode::HSCREEN1}, {"hscreen2", DebugGraphicsMode::HSCREEN2},
{"hscreen3", DebugGraphicsMode::HSCREEN3}, {"hscreen4", DebugGraphicsMode::HSCREEN4},
{"current_gime", DebugGraphicsMode::CurrentGime}};
for (const auto& [text, mode] : modes)
if ([name isEqualToString:[NSString stringWithUTF8String:text]]) return mode;
throw std::invalid_argument("invalid_graphics_buffer_mode");
}
NSString *png(const std::vector<uint32_t>& pixels, unsigned width, unsigned height, size_t maximum) {
if (!width || !height || width > Frame::width || height > Frame::height || pixels.size() != size_t(width) * height)
throw std::runtime_error("playtest_capture_failed");
NSBitmapImageRep *image = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nullptr
pixelsWide:width pixelsHigh:height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES
isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:width * 4 bitsPerPixel:32];
if (!image) throw std::runtime_error("playtest_capture_failed");
auto p = image.bitmapData;
for (size_t i = 0; i < pixels.size(); ++i) {
const auto rgb = pixels[i];
p[i*4] = rgb >> 16; p[i*4+1] = rgb >> 8; p[i*4+2] = rgb; p[i*4+3] = 255;
}
NSData *data = [image representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
if (!data || data.length > maximum) throw std::runtime_error("playtest_capture_limit");
return [data base64EncodedStringWithOptions:0];
}
NSMutableDictionary *graphicsMetadata(const DebugGraphicsPreview& preview, NSString *identity) {
NSMutableArray *ranges = [NSMutableArray array], *palette = [NSMutableArray array];
for (auto color : preview.palette) [palette addObject:@(color)];
bool contiguous = !preview.byteAddresses.empty();
for (size_t i = 0; i < preview.byteAddresses.size();) {
const auto begin = preview.byteAddresses[i];
size_t count = 1;
while (i + count < preview.byteAddresses.size() && preview.byteAddresses[i + count] == begin + count) ++count;
[ranges addObject:@{@"address":@(begin),@"count":@(count)}];
if (ranges.count > 1024) throw std::runtime_error("playtest_capture_limit");
i += count;
}
contiguous = contiguous && ranges.count == 1;
NSMutableDictionary *metadata = [@{@"id":identity, @"selection":@"current_video_registers", @"physical_address":@(preview.address),
@"byte_count":@(preview.bytes.size()), @"contiguous":@(contiguous), @"physical_ranges":ranges,
@"mode":[NSString stringWithUTF8String:preview.modeName.c_str()], @"width":@(preview.width), @"height":@(preview.height),
@"bytes_per_row":@(preview.bytesPerRow), @"pixels_per_byte":@(preview.pixelsPerByte),
@"lines_per_row":@(preview.linesPerRow), @"palette":palette,
@"video_origin":@(preview.videoOrigin), @"row_stride_bytes":@(preview.rowStrideBytes),
@"horizontal_offset_bytes":@(preview.horizontalOffsetBytes), @"vertical_scroll_lines":@(preview.verticalScrollLines),
@"generation":@(preview.generation), @"cycles":@(preview.cycles)} mutableCopy];
if (!preview.canvasIdentifier.empty()) {
metadata[@"canvas_id"] = [NSString stringWithUTF8String:preview.canvasIdentifier.c_str()];
metadata[@"canvas_address"] = @(preview.canvasAddress); metadata[@"canvas_bytes"] = @(preview.canvasBytes);
metadata[@"viewport_offset"] = @(preview.viewportOffset);
}
return metadata;
}
class Playtest {
std::unique_ptr<MachineSession> machine;
std::shared_ptr<VCC::Devices::Fd502Device> floppy;
std::vector<uint8_t> rom;
std::vector<uint64_t> bootKeys;
std::vector<DebugBankedModule> modules;
std::vector<DebugCodeGuard> flatGuards;
std::vector<DebugGraphicsBuffer> graphicsBuffers;
std::vector<uint16_t> stops;
std::string stopModule;
void armEvidence(const std::vector<uint16_t>& points, const std::string& selectedModule) {
if (!flatGuards.empty()) {
if (!selectedModule.empty()) throw std::invalid_argument("unverified_stop_module");
auto guards = flatGuards;
// The native flat guard API expects each stop at the beginning of
// a verified range. Split retained byte ranges without inventing
// instruction boundaries; stop addresses are verified by the host.
for (auto point : points) {
const auto found = std::find_if(guards.begin(), guards.end(), [&](const auto& guard) {
return point >= guard.address && size_t(point - guard.address) < guard.bytes.size();
});
if (found == guards.end()) throw std::invalid_argument("unverified_stop");
const auto offset = size_t(point - found->address);
if (offset) {
DebugCodeGuard tail{point, std::vector<uint8_t>(found->bytes.begin() + offset, found->bytes.end())};
found->bytes.resize(offset); guards.push_back(std::move(tail));
}
}
std::sort(guards.begin(), guards.end(), [](const auto& lhs, const auto& rhs) { return lhs.address < rhs.address; });
machine->debuggerArmDevelopmentBreakpoints(points, guards);
return;
}
if (modules.empty()) {
if (!points.empty()) throw std::invalid_argument("unverified_stop_module");
machine->debuggerClearDevelopmentBreakpoints();
return;
}
auto registered = modules;
bool selected = points.empty();
for (auto& module : registered) {
if (!points.empty() && module.identifier == selectedModule) {
module.breakpointAddresses = points; selected = true;
} else module.breakpointAddresses = std::vector<uint16_t>{};
}
if (!selected) throw std::invalid_argument("unverified_stop_module");
// Keep every verified module available for pauses and steps after a
// bank switch; only the selected module owns the requested stop points.
machine->debuggerArmBankedDevelopmentBreakpoints(points, registered);
}
void armStop() { armEvidence(stops, stopModule); }
void armInspection() { armEvidence({}, {}); }
uint64_t consumed = 0, fieldClock = 0, bootNumber = 0, mediaGeneration = 0;
Processor processor = Processor::MC6809;
NSString *originalDiskHash = nil, *currentMediaID = nil;
NSString *diskHash() const {
const auto *image = floppy ? floppy->image(0) : nullptr;
return image ? sha256(image->bytes()) : @"";
}
void requireMediaExchangeState() const {
if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped");
// Motor activity or previously written bytes do not mean a transfer is
// pending. Only the actual FDC busy state prevents a disk exchange.
if (floppy->snapshot().busy) throw std::runtime_error("playtest_media_busy");
}
NSDictionary *exportMedia() const {
requireMediaExchangeState();
NSMutableDictionary *out = [status() mutableCopy];
if (const auto *image = floppy->image(0)) {
const auto& data = image->bytes();
out[@"disk_base64"] = [[NSData dataWithBytes:data.data() length:data.size()] base64EncodedStringWithOptions:0];
}
return out;
}
NSDictionary *exchangeMedia(NSDictionary *request) {
for (NSString *key in request)
if (![@[@"op", @"expected_media_generation", @"expected_disk_sha256", @"media_id", @"disk_base64"] containsObject:key])
throw std::invalid_argument("invalid_arguments");
const bool inserting = request[@"media_id"] != nil;
if ((request[@"disk_base64"] != nil) != inserting || request.count != (inserting ? 5u : 3u))
throw std::invalid_argument("invalid_arguments");
const auto expected = number(request[@"expected_media_generation"], 0, INT32_MAX);
if (![request[@"expected_disk_sha256"] isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_arguments");
NSString *nextID = nil;
std::optional<VCC::Devices::DiskImage> replacement;
// Complete container validation and allocation precede any change to
// mounted media. Invalid images cannot eject or replace the old disk.
if (inserting) {
nextID = mediaIdentifier(request[@"media_id"]);
replacement.emplace(VCC::Devices::DiskImage::load(bytes(request[@"disk_base64"], maximumDiskBytes)));
}
requireMediaExchangeState();
NSString *oldHash = diskHash(), *oldID = currentMediaID;
if (uint64_t(expected) != mediaGeneration || ![request[@"expected_disk_sha256"] isEqual:oldHash])
throw std::runtime_error("stale_media_exchange");
if (mediaGeneration == INT32_MAX) throw std::runtime_error("playtest_media_limit");
// The parent exports and durably retains the old image first. Explicit
// discard only releases this worker's already-retained mounted copy.
if (replacement) floppy->mount(0, std::move(*replacement), true);
else floppy->eject(0, true);
currentMediaID = nextID; originalDiskHash = diskHash(); ++mediaGeneration;
NSMutableDictionary *out = [status() mutableCopy];
out[@"previous_media_id"] = oldID ?: (id)NSNull.null;
out[@"previous_disk_sha256"] = oldHash;
out[@"advances_execution"] = @NO;
return out;
}
void fields(unsigned n) {
if (consumed + n > fieldBudget) throw std::runtime_error("playtest_field_limit");
for (unsigned i = 0; i < n && machine->snapshot().state == RunState::Running; ++i) {
const auto before = machine->snapshot().frames;
machine->advance(); machine->takeAudio(); ++consumed;
fieldClock += machine->snapshot().frames - before;
}
}
void boot() {
if (++bootNumber > 16) throw std::runtime_error("playtest_restart_limit");
machine->releaseInputs(); machine->cancelPaste(); machine->reset(); machine->resume();
fields(300);
if (!machine->basicAtDirectPrompt()) throw std::runtime_error("playtest_basic_unavailable");
if (!modules.empty() || !flatGuards.empty()) { armStop(); machine->resume(); }
machine->paste(bootKeys);
for (unsigned n = 0; machine->pasteRemaining() && n < 3600; ++n) {
if (machine->snapshot().state == RunState::Paused) { machine->cancelPaste(); break; }
fields(1);
}
if (machine->pasteRemaining()) throw std::runtime_error("playtest_boot_timeout");
fields(600);
}
NSDictionary *status() const {
auto s = machine->snapshot();
const bool hd6309 = s.configuration.processor == Processor::HD6309;
const auto *image = floppy->image(0);
return @{ @"cpu": hd6309 ? @"6309" : @"6809", @"processor": hd6309 ? @"HD6309" : @"MC6809",
@"execution_mode": hd6309 ? (s.cpu.IsNative6309 ? @"native" : @"emulation") : @"not_applicable",
@"md_register": hd6309 ? (id)@(s.cpu.MD) : NSNull.null, @"ram_kb": @512,
@"fields": @(fieldClock), @"field_clock": @(fieldClock), @"boot": @(bootNumber), @"machine_frame": @(s.frames),
@"remaining_field_budget": @(fieldBudget - std::min(fieldBudget, consumed)),
@"remaining_boots": @(bootNumber < 16 ? 16 - bootNumber : 0),
@"cycles": @(s.cycles), @"generation": @(s.generation), @"pc": @(s.cpu.PC),
@"state": s.state == RunState::Paused ? @"paused" : @"running",
@"disk_original_sha256": originalDiskHash ?: @"", @"disk_sha256": diskHash(),
@"disk_present": @(image != nullptr), @"media_id": currentMediaID ?: (id)NSNull.null,
@"media_generation": @(mediaGeneration), @"floppy_busy": @(floppy->snapshot().busy),
@"disk_dirty": @(image && image->dirty()), @"disk_reads": @(floppy->readEvents(0)),
@"disk_writes": @(floppy->writeEvents(0)), @"isolated": @YES, @"input":inputMetadata(s) };
}
NSDictionary *capture() const {
NSMutableDictionary *out = [status() mutableCopy];
out[@"frame_snapshot_kind"] = @"last_published_frame";
try {
out[@"display_buffer"] = graphicsMetadata(machine->debuggerGraphicsPreview(true, true, 0, DebugGraphicsMode::HSCREEN2, false, graphicsBuffers), @"displayed");
} catch (const std::exception& error) {
out[@"display_buffer"] = @{@"selection":@"current_video_registers", @"unavailable":[NSString stringWithUTF8String:error.what()]};
}
try { out[@"screen_text"] = [NSString stringWithUTF8String:machine->copyScreenText().c_str()]; }
catch (const std::exception&) { out[@"screen_text_unavailable"] = @"Guest display is in graphics mode."; }
auto frame = machine->snapshot().frame;
if (frame && frame->pixels.size() == Frame::width * Frame::height) {
out[@"png_base64"] = png(frame->pixels, Frame::width, Frame::height, 650000);
out[@"width"] = @(Frame::width); out[@"height"] = @(Frame::height);
out[@"frame_number"] = @(frame->number);
}
return out;
}
NSDictionary *captureAudio(unsigned requested) {
if (consumed + requested > fieldBudget) throw std::runtime_error("playtest_field_limit");
const auto before = machine->snapshot();
const auto firstField = fieldClock;
std::vector<StereoSample> samples;
samples.reserve(std::min(size_t(requested) * 1024, audioSampleFrameLimit));
auto collect = [&] {
auto next = machine->takeAudio();
if (next.size() > audioSampleFrameLimit - samples.size()) throw std::runtime_error("playtest_audio_limit");
samples.insert(samples.end(), next.begin(), next.end());
};
// Discard audio from earlier input/steps. A capture owns only this
// explicit interval, including any normal leave-breakpoint CPU slice.
machine->takeAudio(); machine->releaseInputs();
try {
if (before.state == RunState::Paused) {
machine->resume();
const auto resumedFields = machine->snapshot().frames - before.frames;
fieldClock += resumedFields; consumed += resumedFields;
collect();
}
for (unsigned attempt = 0; attempt < requested && fieldClock - firstField < requested &&
machine->snapshot().state == RunState::Running; ++attempt) {
const auto previous = machine->snapshot().frames;
machine->advance(); ++consumed;
fieldClock += machine->snapshot().frames - previous;
collect();
}
} catch (...) { machine->releaseInputs(); machine->pause(); throw; }
machine->releaseInputs(); machine->pause();
const auto after = machine->snapshot();
const auto data = wave(samples);
NSMutableDictionary *out = [status() mutableCopy];
out[@"audio_wav_base64"] = [[NSData dataWithBytes:data.data() length:data.size()] base64EncodedStringWithOptions:0];
out[@"audio"] = @{@"mime_type":@"audio/wav", @"sample_rate":@(CassetteDeck::rate), @"channels":@2,
@"encoding":@"pcm_s16le", @"bits_per_sample":@16, @"sample_frames":@(samples.size()),
@"sample_count":@(samples.size() * 2), @"byte_count":@(data.size()), @"sha256":sha256(data),
@"field_start":@(firstField), @"field_end":@(fieldClock), @"fields_requested":@(requested),
@"fields_advanced":@(fieldClock - firstField), @"cycles_start":@(before.cycles), @"cycles_end":@(after.cycles),
@"advances_execution":@YES, @"completed":@(fieldClock - firstField == requested), @"truncated":@NO};
return out;
}
public:
bool stopped = false;
NSDictionary *reply(NSDictionary *r) {
NSString *op = r[@"op"];
if (![op isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_arguments");
if ([op isEqual:@"init"]) {
if (machine) throw std::runtime_error("already_started");
rom = bytes(r[@"system_rom"], 32768, 32768);
auto diskROM = bytes(r[@"disk_rom"], 8192, 8192), disk = bytes(r[@"disk"], maximumDiskBytes);
NSString *initialMediaID = mediaIdentifier(r[@"media_id"] ?: @"primary");
NSArray *keys = r[@"boot_keys"];
if (![keys isKindOfClass:NSArray.class] || keys.count == 0 || keys.count > 256) throw std::invalid_argument("invalid_boot_keys");
for (NSNumber *n in keys) {
if (![n isKindOfClass:NSNumber.class] || n.unsignedLongLongValue >> 56) throw std::invalid_argument("invalid_boot_keys");
bootKeys.push_back(n.unsignedLongLongValue);
}
if ([r[@"cpu"] isEqual:@"6309"]) processor = Processor::HD6309;
else if (r[@"cpu"] && ![r[@"cpu"] isEqual:@"6809"]) throw std::invalid_argument("invalid_cpu");
NSArray *declared = r[@"modules"] ?: @[];
if (![declared isKindOfClass:NSArray.class] || declared.count > 256) throw std::invalid_argument("invalid_modules");
size_t guardTotal = 0;
for (NSDictionary *item in declared) {
if (![item isKindOfClass:NSDictionary.class] || ![item[@"id"] isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_modules");
DebugBankedModule module; module.identifier = [item[@"id"] UTF8String];
NSArray *pages = item[@"pages"], *guards = item[@"guards"];
if (![pages isKindOfClass:NSArray.class] || pages.count == 0 || pages.count > 8 ||
![guards isKindOfClass:NSArray.class] || guards.count == 0 || guards.count > 8192) throw std::invalid_argument("invalid_modules");
for (NSDictionary *page in pages) {
if (![page isKindOfClass:NSDictionary.class]) throw std::invalid_argument("invalid_modules");
module.pages.push_back({uint8_t(number(page[@"logical_page"],0,7)),uint32_t(number(page[@"physical_page"],0,63))});
}
for (NSDictionary *guard in guards) {
if (![guard isKindOfClass:NSDictionary.class]) throw std::invalid_argument("invalid_modules");
int address = number(guard[@"address"],0,65535);
auto value = bytes(guard[@"bytes_base64"], 65536);
guardTotal += value.size();
if (value.size() > 65536 - address || guardTotal > 512*1024) throw std::invalid_argument("invalid_modules");
module.guards.push_back({uint16_t(address),std::move(value)});
}
modules.push_back(std::move(module));
}
NSArray *declaredFlat = r[@"flat_guards"] ?: @[];
if (![declaredFlat isKindOfClass:NSArray.class] || declaredFlat.count > 8192 ||
(declaredFlat.count && !modules.empty())) throw std::invalid_argument("invalid_flat_guards");
std::vector<bool> occupied(65536, false);
size_t flatTotal = 0;
for (NSDictionary *guard in declaredFlat) {
if (![guard isKindOfClass:NSDictionary.class]) throw std::invalid_argument("invalid_flat_guards");
const auto address = number(guard[@"address"], 0, 0xfdff);
auto value = bytes(guard[@"bytes_base64"], 65536);
flatTotal += value.size();
if (value.size() > 0xfe00 - address || flatTotal > 65536) throw std::invalid_argument("invalid_flat_guards");
for (size_t i = 0; i < value.size(); ++i) {
if (occupied[address + i]) throw std::invalid_argument("invalid_flat_guards");
occupied[address + i] = true;
}
flatGuards.push_back({uint16_t(address), std::move(value)});
}
NSArray *buffers = r[@"graphics_buffers"] ?: @[];
if (![buffers isKindOfClass:NSArray.class] || buffers.count > 4) throw std::invalid_argument("invalid_graphics_buffers");
for (NSDictionary *item in buffers) {
if (![item isKindOfClass:NSDictionary.class] || ![item[@"id"] isKindOfClass:NSString.class])
throw std::invalid_argument("invalid_graphics_buffers");
const std::string identifier = [item[@"id"] UTF8String];
if (identifier.empty() || identifier.size() > 64 || identifier.size() != [item[@"id"] lengthOfBytesUsingEncoding:NSUTF8StringEncoding] || identifier == "displayed" ||
!std::all_of(identifier.begin(), identifier.end(), [](unsigned char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-';
}) || std::any_of(graphicsBuffers.begin(), graphicsBuffers.end(), [&](const auto& buffer) { return buffer.identifier == identifier; }))
throw std::invalid_argument("invalid_graphics_buffer_id");
const auto mode = graphicsMode(item[@"mode"]);
const auto origin = uint32_t(number(item[@"physical_address"],0,512*1024-1));
uint32_t span = 0;
if (mode == DebugGraphicsMode::CurrentGime) {
span = uint32_t(number(item[@"canvas_bytes"],8192,512*1024));
if ((span & (span - 1)) || origin % span || span > 512*1024 - origin)
throw std::invalid_argument("invalid_graphics_canvas_span");
for (const auto& other : graphicsBuffers)
if (other.mode == DebugGraphicsMode::CurrentGime && origin < other.physicalAddress + other.canvasBytes && other.physicalAddress < origin + span)
throw std::invalid_argument("ambiguous_graphics_canvases");
} else if (item[@"canvas_bytes"]) throw std::invalid_argument("unexpected_graphics_canvas_span");
graphicsBuffers.push_back({identifier, origin, mode, false, span});
}
if (r[@"stop_at"]) {
if (modules.empty() && flatGuards.empty()) throw std::invalid_argument("unverified_stop");
stops.push_back(uint16_t(number(r[@"stop_at"],0,65535)));
if (!flatGuards.empty()) {
if (r[@"stop_module"]) throw std::invalid_argument("unverified_stop_module");
} else {
if (![r[@"stop_module"] isKindOfClass:NSString.class]) throw std::invalid_argument("unverified_stop_module");
stopModule = [r[@"stop_module"] UTF8String];
}
}
machine = std::make_unique<MachineSession>();
MachineConfiguration config; config.processor = processor; config.ram = 1; config.frameInterval = 1;
machine->configure(config);
floppy = std::make_shared<VCC::Devices::Fd502Device>(diskROM);
floppy->mount(0,VCC::Devices::DiskImage::load(disk));
originalDiskHash = diskHash(); currentMediaID = initialMediaID;
machine->cartridges().configure({nullptr,nullptr,nullptr,nullptr,floppy},true,4);
machine->load(rom,processor);
for (const auto& buffer : graphicsBuffers)
if (buffer.mode != DebugGraphicsMode::CurrentGime)
(void)machine->debuggerGraphicsPreview(false, true, buffer.physicalAddress, buffer.mode);
boot(); return status();
}
if (!machine || stopped) throw std::runtime_error("stale_run");
if ([op isEqual:@"media_status"]) {
if (r.count != 1) throw std::invalid_argument("invalid_arguments");
return status();
}
if ([op isEqual:@"export_media"]) {
if (r.count != 1) throw std::invalid_argument("invalid_arguments");
return exportMedia();
}
if ([op isEqual:@"exchange_media"]) return exchangeMedia(r);
if ([op isEqual:@"input"]) {
if (r.count != 2) throw std::invalid_argument("invalid_arguments");
unsigned total = 0;
const auto plan = inputPlan(r[@"steps"], total);
if (consumed + total > fieldBudget) throw std::runtime_error("playtest_field_limit");
ReleaseInput cleanup{machine.get()};
NSMutableArray *trace = [NSMutableArray arrayWithCapacity:plan.size()];
for (unsigned index = 0; index < plan.size(); ++index) {
const auto& step = plan[index];
const auto before = machine->snapshot();
if (before.state != RunState::Running && index != 0) break;
const auto first = fieldClock;
Snapshot applied;
if (before.state == RunState::Paused) {
armInspection();
// Input is staged through the same setters before the
// normal leave-breakpoint slice can sample the PIA.
applied = machine->resumeWithInput(step.keys, step.joysticks);
const auto advanced = machine->snapshot().frames - before.frames;
fieldClock += advanced; consumed += advanced;
if (advanced > step.fields) throw std::runtime_error("playtest_input_timing");
} else {
machine->setKeyboard(step.keys);
for (unsigned port = 0; port < step.joysticks.size(); ++port) {
const auto& input = step.joysticks[port];
machine->setJoystick(port, input.x, input.y, input.buttons, 0);
}
applied = machine->snapshot();
}
fields(step.fields - unsigned(fieldClock - first));
[trace addObject:@{@"step_index":@(index), @"fields_requested":@(step.fields),
@"fields_advanced":@(fieldClock - first), @"field_start":@(first), @"field_end":@(fieldClock), @"input":inputMetadata(applied)}];
}
machine->releaseInputs();
NSMutableDictionary *result = [status() mutableCopy]; result[@"input_trace"] = trace;
return result;
}
if ([op isEqual:@"input_status"]) {
if (r.count != 1) throw std::invalid_argument("invalid_arguments");
return status();
}
if ([op isEqual:@"capture"]) return capture();
if ([op isEqual:@"audio_capture"]) {
if (r.count != 2 || !r[@"fields"]) throw std::invalid_argument("invalid_arguments");
return captureAudio(number(r[@"fields"], 1, audioFieldLimit));
}
if ([op isEqual:@"graphics_capture"]) {
if (r.count > 2) throw std::invalid_argument("invalid_arguments");
for (NSString *key in r)
if (![key isEqualToString:@"op"] && ![key isEqualToString:@"buffer_id"])
throw std::invalid_argument("invalid_arguments");
std::optional<DebugGraphicsBuffer> selected;
if (r[@"buffer_id"]) {
if (![r[@"buffer_id"] isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_graphics_buffer_id");
const std::string id = [r[@"buffer_id"] UTF8String];
if (id.size() != [r[@"buffer_id"] lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) throw std::invalid_argument("invalid_graphics_buffer_id");
const auto found = std::find_if(graphicsBuffers.begin(), graphicsBuffers.end(), [&](const auto& buffer) { return buffer.identifier == id; });
if (found == graphicsBuffers.end()) throw std::invalid_argument("unknown_graphics_buffer");
selected = *found;
}
const auto captured = machine->debuggerGraphicsCapture(selected, graphicsBuffers);
NSMutableDictionary *out = [status() mutableCopy];
out[@"paused"] = @YES; out[@"snapshot_kind"] = @"paused_register_preview";
auto displayed = graphicsMetadata(captured.displayed, @"displayed");
out[@"display_buffer"] = [displayed copy];
displayed[@"kind"] = @"current_register_preview";
displayed[@"png_base64"] = png(captured.displayed.pixels,captured.displayed.width,captured.displayed.height,350000);
NSMutableArray *images = [NSMutableArray arrayWithObject:displayed];
if (captured.declared) {
auto other = graphicsMetadata(*captured.declared,[NSString stringWithUTF8String:captured.declaredIdentifier.c_str()]);
other[@"selection"] = @"project_declaration"; other[@"kind"] = @"declared_buffer_preview";
other[@"png_base64"] = png(captured.declared->pixels,captured.declared->width,captured.declared->height,350000);
[images addObject:other];
}
out[@"buffers"] = images;
return out;
}
if ([op isEqual:@"restart"]) {
if (floppy->snapshot().busy) throw std::runtime_error("disk_busy");
boot(); return status();
}
if ([op isEqual:@"continue"]) { armInspection(); machine->resume(); return status(); }
if ([op isEqual:@"pause"]) { machine->releaseInputs(); machine->pause(); return status(); }
if ([op isEqual:@"step"]) {
if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped");
const auto before = machine->snapshot().frames;
machine->debuggerStep(); fieldClock += machine->snapshot().frames - before; return status();
}
if ([op isEqual:@"stop_at"]) {
if (modules.empty() && flatGuards.empty()) throw std::runtime_error("unverified_stop");
const auto nextPoint = uint16_t(number(r[@"address"],0,65535));
std::string nextModule;
if (!flatGuards.empty()) {
if (r[@"module_id"]) throw std::invalid_argument("unverified_stop_module");
} else {
if (![r[@"module_id"] isKindOfClass:NSString.class]) throw std::invalid_argument("unverified_stop_module");
nextModule = [r[@"module_id"] UTF8String];
}
armEvidence({nextPoint}, nextModule);
stops = {nextPoint}; stopModule = nextModule;
machine->resume(); return status();
}
if ([op isEqual:@"debug"]) {
if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped");
auto d = machine->debuggerSnapshot(0,65536); auto c = d.cpu;
NSMutableDictionary *out = [status() mutableCopy];
NSMutableDictionary *registers = [@{ @"A":@(c.A), @"B":@(c.B), @"X":@(c.X), @"Y":@(c.Y), @"U":@(c.U), @"S":@(c.S), @"PC":@(c.PC), @"DP":@(c.DP), @"CC":@(c.CC) } mutableCopy];
if (machine->snapshot().configuration.processor == Processor::HD6309) {
registers[@"E"] = @(c.E); registers[@"F"] = @(c.F);
registers[@"W"] = @((unsigned(c.E) << 8) | unsigned(c.F));
registers[@"V"] = @(c.V); registers[@"MD"] = @(c.MD);
}
out[@"registers"] = registers;
out[@"mapping_fingerprint"] = [NSString stringWithFormat:@"%llu",(unsigned long long)machine->snapshot().debuggerMappingFingerprint];
out[@"program_revision"] = @(machine->snapshot().debuggerProgramRevision);
out[@"attached"] = @(machine->snapshot().debuggerDevelopmentAttached);
out[@"paused"] = @YES;
out[@"logical_memory"] = [[NSData dataWithBytes:d.memory.data() length:d.memory.size()] base64EncodedStringWithOptions:0];
out[@"available"] = [[NSData dataWithBytes:d.memoryAvailable.data() length:d.memoryAvailable.size()] base64EncodedStringWithOptions:0];
NSMutableDictionary *pages = [NSMutableDictionary dictionary];
NSMutableArray *sources = [NSMutableArray array];
for (size_t i = 0; i < d.mmu.Effective.size(); ++i) {
const auto& page = d.mmu.Effective[i];
if (page.Source == VCC::MMUSource::RAM) pages[[NSString stringWithFormat:@"%zu",i]] = @(page.SourceStart / 8192);
[sources addObject:@(int(page.Source))];
}
out[@"physical_pages"] = pages; out[@"page_sources"] = sources;
out[@"mmu_enabled"] = @(d.mmu.Enabled); out[@"active_task"] = @(d.mmu.ActiveTask);
out[@"verified_banked_program"] = @(machine->snapshot().debuggerBankedDevelopment);
return out;
}
if ([op isEqual:@"read_memory"]) {
auto d = machine->debuggerMemoryRange(number(r[@"address"],0,65535),number(r[@"count"],1,256),false);
for (auto b : d.available) if (!b) throw std::runtime_error("memory_unavailable");
NSMutableDictionary *out = [status() mutableCopy];
out[@"address"] = @(d.address); out[@"bytes"] = array(d.bytes);
out[@"cycles"] = @(d.cycles); out[@"generation"] = @(d.generation);
return out;
}
if ([op isEqual:@"stop"]) {
machine->releaseInputs(); machine->pause();
NSMutableDictionary *out = [status() mutableCopy];
if (const auto *image = floppy->image(0)) {
const auto& disk = image->bytes();
out[@"disk_base64"] = [[NSData dataWithBytes:disk.data() length:disk.size()] base64EncodedStringWithOptions:0];
}
stopped = true; return out;
}
throw std::invalid_argument("unknown_operation");
}
};
}
int main() {
@autoreleasepool {
Playtest test;
for (;;) {
std::string line; char c;
while (std::cin.get(c) && c != '\n') {
if (line.size() >= wireLimit) return 2;
line.push_back(c);
}
if (line.empty() && !std::cin) break;
@autoreleasepool {
NSDictionary *result;
try {
NSData *data = [NSData dataWithBytes:line.data() length:line.size()];
id request = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if (![request isKindOfClass:NSDictionary.class]) throw std::invalid_argument("invalid_request");
result = @{ @"result": test.reply(request) };
} catch (const std::exception& error) { result = @{ @"error": [NSString stringWithUTF8String:error.what()] ?: @"playtest_failed" }; }
NSData *data = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingSortedKeys error:nil];
if (!data || data.length > wireLimit) return 3;
std::cout.write(static_cast<const char *>(data.bytes),data.length); std::cout << '\n' << std::flush;
}
if (test.stopped) break;
}
}
return 0;
}
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Copy the approved offline reader edition into the app, preserving its relative links."""
import os
import json
from pathlib import Path
import shutil
import sys
from tempfile import TemporaryDirectory
TOOLS = Path(__file__).resolve().parents[3] / "tools"
sys.path.insert(0, str(TOOLS))
sys.path.insert(0, str(TOOLS / "manuals"))
from build_content import content_profile
from lookup_resources import build_resources
def read_regular(root, relative):
path = Path(relative)
if path.is_absolute() or ".." in path.parts:
raise ValueError("Resource input must be repository-relative")
source = root / path
if not source.is_file() or any(p.is_symlink() for p in (source, *source.parents) if p != root and root in p.parents):
raise ValueError("Resource input must be a regular, unlinked file: " + relative)
return source.read_bytes()
def install_files(destination, files):
if destination.is_symlink():
raise ValueError("Resource destination must not be linked")
destination.parent.mkdir(parents=True, exist_ok=True)
with TemporaryDirectory(dir=destination.parent) as temporary:
staged = Path(temporary) / destination.name
staged.mkdir()
for name, data in files.items():
relative = Path(name)
if relative.is_absolute() or ".." in relative.parts:
raise ValueError("Invalid resource output")
target = staged / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
# The app is a build product, never a user's reader cache or documents.
if destination.exists():
shutil.rmtree(destination)
staged.rename(destination)
def stage(project, resources, profile):
project = project.resolve()
root = project.parent.parent
if resources.parts[-2:] != ("Contents", "Resources") or resources.parent.parent.suffix != ".app":
raise ValueError("Expected an app Contents/Resources destination")
if any(p.is_symlink() for p in (resources, resources.parent, resources.parent.parent)):
raise ValueError("App resource destination must not be linked")
marker = resources / "BuildContent.json"
for target in (resources / "ManualLibrary", resources / "RuntimeTemplates", marker):
if target.is_symlink():
raise ValueError("Resource destination must not be linked")
if marker.exists() and (not marker.is_file() or marker.stat().st_nlink != 1):
raise ValueError("Build content marker must be a regular, unlinked file")
if profile == "normal":
prefix = "$(SRCROOT)/../../docs/manuals/"
files = {}
manifest = project / "Tools/ManualLibrary.xcfilelist"
for entry in manifest.read_text().splitlines():
if not entry.startswith(prefix):
raise ValueError("Unexpected manual input: " + entry)
name = entry[len(prefix):]
files[name] = read_regular(root, "docs/manuals/" + name)
elif profile == "source":
prefix = "docs/manuals/"
generated = build_resources(lambda path: read_regular(root, path))
if any(not path.startswith(prefix) for path in generated):
raise ValueError("Unexpected lookup resource")
files = {path[len(prefix):]: data for path, data in generated.items()}
else:
raise ValueError("Unsupported build content profile")
runtime = json.loads(read_regular(root, "platforms/macos/Resources/RuntimeTemplates.json"))
if runtime.get("schemaVersion") != 1 or set(runtime.get("profiles", {})) != {"normal", "source"}:
raise ValueError("Unsupported runtime-template manifest")
templates = {name: read_regular(root, path) for name, path in runtime["profiles"][profile].items()}
if set(templates) != {"PROJECT_SETUP_PREAMBLE.txt"} or not templates["PROJECT_SETUP_PREAMBLE.txt"].strip():
raise ValueError("Missing runtime project setup prompt")
install_files(resources / "ManualLibrary", files)
install_files(resources / "RuntimeTemplates", templates)
with TemporaryDirectory(dir=resources) as temporary:
staged_marker = Path(temporary) / marker.name
staged_marker.write_text(json.dumps({"schemaVersion": 1, "profile": profile,
"manuals": "full" if profile == "normal" else "lookup"}, sort_keys=True) + "\n")
staged_marker.replace(marker)
def main():
project = Path(os.environ["SRCROOT"])
resources = Path(os.environ["TARGET_BUILD_DIR"]) / os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]
stage(project, resources, content_profile())
if __name__ == "__main__":
main()
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Outlined vector adaptation of the historical Tandy Orchestra-90 label.
// Usage: swift platforms/macos/Tools/make-orchestra-label.swift > docs/media/orchestra-90-label.svg
import AppKit
import CoreText
func number(_ x: CGFloat) -> String { String(format: "%.4f", Double(x)) }
func glyphPath(_ text: String, size: CGFloat) -> CGPath {
let font = CTFontCreateWithName("EurostileBold" as CFString, size, nil)
precondition(CTFontCopyPostScriptName(font) as String == "EurostileBold", "Label authoring requires Eurostile Bold; ordinary builds use the committed SVG/PDF assets.")
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))
let path = CGMutablePath()
for run in CTLineGetGlyphRuns(line) as! [CTRun] {
let count = CTRunGetGlyphCount(run)
var glyphs = [CGGlyph](repeating: 0, count: count), points = [CGPoint](repeating: .zero, count: count)
CTRunGetGlyphs(run, CFRange(location: 0, length: 0), &glyphs)
CTRunGetPositions(run, CFRange(location: 0, length: 0), &points)
for i in 0..<count {
if let glyph = CTFontCreatePathForGlyph(font, glyphs[i], nil) {
path.addPath(glyph, transform: CGAffineTransform(translationX: points[i].x, y: points[i].y))
}
}
}
return path
}
func outline(_ text: String, x: CGFloat, y: CGFloat, width: CGFloat, size: CGFloat, color: String, centered: Bool = false) -> String {
let path = glyphPath(text, size: size)
let box = path.boundingBoxOfPath, scale = min(1, width / box.width)
let originX = centered ? x + (width - box.width * scale) / 2 : x
var d = ""
func point(_ p: CGPoint) -> String { "\(number(originX + (p.x-box.minX)*scale)) \(number(y + (box.maxY-p.y)*scale))" }
path.applyWithBlock { e in
let e = e.pointee
switch e.type {
case .moveToPoint: d += "M " + point(e.points[0])
case .addLineToPoint: d += " L " + point(e.points[0])
case .addQuadCurveToPoint: d += " Q " + point(e.points[0]) + " " + point(e.points[1])
case .addCurveToPoint: d += " C " + point(e.points[0]) + " " + point(e.points[1]) + " " + point(e.points[2])
case .closeSubpath: d += " Z "
@unknown default: break
}
}
return "<path aria-label=\"\(text)\" fill=\"\(color)\" d=\"\(d)\"/>"
}
if CommandLine.arguments.contains("--sdc") {
// Center the color bars and title as one logo using the actual glyph ink,
// rather than the maximum width reserved for text that may be shorter.
let logoWidth = 90 + min(343, glyphPath("CoCo SDC", size: 58).boundingBoxOfPath.width)
let logoX = (480 - logoWidth) / 2
print("""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 280" width="480" height="280">
<title>CoCo SDC cartridge label</title>
<desc>Original outlined label based on the Retro Rewind CoCo SDC cartridge reference. No reference-photograph pixels or font files are embedded. See ATTRIBUTION.md.</desc>
<rect width="480" height="280" rx="12" fill="#eeefed"/>
<g transform="translate(\(number(logoX - 20)) 0)">
<path d="M27 53 h19 l-7 40 h-19z" fill="#df5737"/>
<path d="M52 53 h19 l-7 40 h-19z" fill="#239c71"/>
<path d="M77 53 h19 l-7 40 h-19z" fill="#249bc9"/>
</g>
<path d="M210 207 h48 l14 14 v37 h-62z" fill="none" stroke="#53595a" stroke-width="5"/>
<path d="M219 212 v15 m10-15 v15 m10-15 v15" stroke="#53595a" stroke-width="5"/>
""")
print(outline("CoCo SDC", x: logoX + 90, y: 48, width: 343, size: 58, color: "#171d20"))
print(outline("FLOPPY DISK EMULATOR", x: 35, y: 123, width: 410, size: 29, color: "#343b3e", centered: true))
print(outline("FOR COLOR COMPUTERS", x: 40, y: 164, width: 400, size: 27, color: "#343b3e", centered: true))
print("</svg>")
exit(0)
}
let speech = CommandLine.arguments.contains("--speech")
print("""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 280" width="480" height="280">
<title>\(speech ? "Speech/Sound" : "Orchestra-90") cartridge label</title>
<desc>Vector label adapted from historical Tandy cartridge-label references. Eurostile Bold lettering is outlined; no scanned pixels or font files are embedded. See ATTRIBUTION.md.</desc>
<defs><linearGradient id="orchestra-silver" x2="0.2" y2="1"><stop stop-color="#c5c7c9"/><stop offset="0.5" stop-color="#e0e1df"/><stop offset="1" stop-color="#b6b9bc"/></linearGradient></defs>
<rect width="480" height="280" rx="8" fill="url(#orchestra-silver)"/>
<path d="M0 21 H480 M0 259 H480" stroke="#283c92" stroke-width="5"/>
<path d="M0 29 H480 M0 251 H480" stroke="#68964b" stroke-width="5"/>
<path d="M0 37 H480 M0 243 H480" stroke="#b93528" stroke-width="5"/>
""")
print(outline("TANDY", x: 22, y: 63, width: 130, size: 33, color: "#283c92"))
print(outline(speech ? "COLOR COMPUTER" : "ORCHESTRA 90-CC", x: 174, y: 69, width: 280, size: 25, color: "#171c20"))
for (i, line) in (speech ? ["SPEECH", "SOUND", "CARTRIDGE"] : ["STEREO", "MUSIC", "SYNTHESIZER"]).enumerated() {
print(outline(line, x: 174, y: CGFloat(124+i*33), width: 280, size: 31, color: "#171c20"))
}
print("</svg>")
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Author an empty 90 MiB OS-9 RBF filesystem header; no third-party bytes.
The remaining partition bytes must be zero. BASIC volumes begin at LSN 0x5a000.
Layout follows https://sourceforge.net/p/nitros9/wiki/Random_Block_File_Manager/
Run from any directory; --check verifies the committed deterministic template.
"""
from pathlib import Path
import sys
def header():
b = bytearray(32 * 256)
def put(offset, value, size=1): b[offset:offset+size] = value.to_bytes(size, 'big')
put(0, 0x5a000, 3); put(3, 64); put(4, 5760, 2); put(6, 8, 2)
put(8, 24, 3); put(13, 0xff); put(14, 0x5643, 2); put(16, 3); put(17, 64, 2)
date = bytes([126, 11, 2, 0, 0])
b[26:31] = date
name = bytearray(b'VCC Shared Data'); name[-1] |= 0x80; b[31:31+len(name)] = name
# RBF path options: 2880 cylinders, two sides, 64 sectors/track.
put(63, 1); put(66, 0x80); put(67, 1); put(68, 2880, 2); put(70, 2)
put(71, 1); put(72, 64, 2); put(74, 64, 2); put(76, 1); put(77, 8)
b[256] = 0xf0 # Four allocated clusters: LSN 0..31.
# Mark padding beyond the bitmap's declared length as unavailable.
b[256+5760:24*256] = bytes([255]) * (24*256-256-5760)
fd = 24*256
put(fd, 0xbf); b[fd+3:fd+8] = date; put(fd+8, 2); put(fd+9, 64, 4)
b[fd+13:fd+16] = date[:3]; put(fd+16, 25, 3); put(fd+19, 7, 2)
for offset, name in [(25*256,b'..'), (25*256+32,b'.')]:
n=bytearray(name); n[-1]|=128; b[offset:offset+len(n)]=n; put(offset+29,24,3)
return bytes(b)
if __name__ == '__main__':
path = Path(__file__).resolve().parents[1]/'Resources/StarterMedia/Blank OS9 Header.bin'
if '--check' in sys.argv:
assert path.read_bytes() == header(), 'OS-9 header differs from its generator'
else: path.write_bytes(header())
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Author the native Printer Output nameplate using the approved joystick frame.
// Run from the repository root:
// swift platforms/macos/Tools/make-printer-badge.swift > docs/media/tandy-thermal-printer-tp-10-badge.svg
// rsvg-convert -f pdf -o platforms/macos/Resources/Hardware/printer.pdf docs/media/tandy-thermal-printer-tp-10-badge.svg
// An optional first argument supplies a different local Eurostile Bold font path.
// Ordinary app builds use the committed vector assets, without font dependencies.
import AppKit
import CoreText
// Direct font loading also works when the authoring shell cannot reach fontd.
let fontPath = CommandLine.arguments.dropFirst().first ?? "/Library/Fonts/Microsoft/Eurostile Bold.ttf"
guard let provider = CGDataProvider(url: URL(fileURLWithPath: fontPath) as CFURL),
let graphicsFont = CGFont(provider) else { fatalError("Supply the path to a locally licensed Eurostile Bold font.") }
func number(_ x: CGFloat) -> String { String(format: "%.4f", Double(x)) }
func outline(_ text: String, x: CGFloat, y: CGFloat, width: CGFloat, size: CGFloat, color: String) -> String {
let font = CTFontCreateWithGraphicsFont(graphicsFont, size, nil, nil)
precondition(CTFontCopyPostScriptName(font) as String == "EurostileBold", "Label authoring requires Eurostile Bold; ordinary builds use the committed SVG/PDF assets.")
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))
let path = CGMutablePath()
for run in CTLineGetGlyphRuns(line) as! [CTRun] {
let count = CTRunGetGlyphCount(run)
var glyphs = [CGGlyph](repeating: 0, count: count), points = [CGPoint](repeating: .zero, count: count)
CTRunGetGlyphs(run, CFRange(location: 0, length: 0), &glyphs)
CTRunGetPositions(run, CFRange(location: 0, length: 0), &points)
for i in 0..<count {
if let glyph = CTFontCreatePathForGlyph(font, glyphs[i], nil) {
path.addPath(glyph, transform: CGAffineTransform(translationX: points[i].x, y: points[i].y))
}
}
}
let box = path.boundingBoxOfPath, scale = min(1, width / box.width)
var d = ""
func point(_ p: CGPoint) -> String { "\(number(x + (width-box.width*scale)/2 + (p.x-box.minX)*scale)) \(number(y + (box.maxY-p.y)*scale))" }
path.applyWithBlock { e in
let e = e.pointee
switch e.type {
case .moveToPoint: d += "M " + point(e.points[0])
case .addLineToPoint: d += " L " + point(e.points[0])
case .addQuadCurveToPoint: d += " Q " + point(e.points[0]) + " " + point(e.points[1])
case .addCurveToPoint: d += " C " + point(e.points[0]) + " " + point(e.points[1]) + " " + point(e.points[2])
case .closeSubpath: d += " Z "
@unknown default: break
}
}
return "<path aria-label=\"\(text)\" fill=\"\(color)\" d=\"\(d)\"/>"
}
let template = URL(fileURLWithPath: "docs/media/tandy-deluxe-joystick-badge.svg")
let doc = try XMLDocument(contentsOf: template)
guard let root = doc.rootElement(),
let artwork = try root.nodes(forXPath: "./*[local-name()='g']").first as? XMLElement,
let oldLabel = artwork.children?.last(where: { ($0 as? XMLElement)?.attribute(forName: "aria-label")?.stringValue == "DELUXE JOYSTICK" })
else { fatalError("The approved joystick badge structure changed.") }
oldLabel.detach()
let label = try XMLElement(xmlString: "<g aria-label=\"THERMAL PRINTER TP-10\">" +
outline("THERMAL PRINTER", x: 468, y: 49, width: 672, size: 53, color: "url(#joystick-badge-ink)") +
outline("TP-10", x: 468, y: 99, width: 672, size: 49, color: "url(#joystick-badge-ink)") + "</g>")
artwork.addChild(label)
for title in try root.nodes(forXPath: "./*[local-name()='title']") { title.stringValue = "Tandy Thermal Printer TP-10 badge" }
for title in try artwork.nodes(forXPath: "./*[local-name()='title']") { title.stringValue = "TANDY THERMAL PRINTER TP-10" }
for desc in try root.nodes(forXPath: "./*[local-name()='desc']") {
desc.stringValue = "Silver-bordered black nameplate for the native Printer Output window. A custom TANDY THERMAL PRINTER TP-10 nameplate using the joystick badge style; it does not imply printer graphics or control-code emulation."
}
for metadata in try root.nodes(forXPath: "./*[local-name()='metadata']") {
metadata.stringValue = "Original TP-10 window nameplate with a custom TANDY caption adapting the hardware's Radio Shack/TRS-80 identity. No reference-photograph pixels are embedded. TANDY wordmark: Tandy Corporation; https://commons.wikimedia.org/wiki/File:Tandy_computer_logo.svg (identified there as PD-textlogo and trademarked). Frame and wordmark reuse the Deluxe Joystick badge master. Model lettering is outlined from Eurostile Bold. See ATTRIBUTION.md."
}
// Give this standalone asset its own stable identifiers.
let svg = String(data: doc.xmlData(options: [.nodePrettyPrint]), encoding: .utf8)!
print(svg.replacingOccurrences(of: "joystick-", with: "printer-"))
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Assemble the TP-10 illustration and independent vector state overlays.
Run from any directory. Writes the self-contained SVG master using the included
transparent shell PNG. Then run prepare-hardware.py --printer to compile the
runtime printer layers.
"""
from pathlib import Path
import base64
import xml.etree.ElementTree as E
ROOT = Path(__file__).resolve().parents[3]
MEDIA = ROOT / 'docs/media'
S = 'http://www.w3.org/2000/svg'
E.register_namespace('', S)
def element(parent, name, **attributes):
return E.SubElement(parent, f'{{{S}}}{name}', attributes)
root = E.Element(f'{{{S}}}svg', {
'width': '636', 'height': '372', 'viewBox': '-113 89 159 93',
'role': 'img', 'aria-labelledby': 'tp10-title tp10-description'})
element(root, 'title', id='tp10-title').text = 'Tandy TP-10 thermal printer'
element(root, 'desc', id='tp10-description').text = (
'Cream thermal printer with substantial rear housing, sloping top, rounded '
'front wall, domed smoked cover and cylindrical paper roll. Capture light '
'and retained-output marks are separate runtime states.')
element(root, 'metadata').text = (
'Original shaded TP-10 illustration with a custom TANDY caption adapting the Radio Shack/TRS-80 hardware identity. The embedded transparent shell PNG is authored illustration, not a reference photograph; editable vector overlays represent paper and lamp states. Printed marks indicate retained output, not thermal-printer emulation. See ATTRIBUTION.md.'
)
defs = element(root, 'defs')
gradient = element(defs, 'linearGradient', id='tp10-led', x1='0', y1='0', x2='1', y2='1')
element(gradient, 'stop', offset='0', **{'stop-color': '#ffb19b'})
element(gradient, 'stop', offset='0.4', **{'stop-color': '#ff5940'})
element(gradient, 'stop', offset='1', **{'stop-color': '#b52721'})
device = element(root, 'g', id='tp10-printer', **{'data-runtime-when': 'scene=on'})
# Pixel coordinates below reference the 1536 × 1024 source directly.
# One uniform transform preserves its proportions and keeps every overlay aligned.
transform = 'translate(-116 80) scale(0.10677083333333333)'
shell = element(device, 'g', id='tp10-shell', transform=transform)
png = (MEDIA / 'tandy-tp-10-shell.png').read_bytes()
element(shell, 'image', x='0', y='0', width='1536', height='1024',
href='data:image/png;base64,' + base64.b64encode(png).decode('ascii'))
printed = element(device, 'g', id='tp10-paper-printed', transform=transform,
style='display:none', **{'data-runtime-when': 'printerPaper=printed',
'aria-label': 'Captured output is available'})
for row in range(4):
y = 420 + row * 24
for col in range(38):
if col % 13 in (11, 12):
continue
# The sheet bends slightly left toward its feed edge.
x = 400 + col * 10.2 - row * 2.5
element(printed, 'ellipse', cx=f'{x:g}', cy=f'{y:g}', rx='1.65', ry='1.4',
fill='#777b79', opacity='0.55')
off = element(device, 'g', id='tp10-power-off', transform=transform,
**{'data-runtime-when': 'printerPower=off', 'aria-label': 'Printer capture stopped'})
element(off, 'path', d='M1265 574 H1282 L1280 589 H1263 Z', fill='#542126', opacity='0.5')
on = element(device, 'g', id='tp10-power-on', transform=transform, style='display:none',
**{'data-runtime-when': 'printerPower=on', 'aria-label': 'Printer capture enabled'})
element(on, 'path', d='M1265 574 H1282 L1280 589 H1263 Z', fill='url(#tp10-led)')
element(on, 'path', d='M1267 576 H1274 L1273 580 H1266 Z', fill='#ffd3bb')
E.indent(root)
E.ElementTree(root).write(MEDIA / 'tandy-tp-10-printer.svg', encoding='utf-8', xml_declaration=True)
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Refresh bundled credits/art from repository sources; needs librsvg for PDFs."""
from pathlib import Path
import re
import shutil
import subprocess
ROOT = Path(__file__).resolve().parents[3]
OUT = ROOT / 'platforms/macos/Resources/About'
OUT.mkdir(exist_ok=True)
for name in ['dezota', 'dezota-dark', 'founder']:
subprocess.run(['rsvg-convert', '-f', 'pdf', '-o', str(OUT / (name + '.pdf')),
str(ROOT / 'docs/media/about' / (name + '.svg'))], check=True)
source = (ROOT / 'platforms/windows/Vcc.rc').read_text()
section = source[source.index('IDD_ABOUTBOX DIALOGEX'):source.index('IDD_FUNCTION_KEYS DIALOGEX')]
paragraphs = re.findall(r'LTEXT\s+"([^"]+)"', section)
(OUT / 'WindowsAbout.txt').write_text('\n\n'.join(p.rstrip() for p in paragraphs[2:]) + '\n')
for source, target in [('COPYING', 'GPL.txt'),
('platforms/windows/resources/vcc.bmp', 'windows-vcc.bmp'), ('platforms/windows/resources/3guys.bmp', 'windows-founders.bmp')]:
shutil.copyfile(ROOT / source, OUT / target)
# The approved CopyrightNotice, ArtworkNotice, ROMNotice and concise
# ThirdPartyNotices are authored resources, not generated from design history.
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Bundle authored project templates from their single repository source."""
import argparse
import os
from pathlib import Path
import shutil
# Deliberately enumerate source files: a developer's command-line make products,
# local settings, ROMs or disk images must never enter a distributed template.
HELLO_DISK_FILES = (
'main.c', 'include/hello.h', 'src/display.c', 'src/disk.c',
'assets/words.txt', 'tools/build-data.pl', 'Makefile',
'vccplus-project.json', 'README.md', '.gitignore',
)
def stage(source: Path, destination: Path, lander=None):
if (destination.name != 'DevelopmentTemplates'
or destination.parent.name != 'Resources'
or destination.parent.parent.name != 'Contents'
or destination.parent.parent.parent.suffix != '.app'):
raise ValueError('Destination must be APP.app/Contents/Resources/DevelopmentTemplates')
payload = []
templates = [(source, "HelloDisk", HELLO_DISK_FILES)]
if lander is not None:
templates.append((lander, "TalkingPlanetLander", ("main.c", "Makefile", "vccplus-project.json", "README.md", ".gitignore")))
for base, name, filenames in templates:
for relative in filenames:
path = base / relative
if not path.is_file() or any(part.is_symlink() for part in (path, *path.parents)):
raise ValueError('Template source must be a regular, unlinked file: ' + relative)
payload.append((Path(name) / relative, path.read_bytes()))
if destination.is_symlink():
raise ValueError('Template destination must not be a symbolic link')
if destination.exists():
shutil.rmtree(destination)
for relative, data in payload:
target = destination / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
print('Included authored C project templates (source only).')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path)
parser.add_argument('--destination', type=Path)
args = parser.parse_args()
source = args.source or Path(os.environ['SRCROOT']).parent.parent / 'examples/cmoc/HelloDisk'
destination = args.destination or (Path(os.environ['TARGET_BUILD_DIR']) /
os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH'] / 'DevelopmentTemplates')
stage(source.resolve(), destination, None if args.source else (source.parent / "TalkingPlanetLander").resolve())
if __name__ == '__main__':
main()
+334
View File
@@ -0,0 +1,334 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Compile the approved SVG artwork to cropped native PDF layers.
Requires Python 3 and Homebrew librsvg, only when editing artwork; Xcode uses
committed PDFs. --author-master rebuilds the production master from approved
sources. Ordinary invocations compile the editable production master as-is.
"""
from pathlib import Path
import copy, ctypes as C, ctypes.util, json, re, subprocess, argparse
import xml.etree.ElementTree as E
ROOT=Path(__file__).resolve().parents[3]
MEDIA=ROOT/'docs/media'; OUT=ROOT/'platforms/macos/Resources/Hardware'
S='http://www.w3.org/2000/svg'; E.register_namespace('',S)
def tag(n): return '{'+S+'}'+n
def get(r,id): return next(e for e in r.iter() if e.get('id')==id)
def clone(e): return copy.deepcopy(e)
def group(id,**attrs): return E.Element(tag('g'),{'id':id,**attrs})
def remove(r,e):
for p in r.iter():
if e in list(p): p.remove(e);return
def author():
proposal=E.parse(MEDIA/'proposal/stacked-system.svg').getroot()
scene=next(e for e in proposal if any(c.get('id')=='system-cassette-installed' for c in e))
xml=E.tostring(scene,encoding='unicode').replace('system-','')
scene=E.fromstring(xml);scene.attrib={}
r=E.Element(tag('svg'),{'viewBox':'-120 0 960 457','width':'960','height':'457'})
r.extend(list(scene))
defs=r.find(tag('defs'))
original=E.parse(MEDIA/'tandy-color-computer-3-full-system.svg').getroot()
# Namespaced source controllers provide actual projected geometry at all depths.
originals=E.fromstring(E.tostring(original,encoding='unicode').replace('id="','id="source-').replace('url(#','url(#source-'))
defs.extend(clone(originals.find(tag('defs'))))
virt=E.parse(MEDIA/'tandy-color-computer-3-virtual-system.svg').getroot()
# Remove all static sample pixels. Screen aperture is occupied by live Metal.
remove(r,get(r,'basic-startup-screen'))
for e in get(r,'monitor'):
if e.get('fill')=='#00ff00':e.set('fill','#000000')
for e in get(r,'glass-edge'):e.set('stop-color','#07100a')
get(r,'monitor').set('data-runtime-part','monitor')
get(r,'multi-pak-installed').set('data-runtime-when','mpi=on')
get(r,'mpi-slot-population').set('data-runtime-when','mpi=on')
get(r,'mpi-slot-population').attrib.pop('data-max-drive-controllers',None)
for id,key in [('computer-ram-options','ram'),('computer-processor-badges','cpu'),('mpi-selector-positions','startup')]:
for e in get(r,id):
if e.tag!=tag('g'):continue
suffix=e.get('id').removeprefix('computer-ram-') if key=='ram' else ('6309' if 'hitachi' in e.get('id') else '6809') if key=='cpu' else e.get('data-slot')
e.set('data-runtime-when',key+'='+suffix);e.set('style','display:none')
for e in list(r.iter()):
if e.get('data-ui-role')=='media-state':
parent=next(p for p in r.iter() if e in list(p))
id=parent.get('id'); key='tape' if id=='cassette-media' else id.removeprefix('vds-').removesuffix('-media')
e.set('data-runtime-when',key+'='+e.get('data-state'));e.set('style','display:none')
if e.get('data-ui-role')=='activity-led':
key=e.get('id').replace('cassette','tape').removeprefix('vds-').removesuffix('-activity-led')+'Activity'
for c in e:
if c.get('data-state'): c.set('data-runtime-when',key+'='+c.get('data-state'));c.set('style','display:none')
for id,key in [('stack-hard','hardCase'),('stack-floppy-low','floppyCase'),('stack-floppy-high','floppyCase')]:get(r,id).set('data-runtime-when',key+'=on')
# Both controllers have their own occupancy choice, in every physical slot.
# Front labels are affine mapped between projected front faces; bodies use
# the original per-slot geometry rather than a flat vertical translation.
def labelRect(e):
p=next(c for c in e if c.tag==tag('path'))
nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',p.get('d'))))
return (min(nums[::2]),min(nums[1::2]),max(nums[::2])-min(nums[::2]),max(nums[1::2])-min(nums[1::2]))
labels={kind:clone(get(r,f'proposal-slot{n}-fd501-controller-label-artwork')) for kind,n in [('floppy',4),('hard',3)]}
for n in range(1,5):
parent=get(r,f'mpi-slot-{n}-population');parent.clear();parent.set('id',f'mpi-slot-{n}-population')
rom=clone(get(virt,f'mpi-slot-{n}-rom'));rom.set('style','display:none');rom.set('data-runtime-when',f'slot{n}=rom');parent.append(rom)
for kind in ['floppy','hard']:
card=clone(get(originals,f'source-fd501-controller-slot-{n}'))
card.set('id',f'mpi-slot-{n}-{kind}');card.set('style','display:none');card.set('data-runtime-when',f'slot{n}={kind}')
old=get(card,f'source-fd501-controller-label-artwork-slot-{n}')
a=labelRect(labels[kind]);b=labelRect(old)
label=clone(labels[kind]);label.set('transform',f'translate({b[0]} {b[1]}) scale({b[2]/a[2]} {b[3]/a[3]}) translate({-a[0]} {-a[1]})')
# Unique identifiers for all cloned descendants and referenced gradients.
for e in card.iter():
if e.get('id') and e is not card:e.set('id',f'{kind}-{n}-'+e.get('id'))
remove(card,old)
for e in label.iter():
if e.get('id'):e.set('id',f'{kind}-{n}-'+e.get('id'))
card.append(label);parent.append(card)
# Original proposal routes consist of 17 paths each. Warp only the near
# endpoint to each real slot, holding the far stack endpoint fixed.
ribbons=get(r,'proposal-controller-ribbons');paths=list(ribbons);ribbons.clear();ribbons.set('id','controller-routes')
coords={1:(421.0,238.0),2:(414.9,220.0),3:(408.0,204.0),4:(401.0,189.0)}
for kind,base,start in [('hard',3,0),('floppy',4,17)]:
for n in range(1,5):
g=group(f'{kind}-route-{n}',**{'data-runtime-when':f'slot{n}={kind}'})
dx,dy=coords[n][0]-coords[base][0],coords[n][1]-coords[base][1]
for path in paths[start:start+17]:
p=clone(path)
def warp(m):
x,y=float(m[1]),float(m[2]);w=max(0,min(1,(570-x)/160))
return f'{x+dx*w:.4f} {y+dy*w:.4f}'
p.set('d',re.sub(r'(-?\d+\.\d+)[ ,](-?\d+\.\d+)',warp,p.get('d')));g.append(p)
ribbons.append(g)
# Complete hardware is blank until the adapter applies every state.
get(r,'cassette-installed').set('data-runtime-when','scene=on')
get(r,'joystick-installed').set('data-runtime-when','scene=on')
for e in r.iter():
for k in list(e.attrib):
if k.startswith('{http://www.inkscape'):del e.attrib[k]
# Catch accidental duplicate definitions before compiling any assets.
ids=[e.get('id') for e in r.iter() if e.get('id')]
assert len(ids)==len(set(ids)), 'Duplicate SVG IDs'
E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True)
def orchestra():
# Keep the approved per-slot shell/perspective; replace only its front label.
r=E.parse(MEDIA/'runtime-system.svg').getroot()
master=E.parse(MEDIA/'orchestra-90-label.svg').getroot()
defs=r.find(tag('defs'))
for e in list(defs):
if e.get('id')=='orchestra-silver':defs.remove(e)
defs.extend(clone(master.find(tag('defs'))))
for n in range(1,5):
parent=get(r,f'mpi-slot-{n}-population')
for e in list(parent):
if e.get('data-runtime-when')==f'slot{n}=orchestra':parent.remove(e)
card=clone(get(r,f'mpi-slot-{n}-floppy'))
card.set('data-runtime-when',f'slot{n}=orchestra');card.set('data-cartridge','orchestra')
housing=next(e for e in card if 'controller-housing-slot' in e.get('id',''))
for e in housing.iter():
fill=e.get('fill','')
if fill.startswith('url(#source-fd501-controller-'):
e.set('fill',{'url(#source-fd501-controller-side)':'#b9ad97','url(#source-fd501-controller-top)':'#f3ead8','url(#source-fd501-controller-front)':'#e2d5bd'}.get(fill,'#d1c4ab'))
if e.get('stroke'):e.set('stroke','#b2a48b')
# Replace the controller's top recess with the two real RCA sockets.
# Project the entire socket into the top plane, including its circular rings.
# The rear edge shifts left, following the housing's receding side edge.
top=list(housing)[2]
nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',top.get('d'))))
tx,ty=min(nums[::2]),min(nums[1::2]);tw,th=max(nums[::2])-tx,max(nums[1::2])-ty
side=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',list(housing)[1].get('d'))))
slope=(side[0]-side[2])/(side[7]-side[5])
for e in list(housing):
if e.get('fill') in ['#0c181c','#4f5958']:housing.remove(e)
sockets=E.SubElement(housing,tag('g'),{'id':f'rca-sockets-{n}','aria-label':'Left and right RCA audio sockets'})
for fraction in [.43,.64]:
cx,cy=tx+tw*fraction,ty+th*.5
width,depth=tw*.13,th*.48
socket=E.SubElement(sockets,tag('g'),{'transform':f'matrix({width} 0 {depth*slope} {depth} {cx} {cy})'})
E.SubElement(socket,tag('rect'),{'x':'-.5','y':'-.5','width':'1','height':'1','rx':'.06','fill':'#483d2a'})
E.SubElement(socket,tag('circle'),{'r':'.36','fill':'#c7a75f','stroke':'#826c3e','stroke-width':'.035'})
E.SubElement(socket,tag('circle'),{'r':'.22','fill':'#171b1c'})
label=next(e for e in card if e.get('id','').endswith('controller-label-artwork'))
paths=[e for e in label if e.tag==tag('path')]
paper=paths[2]
nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',paper.get('d'))))
x,y=min(nums[::2]),min(nums[1::2]);w,h=max(nums[::2])-x,max(nums[1::2])-y
frames=[clone(e) for e in paths[:2]]
transform=label.get('transform','')
label.clear();label.set('id',f'controller-slot-{n}-label');label.set('transform',transform);label.extend(frames)
artwork=E.SubElement(label,tag('g'),{'transform':f'translate({x} {y}) scale({w/480} {h/280})'})
artwork.extend(clone(e) for e in master if e.tag not in [tag('defs'),tag('title'),tag('desc')])
for e in card.iter():
if e.get('id'):e.set('id','orchestra-'+e.get('id'))
if e.tag==tag('title'):e.text='Orchestra-90 stereo music cartridge'
parent.insert(1,card)
ids=[e.get('id') for e in r.iter() if e.get('id')]
assert len(ids)==len(set(ids)), 'Duplicate SVG IDs'
E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True)
def speech():
# Service-manual shell/label derivative, using the same scene perspective.
r=E.parse(MEDIA/'runtime-system.svg').getroot()
master=E.parse(MEDIA/'speech-sound-label.svg').getroot()
for n in range(1,5):
parent=get(r,f'mpi-slot-{n}-population')
for e in list(parent):
if e.get('data-runtime-when')==f'slot{n}=speech':parent.remove(e)
card=clone(next(e for e in parent if e.get('data-runtime-when')==f'slot{n}=orchestra'))
card.set('data-runtime-when',f'slot{n}=speech');card.set('data-cartridge','speech')
for e in card.iter():
for child in list(e):
if 'rca-sockets-' in child.get('id',''):e.remove(child)
if e.get('fill') in ['#b9ad97','#f3ead8','#e2d5bd']:
e.set('fill',{'#b9ad97':'#aaa99c','#f3ead8':'#e6e5d8','#e2d5bd':'#d5d4c7'}[e.get('fill')])
label=next(e for e in card if e.get('id','').endswith(f'controller-slot-{n}-label'))
artwork=next(e for e in label if e.tag==tag('g'))
for e in list(artwork):artwork.remove(e)
artwork.extend(clone(e) for e in master if e.tag not in [tag('defs'),tag('title'),tag('desc')])
for e in card.iter():
if e.get('id'):e.set('id',e.get('id').replace('orchestra-','speech-'))
if e.tag==tag('title'):e.text='Speech/Sound Cartridge'
parent.insert(2,card)
ids=[e.get('id') for e in r.iter() if e.get('id')]
assert len(ids)==len(set(ids)), 'Duplicate SVG IDs'
E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True)
def sdc():
# Compact smooth shell seated at each existing ROM socket's projected depth.
# A separate small lens changes with transfer state; the shell is cached.
r=E.parse(MEDIA/'runtime-system.svg').getroot()
master=E.parse(MEDIA/'coco-sdc-label.svg').getroot()
for n in range(1,5):
parent=get(r,f'mpi-slot-{n}-population')
for e in list(parent):
if e.get('data-runtime-when')==f'slot{n}=sdc':parent.remove(e)
rom=get(parent,f'rom-cartridge-slot-{n}-shell')
front=next(e for e in rom if e.get('fill')=='url(#rom-shell-front)')
nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',front.get('d'))))
x,y=min(nums[::2]),min(nums[1::2]);w,h=max(nums[::2])-x,max(nums[1::2])-y
bottom=y+h;h*=1.12;y=bottom-h
# Receding top edge follows the same slot-dependent depth as the ROM shell.
top=next(e for e in rom if e.get('fill')=='url(#rom-shell-top)')
nums=list(map(float,re.findall(r'-?\d+(?:\.\d+)?',top.get('d'))))
dx=x-min(nums[::2]);dy=min(float(v) for v in nums[1::2])
originalY=bottom-h/1.12;depth=originalY-dy
card=group(f'mpi-slot-{n}-sdc',style='display:none',**{'data-runtime-when':f'slot{n}=sdc','data-cartridge':'sdc','data-slot':str(n)})
E.SubElement(card,tag('title')).text='CoCo SDC SD card cartridge'
def path(d,fill,**attrs):return E.SubElement(card,tag('path'),{'d':d,'fill':fill,**attrs})
path(f'M{x} {y+2} L{x-dx} {y-depth+2} L{x-dx} {bottom-depth} L{x} {bottom}Z','url(#rom-shell-side)')
path(f'M{x} {y+2} Q{x} {y} {x+2} {y} H{x+w-2} Q{x+w} {y} {x+w-1} {y-2} L{x+w-dx-2} {y-depth} H{x-dx+2} Q{x-dx} {y-depth} {x-dx} {y-depth+2}Z','url(#rom-shell-top)')
E.SubElement(card,tag('rect'),{'x':str(x),'y':str(y),'width':str(w),'height':str(h),'rx':'1.8','fill':'url(#rom-shell-front)','stroke':'#11191b','stroke-width':'.5'})
path(f'M{x+2} {y+1} H{x+w-2}','none',stroke='#65706f',**{'stroke-width':'.4'})
path(f'M{x+1.2} {bottom-3} H{x+w-1.2}','none',stroke='#0b1113',**{'stroke-width':'.6'})
label=E.SubElement(card,tag('g'),{'transform':f'translate({x+5} {y+5}) scale({(w-10)/480} {(h*.68)/280})'})
label.extend(clone(e) for e in master if e.tag not in [tag('title'),tag('desc')])
# SD slot visible on the receding top surface. It is decorative, not a picker.
slot=E.SubElement(card,tag('g'),{'transform':f'matrix(1 0 {dx/depth} 1 {x} {y})'})
E.SubElement(slot,tag('rect'),{'x':str(w*.32),'y':str(-depth*.68),'width':str(w*.36),'height':str(depth*.28),'rx':'.5','fill':'#090f11','stroke':'#56605e','stroke-width':'.3'})
cx,cy=x+w-8,bottom-7
E.SubElement(card,tag('circle'),{'cx':str(cx),'cy':str(cy),'r':'2','fill':'#0b1114','stroke':'#626967','stroke-width':'.4'})
for state,color in [('empty','#484c50'),('loaded','#2ac65c'),('read','#f49b24'),('write','#e63c36')]:
led=E.SubElement(card,tag('g'),{'id':f'sdc-slot-{n}-{state}','data-runtime-when':f'sdcActivity={state}','style':'display:none'})
E.SubElement(led,tag('circle'),{'cx':str(cx),'cy':str(cy),'r':'1.45','fill':color})
E.SubElement(led,tag('ellipse'),{'cx':str(cx-.3),'cy':str(cy-.5),'rx':'.65','ry':'.35','fill':'#ffffff','opacity':'.45'})
parent.append(card)
ids=[e.get('id') for e in r.iter() if e.get('id')]
assert len(ids)==len(set(ids)), 'Duplicate SVG IDs'
E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True)
def printer():
# Add the standalone thermal printer last: existing layer indices and scene
# coordinates remain unchanged. The editable SVG is the production master;
# make-tp10-printer.py assembles its committed shaded shell and state overlays.
r=E.parse(MEDIA/'runtime-system.svg').getroot()
master=E.parse(MEDIA/'tandy-tp-10-printer.svg').getroot()
defs=r.find(tag('defs'))
for e in list(defs):
if e.get('id','').startswith('tp10-'):defs.remove(e)
for e in list(r):
if e.get('id')=='tp10-printer':r.remove(e)
defs.extend(clone(master.find(tag('defs'))))
r.append(clone(get(master,'tp10-printer')))
ids=[e.get('id') for e in r.iter() if e.get('id')]
assert len(ids)==len(set(ids)), 'Duplicate SVG IDs'
E.indent(r);E.ElementTree(r).write(MEDIA/'runtime-system.svg',encoding='utf-8',xml_declaration=True)
class Rect(C.Structure):_fields_=[(x,C.c_double) for x in ['x','y','width','height']]
def compile_art():
lib=C.CDLL('/opt/homebrew/lib/librsvg-2.dylib' if Path('/opt/homebrew/lib/librsvg-2.dylib').exists() else C.util.find_library('rsvg-2'))
lib.rsvg_handle_new_from_data.argtypes=[C.c_char_p,C.c_size_t,C.c_void_p];lib.rsvg_handle_new_from_data.restype=C.c_void_p
lib.rsvg_handle_render_document.argtypes=[C.c_void_p,C.c_void_p,C.POINTER(Rect),C.c_void_p]
obj=C.CDLL(C.util.find_library('gobject-2.0'));obj.g_object_unref.argtypes=[C.c_void_p]
cairo=C.CDLL(C.util.find_library('cairo'))
cairo.cairo_image_surface_create.argtypes=[C.c_int,C.c_int,C.c_int];cairo.cairo_image_surface_create.restype=C.c_void_p
cairo.cairo_create.argtypes=[C.c_void_p];cairo.cairo_create.restype=C.c_void_p
cairo.cairo_image_surface_get_data.argtypes=[C.c_void_p];cairo.cairo_image_surface_get_data.restype=C.c_void_p
for method in ['cairo_destroy','cairo_surface_destroy','cairo_surface_flush']:getattr(cairo,method).argtypes=[C.c_void_p]
def visible_bounds(handle):
# Ink geometry includes zero-area outlined space glyphs and ignores clipping.
# Measure actual alpha at 2x solely to crop layers, never as runtime art.
width,height=1920,914
surface=cairo.cairo_image_surface_create(0,width,height);context=cairo.cairo_create(surface)
assert lib.rsvg_handle_render_document(handle,context,C.byref(Rect(0,0,width,height)),None)
cairo.cairo_surface_flush(surface)
pixels=C.string_at(cairo.cairo_image_surface_get_data(surface),width*height*4)
left,top,right,bottom=width,height,0,0
for y in range(height):
row=pixels[(y*width*4)+3:(y+1)*width*4:4]
if row.strip(b'\0'):
left=min(left,width-len(row.lstrip(b'\0')));right=max(right,len(row.rstrip(b'\0')))
top=min(top,y);bottom=y+1
cairo.cairo_destroy(context);cairo.cairo_surface_destroy(surface)
return (left/2-120-.5,top/2-.5,(right-left)/2+1,(bottom-top)/2+1) if right>left else None
OUT.mkdir(parents=True,exist_ok=True)
source=E.parse(MEDIA/'runtime-system.svg').getroot();defs=source.find(tag('defs'))
layers=[]
def emit(nodes,ancestors,conditions,part):
r=E.Element(tag('svg'),{'viewBox':'-120 0 960 457','width':'960','height':'457'});r.append(clone(defs));p=r
for ancestor in ancestors:
a=E.Element(tag('g'),{k:v for k,v in ancestor.attrib.items() if k not in ['id','style','data-runtime-when','data-runtime-part']});p.append(a);p=a
p.extend(clone(e) for e in nodes)
data=E.tostring(r);handle=lib.rsvg_handle_new_from_data(data,len(data),None)
bounds=visible_bounds(handle);obj.g_object_unref(handle)
if not bounds:return
x,y,w,h=bounds
r.set('viewBox',f'{x} {y} {w} {h}');r.set('width',str(w));r.set('height',str(h))
filename=f'layer-{len(layers):03d}.pdf'
subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/filename)],input=E.tostring(r),check=True)
layers.append({'file':filename,'bounds':[x,y,w,h],'when':conditions,'part':part})
def walk(e,ancestors,conditions,part):
conditions=dict(conditions)
if e.get('data-runtime-when'):
k,v=e.get('data-runtime-when').split('=');conditions[k]=v
part=e.get('data-runtime-part',part)
e=clone(e)
if e.get('data-runtime-when'):e.set('style','display:inline')
dynamic=any(c is not e and (c.get('data-runtime-when') or c.get('data-runtime-part')) for c in e.iter())
if not dynamic:emit([e],ancestors,conditions,part);return
batch=[]
for c in e:
if c.tag in [tag('title'),tag('desc'),tag('metadata')]:continue
if any(d.get('data-runtime-when') or d.get('data-runtime-part') for d in c.iter()):
if batch:emit(batch,ancestors+[e],conditions,part);batch=[]
walk(c,ancestors+[e],conditions,part)
else:batch.append(c)
if batch:emit(batch,ancestors+[e],conditions,part)
for c in source:
if c.tag==tag('g'):walk(c,[],{},'scene')
(OUT/'layers.json').write_text(json.dumps(layers,indent=2)+'\n')
# Freestanding desk reference control, composed separately from emulated hardware.
subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/'manual-help.pdf'),str(MEDIA/'manual-help.svg')],check=True)
# Standalone, unskewed badges. Native semantic text accompanies these outlines.
badges={'motorola':'motorola-inside-badge','hitachi':'hitachi-inside-badge','mpi':'tandy-multi-pak-interface-badge','floppy':'tandy-fd-502-disk-drive-badge','hard':'tandy-virtual-drive-system-badge','cassette':'tandy-computer-cassette-recorder-badge','joystick':'tandy-deluxe-joystick-badge','printer':'tandy-thermal-printer-tp-10-badge'}
for key,name in badges.items():subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/(key+'.pdf')),str(MEDIA/(name+'.svg'))],check=True)
for ram in ['128kb','512kb','2mb','8mb']:
r=E.parse(MEDIA/'tandy-128k-color-computer-3-badge.svg').getroot()
for e in get(r,'computer-ram-options'):
if e.tag==tag('g'):e.set('style','display:inline' if e.get('id')=='computer-ram-'+ram else 'display:none')
subprocess.run(['rsvg-convert','-f','pdf','-o',str(OUT/('coco-'+ram+'.pdf'))],input=E.tostring(r),check=True)
print(f'Compiled {len(layers)} cropped layers and {len(badges)+4} badges')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--author-master',action='store_true');p.add_argument('--orchestra',action='store_true');p.add_argument('--speech',action='store_true');p.add_argument('--printer',action='store_true');p.add_argument('--sdc',action='store_true');args=p.parse_args()
if args.author_master:author()
if args.author_master or args.orchestra or args.speech:orchestra()
if args.author_master or args.speech:speech()
if args.author_master or args.printer:printer()
if args.author_master or args.sdc:sdc()
compile_art()
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Prepare the explicitly supplied private archive image with HD1 and DriveWire guest modules.
Never modifies the input. No OS or archived application bytes are in this tool.
The exact source hash pins all layout assumptions; unknown inputs are rejected.
"""
import hashlib
from pathlib import Path
import sys
SOURCE_SHA256 = '2ccd07cdfd6aa4d8a1d3ceff04f0a6c3490bde23e40e7c136830334f2264f462'
PREPARED_SHA256 = 'b4a3bf2804a229e7ebf5bc711f326b64fc35171bd4d975caee69d86c9ccb3954'
def add_drivewire_startup(image):
"""Add a persistent module pack to the OS-9 partition of the pinned seed."""
def integer(offset, length):
return int.from_bytes(image[offset:offset + length], 'big')
def extent(descriptor):
offset = descriptor * 256
size = integer(offset + 9, 4)
start = integer(offset + 16, 3) * 256
capacity = integer(offset + 19, 2) * 256
if size > capacity or integer(offset + 21, 3):
raise ValueError('Expected single-extent OS-9 file')
return start, size, capacity
def directory(descriptor):
start, size, _ = extent(descriptor)
result = {}
for offset in range(start, start + size, 32):
raw = image[offset:offset + 29]
if raw[0]:
name = bytes(c & 127 for c in raw).split(b'\0')[0].lower()
result[name] = integer(offset + 29, 3)
return result
root = directory(integer(8, 3))
pack_directory = root[b'boot_with_beckerdw']
drivers = directory(pack_directory)
pack = bytearray()
for name in (b'dwio', b'scdwv', b'n', b'n1'):
start, size, _ = extent(drivers[name])
pack.extend(image[start:start + size])
# The archive uses one sector per allocation bit. This region is the
# first eight contiguous *zeroed* free sectors of the pinned original.
# Never reuse sectors marked allocated, or overwrite recoverable old data.
sector = 0x28000
data_sectors = (len(pack) + 255) // 256
sector_count = 1 + data_sectors # one file descriptor, then its extent
if integer(6, 2) != 1 or sector + sector_count > integer(4, 2) * 8:
raise ValueError('Unexpected allocation bitmap')
for i in range(sector, sector + sector_count):
mask = 0x80 >> (i % 8)
if image[256 + i // 8] & mask or any(image[i*256:(i+1)*256]):
raise ValueError('DriveWire pack requires free, zeroed sectors')
image[256 + i // 8] |= mask
# Borrow owner, timestamps and regular-file attributes from dwio. The pack
# needs owner read + execute permissions for the stock "load" command.
offset = sector * 256
template = drivers[b'dwio'] * 256
image[offset:offset + 16] = image[template:template + 16]
image[offset] |= 0x04
image[offset + 9:offset + 13] = len(pack).to_bytes(4, 'big')
image[offset + 16:offset + 19] = (sector + 1).to_bytes(3, 'big')
image[offset + 19:offset + 21] = data_sectors.to_bytes(2, 'big')
image[offset + 256:offset + 256 + len(pack)] = pack
start, size, capacity = extent(pack_directory)
entry = start + size
if b'dwnet' in drivers or size + 32 > capacity:
raise ValueError('Expected unused directory entry for the module pack')
image[entry:entry + 32] = bytes(32)
image[entry:entry + 5] = b'dwne\xf4'
image[entry + 29:entry + 32] = sector.to_bytes(3, 'big')
offset = pack_directory * 256 + 9
image[offset:offset + 4] = (size + 32).to_bytes(4, 'big')
# Load the pack after the utilities, before the interactive shells start.
# Loading the modules does not open a connection or attach /N. Guest
# applications open the device on demand when the host setting is enabled.
descriptor = root[b'startup']
start, size, capacity = extent(descriptor)
startup = image[start:start + size]
marker = b'load utilpak1\r'
if startup.count(marker) != 1:
raise ValueError('Unexpected OS-9 startup script')
startup = startup.replace(marker, marker + b'load /dd/boot_with_beckerdw/dwnet\r')
if len(startup) > capacity:
raise ValueError('Insufficient space in existing startup extent')
image[start:start + len(startup)] = startup
offset = descriptor * 256 + 9
image[offset:offset + 4] = len(startup).to_bytes(4, 'big')
def prepare(source):
digest = hashlib.sha256(source).hexdigest()
if digest == PREPARED_SHA256:
return source
if digest != SOURCE_SHA256:
raise ValueError('Expected the original VCCEmuDisk.vhd from the NitrOS-9 L2 V3.3.0 archive')
b = bytearray(source)
def u(o,n=3):return int.from_bytes(b[o:o+n],'big')
def put(o,v,n):b[o:o+n]=v.to_bytes(n,'big')
def crc(data):
value=0xffffff
for c in data:
value ^= c << 16
for _ in range(8):
value <<= 1
if value & 0x1000000:value ^= 0x800063
value &= 0xffffff
return (value ^ 0xffffff).to_bytes(3,'big')
def file(base,fd):
o=base+fd*256;size=u(o+9,4);start=base+u(o+16)*256;capacity=u(o+19,2)*256
if size>capacity or u(o+21)!=0:raise ValueError('Expected single contiguous file')
return o,start,size,capacity
def boot_file(base):
_,r,size,_=file(base,u(base+8))
for off in range(r,r+size,32):
name=bytes(c&127 for c in b[off:off+29]).split(b'\0')[0].lower()
if name==b'os9boot':return file(base,u(off+29))
raise ValueError('No OS9Boot file')
def add_h1(base):
fd,start,size,capacity=boot_file(base)
boot=b[start:start+size];o=0;h0=None;modules=[];patched=False
while o<len(boot):
if boot[o:o+2]!=b'\x87\xcd':raise ValueError('Bad module header')
length=int.from_bytes(boot[o+2:o+4],'big');name_offset=int.from_bytes(boot[o+4:o+6],'big');name=''
for c in boot[o+name_offset:o+length]:
name+=chr(c&127)
if c&128:break
if name.lower()=='h1':raise ValueError('Unexpected existing H1 module')
module=bytearray(boot[o:o+length])
if name.lower()=='h0':h0=bytearray(module)
if name.lower()=='emudsk':
# The archived driver rejects every unit except zero. Replace
# its five-byte TST PD.DRV,Y / BNE NotReady with a call to an
# appended helper and BCS to the same error branch. All old
# code offsets stay unchanged. The helper selects FF86 on
# every read/write, preserving A (the command) and rejecting
# units >1. This is the VCC two-drive register contract.
def redirect(pattern, helper, suffix):
nonlocal module
pattern=bytes.fromhex(pattern);helper=bytes.fromhex(helper)
if module.count(pattern)!=1:raise ValueError('Unexpected EmuDsk code layout')
off=module.index(pattern);target=len(module)-3
replacement=bytes([0x17])+int(target-off-3).to_bytes(2,'big',signed=True)+bytes.fromhex(suffix)
if len(replacement)>len(pattern):raise ValueError('Patch exceeds original instruction area')
module[off:off+len(pattern)]=replacement+bytes([0x12])*(len(pattern)-len(replacement))
module=module[:-3]+helper+bytes(3)
# GetSect: select each unit, preserving the command in A.
redirect('6d a8 21 26 17',
'34 02 a6 a8 21 81 02 24 07 b7 ff 86 1c fe 35 82 1a 01 35 82', '25 17')
# Init: V.NDRV=2, two 38-byte tables at DRVBEG=15. The
# original 255-byte static allocation already has room.
redirect('86 ff 30 4f a7 84 a7 88 15 5f 39',
'cc ff 02 e7 46 30 4f a7 84 a7 88 15 30 88 26 5a 26 f5 39', '5f 39')
# Read LSN0 into the selected unit's table, not always unit 0.
redirect('33 4f c6 15', '33 4f a6 a8 21 c6 26 3d 33 cb c6 15 39', '')
module[2:4]=len(module).to_bytes(2,'big')
parity=255
for c in module[:8]:parity^=c
module[8]=parity;module[-3:]=crc(module[:-3]);patched=True
modules.append(module)
if length<9:raise ValueError('Invalid module length')
o+=length
if not patched or h0 is None or len(h0)!=47:raise ValueError('Expected 47-byte H0 descriptor')
# Descriptor header is unchanged. Unit number is its path option DRV;
# the final character of its name retains the OS-9 high-bit terminator.
name_offset=int.from_bytes(h0[4:6],'big')
h0[0x13]=1;h0[name_offset+1]=ord('1')|128;h0[-3:]=crc(h0[:-3])
prepared=b''.join(modules)+h0
if len(prepared)>capacity:raise ValueError('No unused allocated boot-file space')
b[start:start+len(prepared)]=prepared;put(fd+9,len(prepared),4)
if u(base+24,2)==size:put(base+24,len(prepared),2)
return size,len(prepared)-size
# Keep both the OS-9 root boot file and the RGBDOS volume-255 boot file
# consistent. New bytes stay in their already allocated final sectors.
add_h1(0)
old,added=add_h1((0x5a000+255*630)*256)
if u(24,2)==old:put(24,old+added,2)
add_drivewire_startup(b)
return bytes(b)
if __name__=='__main__':
if len(sys.argv)!=3:raise SystemExit('Usage: prepare-nitros9.py original.vhd prepared.vhd')
source,target=map(Path,sys.argv[1:])
if source.resolve()==target.resolve():raise SystemExit('Input and output must differ')
if target.exists() and source.samefile(target):
raise SystemExit('Input and output must refer to different files')
prepared = prepare(source.read_bytes())
target.write_bytes(prepared)
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Copy an optional locally built compiler runtime into an Xcode app bundle."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tools/toolchain"))
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tools"))
from runtime_inputs import validate_private_inputs
from build_content import content_profile
MACHO = ('libexec/cmoc', 'bin/cpp', 'bin/mcpp', 'bin/make', 'bin/lwasm',
'bin/lwlink', 'bin/lwar', 'bin/writecocofile')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path)
parser.add_argument('--destination', type=Path)
args = parser.parse_args()
profile = content_profile()
source = args.source or (Path(os.environ.get('VCC_SOURCE_TOOLCHAIN_DIR') or
str(Path(os.environ['SRCROOT']) / 'LocalResources/SourceToolchainBundle'))
if profile == 'source' else Path(os.environ['SRCROOT']) / 'LocalResources/ToolchainBundle')
destination = args.destination or (Path(os.environ['TARGET_BUILD_DIR']) /
os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH'] / 'Toolchain')
# Restrict cleanup to this build phase's app resource directory.
if destination.name != 'Toolchain' or destination.parent.name != 'Resources' or destination.parent.parent.name != 'Contents' or destination.parent.parent.parent.suffix != '.app':
parser.error('Destination must be APP.app/Contents/Resources/Toolchain')
if source.exists():
record = json.loads((source / 'manifest.json').read_text())
if record.get('schemaVersion') != 1:
parser.error('Unsupported toolchain manifest')
if profile == 'source' and record.get('privateRuntimeInputs') is not False:
parser.error('Source content profile requires an explicitly source-only compiler runtime')
try:
validate_private_inputs(source, record)
except ValueError as error:
parser.error(str(error))
disk = record.get('decbfile')
if disk:
if disk.get('profile') != 'rom-backed-core' or disk.get('standaloneDriverIncluded') is not False:
parser.error('Unsupported disk-library profile')
for relative, key in [('share/cmoc/lib/libdecbfile.a', 'archiveSHA256'),
('share/cmoc/include/decbfile.h', 'headerSHA256')]:
if hashlib.sha256((source / relative).read_bytes()).hexdigest() != disk.get(key):
parser.error('Disk-library payload does not match its manifest: ' + relative)
declared = set(record.get('architectures', []))
requested = set(os.environ.get('ARCHS', '').split()) & {'arm64', 'x86_64'}
required = requested or declared
if not declared or declared - {'arm64', 'x86_64'} or not required.issubset(declared):
parser.error('Toolchain architectures do not cover this app build')
helpers = {relative: sorted(declared) for relative in MACHO}
for relative, architectures in record.get('nativeHelpers', {}).items():
path = Path(relative)
if path.is_absolute() or '..' in path.parts or not architectures or not set(architectures).issubset(declared):
parser.error('Invalid native helper declaration: ' + relative)
helpers[relative] = architectures
for relative, architectures in helpers.items():
slices = set(subprocess.check_output(['/usr/bin/lipo', '-archs', str(source / relative)], text=True).split())
if not set(architectures).issubset(slices):
parser.error('Toolchain helper is missing a declared architecture: ' + relative)
for item in source.rglob('*'):
if item.is_symlink(): parser.error('Toolchain bundle must not contain symbolic links')
if item.is_file():
with item.open('rb') as stream: magic = stream.read(4)
if magic in (b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf', b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca') and item.relative_to(source).as_posix() not in helpers:
parser.error('Undeclared native helper: ' + str(item.relative_to(source)))
for library in record.get('libraries', {}).values():
for relative, expected in library['filesSHA256'].items():
path = Path(relative)
if path.is_absolute() or '..' in path.parts or hashlib.sha256((source / path).read_bytes()).hexdigest() != expected:
parser.error('Library payload does not match its manifest: ' + relative)
if record.get('perl') and ('bin/perl' not in helpers or not (source / 'bin/install-coco-boot-loader').is_file()):
parser.error('Perl runtime is incomplete')
for relative in (*MACHO, 'bin/cmoc', 'share/cmoc/include/cmoc.h'):
if not (source / relative).is_file(): parser.error('Incomplete toolchain: ' + relative)
if destination.exists(): shutil.rmtree(destination)
if not source.exists():
print('Optional CMOC runtime not staged; C Development will report that its tools are unavailable.')
return
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(source, destination)
# Cache keys consume the installed manifest. Fingerprint actual payload
# bytes before signing so a locally rebuilt compiler/helper also invalidates
# old dependencies/objects even when its upstream version is unchanged.
payload = hashlib.sha256()
for item in sorted(source.rglob('*')):
if item.is_file() and item.relative_to(source).as_posix() != 'manifest.json':
relative = item.relative_to(source).as_posix().encode('utf-8')
payload.update(len(relative).to_bytes(8, 'big'))
payload.update(relative)
payload.update(hashlib.sha256(item.read_bytes()).digest())
record['payloadSHA256'] = payload.hexdigest()
(destination / 'manifest.json').write_text(json.dumps(record, indent=2) + '\n')
# Raw executables inside Resources are not automatically signed by Xcode.
# Release packaging replaces these ad-hoc signatures with Developer ID.
for relative in sorted(helpers, key=lambda name: (-name.count('/'), name)):
subprocess.run(['/usr/bin/codesign', '--force', '--sign', '-', '--timestamp=none',
str(destination / relative)], check=True)
print('Included self-contained CMOC/LWTools/mcpp/Make runtime, optional Perl/libraries and upstream notices.')
if __name__ == '__main__': main()
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Regress template staging through canonical and symlink-spelled checkouts."""
import importlib.util
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).with_name('prepare-development-templates.py')
SPEC = importlib.util.spec_from_file_location('development_templates', SCRIPT)
TEMPLATES = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(TEMPLATES)
LANDER_FILES = ('main.c', 'Makefile', 'vccplus-project.json', 'README.md', '.gitignore')
class DevelopmentTemplateTests(unittest.TestCase):
def setUp(self):
self.work = tempfile.TemporaryDirectory()
self.addCleanup(self.work.cleanup)
# tempfile can itself use a symlink-spelled macOS temporary directory.
self.root = Path(self.work.name).resolve()
self.checkout = self.root / 'physical-checkout'
(self.checkout / 'platforms/macos').mkdir(parents=True)
self.sources = self.checkout / 'examples/cmoc'
for name, files in [('HelloDisk', TEMPLATES.HELLO_DISK_FILES),
('TalkingPlanetLander', LANDER_FILES)]:
for relative in files:
path = self.sources / name / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(name + '/' + relative + '\n')
self.alias = self.root / 'checkout-alias'
self.alias.symlink_to(self.checkout, target_is_directory=True)
self.destination = self.root / 'Result.app/Contents/Resources/DevelopmentTemplates'
def test_default_templates_stage_through_ancestor_alias_without_build_products(self):
(self.sources / 'TalkingPlanetLander/program.dsk').write_bytes(b'not a template')
environment = dict(os.environ, SRCROOT=str(self.alias / 'platforms/macos'))
subprocess.run([sys.executable, str(SCRIPT), '--destination', str(self.destination)],
env=environment, check=True, capture_output=True, text=True)
expected = {str(path.relative_to(self.sources)): path.read_bytes()
for path in self.sources.rglob('*') if path.is_file() and path.suffix != '.dsk'}
actual = {str(path.relative_to(self.destination)): path.read_bytes()
for path in self.destination.rglob('*') if path.is_file()}
self.assertEqual(actual, expected)
def test_linked_template_file_stays_rejected_before_existing_output_changes(self):
self.destination.mkdir(parents=True)
marker = self.destination / 'previous'
marker.write_bytes(b'existing bundle')
leaf = self.sources / 'TalkingPlanetLander/main.c'
leaf.unlink()
outside = self.root / 'outside.c'
outside.write_text('not an approved regular template file\n')
leaf.symlink_to(outside)
with self.assertRaisesRegex(ValueError, 'unlinked file'):
TEMPLATES.stage(self.sources / 'HelloDisk', self.destination,
self.sources / 'TalkingPlanetLander')
self.assertEqual(marker.read_bytes(), b'existing bundle')
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Update outlined FD 501 labels to FD 502 without changing their perspective.
The digit 2 is from the Eurostile-outlined controller label. Stable SVG IDs
remain independent of the displayed product identities.
Idempotent; ordinary artwork compilation does not require this migration.
"""
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[3]
NUMBER = r"-?\d+(?:\.\d+)?"
ONE = [1111.25395,43.12691,1111.25395,72,1101.90949,72,1101.90949,47.90738,1089.10145,55.35304,1083.54531,51.82058,1099.45613,43.12691]
TWO = 'M 414.70665 236.92635 L 414.70665 237.35687 L 411.32842 237.35687 L 411.32842 236.77305 Q 411.32842 236.31944 411.58212 236.17033 Q 411.83581 236.02123 412.78839 235.91203 Q 413.5773 235.82172 413.72297 235.74717 Q 413.86864 235.67262 413.86864 235.36181 Q 413.86864 235.0636 413.72297 234.9838 Q 413.5773 234.904 413.03063 234.904 Q 412.46759 234.904 412.32029 234.98485 Q 412.17298 235.0657 412.17298 235.37861 L 412.17298 235.50041 L 411.34152 235.50041 L 411.34152 235.38071 Q 411.34152 234.841 411.68851 234.65409 Q 412.0355 234.46719 413.0339 234.46719 Q 414.0094 234.46719 414.35802 234.65619 Q 414.70665 234.8452 414.70665 235.37441 Q 414.70665 235.87422 414.4415 236.04328 Q 414.17635 236.21234 413.22049 236.32574 Q 412.43159 236.41814 412.30392 236.48219 Q 412.17626 236.54624 412.17626 236.84865 L 412.17626 236.92635 Z'
def points(path):
n=list(map(float,re.findall(NUMBER,path)))
return list(zip(n[::2],n[1::2]))
def solve(a,b):
rows=[row+[v] for row,v in zip(a,b)]
for col in range(8):
pivot=max(range(col,8),key=lambda i:abs(rows[i][col]))
rows[col],rows[pivot]=rows[pivot],rows[col]
divisor=rows[col][col]
assert abs(divisor)>1e-12
rows[col]=[v/divisor for v in rows[col]]
for i in range(8):
if i!=col:
factor=rows[i][col]
rows[i]=[x-factor*y for x,y in zip(rows[i],rows[col])]
return [row[-1] for row in rows]
def replace_digit(path):
original=list(zip(ONE[::2],ONE[1::2])); target=points(path)
assert len(target)==len(original), 'Unexpected digit 1 outline'
# Normalize source coordinates for a well-conditioned projective fit.
norm=lambda p:((p[0]-1083.54531)/40,(p[1]-42.89424)/29.33843)
a=[];b=[]
for i in [0,1,2,4]:
x,y=norm(original[i]);u,v=target[i]
a.extend([[x,y,1,0,0,0,-u*x,-u*y],[0,0,0,x,y,1,-v*x,-v*y]])
b.extend([u,v])
h=solve(a,b)
def project(x,y):
d=h[6]*x+h[7]*y+1
return ((h[0]*x+h[1]*y+h[2])/d,(h[3]*x+h[4]*y+h[5])/d)
for old,new in zip(original,target):
mapped=project(*norm(old))
assert max(abs(x-y) for x,y in zip(mapped,new))<.005, 'Perspective mismatch'
pts=points(TWO)
x0=min(x for x,y in pts);x1=max(x for x,y in pts)
y0=min(y for x,y in pts);y1=max(y for x,y in pts)
def convert(m):
x,y=map(float,m.groups());u,v=project((x-x0)/(x1-x0),(y-y0)/(y1-y0))
return f'{u:.5f} {v:.5f}'
return re.sub('('+NUMBER+r')\s+('+NUMBER+')',convert,TWO)
def migrate(path):
text=path.read_text();count=0
def label(m):
nonlocal count
block=m.group();matches=list(re.finditer(r'<path\b[^>]*\bd="([^"]+)"',block))
assert matches
last=matches[-1];start,end=last.span(1)
block=block[:start]+replace_digit(last.group(1))+block[end:]
count+=1
return block.replace('aria-label="DISK DRIVE FD 501"','aria-label="DISK DRIVE FD 502"').replace('aria-label="FD 501"','aria-label="FD 502"')
updated=re.sub(r'<g\b[^>]*aria-label="(?:DISK DRIVE FD 501|FD 501)"[^>]*>.*?</g>',label,text,flags=re.S)
# Accessibility descriptions follow visible labels; source metadata is retained.
updated=re.sub(r'<(?:title|desc)\b[^>]*>.*?</(?:title|desc)>',lambda m:m.group().replace('FD 501','FD 502').replace('FD-501','FD-502'),updated,flags=re.S)
if updated!=text:path.write_text(updated)
return count
if __name__=='__main__':
count=sum(migrate(p) for p in (ROOT/'docs/media').rglob('*.svg'))
print(f'Updated {count} outlined labels')