uro-cli 0.18.0__tar.gz → 0.19.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: uro-cli
3
- Version: 0.18.0
3
+ Version: 0.19.0
4
4
  Summary: Uro Engine reference client — play, dry-run, and dev tools against the engine
5
5
  Project-URL: Homepage, https://github.com/cupskeee/uro
6
6
  Project-URL: Repository, https://github.com/cupskeee/uro
@@ -12,8 +12,8 @@ Requires-Python: >=3.12
12
12
  Requires-Dist: python-dotenv>=1.0
13
13
  Requires-Dist: rich>=13.9
14
14
  Requires-Dist: typer>=0.27.2
15
- Requires-Dist: uro-core[llm,postgres]==0.18.0
16
- Requires-Dist: uro-server==0.18.0
15
+ Requires-Dist: uro-core[llm,postgres]==0.19.0
16
+ Requires-Dist: uro-server==0.19.0
17
17
  Requires-Dist: websockets>=16.1
18
18
  Description-Content-Type: text/markdown
19
19
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "uro-cli"
3
- version = "0.18.0"
3
+ version = "0.19.0"
4
4
  description = "Uro Engine reference client — play, dry-run, and dev tools against the engine"
5
5
  license = "MIT"
6
6
  license-files = ["LICENSE"]
@@ -13,8 +13,8 @@ requires-python = ">=3.12"
13
13
  # pair a new uro-cli with an old uro-core; `just release` bumps all three together, and the
14
14
  # `{workspace = true}` sources make a drifted pin fail `uv sync` locally.
