Spaces:
Runtime error
Runtime error
File size: 21,865 Bytes
d7204a9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 | """
Command-line entry point for WorldSmithAI.
This module is intended to live at the repository root beside app.py and
callbacks.py. It provides a local CLI for generating, validating, building,
simulating, visualizing, and narrating WorldSmithAI worlds.
It does not import Gradio and does not assume an app/ package.
Example usage:
python main.py --example research --steps 60
python main.py --dsl examples/farm.json --steps 80 --output-dir outputs/farm_run
python main.py --prompt "A fantasy kingdom with dragons, mages, trade, and mana" --steps 70
python main.py --dsl examples/research.json --validate-only
python main.py --prompt "A startup economy with founders and investors" --generate-only
Future extensibility:
- Add optional model-client backends for prompt generation.
- Add multi-run experiments.
- Add benchmark mode.
- Add artifact bundle export.
- Add CI smoke-test command.
- Add run comparison summaries.
"""
from __future__ import annotations
import argparse
import json
import logging
import math
import os
import sys
import traceback
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any
from callbacks import (
CallbackConfig,
CallbackResult,
apply_step_override,
callback_failure_result,
generate_world_from_prompt,
parse_constraints,
run_worldsmith_pipeline,
simulate_dsl_pipeline,
)
from dsl.parser import parse_world_spec
from dsl.validator import validate_world_spec
logger = logging.getLogger(__name__)
APP_NAME = "WorldSmithAI"
DEFAULT_PROMPT = (
"Create a compact research ecosystem where scientists, engineers, reviewers, "
"curators, and funding agents exchange knowledge, collaborate, compete for "
"attention, allocate funding, and adapt goals over time."
)
DEFAULT_OUTPUT_ROOT = "outputs"
@dataclass(frozen=True)
class MainRunResult:
"""Structured CLI result.
Attributes:
callback_result: Framework callback result.
output_dir: Directory where CLI artifact files were written.
written_files: Mapping from artifact label to file path.
source_label: Human-readable source description.
"""
callback_result: CallbackResult
output_dir: Path
written_files: Mapping[str, str] = field(default_factory=dict)
source_label: str = "unknown"
@property
def success(self) -> bool:
"""Return whether the underlying callback result succeeded."""
return self.callback_result.success
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-friendly run summary."""
return {
"success": self.success,
"source_label": self.source_label,
"output_dir": str(self.output_dir),
"written_files": dict(self.written_files),
"callback_result": self.callback_result.to_dict(),
}
class MainError(RuntimeError):
"""Raised when CLI arguments or execution are invalid."""
def main(argv: Sequence[str] | None = None) -> int:
"""Run the WorldSmithAI CLI.
Args:
argv: Optional command-line arguments. When omitted, sys.argv is used.
Returns:
Process exit code.
"""
parser = build_arg_parser()
args = parser.parse_args(argv)
configure_logging(args.log_level)
try:
if args.list_examples:
print_examples(args.examples_dir)
return 0
result = run_from_args(args)
if not args.quiet:
print_console_summary(result)
if args.print_summary:
print(json.dumps(_json_safe(result.to_dict()), indent=2, sort_keys=True))
return 0 if result.success else 2
except KeyboardInterrupt:
print("Interrupted.", file=sys.stderr)
return 130
except Exception as exc:
logger.exception("WorldSmithAI CLI failed")
failure = callback_failure_result(exc)
if not args.quiet:
print(failure.status_message, file=sys.stderr)
if args.debug:
print(traceback.format_exc(), file=sys.stderr)
return 1
def build_arg_parser() -> argparse.ArgumentParser:
"""Build the CLI argument parser."""
parser = argparse.ArgumentParser(
prog="worldsmithai",
description="Run WorldSmithAI from the command line.",
)
input_group = parser.add_mutually_exclusive_group()
input_group.add_argument(
"--prompt",
"-p",
type=str,
default=None,
help="Natural-language world prompt. Uses deterministic fallback generation unless a client is wired externally.",
)
input_group.add_argument(
"--dsl",
type=str,
default=None,
help="Path to a WorldSpec JSON file, or '-' to read from stdin.",
)
input_group.add_argument(
"--example",
"-e",
type=str,
default=None,
help="Example name or path. Examples include farm, civilization, and research.",
)
parser.add_argument(
"--list-examples",
action="store_true",
help="List available examples and exit.",
)
parser.add_argument(
"--examples-dir",
type=str,
default="examples",
help="Directory containing example JSON files.",
)
parser.add_argument(
"--constraints",
"-c",
type=str,
default=None,
help="Optional constraints as JSON text, plain text, or @path/to/file.",
)
parser.add_argument(
"--steps",
"-s",
type=int,
default=None,
help="Override simulation steps.",
)
parser.add_argument(
"--output-dir",
"-o",
type=str,
default=None,
help="Directory where output artifacts should be written.",
)
parser.add_argument(
"--animation-format",
choices=("gif", "mp4"),
default="gif",
help="Animation format. GIF is safest for local and Spaces demos.",
)
parser.add_argument(
"--max-animation-frames",
type=int,
default=int(os.getenv("WORLDSMITHAI_MAX_FRAMES", "80")),
help="Maximum number of animation frames to capture.",
)
parser.add_argument(
"--generate-only",
action="store_true",
help="Generate DSL from --prompt and write JSON without running simulation.",
)
parser.add_argument(
"--validate-only",
action="store_true",
help="Validate DSL input without building or simulating the world.",
)
parser.add_argument(
"--strict",
action="store_true",
help="Treat semantic validation issues as errors where configured.",
)
parser.add_argument(
"--no-animation",
action="store_true",
help="Do not generate animation artifacts.",
)
parser.add_argument(
"--no-charts",
action="store_true",
help="Do not generate population or resource charts.",
)
parser.add_argument(
"--no-final-image",
action="store_true",
help="Do not generate final world-state image.",
)
parser.add_argument(
"--no-narrative",
action="store_true",
help="Do not generate narrative summary.",
)
parser.add_argument(
"--no-metric-history",
action="store_true",
help="Do not collect per-step metric history.",
)
parser.add_argument(
"--print-summary",
action="store_true",
help="Print full JSON run summary to stdout.",
)
parser.add_argument(
"--quiet",
"-q",
action="store_true",
help="Suppress human-readable console output.",
)
parser.add_argument(
"--debug",
action="store_true",
help="Print tracebacks on failure.",
)
parser.add_argument(
"--log-level",
type=str,
default=os.getenv("WORLDSMITHAI_LOG_LEVEL", "INFO"),
help="Logging level.",
)
return parser
def run_from_args(args: argparse.Namespace) -> MainRunResult:
"""Run the requested CLI action from parsed arguments."""
output_dir = resolve_output_dir(args.output_dir)
config = build_callback_config(args, output_dir=output_dir)
if args.generate_only:
return run_generate_only(args, config=config, output_dir=output_dir)
if args.validate_only:
return run_validate_only(args, config=config, output_dir=output_dir)
source_kind, source_value, source_label = resolve_world_source(args)
if source_kind == "prompt":
callback_result = run_worldsmith_pipeline(
prompt=source_value,
constraints=parse_constraints(read_constraints_argument(args.constraints)),
client=None,
config=config,
)
elif source_kind == "dsl":
callback_result = simulate_dsl_pipeline(
dsl_json=source_value,
client=None,
config=config,
)
else:
raise MainError(f"Unsupported source kind: {source_kind}")
written_files = write_callback_result_files(
callback_result,
output_dir=output_dir,
source_label=source_label,
)
return MainRunResult(
callback_result=callback_result,
output_dir=output_dir,
written_files=written_files,
source_label=source_label,
)
def run_generate_only(
args: argparse.Namespace,
*,
config: CallbackConfig,
output_dir: Path,
) -> MainRunResult:
"""Generate a WorldSpec from prompt and write it without simulation."""
prompt = args.prompt or DEFAULT_PROMPT
constraints = parse_constraints(read_constraints_argument(args.constraints))
generation = generate_world_from_prompt(
prompt=prompt,
constraints=constraints,
client=None,
config=config,
)
spec = apply_step_override(generation.spec, config.steps)
report = validate_world_spec(spec, config=config.resolved_validation_config())
status = (
f"Generated WorldSpec {spec.id!r}: "
f"{len(spec.agents)} agent(s), {len(spec.resources)} resource(s), "
f"{len(spec.behavior_names)} behavior reference(s). "
f"Validation: {len(report.errors)} error(s), {len(report.warnings)} warning(s)."
)
callback_result = CallbackResult(
success=report.is_valid,
status_message=status,
world_spec_json=spec.to_json_string(indent=2, exclude_none=True),
validation_json=safe_json_dumps(report.to_dict()),
metrics_json=safe_json_dumps(
{
"success": report.is_valid,
"generation": generation.to_dict(),
"validation": report.to_dict(),
}
),
narrative="Generation-only mode completed. No simulation was run.",
metadata={
"mode": "generate_only",
"prompt": prompt,
},
)
written_files = write_callback_result_files(
callback_result,
output_dir=output_dir,
source_label="prompt:generate_only",
)
return MainRunResult(
callback_result=callback_result,
output_dir=output_dir,
written_files=written_files,
source_label="prompt:generate_only",
)
def run_validate_only(
args: argparse.Namespace,
*,
config: CallbackConfig,
output_dir: Path,
) -> MainRunResult:
"""Validate a DSL source and write validation report without simulation."""
source_kind, source_value, source_label = resolve_world_source(args)
if source_kind == "prompt":
raise MainError("--validate-only requires --dsl or --example, not --prompt")
spec = parse_world_spec(source_value)
spec = apply_step_override(spec, config.steps)
report = validate_world_spec(spec, config=config.resolved_validation_config())
status = (
f"Validated WorldSpec {spec.id!r}. "
f"Validation: {len(report.errors)} error(s), {len(report.warnings)} warning(s)."
)
callback_result = CallbackResult(
success=report.is_valid,
status_message=status,
world_spec_json=spec.to_json_string(indent=2, exclude_none=True),
validation_json=safe_json_dumps(report.to_dict()),
metrics_json=safe_json_dumps({"success": report.is_valid, "validation": report.to_dict()}),
narrative="Validation-only mode completed. No simulation was run.",
metadata={
"mode": "validate_only",
"source_label": source_label,
},
)
written_files = write_callback_result_files(
callback_result,
output_dir=output_dir,
source_label=source_label,
)
return MainRunResult(
callback_result=callback_result,
output_dir=output_dir,
written_files=written_files,
source_label=source_label,
)
def build_callback_config(args: argparse.Namespace, *, output_dir: Path) -> CallbackConfig:
"""Build callback configuration from CLI args."""
return CallbackConfig(
output_dir=output_dir,
steps=args.steps,
max_animation_frames=max(1, int(args.max_animation_frames)),
animation_format=args.animation_format,
generate_animation=not bool(args.no_animation),
generate_charts=not bool(args.no_charts),
generate_final_image=not bool(args.no_final_image),
generate_narrative=not bool(args.no_narrative),
collect_metric_history=not bool(args.no_metric_history),
strict_validation_for_app=bool(args.strict),
)
def resolve_world_source(args: argparse.Namespace) -> tuple[str, str, str]:
"""Resolve CLI input into a source kind, source text, and source label."""
if args.prompt:
return "prompt", str(args.prompt).strip(), "prompt"
if args.dsl:
dsl_text = read_text_source(args.dsl)
return "dsl", dsl_text, f"dsl:{args.dsl}"
if args.example:
example_path = resolve_example_path(args.example, examples_dir=args.examples_dir)
return "dsl", example_path.read_text(encoding="utf-8"), f"example:{example_path.name}"
default_example = resolve_default_example(examples_dir=args.examples_dir)
if default_example is not None:
return "dsl", default_example.read_text(encoding="utf-8"), f"example:{default_example.name}"
return "prompt", DEFAULT_PROMPT, "default_prompt"
def discover_examples(examples_dir: str | Path = "examples") -> dict[str, Path]:
"""Discover available example JSON files."""
directory = Path(examples_dir)
if not directory.exists():
return {}
examples: dict[str, Path] = {}
for path in sorted(directory.glob("*.json")):
examples[path.stem.lower()] = path
examples[path.stem.replace("_", " ").lower()] = path
examples[path.name.lower()] = path
return examples
def resolve_example_path(example: str, *, examples_dir: str | Path = "examples") -> Path:
"""Resolve an example name or path to a JSON file path."""
candidate = Path(example)
if candidate.exists():
return candidate
if candidate.suffix != ".json":
json_candidate = candidate.with_suffix(".json")
if json_candidate.exists():
return json_candidate
examples = discover_examples(examples_dir)
key = example.strip().lower()
if key in examples:
return examples[key]
simplified_key = key.replace("_", " ")
if simplified_key in examples:
return examples[simplified_key]
known = sorted(set(str(path) for path in examples.values()))
raise MainError(f"Unknown example {example!r}. Known example files: {known}")
def resolve_default_example(*, examples_dir: str | Path = "examples") -> Path | None:
"""Return the preferred default example path, if available."""
examples = discover_examples(examples_dir)
for key in ("research", "farm", "civilization"):
if key in examples:
return examples[key]
unique_paths = sorted(set(examples.values()))
return unique_paths[0] if unique_paths else None
def print_examples(examples_dir: str | Path = "examples") -> None:
"""Print available example worlds."""
examples = discover_examples(examples_dir)
unique_paths = sorted(set(examples.values()))
if not unique_paths:
print(f"No examples found in {examples_dir!s}.")
return
print("Available examples:")
for path in unique_paths:
print(f" - {path.stem}: {path}")
def read_text_source(source: str) -> str:
"""Read DSL text from a path or stdin marker."""
if source == "-":
return sys.stdin.read()
path = Path(source)
if not path.exists():
raise MainError(f"DSL file not found: {source}")
return path.read_text(encoding="utf-8")
def read_constraints_argument(value: str | None) -> str | Mapping[str, Any] | None:
"""Read constraints from CLI text or @file syntax."""
if value is None:
return None
text = str(value).strip()
if not text:
return None
if text.startswith("@"):
path = Path(text[1:])
if not path.exists():
raise MainError(f"Constraints file not found: {path}")
return path.read_text(encoding="utf-8")
return text
def resolve_output_dir(output_dir_arg: str | None) -> Path:
"""Resolve and create the CLI output directory."""
if output_dir_arg:
output_dir = Path(output_dir_arg)
elif os.getenv("WORLDSMITHAI_OUTPUT_DIR"):
output_dir = Path(os.environ["WORLDSMITHAI_OUTPUT_DIR"])
else:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_dir = Path(DEFAULT_OUTPUT_ROOT) / f"run_{timestamp}"
output_dir.mkdir(parents=True, exist_ok=True)
return output_dir
def write_callback_result_files(
result: CallbackResult,
*,
output_dir: Path,
source_label: str,
) -> dict[str, str]:
"""Write standard JSON, Markdown, and summary files for a callback result."""
output_dir.mkdir(parents=True, exist_ok=True)
written: dict[str, str] = {}
written["world_spec_json"] = write_text_file(
output_dir / "world_spec.json",
result.world_spec_json or "{}",
)
written["validation_report_json"] = write_text_file(
output_dir / "validation_report.json",
result.validation_json or "{}",
)
written["metrics_json"] = write_text_file(
output_dir / "metrics.json",
result.metrics_json or "{}",
)
written["narrative_md"] = write_text_file(
output_dir / "narrative.md",
result.narrative or "No narrative generated.",
)
summary_payload = {
"app": APP_NAME,
"source_label": source_label,
"success": result.success,
"status_message": result.status_message,
"standard_files": written,
"artifacts": None if result.artifacts is None else result.artifacts.to_dict(),
"callback_result": result.to_dict(),
}
written["run_summary_json"] = write_text_file(
output_dir / "run_summary.json",
safe_json_dumps(summary_payload),
)
return written
def write_text_file(path: Path, text: str) -> str:
"""Write UTF-8 text to a file and return the path string."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return str(path)
def print_console_summary(result: MainRunResult) -> None:
"""Print a concise human-readable run summary."""
callback_result = result.callback_result
print()
print(f"{APP_NAME} run summary")
print("=" * 72)
print(f"Success: {callback_result.success}")
print(f"Source: {result.source_label}")
print(f"Output directory: {result.output_dir}")
print(f"Status: {callback_result.status_message}")
print()
print("Written files:")
for label, path in sorted(result.written_files.items()):
print(f" - {label}: {path}")
if callback_result.artifacts is not None:
artifacts = callback_result.artifacts.to_dict()
artifact_items = [(key, value) for key, value in artifacts.items() if value and key != "output_dir"]
if artifact_items:
print()
print("Generated artifacts:")
for label, path in artifact_items:
print(f" - {label}: {path}")
print()
def configure_logging(level: str) -> None:
"""Configure logging for CLI execution."""
logging.basicConfig(
level=str(level).upper(),
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
def safe_json_dumps(value: Any) -> str:
"""Serialize a value as pretty JSON."""
return json.dumps(
_json_safe(value),
indent=2,
sort_keys=True,
ensure_ascii=False,
)
def _json_safe(value: Any) -> Any:
"""Return a JSON-friendly representation of arbitrary values."""
if value is None or isinstance(value, (str, bool)):
return value
if isinstance(value, int) and not isinstance(value, bool):
return value
if isinstance(value, float):
if not math.isfinite(value):
return None
return value
if isinstance(value, Mapping):
return {str(key): _json_safe(nested) for key, nested in value.items()}
if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
return [_json_safe(item) for item in value]
if hasattr(value, "to_dict") and callable(value.to_dict):
return _json_safe(value.to_dict())
if hasattr(value, "model_dump") and callable(value.model_dump):
return _json_safe(value.model_dump(mode="json"))
return str(value)
if __name__ == "__main__":
raise SystemExit(main()) |