yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
command_registry.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <iostream>
5#include <sstream>
6
7#include "absl/strings/str_cat.h"
8#include "absl/strings/str_format.h"
9#include "absl/strings/str_join.h"
11
12namespace yaze {
13namespace cli {
14
15namespace {
16std::string EscapeJson(const std::string& input) {
17 std::string escaped;
18 escaped.reserve(input.size());
19 for (char c : input) {
20 switch (c) {
21 case '\\\\':
22 escaped.append("\\\\");
23 break;
24 case '\"':
25 escaped.append("\\\"");
26 break;
27 case '\n':
28 escaped.append("\\n");
29 break;
30 case '\r':
31 escaped.append("\\r");
32 break;
33 case '\t':
34 escaped.append("\\t");
35 break;
36 default:
37 escaped.push_back(c);
38 }
39 }
40 return escaped;
41}
42
43void AppendStringArray(std::ostringstream& out,
44 const std::vector<std::string>& values) {
45 out << "[";
46 for (size_t i = 0; i < values.size(); ++i) {
47 if (i > 0)
48 out << ", ";
49 out << "\"" << EscapeJson(values[i]) << "\"";
50 }
51 out << "]";
52}
53} // namespace
54
56 static CommandRegistry instance;
57 static bool initialized = false;
58 if (!initialized) {
59 instance.RegisterCliCommands();
60 initialized = true;
61 }
62 return instance;
63}
64
66 std::unique_ptr<resources::CommandHandler> handler,
67 const CommandMetadata& metadata) {
68 std::string name = handler->GetName();
69
70 // Store metadata
71 metadata_[name] = metadata;
72
73 // Register aliases
74 for (const auto& alias : metadata.aliases) {
75 aliases_[alias] = name;
76 }
77
78 // Store handler
79 handlers_[name] = std::move(handler);
80}
81
83 std::vector<std::unique_ptr<resources::CommandHandler>> handlers) {
84 for (auto& handler : handlers) {
85 std::string name = handler->GetName();
86
87 if (handlers_.find(name) != handlers_.end()) {
88 continue;
89 }
90
91 // Build metadata from handler
92 auto descriptor = handler->Describe();
93 CommandMetadata metadata;
94 metadata.name = name;
95 metadata.usage = handler->GetUsage();
96 metadata.available_to_agent = true; // Most commands available to agent
97 metadata.requires_rom = handler->RequiresRom();
98 metadata.requires_grpc = false;
99
100 // Categorize and enhance metadata based on command type
101 if (name.find("resource-") == 0) {
102 metadata.category = "resource";
103 metadata.description = "Resource inspection and search";
104 if (name == "resource-list") {
105 metadata.examples = {"z3ed resource-list --type=dungeon --format=json",
106 "z3ed resource-list --type=sprite --format=table"};
107 }
108 } else if (name.find("dungeon-") == 0) {
109 metadata.category = "dungeon";
110 metadata.description = "Dungeon inspection and editing";
111 if (name == "dungeon-describe-room") {
112 metadata.examples = {
113 "z3ed dungeon-describe-room --room=5 --format=json"};
114 } else if (name == "dungeon-stream-plan") {
115 metadata.description =
116 "Read-only stream inventory, alias/overlap, and free-space "
117 "diagnostics; replacement-aware immutable move output is pending";
118 metadata.examples = {
119 "z3ed dungeon-stream-plan --kind=objects "
120 "--manifest=hack_manifest.json --rom=game.sfc --format=json",
121 "z3ed dungeon-stream-plan --kind=pot_items "
122 "--manifest=hack_manifest.json --rom=game.sfc --format=text"};
123 } else if (name == "dungeon-place-sprite") {
124 metadata.description =
125 "Place a dungeon sprite (dry-run by default, --write to apply)";
126 metadata.examples = {
127 "z3ed dungeon-place-sprite --room=0x77 --id=0xA3 --x=16 --y=21 "
128 "--subtype=4 --rom=Roms/oos168.sfc --format=json",
129 "z3ed dungeon-place-sprite --room=0x77 --id=0xA3 --x=16 --y=21 "
130 "--subtype=4 --write --rom=/tmp/oos-work.sfc --format=json"};
131 } else if (name == "dungeon-remove-sprite") {
132 metadata.description =
133 "Remove a dungeon sprite by index or exact coordinates";
134 metadata.examples = {
135 "z3ed dungeon-remove-sprite --room=0x77 --index=2 "
136 "--rom=/tmp/oos-work.sfc --format=json",
137 "z3ed dungeon-remove-sprite --room=0x77 --x=16 --y=21 --write "
138 "--rom=/tmp/oos-work.sfc --format=json"};
139 } else if (name == "dungeon-place-object") {
140 metadata.description =
141 "Place a dungeon object with immutable capacity/COW preflight "
142 "(dry-run by default)";
143 metadata.examples = {
144 "z3ed dungeon-place-object --room=0x98 --id=0x0031 --x=20 --y=20 "
145 "--size=4 --rom=/tmp/oos-work.sfc --format=json",
146 "z3ed dungeon-place-object --room=0x98 --id=0x0031 --x=20 --y=20 "
147 "--size=4 --manifest=hack_manifest.json --write "
148 "--rom=/tmp/oos-work.sfc --format=json"};
149 } else if (name == "dungeon-oracle-preflight") {
150 metadata.description =
151 "Oracle ROM safety preflight: water-fill region/table, collision "
152 "maps, and optional required-room checks";
153 metadata.examples = {
154 "z3ed dungeon-oracle-preflight --rom oos168x.sfc --format=json",
155 "z3ed dungeon-oracle-preflight --rom oos168x.sfc "
156 "--required-water-fill-rooms=0x25,0x27 --format=json",
157 "z3ed dungeon-oracle-preflight --rom oos168x.sfc "
158 "--report=/tmp/preflight.json"};
159 } else if (name == "dungeon-set-collision-tile") {
160 metadata.description =
161 "Set one or more custom collision tiles in a dungeon room";
162 metadata.examples = {
163 "z3ed dungeon-set-collision-tile --room=0xB8 "
164 "--tiles=\"10,5,0xB7;50,45,0xBA\" --rom=/tmp/oos-work.sfc "
165 "--format=json",
166 "z3ed dungeon-set-collision-tile --room=0xB8 "
167 "--tiles=\"10,5,0xB7;50,45,0xBA\" --write "
168 "--rom=/tmp/oos-work.sfc --format=json"};
169 }
170 } else if (name.find("overworld-") == 0) {
171 metadata.category = "overworld";
172 metadata.description = "Overworld inspection and editing";
173 if (name == "overworld-find-tile") {
174 metadata.examples = {
175 "z3ed overworld-find-tile --tile=0x42 --format=json"};
176 }
177 } else if (name.find("project-bundle-") == 0) {
178 metadata.category = "project";
179 metadata.requires_rom = false;
180 if (name == "project-bundle-verify") {
181 metadata.description = "Project bundle verification";
182 metadata.examples = {
183 "z3ed project-bundle-verify --project MyProject.yazeproj "
184 "--format=json",
185 "z3ed project-bundle-verify --project project.yaze "
186 "--report report.json",
187 "z3ed project-bundle-verify --project MyProject.yazeproj "
188 "--check-rom-hash --format=json"};
189 } else if (name == "project-bundle-pack") {
190 metadata.description = "Pack bundle into zip archive";
191 metadata.examples = {
192 "z3ed project-bundle-pack --project MyProject.yazeproj "
193 "--out MyProject.zip --format=json",
194 "z3ed project-bundle-pack --project MyProject.yazeproj "
195 "--out MyProject.zip --overwrite"};
196 } else if (name == "project-bundle-unpack") {
197 metadata.description = "Unpack zip archive into bundle";
198 metadata.examples = {
199 "z3ed project-bundle-unpack --archive MyProject.zip "
200 "--out ./projects --format=json",
201 "z3ed project-bundle-unpack --archive MyProject.zip "
202 "--out ./projects --overwrite",
203 "z3ed project-bundle-unpack --archive MyProject.zip "
204 "--out ./projects --keep-partial-output",
205 "z3ed project-bundle-unpack --archive MyProject.zip "
206 "--out ./projects --dry-run"};
207 }
208 } else if (name.find("rom-") == 0) {
209 metadata.category = "rom";
210 metadata.description = "ROM inspection and validation";
211 if (name == "rom-info") {
212 metadata.examples = {"z3ed rom-info --rom=zelda3.sfc"};
213 } else if (name == "rom-validate") {
214 metadata.examples = {"z3ed rom-validate --rom=zelda3.sfc"};
215 } else if (name == "rom-doctor") {
216 metadata.examples = {"z3ed rom-doctor --rom=zelda3.sfc --format=json"};
217 } else if (name == "rom-diff") {
218 metadata.examples = {
219 "z3ed rom-diff --rom_a=base.sfc --rom_b=target.sfc"};
220 } else if (name == "rom-compare") {
221 metadata.examples = {
222 "z3ed rom-compare --rom=target.sfc --baseline=vanilla.sfc"};
223 }
224 } else if (name.find("emulator-") == 0) {
225 metadata.category = "emulator";
226 metadata.description = "Emulator control and debugging";
227 metadata.requires_grpc = true;
228 if (name == "emulator-set-breakpoint") {
229 metadata.examples = {
230 "z3ed emulator-set-breakpoint --address=0x83D7 --description='NMI "
231 "handler'"};
232 }
233 } else if (name.find("mesen-") == 0) {
234 metadata.category = "mesen2";
235 metadata.description = "Mesen2 socket automation and introspection";
236 metadata.requires_rom = false;
237 if (name == "mesen-state-capture") {
238 metadata.examples = {
239 "z3ed mesen-state-capture --state=foo.state "
240 "--rom-file=Roms/oos168x.sfc --scenario=d6_room_88",
241 "z3ed mesen-state-capture --state=Roms/SaveStates/d6_room_88.state "
242 "--rom-file=Roms/oos168x.sfc --slot=1 "
243 "--states-dir=~/Library/Application\\ Support/Mesen2/SaveStates"};
244 } else if (name == "mesen-state-hook") {
245 metadata.examples = {
246 "z3ed mesen-state-hook --state=foo.state "
247 "--rom-file=Roms/oos168x.sfc --scenario=d6_room_88",
248 "z3ed mesen-state-hook --state=foo.state "
249 "--rom-file=Roms/oos168x.sfc --format=json"};
250 }
251 } else if (name.find("gui-") == 0) {
252 metadata.category = "gui";
253 metadata.description = "GUI automation";
254 metadata.requires_grpc = true;
255 } else if (name.find("hex-") == 0) {
256 metadata.category = "graphics";
257 metadata.description = "Hex data manipulation";
258 } else if (name.find("palette-") == 0) {
259 metadata.category = "graphics";
260 metadata.description = "Palette operations";
261 } else if (name.find("sprite-") == 0) {
262 metadata.category = "graphics";
263 metadata.description = "Sprite operations";
264 } else if (name.find("message-") == 0 || name.find("dialogue-") == 0) {
265 metadata.category = "game";
266 metadata.description = name.find("message-") == 0 ? "Message inspection"
267 : "Dialogue inspection";
268 } else if (name.find("music-") == 0) {
269 metadata.category = "game";
270 metadata.description = "Music/audio inspection";
271 } else if (name.find("oracle-") == 0) {
272 metadata.category = "oracle";
273 metadata.description = "Oracle-of-Secrets project tooling";
274 if (name == "oracle-menu-index") {
275 metadata.examples = {
276 "z3ed oracle-menu-index --project=/path/to/oracle-of-secrets "
277 "--format=json",
278 "z3ed oracle-menu-index --table=Menu_ItemCursorPositions "
279 "--missing-bins --format=json"};
280 } else if (name == "oracle-menu-set-offset") {
281 metadata.examples = {
282 "z3ed oracle-menu-set-offset "
283 "--asm=Menu/menu_select_item.asm "
284 "--table=Menu_ItemCursorPositions --index=0 --row=7 --col=2",
285 "z3ed oracle-menu-set-offset "
286 "--asm=Menu/menu_select_item.asm "
287 "--table=Menu_ItemCursorPositions --index=0 --row=7 --col=2 "
288 "--write"};
289 } else if (name == "oracle-menu-validate") {
290 metadata.examples = {
291 "z3ed oracle-menu-validate --project=/path/to/oracle-of-secrets",
292 "z3ed oracle-menu-validate --project=/path/to/oracle-of-secrets "
293 "--strict --max-row=31 --max-col=31"};
294 } else if (name == "oracle-smoke-check") {
295 metadata.examples = {
296 "z3ed oracle-smoke-check --rom oos168.sfc --format=json",
297 "z3ed oracle-smoke-check --rom oos168.sfc --strict-readiness "
298 "--format=json",
299 "z3ed oracle-smoke-check --rom oos168.sfc "
300 "--min-d6-track-rooms=4 --format=json",
301 "z3ed oracle-smoke-check --rom oos168.sfc "
302 "--report=/tmp/smoke.json"};
303 }
304 } else if (name == "simple-chat" || name == "chat") {
305 metadata.category = "agent";
306 metadata.description = "AI conversational agent";
307 metadata.available_to_agent = false; // Meta-command
308 metadata.requires_rom = false;
309 metadata.examples = {
310 "z3ed simple-chat --rom=zelda3.sfc",
311 "z3ed simple-chat \"What dungeons exist?\" --rom=zelda3.sfc"};
312 } else if (name.find("tools-") == 0) {
313 metadata.category = "tools";
314 if (name == "tools-list") {
315 metadata.description = "List available test helper tools";
316 metadata.requires_rom = false;
317 metadata.available_to_agent = true;
318 } else if (name == "tools-harness-state") {
319 metadata.description = "Generate WRAM state for test harnesses";
320 metadata.examples = {
321 "z3ed tools-harness-state --rom=zelda3.sfc --output=state.h"};
322 } else if (name == "tools-extract-values") {
323 metadata.description = "Extract vanilla ROM values";
324 metadata.examples = {"z3ed tools-extract-values --rom=zelda3.sfc"};
325 } else if (name == "tools-extract-golden") {
326 metadata.description = "Extract comprehensive golden data for testing";
327 metadata.examples = {
328 "z3ed tools-extract-golden --rom=zelda3.sfc --output=golden.h"};
329 } else if (name == "tools-patch-v3") {
330 metadata.description = "Create v3 ZSCustomOverworld patched ROM";
331 metadata.examples = {
332 "z3ed tools-patch-v3 --rom=zelda3.sfc --output=patched.sfc"};
333 } else {
334 metadata.description = "Test helper tool";
335 }
336 } else if (name.find("test-") == 0) {
337 metadata.category = "test";
338 metadata.description = "Test discovery and execution";
339 if (name == "test-list") {
340 metadata.requires_rom = false;
341 metadata.examples = {"z3ed test-list", "z3ed test-list --format json"};
342 } else if (name == "test-run") {
343 metadata.examples = {"z3ed test-run --label stable",
344 "z3ed test-run --label gui"};
345 } else if (name == "test-status") {
346 metadata.requires_rom = false;
347 metadata.examples = {"z3ed test-status --format json"};
348 }
349 } else {
350 metadata.category = "misc";
351 metadata.description = "Miscellaneous command";
352 }
353
354 // Prefer handler-provided summary if present
355 if (!descriptor.summary.empty() &&
356 descriptor.summary != "Command summary not provided.") {
357 metadata.description = descriptor.summary;
358 }
359
360 // Keep TODO reference if supplied by handler
361 if (!descriptor.todo_reference.empty() &&
362 descriptor.todo_reference != "todo#unassigned") {
363 metadata.todo_reference = descriptor.todo_reference;
364 }
365
366 Register(std::move(handler), metadata);
367 }
368}
369
370resources::CommandHandler* CommandRegistry::Get(const std::string& name) const {
371 // Check direct name
372 auto it = handlers_.find(name);
373 if (it != handlers_.end()) {
374 return it->second.get();
375 }
376
377 // Check aliases
378 auto alias_it = aliases_.find(name);
379 if (alias_it != aliases_.end()) {
380 auto handler_it = handlers_.find(alias_it->second);
381 if (handler_it != handlers_.end()) {
382 return handler_it->second.get();
383 }
384 }
385
386 return nullptr;
387}
388
390 const std::string& name) const {
391 // Resolve alias first
392 std::string canonical_name = name;
393 auto alias_it = aliases_.find(name);
394 if (alias_it != aliases_.end()) {
395 canonical_name = alias_it->second;
396 }
397
398 auto it = metadata_.find(canonical_name);
399 return (it != metadata_.end()) ? &it->second : nullptr;
400}
401
403 const std::string& category) const {
404 std::vector<std::string> result;
405 for (const auto& [name, metadata] : metadata_) {
406 if (metadata.category == category) {
407 result.push_back(name);
408 }
409 }
410 return result;
411}
412
413std::vector<std::string> CommandRegistry::GetCategories() const {
414 std::vector<std::string> categories;
415 for (const auto& [_, metadata] : metadata_) {
416 if (std::find(categories.begin(), categories.end(), metadata.category) ==
417 categories.end()) {
418 categories.push_back(metadata.category);
419 }
420 }
421 return categories;
422}
423
424std::vector<std::string> CommandRegistry::GetAgentCommands() const {
425 std::vector<std::string> result;
426 for (const auto& [name, metadata] : metadata_) {
427 if (metadata.available_to_agent) {
428 result.push_back(name);
429 }
430 }
431 return result;
432}
433
435 std::ostringstream out;
436 out << "{\n \"commands\": [\n";
437
438 bool first = true;
439 for (const auto& [_, metadata] : metadata_) {
440 if (!first)
441 out << ",\n";
442 first = false;
443
444 out << " {\n";
445 out << " \"name\": \"" << EscapeJson(metadata.name) << "\",\n";
446 out << " \"category\": \"" << EscapeJson(metadata.category) << "\",\n";
447 out << " \"description\": \"" << EscapeJson(metadata.description)
448 << "\",\n";
449 out << " \"usage\": \"" << EscapeJson(metadata.usage) << "\",\n";
450 out << " \"available_to_agent\": "
451 << (metadata.available_to_agent ? "true" : "false") << ",\n";
452 out << " \"requires_rom\": "
453 << (metadata.requires_rom ? "true" : "false") << ",\n";
454 out << " \"requires_grpc\": "
455 << (metadata.requires_grpc ? "true" : "false") << ",\n";
456 if (!metadata.todo_reference.empty()) {
457 out << " \"todo_reference\": \""
458 << EscapeJson(metadata.todo_reference) << "\",\n";
459 } else {
460 out << " \"todo_reference\": \"\",\n";
461 }
462 out << " \"aliases\": ";
463 AppendStringArray(out, metadata.aliases);
464 out << ",\n";
465 out << " \"examples\": ";
466 AppendStringArray(out, metadata.examples);
467 out << "\n";
468 out << " }";
469 }
470
471 out << "\n ]\n}";
472 return out.str();
473}
474
475std::string CommandRegistry::GenerateHelp(const std::string& name) const {
476 auto* metadata = GetMetadata(name);
477 if (!metadata) {
478 return absl::StrFormat("Command '%s' not found", name);
479 }
480
481 std::ostringstream help;
482 help << "\n\033[1;36m" << metadata->name << "\033[0m - "
483 << metadata->description << "\n\n";
484 help << "\033[1;33mUsage:\033[0m\n";
485 help << " " << metadata->usage << "\n\n";
486
487 if (!metadata->examples.empty()) {
488 help << "\033[1;33mExamples:\033[0m\n";
489 for (const auto& example : metadata->examples) {
490 help << " " << example << "\n";
491 }
492 help << "\n";
493 }
494
495 if (metadata->requires_rom) {
496 help << "\033[1;33mRequires:\033[0m ROM file (--rom=<path>)\n";
497 }
498 if (metadata->requires_grpc) {
499 help << "\033[1;33mRequires:\033[0m YAZE running with gRPC enabled\n";
500 }
501
502 if (!metadata->aliases.empty()) {
503 help << "\n\033[1;33mAliases:\033[0m "
504 << absl::StrJoin(metadata->aliases, ", ") << "\n";
505 }
506
507 return help.str();
508}
509
511 const std::string& category) const {
512 auto commands = GetCommandsInCategory(category);
513 if (commands.empty()) {
514 return absl::StrFormat("No commands in category '%s'", category);
515 }
516
517 std::ostringstream help;
518 help << "\n\033[1;36m" << category << " commands:\033[0m\n\n";
519
520 for (const auto& cmd : commands) {
521 auto* metadata = GetMetadata(cmd);
522 if (metadata) {
523 help << " \033[1;33m" << cmd << "\033[0m\n";
524 help << " " << metadata->description << "\n";
525 if (!metadata->usage.empty()) {
526 help << " Usage: " << metadata->usage << "\n";
527 }
528 help << "\n";
529 }
530 }
531
532 return help.str();
533}
534
536 std::ostringstream help;
537 help << "\n\033[1;36mAll z3ed Commands:\033[0m\n\n";
538
539 auto categories = GetCategories();
540 for (const auto& category : categories) {
541 help << GenerateCategoryHelp(category);
542 }
543
544 return help.str();
545}
546
547absl::Status CommandRegistry::Execute(const std::string& name,
548 const std::vector<std::string>& args,
549 Rom* rom_context,
550 std::string* captured_output) {
551 auto* handler = Get(name);
552 if (!handler) {
553 return absl::NotFoundError(absl::StrFormat("Command '%s' not found", name));
554 }
555
556 const bool command_help_requested =
557 std::find(args.begin(), args.end(), "--help") != args.end() ||
558 std::find(args.begin(), args.end(), "-h") != args.end();
559 if (command_help_requested) {
560 const std::string help = GenerateHelp(name);
561 if (captured_output != nullptr) {
562 *captured_output = help;
563 } else {
564 std::cout << help << "\n";
565 }
566 return absl::OkStatus();
567 }
568
569 absl::Status status = handler->Run(args, rom_context, captured_output);
570
571 // If a command was invoked without its required arguments, surface full
572 // command help in addition to the normal parser error/usage line.
573 if (!status.ok() && status.code() == absl::StatusCode::kInvalidArgument &&
574 args.empty()) {
575 const std::string help = GenerateHelp(name);
576 if (captured_output != nullptr) {
577 if (!captured_output->empty()) {
578 captured_output->append("\n\n");
579 }
580 captured_output->append(help);
581 } else {
582 std::cout << help << "\n";
583 }
584 }
585
586 return status;
587}
588
589bool CommandRegistry::HasCommand(const std::string& name) const {
590 return Get(name) != nullptr;
591}
592
596
597} // namespace cli
598} // namespace yaze
The Rom class is used to load, save, and modify Rom data. This is a generic SNES ROM container and do...
Definition rom.h:28
Single source of truth for all z3ed commands.
std::map< std::string, std::string > aliases_
std::vector< std::string > GetCommandsInCategory(const std::string &category) const
Get all commands in a category.
static CommandRegistry & Instance()
std::string GenerateCategoryHelp(const std::string &category) const
Generate category help text.
std::string ExportFunctionSchemas() const
Export function schemas for AI tool calling (JSON)
const CommandMetadata * GetMetadata(const std::string &name) const
Get command metadata.
std::string GenerateCompleteHelp() const
Generate complete help text (all commands)
std::vector< std::string > GetAgentCommands() const
Get all commands available to AI agents.
std::map< std::string, CommandMetadata > metadata_
absl::Status Execute(const std::string &name, const std::vector< std::string > &args, Rom *rom_context=nullptr, std::string *captured_output=nullptr)
Execute a command by name.
std::map< std::string, std::unique_ptr< resources::CommandHandler > > handlers_
resources::CommandHandler * Get(const std::string &name) const
Get a command handler by name or alias.
bool HasCommand(const std::string &name) const
Check if command exists.
std::vector< std::string > GetCategories() const
Get all categories.
void Register(std::unique_ptr< resources::CommandHandler > handler, const CommandMetadata &metadata)
Register a command handler.
std::string GenerateHelp(const std::string &name) const
Generate help text for a command.
void RegisterHandlers(std::vector< std::unique_ptr< resources::CommandHandler > > handlers)
Register a set of command handlers (idempotent)
Base class for CLI command handlers.
std::string EscapeJson(const std::string &input)
void AppendStringArray(std::ostringstream &out, const std::vector< std::string > &values)
std::vector< std::unique_ptr< resources::CommandHandler > > CreateCliCommandHandlers()
Factory function to create all CLI-level command handlers.