15
15
  dependencies = [
16
- "uro-core[postgres,llm]==0.18.0",
17
- "uro-server==0.18.0",
16
+ "uro-core[postgres,llm]==0.19.0",
17
+ "uro-server==0.19.0",
18
18
  "typer>=0.27.2",
19
19
  "rich>=13.9",
20
20
  "websockets>=16.1",
@@ -67,6 +67,9 @@ outbox_app = typer.Typer(
67
67
  help="The transactional outbox — publish committed beats to other processes (D-57).",
68
68
  )
69
69
  ruleset_app = typer.Typer(no_args_is_help=True, help="The built-in ruleset registry (docs/06).")
70
+ rules_app = typer.Typer(
71
+ no_args_is_help=True, help="World rules (rules.yaml / agendas.yaml): their grammar (docs/17)."
72
+ )
70
73
  policy_app = typer.Typer(
71
74
  no_args_is_help=True,
72
75
  help="Which emergent world state play may create — the instance's extraction policy (D-49).",
@@ -84,6 +87,7 @@ app.add_typer(provider_app, name="provider")
84
87
  provider_app.add_typer(credential_app, name="credential")
85
88
  app.add_typer(outbox_app, name="outbox")
86
89
  app.add_typer(ruleset_app, name="ruleset")
90
+ app.add_typer(rules_app, name="rules")
87
91
  app.add_typer(policy_app, name="extraction-policy")
88
92
  app.add_typer(memory_app, name="memory")
89
93
 
@@ -114,6 +118,41 @@ async def _metered(router: ProviderRouter) -> AsyncIterator[ProviderRouter]:
114
118
  await store.close()
115
119
 
116
120
 
121
+ async def _play_creates_actors() -> bool:
122
+ """Whether this instance lets play create actors (its extraction policy, D-49), read best
123
+ effort like `_metered`: with no database, the default (on), as a pure parse assumes."""
124
+ try:
125
+ store = build_store()
126
+ await asyncio.wait_for(connect_store(store), timeout=5)
127
+ except Exception:
128
+ return True
129
+ try:
130
+ return (await store.get_extraction_policy()).extract_actors
131
+ finally:
132
+ await store.close()
133
+
134
+
135
+ def _require_migrated(store: PostgresEventStore) -> None:
136
+ """Refuse to serve a database this code's migrations haven't all reached: it would fail at
137
+ the first write that needs a new column, mid-play. Names what's pending and the fix."""
138
+
139
+ async def _pending() -> list[str]:
140
+ await connect_store(store)
141
+ try:
142
+ return await store.pending_migrations()
143
+ finally:
144
+ await store.close()
145
+
146
+ pending = asyncio.run(_pending())
147
+ if pending:
148
+ typer.echo(
149
+ f"error: the database is missing {len(pending)} migration(s) this code needs: "
150
+ f"{', '.join(pending)}. Run `uro db migrate` first.",
151
+ err=True,
152
+ )
153
+ raise typer.Exit(1)
154
+
155
+
117
156
  def _run_async(coro_factory) -> None: # type: ignore[no-untyped-def]
118
157
  """Run an async command, turning config/credential/lookup errors into a clean message."""
119
158
  try:
@@ -244,17 +283,34 @@ def world_new(
244
283
  "", "--ruleset", help="a built-in ruleset id (`uro ruleset list`); default uro-basic"
245
284
  ),
246
285
  pc: str = typer.Option("Player", "--pc", help="the player character's name"),
286
+ description: str = typer.Option(
287
+ "", "--description", help="a short pitch for whoever lists the world (D-104)"
288
+ ),
289
+ content_rating: str = typer.Option(
290
+ None,
291
+ "--content-rating",
292
+ help="declare the world's content ceiling: none | mild | mature | explicit (D-104)",
293
+ ),
247
294
  ) -> None:
248
295
  """Create a world (+ its main branch) and a ready-to-play campaign with a default,
249
296
  sheeted PC. Prints the campaign id."""
250
297
 
251
298
  async def _run() -> None:
299
+ from uro_core.worldpack.models import ContentDecl
300
+
252
301
  rs = build_ruleset(ruleset) # an unknown id fails here, before any write
302
+ content = (
303
+ ContentDecl.model_validate({"rating": content_rating}).model_dump()
304
+ if content_rating
305
+ else None
306
+ )
253
307
  sheet, ruleset_id = _build_pc_sheet(rs), rs.id
254
308
  store = build_store()
255
309
  await connect_store(store)
256
310
  try:
257
- world = await store.create_world(name, ruleset_id=ruleset)
311
+ world = await store.create_world(
312
+ name, ruleset_id=ruleset, description=description, content=content
313
+ )
258
314
  campaign = await store.start_campaign(
259
315
  world.world_id,
260
316
  world.main_branch_id,
@@ -273,6 +329,21 @@ def world_new(
273
329
  _run_async(_run)
274
330
 
275
331
 
332
+ @world_app.command("parse")
333
+ def world_parse(path: str) -> None:
334
+ """Print the pack at <path> as Uro reads it, as JSON (D-105): the manifest with every default
335
+ filled in, the seeds, lore, prompt files and rule pack. Nothing is imported."""
336
+ from uro_core.errors import PackError
337
+ from uro_core.worldpack.parse import parse_pack
338
+
339
+ try:
340
+ pack = parse_pack(path)
341
+ except PackError as exc:
342
+ typer.echo(f"error: {exc}", err=True)
343
+ raise typer.Exit(1) from exc
344
+ typer.echo(json.dumps(pack.model_dump(mode="json"), indent=2))
345
+
346
+
276
347
  @world_app.command("validate")
277
348
  def world_validate(path: str) -> None:
278
349
  """Parse a world pack and report its sufficiency (docs/09) — the creator loop, no import."""
@@ -326,10 +397,15 @@ def world_create(
326
397
  store = build_store()
327
398
  try:
328
399
  pack = parse_pack(path)
329
- # build the provider only when a gap needs it: a runnable pack needs no key
330
- needs_fill = backfill and check_sufficiency(pack).grade != "runnable"
331
- router = build_router(provider, model) if needs_fill else None
332
400
  await connect_store(store)
401
+ # build the provider only when a gap needs it (a runnable pack needs no key), graded
402
+ # as the import grades it: with this instance's extraction policy (D-108 review)
403
+ makes_people = (await store.get_extraction_policy()).extract_actors
404
+ needs_fill = (
405
+ backfill
406
+ and check_sufficiency(pack, play_creates_actors=makes_people).grade != "runnable"
407
+ )
408
+ router = build_router(provider, model) if needs_fill else None
333
409
  if router is not None: # the backfill's calls are metered like any other (D-66)
334
410
  router.recorder = store.record_llm_call
335
411
  result = await import_pack(store, pack, backfill_router=router)
@@ -343,34 +419,44 @@ def world_create(
343
419
  for a in result.backfilled:
344
420
  typer.echo(f" backfilled + committed: {a}")
345
421
  if pack.manifest.history.vocabulary is not None: # D-97: seeding speaks the pack's words
346
- typer.echo(f"seed history: uro world seed {path} --seed 42")
422
+ typer.echo(f"seed history: uro world seed {world.world_id} --seed 42")
347
423
 
348
424
  _run_async(_run)
349
425
 
350
426
 
351
427
  @world_app.command("seed")
352
428
  def world_seed(
353
- path: str,
429
+ target_ref: str = typer.Argument(
430
+ ...,
431
+ metavar="WORLD_OR_PACK",
432
+ help="a world (id or name), or the pack directory it was made from",
433
+ ),
354
434
  seed: int = typer.Option(42, "--seed", help="RNG seed for History"),
355
435
  world: str = typer.Option(
356
- None, "--world", help="the world to seed (id or name; default: the pack's name)"
436
+ None,
437
+ "--world",
438
+ help="with a pack: the world to seed (id or name; default: the pack's name)",
357
439
  ),
358
440
  ) -> None:
359
- """Run History seeding on the world imported from <path>: layer a seed-dependent past
360
- (power groups, their leaders and conflicts, in the pack's \\[history.vocabulary]) on top of
361
- the authored geography (docs/09). Same pack + a different seed → a different history on
362
- identical geography."""
441
+ """Run History seeding on a world: layer a seed-dependent past (power groups, their leaders
442
+ and conflicts, in the manifest's \\[history.vocabulary]) on top of the authored geography
443
+ (docs/09). A world keeps the manifest it was made from (D-104), so naming the world is enough;
444
+ a world made before that takes its pack directory. Same manifest + a different seed → a
445
+ different history on identical geography."""
363
446
 
364
447
  async def _run() -> None:
448
+ from pathlib import Path
449
+
365
450
  from uro_core.errors import PackError
366
451
  from uro_core.worldpack.create import seed_world
367
452
  from uro_core.worldpack.parse import parse_pack
368
453
 
369
454
  store = build_store()
370
455
  try:
371
- pack = parse_pack(path)
456
+ pack = parse_pack(target_ref) if (Path(target_ref) / "world.toml").is_file() else None
372
457
  await connect_store(store)
373
- target = await _world_or_exit(store, world or pack.manifest.name)
458
+ name = world or (pack.manifest.name if pack is not None else target_ref)
459
+ target = await _world_or_exit(store, name)
374
460
  result = await seed_world(store, target, pack, seed)
375
461
  except PackError as exc:
376
462
  typer.echo(f"error: {exc}", err=True)
@@ -406,13 +492,18 @@ def world_backfill(
406
492
  except PackError as exc:
407
493
  typer.echo(f"error: {exc}", err=True)
408
494
  raise typer.Exit(1) from exc
409
- before = check_sufficiency(pack)
495
+ # graded as the import (and POST /worlds/backfill) grade it: this instance's extraction
496
+ # policy, when the database answers (D-108 review)
497
+ makes_people = await _play_creates_actors()
498
+ before = check_sufficiency(pack, play_creates_actors=makes_people)
410
499
  if before.grade == "runnable":
411
500
  typer.echo("pack is already runnable — nothing to backfill")
412
501
  return
413
502
  async with _metered(build_router(provider, model)) as router:
414
- augmented, added = await backfill_gaps(pack, router, report=before)
415
- after = check_sufficiency(augmented)
503
+ augmented, added = await backfill_gaps(
504
+ pack, router, report=before, play_creates_actors=makes_people
505
+ )
506
+ after = check_sufficiency(augmented, play_creates_actors=makes_people)
416
507
  typer.echo(f"backfill: {before.grade} → {after.grade}")
417
508
  for a in added:
418
509
  typer.echo(f" + {a}")
@@ -742,6 +833,7 @@ def serve(
742
833
  except (RuntimeError, ValueError) as exc: # incl. DatabaseUnavailable (a RuntimeError subclass)
743
834
  typer.echo(f"error: {exc}", err=True)
744
835
  raise typer.Exit(1) from exc
836
+ _require_migrated(store)
745
837
  engine = Engine(store, router, ruleset=build_ruleset(ruleset))
746
838
  # Pick the turn shape (OQ-7, D-31/D-38/D-39). UNSET (--arbiter not given) is AUTO: solo for one
747
839
  # token (the dev loop → SoloArbiter), party for >1. Set EXPLICITLY, the shape binds regardless
@@ -825,6 +917,13 @@ def connect(
825
917
  async def _client() -> None:
826
918
  try:
827
919
  async with websockets.connect(uri) as ws:
920
+ # A refusal is a close code right after the socket opens (D-107); a seat is
921
+ # announced (participant_joined). Wait a moment for either before saying so.
922
+ first: str | bytes | None = None
923
+ with contextlib.suppress(TimeoutError, websockets.ConnectionClosed):
924
+ first = await asyncio.wait_for(ws.recv(), timeout=1.5)
925
+ if ws.close_code is not None:
926
+ _refused(ws.close_code, campaign_id)
828
927
  typer.echo(f"connected to {campaign_id} as {token!r}. Type an action; /quit.\n")
829
928
  # An intent is SETTLED by one of these, each echoing the intent's text. The prompt
830
929
  # waits for it: shown at once, it sat above the streaming narration and was gone by
@@ -861,9 +960,17 @@ def connect(
861
960
  if hit is not None:
862
961
  hit[1].set()
863
962
 
963
+ async def frames() -> AsyncIterator[str | bytes]:
964
+ if first is not None: # the frame that told us we were seated
965
+ yield first
966
+ # a server that goes away ends the session: the prompt loop sees it
967
+ with contextlib.suppress(websockets.ConnectionClosed):
968
+ async for raw in ws:
969
+ yield raw
970
+
864
971
  async def receive() -> None:
865
972
  nonlocal echoes, seen_day
866
- async for raw in ws:
973
+ async for raw in frames():
867
974
  msg = json.loads(raw)
868
975
  kind = msg.get("type")
869
976
  echoes = echoes or "intent_id" in msg
@@ -934,30 +1041,44 @@ def connect(
934
1041
 
935
1042
  receiver = asyncio.create_task(receive())
936
1043
  loop = asyncio.get_event_loop()
937
- while True:
938
- intent = (await loop.run_in_executor(None, input, "> ")).strip()
939
- if intent in ("/quit", "/exit"):
940
- break
941
- if intent.startswith("/say "): # non-canon table-talk (D-38)
942
- await ws.send(json.dumps({"type": "table_talk", "text": intent[5:]}))
943
- elif intent.startswith("/vote "): # non-canon consensus vote (D-38)
944
- await ws.send(json.dumps({"type": "vote", "choice": intent[6:]}))
945
- elif intent:
946
- rid = uuid.uuid4().hex
947
- settled = asyncio.Event()
948
- pending[rid] = (intent, settled)
949
- await ws.send(json.dumps({"type": "intent", "text": intent, "id": rid}))
950
- waiting = asyncio.ensure_future(settled.wait())
951
- # a slow beat (a reasoning model's extraction) still settles well inside
952
- # this; past it — or if the server goes away — the prompt comes back anyway
953
- await asyncio.wait(
954
- {waiting, receiver}, timeout=600, return_when=asyncio.FIRST_COMPLETED
955
- )
956
- waiting.cancel()
957
- pending.pop(rid, None)
958
- if receiver.done(): # the server closed the connection
1044
+ # A server that closes the socket while the player is at the prompt (a revoked
1045
+ # token, a removed campaign) ends the session here, then says why (D-107 review).
1046
+ try:
1047
+ while True:
1048
+ intent = (await loop.run_in_executor(None, input, "> ")).strip()
1049
+ if receiver.done(): # closed while the player typed
959
1050
  break
1051
+ if intent in ("/quit", "/exit"):
1052
+ break
1053
+ if intent.startswith("/say "): # non-canon table-talk (D-38)
1054
+ await ws.send(json.dumps({"type": "table_talk", "text": intent[5:]}))
1055
+ elif intent.startswith("/vote "): # non-canon consensus vote (D-38)
1056
+ await ws.send(json.dumps({"type": "vote", "choice": intent[6:]}))
1057
+ elif intent:
1058
+ rid = uuid.uuid4().hex
1059
+ settled = asyncio.Event()
1060
+ pending[rid] = (intent, settled)
1061
+ await ws.send(json.dumps({"type": "intent", "text": intent, "id": rid}))
1062
+ waiting = asyncio.ensure_future(settled.wait())
1063
+ # a slow beat (a reasoning model's extraction) still settles well
1064
+ # inside this; past it, or if the server goes away, the prompt returns
1065
+ await asyncio.wait(
1066
+ {waiting, receiver},
1067
+ timeout=600,
1068
+ return_when=asyncio.FIRST_COMPLETED,
1069
+ )
1070
+ waiting.cancel()
1071
+ pending.pop(rid, None)
1072
+ if receiver.done(): # the server closed the connection
1073
+ break
1074
+ except websockets.ConnectionClosed:
1075
+ pass
960
1076
  receiver.cancel()
1077
+ if ws.close_code in _REFUSALS: # refused after a while (a token revoked mid-session)
1078
+ _refused(ws.close_code, campaign_id)
1079
+ except websockets.InvalidStatus as exc: # a server older than D-107 refuses the handshake
1080
+ typer.echo(f"refused by {server}: {exc}", err=True)
1081
+ raise typer.Exit(1) from exc
961
1082
  except OSError as exc:
962
1083
  typer.echo(f"could not connect to {server}: {exc} (is `uro serve` running?)", err=True)
963
1084
  raise typer.Exit(1) from exc
@@ -965,6 +1086,20 @@ def connect(
965
1086
  asyncio.run(_client())
966
1087
 
967
1088
 
1089
+ _REFUSALS = {
1090
+ 4401: "the server doesn't know this token",
1091
+ 4403: "this token is for another campaign",
1092
+ 4404: "no such campaign on this server",
1093
+ }
1094
+
1095
+
1096
+ def _refused(code: int, campaign_id: str) -> None:
1097
+ """Say why the server closed the play socket (D-107), and exit 1."""
1098
+ why = _REFUSALS.get(code, "the server closed the connection")
1099
+ typer.echo(f"refused ({campaign_id}): {why} [{code}]", err=True)
1100
+ raise typer.Exit(1)
1101
+
1102
+
968
1103
  def _server_post(server: str, path: str, token: str, body: dict[str, Any] | None) -> dict[str, Any]:
969
1104
  """POST JSON (or GET, when `body` is None) to a running `uro serve` — stdlib urllib, no extra
970
1105
  dep — authed by ?token."""
@@ -1300,6 +1435,14 @@ def world_list() -> None:
1300
1435
  typer.echo("(no worlds — create one with `uro world new` or `uro world create`)")
1301
1436
  for w in worlds:
1302
1437
  typer.echo(f"{w.world_id} {w.name}")
1438
+ # what the world says about itself (D-104), when it says anything
1439
+ about = [
1440
+ *([w.description] if w.description else []),
1441
+ *([f"tone: {', '.join(w.tone)}"] if w.tone else []),
1442
+ *([f"content: {w.content.get('rating')}"] if w.content else []),
1443
+ ]
1444
+ if about:
1445
+ typer.echo(f" {' · '.join(about)}")
1303
1446
 
1304
1447
  _run_async(_run)
1305
1448
 
@@ -1522,6 +1665,53 @@ def calls(
1522
1665
  _run_async(_run)
1523
1666
 
1524
1667
 
1668
+ @rules_app.command("schema")
1669
+ def rules_schema() -> None:
1670
+ """Print the world-rules grammar as JSON Schema (D-105), with the version this engine writes
1671
+ and the versions it reads."""
1672
+ from uro_core.worldpack import rules as R
1673
+
1674
+ typer.echo(
1675
+ json.dumps(
1676
+ {
1677
+ "rules_api_version": R.RULES_API_VERSION,
1678
+ "supported_versions": sorted(R._SUPPORTED_VERSIONS),
1679
+ "rule_pack_schema": R.rule_pack_schema(),
1680
+ },
1681
+ indent=2,
1682
+ )
1683
+ )
1684
+
1685
+
1686
+ @rules_app.command("validate")
1687
+ def rules_validate(path: str) -> None:
1688
+ """Check world rules on their own, as creating a world would (D-105): <path> is a pack
1689
+ directory (its rules.yaml / agendas.yaml), or a JSON file holding one rule pack
1690
+ ({rules_api_version, rules, agendas})."""
1691
+ from pathlib import Path
1692
+
1693
+ from uro_core.errors import PackError
1694
+ from uro_core.worldpack.parse import _rule_pack
1695
+ from uro_core.worldpack.rules import check_rule_pack
1696
+
1697
+ target = Path(path)
1698
+ try:
1699
+ if target.is_dir():
1700
+ pack = _rule_pack(target)
1701
+ if pack is None:
1702
+ typer.echo(f"error: {path} has no rules.yaml or agendas.yaml", err=True)
1703
+ raise typer.Exit(1)
1704
+ else:
1705
+ pack = check_rule_pack(json.loads(target.read_text()))
1706
+ except (PackError, ValueError, OSError) as exc: # json.JSONDecodeError is a ValueError
1707
+ typer.echo(f"error: {exc}", err=True)
1708
+ raise typer.Exit(1) from exc
1709
+ typer.echo(
1710
+ f"ok: {len(pack.rules)} rules, {len(pack.agendas)} agendas "
1711
+ f"(rules_api_version {pack.rules_api_version})"
1712
+ )
1713
+
1714
+
1525
1715
  @ruleset_app.command("list")
1526
1716
  def ruleset_list() -> None:
1527
1717
  """The rulesets a world can declare (`\\[ruleset] id` in world.toml): the built-ins and
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes