uro-cli 0.20.0__tar.gz → 0.21.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.20.0
3
+ Version: 0.21.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.20.0
16
- Requires-Dist: uro-server==0.20.0
15
+ Requires-Dist: uro-core[llm,postgres]==0.21.0
16
+ Requires-Dist: uro-server==0.21.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.20.0"
3
+ version = "0.21.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.20.0",
17
- "uro-server==0.20.0",
16
+ "uro-core[postgres,llm]==0.21.0",
17
+ "uro-server==0.21.0",
18
18
  "typer>=0.27.2",
19
19
  "rich>=13.9",
20
20
  "websockets>=16.1",
@@ -18,11 +18,12 @@ from typing import Any
18
18
  import typer
19
19
  from dotenv import find_dotenv, load_dotenv
20
20
  from uro_core.adapters.postgres.store import PostgresEventStore
21
+ from uro_core.pipeline.encounter import ChoiceRefused, TurnChoice
21
22
  from uro_core.pipeline.engine import BeatMechanics, BeatResult, Engine
22
23
  from uro_core.ports.model_registry import ROLES
23
24
  from uro_core.providers.router import ProviderRouter
24
25
  from uro_core.rulesets import registry
25
- from uro_core.rulesets.base import CharSpec, Ruleset
26
+ from uro_core.rulesets.base import CharSpec, CharSpecError, Ruleset
26
27
  from uro_core.rulesets.rng import Rng
27
28
  from uro_core.timeline.gear import starting_gear
28
29
  from uro_core.timeline.models import FORK_TIME_SKIP, World
@@ -211,6 +212,48 @@ async def _time_skip_ruleset(pick: Awaitable[Ruleset]) -> Ruleset | None:
211
212
  return None
212
213
 
213
214
 
215
+ def _json_option(raw: str | None, flag: str) -> dict[str, Any] | None:
216
+ """A JSON-object option (`--spec`, `--ruleset-config`): inline JSON, or `@path` to a file."""
217
+ if raw is None:
218
+ return None
219
+ try:
220
+ text = Path(raw[1:]).read_text() if raw.startswith("@") else raw
221
+ value = json.loads(text)
222
+ except (OSError, ValueError) as exc:
223
+ typer.echo(f"{flag}: not a JSON object ({exc})", err=True)
224
+ raise typer.Exit(2) from exc
225
+ if not isinstance(value, dict):
226
+ typer.echo(f"{flag}: not a JSON object", err=True)
227
+ raise typer.Exit(2)
228
+ return value
229
+
230
+
231
+ def _json_list_option(raw: str | None, flag: str) -> list[Any] | None:
232
+ """A JSON-array option (`--holdings`): inline JSON, or `@path` to a file."""
233
+ if raw is None:
234
+ return None
235
+ try:
236
+ value = json.loads(Path(raw[1:]).read_text() if raw.startswith("@") else raw)
237
+ except (OSError, ValueError) as exc:
238
+ typer.echo(f"{flag}: not a JSON list ({exc})", err=True)
239
+ raise typer.Exit(2) from exc
240
+ if not isinstance(value, list):
241
+ typer.echo(f"{flag}: not a JSON list", err=True)
242
+ raise typer.Exit(2)
243
+ return value
244
+
245
+
246
+ def _echo_refused(exc: Exception) -> None:
247
+ """A refused start, join or build, with each spec problem on its own line (D-112)."""
248
+ if isinstance(exc, CharSpecError):
249
+ typer.echo("the character can't be built:", err=True)
250
+ for p in exc.problems:
251
+ where = ".".join(str(x) for x in p.loc)
252
+ typer.echo(f" {where + ': ' if where else ''}{p.message}", err=True)
253
+ else:
254
+ typer.echo(f"error: {exc.args[0] if exc.args else exc}", err=True)
255
+
256
+
214
257
  def _build_pc_sheet(ruleset: Ruleset) -> dict[str, Any]:
215
258
  """A default character sheet from the world's bound ruleset (with the world's settings), so
216
259
  every PC can be checked (docs/06) — a PbtA world mints a PbtA sheet."""
