Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -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)];
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user