@@ -496,7 +539,7 @@ def world_backfill(
496
539
  # policy, when the database answers (D-108 review)
497
540
  makes_people = await _play_creates_actors()
498
541
  before = check_sufficiency(pack, play_creates_actors=makes_people)
499
- if before.grade == "runnable":
542
+ if before.grade == "runnable" and pack.characters:
500
543
  typer.echo("pack is already runnable — nothing to backfill")
501
544
  return
502
545
  async with _metered(build_router(provider, model)) as router:
@@ -659,15 +702,33 @@ def play(
659
702
  break
660
703
  if not intent:
661
704
  continue
705
+ if intent.startswith("/choose "): # D-113: /choose <id> <json answer>
706
+ from uro_core.characters import ChoiceError, answer_character_choice
707
+
708
+ cid, _, raw = intent[8:].strip().partition(" ")
709
+ try:
710
+ view = await answer_character_choice(
711
+ store, campaign, PARTICIPANT, cid, json.loads(raw) if raw else {}
712
+ )
713
+ left = ", ".join(c.id for c in view.choices) or "none"
714
+ typer.echo(f" · answered {cid}; choices left: {left}")
715
+ except (ValueError, CharSpecError, ChoiceError, KeyError) as exc:
716
+ _echo_refused(exc)
717
+ continue
718
+ choice = parse_act(intent) # D-112: `/act <kind> [target]` on a fight turn
719
+ if intent.startswith("/act") and choice is None:
720
+ typer.echo("usage: /act <action> [target]", err=True)
721
+ continue
662
722
  try:
663
723
  results: list[BeatResult] = []
664
724
  mechanics: list[BeatMechanics] = []
665
725
  async for chunk in engine.run_beat_stream(
666
726
  campaign,
667
727
  PARTICIPANT,
668
- intent,
728
+ intent[4:].strip() if choice is not None else intent,
669
729
  on_result=results.append,
670
730
  on_mechanics=mechanics.append,
731
+ action=TurnChoice.model_validate(choice) if choice else None,
671
732
  ):
672
733
  if mechanics: # the rules' answer, before the story (D-100)
673
734
  m = mechanics.pop()
@@ -683,6 +744,12 @@ def play(
683
744
  typer.echo(line)
684
745
  if results:
685
746
  day = results[0].world_day
747
+ except ChoiceRefused as exc:
748
+ sys.stdout.write("\n")
749
+ for line in refusal_lines(
750
+ str(exc), [a.model_dump() for a in exc.legal_actions]
751
+ ):
752
+ typer.echo(line, err=True)
686
753
  except Exception as exc:
687
754
  sys.stdout.write("\n")
688
755
  typer.echo(f"beat failed ({exc}); nothing was saved — try again.", err=True)
@@ -701,9 +768,28 @@ def _details(result: BeatResult) -> dict[str, Any]:
701
768
  "world_day": result.world_day,
702
769
  "created": [c.model_dump() for c in result.created],
703
770
  "threads_changed": [t.model_dump() for t in result.threads_changed],
771
+ "encounter": result.encounter.model_dump() if result.encounter is not None else None,
772
+ "choices": [c.model_dump() for c in result.choices],
704
773
  }
705
774
 
706
775
 
776
+ def parse_act(line: str) -> dict[str, Any] | None:
777
+ """`/act <kind> [target]` as an encounter action (D-112), or None when it isn't one."""
778
+ parts = line.split()
779
+ if len(parts) < 2 or parts[0] != "/act":
780
+ return None
781
+ return {"kind": parts[1], "target_id": parts[2] if len(parts) > 2 else None}
782
+
783
+
784
+ def refusal_lines(reason: str, legal: list[dict[str, Any]]) -> list[str]:
785
+ """A refused fight-turn action and what may be done instead (D-112)."""
786
+ lines = [f" ! {reason}"]
787
+ for a in legal:
788
+ targets = f" <{'|'.join(a.get('targets') or [])}>" if a.get("targets") else ""
789
+ lines.append(f" /act {a['kind']}{targets}")
790
+ return lines
791
+
792
+
707
793
  def mechanics_lines(details: dict[str, Any]) -> list[str]:
708
794
  """Each check's outcome and a fight — what the rules decided (shown before the narration
709
795
  when the server sends `beat_checks`, D-100)."""
@@ -730,6 +816,13 @@ def beat_detail_lines(
730
816
  for t in details.get("threads_changed") or []: # D-103: any plot whose state moved
731
817
  moved = f"{t['from_state']} → {t['to_state']}" if t["from_state"] else t["to_state"]
732
818
  lines.append(f" ~ plot {moved}: {t['stakes']}")
819
+ if mine: # D-113: choices the ruleset left on the player's own character
820
+ for c in details.get("choices") or []:
821
+ lines.append(f" ? {c['id']}: {c['prompt']} — `uro character choose` or /choose")
822
+ wait = details.get("encounter") # D-112: the fight waits on a player's choice
823
+ if wait:
824
+ lines.append(f" · the fight waits on {wait['actor_id']}:")
825
+ lines += refusal_lines("", wait.get("legal_actions") or [])[1:]
733
826
  created = details.get("created") or []
734
827
  if created:
735
828
  lines.append(" + new: " + ", ".join(f"{c['name']} ({c['kind']})" for c in created))
@@ -887,7 +980,8 @@ def serve(
887
980
  )
888
981
  typer.echo(f" LLM: {llm_source}")
889
982
  for t, p in tokens.items():
890
- typer.echo(f" token {t!r} → {p}")
983
+ role = " (operator)" if t in admin_tokens else ""
984
+ typer.echo(f" token {_mask_token(t)} → {p}{role}")
891
985
  if cors_origin:
892
986
  typer.echo(f" CORS: allowing {', '.join(cors_origin)}")
893
987
  if nats_url:
@@ -895,6 +989,14 @@ def serve(
895
989
  uvicorn.run(fastapi_app, host=host, port=port, log_level="warning")
896
990
 
897
991
 
992
+ def _mask_token(token: str) -> str:
993
+ """A token as the startup lines show it: enough to tell tokens apart, never the secret itself.
994
+ A terminal's scrollback and a process log are read by more people than the token's holder."""
995
+ if len(token) < 12:
996
+ return f"**** ({len(token)} chars)"
997
+ return f"{token[:4]}…{token[-2:]} ({len(token)} chars)"
998
+
999
+
898
1000
  @app.command()
899
1001
  def connect(
900
1002
  campaign_id: str,
@@ -938,12 +1040,14 @@ def connect(
938
1040
  "not_your_turn",
939
1041
  "proposal_opened",
940
1042
  "intent_rejected",
1043
+ "encounter_action_refused", # D-112: a fight waits on a different choice
941
1044
  }
942
1045
  # intent id → (its text, set when it settles). The server echoes the id as
943
1046
  # `intent_id`, so another player's identical text never settles ours. Only a server
944
1047
  # that has never echoed one (an older one) is matched by text; once one has, a frame
945
1048
  # without an id is another client's.
946
1049
  pending: dict[str, tuple[str, asyncio.Event]] = {}
1050
+ asked: set[str] = set() # the ids of this client's `choose` frames (D-113)
947
1051
  echoes = False
948
1052
  seen_day: int | None = None # the day the last beat_committed showed
949
1053
  checked: set[str] = set() # intents whose beat_checks were already printed
@@ -1027,6 +1131,17 @@ def connect(
1027
1131
  typer.echo(
1028
1132
  f"\n ✗ beat failed ({msg.get('intent', '')!r}): {msg['error']}"
1029
1133
  )
1134
+ elif kind == "choice_answered" and str(msg.get("intent_id")) in asked:
1135
+ left = ", ".join(c["id"] for c in msg.get("choices") or []) or "none"
1136
+ typer.echo(f" · answered {msg.get('choice_id')}; choices left: {left}")
1137
+ elif kind == "choice_refused" and str(msg.get("intent_id")) in asked:
1138
+ typer.echo(f" ! {msg.get('reason')}")
1139
+ elif kind == "encounter_action_refused" and ours:
1140
+ # every seat hears it; only the player who acted is shown it (review)
1141
+ for line in refusal_lines(
1142
+ msg["reason"], msg.get("legal_actions") or []
1143
+ ):
1144
+ typer.echo(line)
1030
1145
  elif kind == "intent_rejected":
1031
1146
  typer.echo(
1032
1147
  f" ✗ [{msg['participant_id']}] intent rejected: {msg['text']!r}"
@@ -1050,6 +1165,26 @@ def connect(
1050
1165
  break
1051
1166
  if intent in ("/quit", "/exit"):
1052
1167
  break
1168
+ if intent.startswith("/choose "): # D-113: /choose <id> <json answer>
1169
+ cid, _, raw = intent[8:].strip().partition(" ")
1170
+ try:
1171
+ ans = json.loads(raw) if raw.strip() else {}
1172
+ except ValueError:
1173
+ typer.echo("usage: /choose <choice_id> <json answer>")
1174
+ continue
1175
+ cid_req = uuid.uuid4().hex
1176
+ asked.add(cid_req)
1177
+ await ws.send(
1178
+ json.dumps(
1179
+ {
1180
+ "type": "choose",
1181
+ "choice_id": cid,
1182
+ "answer": ans,
1183
+ "id": cid_req,
1184
+ }
1185
+ )
1186
+ )
1187
+ continue
1053
1188
  if intent.startswith("/say "): # non-canon table-talk (D-38)
1054
1189
  await ws.send(json.dumps({"type": "table_talk", "text": intent[5:]}))
1055
1190
  elif intent.startswith("/vote "): # non-canon consensus vote (D-38)
@@ -1057,8 +1192,16 @@ def connect(
1057
1192
  elif intent:
1058
1193
  rid = uuid.uuid4().hex
1059
1194
  settled = asyncio.Event()
1060
- pending[rid] = (intent, settled)
1061
- await ws.send(json.dumps({"type": "intent", "text": intent, "id": rid}))
1195
+ act = parse_act(intent) # D-112: `/act <kind> [target]`, a fight turn
1196
+ if act is None and intent.split()[0] == "/act":
1197
+ typer.echo("usage: /act <action> [target]")
1198
+ continue
1199
+ text = intent[4:].strip() if act is not None else intent
1200
+ pending[rid] = (text, settled)
1201
+ frame: dict[str, Any] = {"type": "intent", "text": text, "id": rid}
1202
+ if act is not None:
1203
+ frame["action"] = act
1204
+ await ws.send(json.dumps(frame))
1062
1205
  waiting = asyncio.ensure_future(settled.wait())
1063
1206
  # a slow beat (a reasoning model's extraction) still settles well
1064
1207
  # inside this; past it, or if the server goes away, the prompt returns
@@ -1723,10 +1866,15 @@ def ruleset_list() -> None:
1723
1866
  rs = registry.resolve(rid)
1724
1867
  sheet = ", ".join(rs.sheet_schema().get("properties", {}))
1725
1868
  settings = rs.config_schema().get("properties", {})
1869
+ from uro_core.rulesets.base import spec_schema_of
1870
+
1871
+ spec_keys = ", ".join(spec_schema_of(rs).get("properties", {}))
1726
1872
  except Exception as exc:
1727
1873
  typer.echo(f"{rid} (can't list with default settings: {exc})")
1728
1874
  continue
1729
1875
  typer.echo(f"{rs.id}@{rs.version} sheet: {sheet}")
1876
+ if spec_keys: # what `--spec` may hold (D-112)
1877
+ typer.echo(f" spec: {spec_keys}")
1730
1878
  for key, spec in settings.items():
1731
1879
  what = spec.get("description", "")
1732
1880
  typer.echo(f" {key:<24} default {spec.get('default')!s:<5} {what}")
@@ -2007,13 +2155,36 @@ def campaign_new(
2007
2155
  branch_name: str = typer.Option(
2008
2156
  None, "--branch-name", help="with --own-branch: the new branch's name (default play-…)"
2009
2157
  ),
2158
+ spec: str = typer.Option(
2159
+ None, "--spec", help="the PC's build as JSON, or @file.json (the ruleset's spec, D-112)"
2160
+ ),
2161
+ ruleset_id: str = typer.Option(
2162
+ None, "--ruleset", help="this campaign's own ruleset (D-112; default: inherit)"
2163
+ ),
2164
+ ruleset_config: str = typer.Option(
2165
+ None, "--ruleset-config", help="this campaign's own settings as JSON, or @file.json"
2166
+ ),
2167
+ encounters: str = typer.Option(
2168
+ "auto", "--encounters", help="auto (a fight is one beat) | turns (pick each action)"
2169
+ ),
2170
+ holdings: str = typer.Option(
2171
+ None, "--holdings", help="what the PC starts holding: JSON [{name, data?}] or @file (D-113)"
2172
+ ),
2173
+ character: str = typer.Option(
2174
+ None, "--character", help="begin as a character the world suggests (`world characters`)"
2175
+ ),
2010
2176
  ) -> None:
2011
2177
  """Start a campaign on a branch, binding a PC (adopt an existing actor, or create one).
2012
- With --own-branch it gets a branch of its own, so it can later be removed alone (D-99)."""
2178
+ With --own-branch it gets a branch of its own, so it can later be removed alone (D-99).
2179
+ --ruleset / --ruleset-config give the campaign its own game (D-112); otherwise a fork plays
2180
+ the story it came from's, and any other branch its world's."""
2013
2181
 
2014
2182
  async def _run() -> None:
2015
- if (adopt is None) == (pc is None):
2016
- typer.echo("provide exactly one of --adopt <actor_id> or --pc <name>", err=True)
2183
+ if (adopt is None) == (pc is None and character is None):
2184
+ typer.echo(
2185
+ "provide exactly one of --adopt <actor_id> or --pc <name> (or --character)",
2186
+ err=True,
2187
+ )
2017
2188
  raise typer.Exit(1)
2018
2189
  store = build_store()
2019
2190
  await connect_store(store)
@@ -2037,33 +2208,29 @@ def campaign_new(
2037
2208
  typer.echo(f"error: {exc}", err=True)
2038
2209
  raise typer.Exit(1) from exc
2039
2210
  try: # from here on, a failure removes the playthrough's fork (D-100 review)
2040
- # Bind the WORLD's declared ruleset (docs/06, D-30): a PbtA world's campaign is
2041
- # played under uro_pbta, not the hard-coded default. ('' → registry default.)
2042
- pin = await store.world_ruleset(b.branch_id)
2043
- # with the world's settings
2044
- rs = await registry.resolve_for_branch(store, b.branch_id)
2045
- # Every PC needs a sheet so the mechanics gate can check it. A fresh PC gets one; an
2046
- # adopted actor is sheeted only if it lacks one (a re-adopted PC keeps its sheet).
2047
- pc_sheet = None
2048
- if pc is not None or (
2049
- adopt is not None and await store.get_sheet(b.branch_id, adopt) is None
2050
- ):
2051
- pc_sheet = _build_pc_sheet(rs)
2052
- ruleset_id = rs.id
2053
- campaign = await store.start_campaign(
2054
- w.world_id,
2055
- b.branch_id,
2056
- participant_id=participant,
2057
- adopt_actor_id=adopt,
2058
- new_pc_name=pc,
2059
- pc_sheet=pc_sheet,
2060
- starting_items=(
2061
- await starting_gear(store, b.branch_id) if pc is not None else None
2062
- ),
2063
- ruleset_id=ruleset_id,
2064
- ruleset_version=pin.version,
2065
- seed=seed,
2066
- )
2211
+ # The campaign's game and its PC's build (D-112), through the one core path the
2212
+ # server uses: the named ruleset, else a fork's story's, else the world's.
2213
+ from uro_core.characters import start_campaign
2214
+
2215
+ try:
2216
+ campaign = await start_campaign(
2217
+ store,
2218
+ w.world_id,
2219
+ b.branch_id,
2220
+ participant_id=participant,
2221
+ adopt_actor_id=adopt,
2222
+ new_pc_name=pc,
2223
+ spec=_json_option(spec, "--spec"),
2224
+ ruleset_id=ruleset_id,
2225
+ ruleset_config=_json_option(ruleset_config, "--ruleset-config"),
2226
+ seed=seed,
2227
+ encounters=encounters,
2228
+ holdings=_json_list_option(holdings, "--holdings"),
2229
+ character=character,
2230
+ )
2231
+ except (CharSpecError, ValueError, KeyError) as exc:
2232
+ _echo_refused(exc)
2233
+ raise typer.Exit(1) from exc
2067
2234
  except BaseException:
2068
2235
  if own_branch: # nothing half-made: the playthrough's fork goes too
2069
2236
  await store.delete_branch(b.branch_id)
@@ -2077,6 +2244,41 @@ def campaign_new(
2077
2244
  _run_async(_run)
2078
2245
 
2079
2246
 
2247
+ @campaign_app.command("encounter")
2248
+ def campaign_encounter(
2249
+ campaign_id: str,
2250
+ participant: str = typer.Option(None, "--participant", help="whose fight (default: any)"),
2251
+ ) -> None:
2252
+ """The fight waiting on a player's choice in a campaign that plays fights turn by turn
2253
+ (D-112): whose turn it is and the actions to send (`/act` in `uro play`/`uro connect`)."""
2254
+
2255
+ async def _run() -> None:
2256
+ store = build_store()
2257
+ await connect_store(store)
2258
+ try:
2259
+ c = await _campaign_or_exit(store, campaign_id)
2260
+ engine = Engine(
2261
+ store,
2262
+ build_router("stub", None),
2263
+ ruleset=await registry.resolve_for_campaign(store, c),
2264
+ )
2265
+ try:
2266
+ wait = await engine.fight_status(c, participant)
2267
+ except ChoiceRefused as exc:
2268
+ typer.echo(f"error: {exc}", err=True)
2269
+ raise typer.Exit(1) from exc
2270
+ finally:
2271
+ await store.close()
2272
+ if wait is None:
2273
+ typer.echo("(no fight is waiting on a choice)")
2274
+ return
2275
+ typer.echo(f"the fight {wait.encounter_id} waits on {wait.actor_id}:")
2276
+ for line in refusal_lines("", [a.model_dump() for a in wait.legal_actions])[1:]:
2277
+ typer.echo(line)
2278
+
2279
+ _run_async(_run)
2280
+
2281
+
2080
2282
  @campaign_app.command("time-skip")
2081
2283
  def campaign_time_skip(
2082
2284
  campaign_id: str,
@@ -2174,14 +2376,26 @@ def campaign_join(
2174
2376
  participant: str = typer.Option(..., "--participant", help="joining participant id"),
2175
2377
  adopt: str = typer.Option(None, "--adopt", help="adopt an existing actor as this PC"),
2176
2378
  pc: str = typer.Option(None, "--pc", help="create a fresh PC with this name"),
2379
+ spec: str = typer.Option(
2380
+ None, "--spec", help="the PC's build as JSON, or @file.json (the ruleset's spec, D-112)"
2381
+ ),
2382
+ holdings: str = typer.Option(
2383
+ None, "--holdings", help="what the PC starts holding: JSON [{name, data?}] or @file (D-113)"
2384
+ ),
2385
+ character: str = typer.Option(
2386
+ None, "--character", help="begin as a character the world suggests (`world characters`)"
2387
+ ),
2177
2388
  ) -> None:
2178
2389
  """Seat an ADDITIONAL participant on a live campaign, binding their OWN PC (docs/08, OQ-7) —
2179
2390
  the party-join path. Round-robin free-roam then rotates turns across the party (`uro serve`
2180
2391
  with multiple --token spins up a PartyArbiter)."""
2181
2392
 
2182
2393
  async def _run() -> None:
2183
- if (adopt is None) == (pc is None):
2184
- typer.echo("provide exactly one of --adopt <actor_id> or --pc <name>", err=True)
2394
+ if (adopt is None) == (pc is None and character is None):
2395
+ typer.echo(
2396
+ "provide exactly one of --adopt <actor_id> or --pc <name> (or --character)",
2397
+ err=True,
2398
+ )
2185
2399
  raise typer.Exit(1)
2186
2400
  store = build_store()
2187
2401
  await connect_store(store)
@@ -2190,23 +2404,23 @@ def campaign_join(
2190
2404
  if campaign is None:
2191
2405
  typer.echo(f"no such campaign: {campaign_id}", err=True)
2192
2406
  raise typer.Exit(1)
2193
- # Sheet a fresh PC (or an adopted actor lacking one) from the campaign's bound ruleset.
2194
- pc_sheet = None
2195
- if pc is not None or (
2196
- adopt is not None and await store.get_sheet(campaign.branch_id, adopt) is None
2197
- ):
2198
- pc_sheet = _build_pc_sheet(await registry.resolve_for_campaign(store, campaign))
2199
- actor = await store.bind_pc(
2200
- campaign_id,
2201
- participant,
2202
- adopt_actor_id=adopt,
2203
- new_pc_name=pc,
2204
- pc_sheet=pc_sheet,
2205
- starting_items=(
2206
- await starting_gear(store, campaign.branch_id) if pc is not None else None
2207
- ),
2208
- ruleset_id=campaign.ruleset_id,
2209
- )
2407
+ # Sheet the PC from --spec under the campaign's game (D-112), as the server does.
2408
+ from uro_core.characters import join_campaign
2409
+
2410
+ try:
2411
+ actor = await join_campaign(
2412
+ store,
2413
+ campaign,
2414
+ participant_id=participant,
2415
+ adopt_actor_id=adopt,
2416
+ new_pc_name=pc,
2417
+ spec=_json_option(spec, "--spec"),
2418
+ holdings=_json_list_option(holdings, "--holdings"),
2419
+ character=character,
2420
+ )
2421
+ except (CharSpecError, ValueError, KeyError) as exc:
2422
+ _echo_refused(exc)
2423
+ raise typer.Exit(1) from exc
2210
2424
  finally:
2211
2425
  await store.close()
2212
2426
  typer.echo(f"joined: participant {participant!r} → PC {actor}")
@@ -2214,6 +2428,256 @@ def campaign_join(
2214
2428
  _run_async(_run)
2215
2429
 
2216
2430
 
2431
+ character_app = typer.Typer(
2432
+ no_args_is_help=True,
2433
+ help="A participant's character: preview a build, show it, rebuild it before play (D-112).",
2434
+ )
2435
+ app.add_typer(character_app, name="character")
2436
+
2437
+
2438
+ @world_app.command("characters")
2439
+ def world_characters(world: str) -> None:
2440
+ """The player characters a world's author suggests (D-113): start as one with
2441
+ `campaign new --character <id>`."""
2442
+
2443
+ async def _run() -> None:
2444
+ store = build_store()
2445
+ await connect_store(store)
2446
+ try:
2447
+ w = await _world_or_exit(store, world)
2448
+ suggested = await store.world_characters(w.main_branch_id)
2449
+ finally:
2450
+ await store.close()
2451
+ if not suggested:
2452
+ typer.echo("(the world suggests no characters)")
2453
+ for c in suggested:
2454
+ tag = "" if c.get("provenance", "author") == "author" else f" [{c['provenance']}]"
2455
+ typer.echo(
2456
+ f"{c['id']} {c['name']}{tag}" + (f" — {c['line']}" if c.get("line") else "")
2457
+ )
2458
+
2459
+ _run_async(_run)
2460
+
2461
+
2462
+ @character_app.command("show")
2463
+ def character_show(
2464
+ campaign_id: str,
2465
+ participant: str = typer.Option(PARTICIPANT, "--participant", help="whose character"),
2466
+ ) -> None:
2467
+ """A participant's character: name, sheet, what it holds, and whether its build is open."""
2468
+
2469
+ async def _run() -> None:
2470
+ from uro_core.characters import own_character
2471
+
2472
+ store = build_store()
2473
+ await connect_store(store)
2474
+ try:
2475
+ c = await _campaign_or_exit(store, campaign_id)
2476
+ try:
2477
+ view = await own_character(store, c, participant)
2478
+ except KeyError as exc:
2479
+ typer.echo(f"error: {exc.args[0]}", err=True)
2480
+ raise typer.Exit(1) from exc
2481
+ finally:
2482
+ await store.close()
2483
+ state = "open until the first beat" if view.build_open else f"frozen: {view.frozen_reason}"
2484
+ typer.echo(f"{view.name} [{view.actor_id}] ruleset {view.ruleset} build {state}")
2485
+ typer.echo(json.dumps(view.sheet, indent=2, sort_keys=True))
2486
+ for c in view.choices: # D-113: what the ruleset left for this player to decide
2487
+ typer.echo(f" ? {c.id}: {c.prompt}")
2488
+ for o in c.options:
2489
+ typer.echo(f" {json.dumps(o, sort_keys=True)}")
2490
+ for h in view.holdings:
2491
+ typer.echo(
2492
+ f" holds {h['name']} [{h['item_id']}]" + (f" {h['data']}" if h["data"] else "")
2493
+ )
2494
+
2495
+ _run_async(_run)
2496
+
2497
+
2498
+ @character_app.command("preview")
2499
+ def character_preview(
2500
+ target: str = typer.Argument(..., help="a world (a new campaign's game) or a campaign id"),
2501
+ spec: str = typer.Option(None, "--spec", help="the build as JSON, or @file.json"),
2502
+ branch: str = typer.Option("main", "--branch", help="for a world: the branch to start on"),
2503
+ ruleset_id: str = typer.Option(None, "--ruleset", help="for a world: a campaign's own ruleset"),
2504
+ ruleset_config: str = typer.Option(
2505
+ None, "--ruleset-config", help="for a world: a campaign's own settings as JSON"
2506
+ ),
2507
+ ) -> None:
2508
+ """The sheet a build would make, or the ruleset's problems with it. Writes nothing."""
2509
+
2510
+ async def _run() -> None:
2511
+ from uro_core.characters import preview_character
2512
+
2513
+ store = build_store()
2514
+ await connect_store(store)
2515
+ try:
2516
+ data = _json_option(spec, "--spec")
2517
+ campaign = await store.get_campaign(target)
2518
+ try:
2519
+ if campaign is not None:
2520
+ preview = await preview_character(
2521
+ store, branch_id=campaign.branch_id, spec=data, campaign=campaign
2522
+ )
2523
+ else:
2524
+ w = await _world_or_exit(store, target)
2525
+ b = await store.get_branch_by_name(w.world_id, branch)
2526
+ if b is None:
2527
+ typer.echo(f"no such branch: {branch}", err=True)
2528
+ raise typer.Exit(1)
2529
+ preview = await preview_character(
2530
+ store,
2531
+ branch_id=b.branch_id,
2532
+ spec=data,
2533
+ ruleset_id=ruleset_id,
2534
+ ruleset_config=_json_option(ruleset_config, "--ruleset-config"),
2535
+ )
2536
+ except (ValueError, KeyError) as exc:
2537
+ _echo_refused(exc)
2538
+ raise typer.Exit(1) from exc
2539
+ finally:
2540
+ await store.close()
2541
+ if not preview.ok:
2542
+ _echo_refused(CharSpecError(preview.problems))
2543
+ raise typer.Exit(1)
2544
+ typer.echo(f"ok ({preview.ruleset}):")
2545
+ typer.echo(json.dumps(preview.sheet, indent=2, sort_keys=True))
2546
+
2547
+ _run_async(_run)
2548
+
2549
+
2550
+ @character_app.command("propose")
2551
+ def character_propose(
2552
+ target: str = typer.Argument(..., help="a world (a new campaign's game) or a campaign id"),
2553
+ description: str = typer.Argument(..., help="the player's words for their character"),
2554
+ provider: str = typer.Option("openai", help="stub | local | openai | anthropic"),
2555
+ model: str = typer.Option(None, help="model id for the worldsmith role"),
2556
+ branch: str = typer.Option("main", "--branch", help="for a world: the branch to start on"),
2557
+ ruleset_id: str = typer.Option(None, "--ruleset", help="for a world: a campaign's own ruleset"),
2558
+ ruleset_config: str = typer.Option(
2559
+ None, "--ruleset-config", help="for a world: a campaign's own settings as JSON"
2560
+ ),
2561
+ ) -> None:
2562
+ """Propose a build from a description through the model, checked like a preview (D-112). Saves
2563
+ nothing: pass the printed spec to `campaign new|join --spec`."""
2564
+
2565
+ async def _run() -> None:
2566
+ from uro_core.characters import propose_character
2567
+ from uro_core.errors import ProviderError
2568
+
2569
+ store = build_store()
2570
+ await connect_store(store)
2571
+ try:
2572
+ campaign = await store.get_campaign(target)
2573
+ if campaign is not None:
2574
+ branch_id = campaign.branch_id
2575
+ else:
2576
+ w = await _world_or_exit(store, target)
2577
+ b = await store.get_branch_by_name(w.world_id, branch)
2578
+ if b is None:
2579
+ typer.echo(f"no such branch: {branch}", err=True)
2580
+ raise typer.Exit(1)
2581
+ branch_id = b.branch_id
2582
+ router = build_router(provider, model)
2583
+ router.recorder = store.record_llm_call
2584
+ try:
2585
+ proposal = await propose_character(
2586
+ store,
2587
+ router,
2588
+ branch_id=branch_id,
2589
+ description=description,
2590
+ campaign=campaign,
2591
+ ruleset_id=ruleset_id,
2592
+ ruleset_config=_json_option(ruleset_config, "--ruleset-config"),
2593
+ )
2594
+ except (ProviderError, ValueError, KeyError) as exc:
2595
+ _echo_refused(exc)
2596
+ raise typer.Exit(1) from exc
2597
+ finally:
2598
+ await store.close()
2599
+ typer.echo(
2600
+ f"{'ok' if proposal.ok else 'not buildable'} ({proposal.ruleset})"
2601
+ + (f": {proposal.name}" if proposal.name else "")
2602
+ )
2603
+ typer.echo(json.dumps(proposal.spec, indent=2, sort_keys=True))
2604
+ if not proposal.ok:
2605
+ _echo_refused(CharSpecError(proposal.problems))
2606
+ raise typer.Exit(1)
2607
+
2608
+ _run_async(_run)
2609
+
2610
+
2611
+ @character_app.command("choose")
2612
+ def character_choose(
2613
+ campaign_id: str,
2614
+ choice_id: str,
2615
+ answer: str = typer.Argument(..., help='the answer as JSON, e.g. \'{"ability": "CON"}\''),
2616
+ participant: str = typer.Option(PARTICIPANT, "--participant", help="whose character"),
2617
+ ) -> None:
2618
+ """Answer a choice the ruleset left on a character (D-113): `uro character show` lists them."""
2619
+
2620
+ async def _run() -> None:
2621
+ from uro_core.characters import ChoiceError, answer_character_choice
2622
+
2623
+ store = build_store()
2624
+ await connect_store(store)
2625
+ try:
2626
+ c = await _campaign_or_exit(store, campaign_id)
2627
+ try:
2628
+ view = await answer_character_choice(
2629
+ store, c, participant, choice_id, _json_option(answer, "answer") or {}
2630
+ )
2631
+ except (CharSpecError, ChoiceError, KeyError) as exc:
2632
+ _echo_refused(exc)
2633
+ raise typer.Exit(1) from exc
2634
+ finally:
2635
+ await store.close()
2636
+ left = ", ".join(ch.id for ch in view.choices) or "none"
2637
+ typer.echo(f"answered; choices left: {left}")
2638
+
2639
+ _run_async(_run)
2640
+
2641
+
2642
+ @character_app.command("rebuild")
2643
+ def character_rebuild(
2644
+ campaign_id: str,
2645
+ participant: str = typer.Option(PARTICIPANT, "--participant", help="whose character"),
2646
+ spec: str = typer.Option(None, "--spec", help="the new build as JSON, or @file.json"),
2647
+ name: str = typer.Option(None, "--name", help="a new name"),
2648
+ holdings: str = typer.Option(
2649
+ None, "--holdings", help="replace the chosen holdings: JSON [{name, data?}] or @file"
2650
+ ),
2651
+ ) -> None:
2652
+ """Replace a character's build, name and/or chosen holdings before the story starts (until the
2653
+ first beat after it was bound); after that only play changes a character."""
2654
+
2655
+ async def _run() -> None:
2656
+ from uro_core.characters import CharacterFrozen, rebuild_character
2657
+
2658
+ store = build_store()
2659
+ await connect_store(store)
2660
+ try:
2661
+ c = await _campaign_or_exit(store, campaign_id)
2662
+ try:
2663
+ view = await rebuild_character(
2664
+ store,
2665
+ c,
2666
+ participant,
2667
+ spec=_json_option(spec, "--spec"),
2668
+ name=name,
2669
+ holdings=_json_list_option(holdings, "--holdings"),
2670
+ )
2671
+ except (CharSpecError, CharacterFrozen, KeyError) as exc:
2672
+ _echo_refused(exc)
2673
+ raise typer.Exit(1) from exc
2674
+ finally:
2675
+ await store.close()
2676
+ typer.echo(f"rebuilt: {view.name} [{view.actor_id}]")
2677
+
2678
+ _run_async(_run)
2679
+
2680
+
2217
2681
  @app.command("dry-run")
2218
2682
  def dry_run(
2219
2683
  campaign_id: str,
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes