Adds GET /agents fetch + ListView picker for bare `--new` (TUI mode without --agent). Three in-place amendments: - ratatoskr.sessions: new `list_agents()` + `AgentInfo` frozen dataclass with omit-when-null/empty defaults mirroring SessionInfo's INV-001/INV-002 origin-conditional pattern. Non-200 responses raise the existing SessionApiFailed (no new exception). - ratatoskr.cli: `_parse_args` softens `--agent` from absolute to mode-conditional — required for `--send --new`, optional for bare `--new`, forbidden with `--session` (unchanged INV-004). - ratatoskr.tui: new `AgentPickerApp(App[str | None])` — separate Textual App (not Screen-within-RatatoskrApp) so list_agents errors land on real stderr before any alt-screen opens (preserves issue #6's INV-001). `_resolve_then_run` gains a pre-create branch: fetch agents → empty list → exit 13; non-200 → exit 20; network error → exit 21; picker dismissed → exit 0; otherwise thread chosen agent_id into create_session. Contract: docs/contracts/issues/8.contract.md (drift-check clean). Tests: +18 (227 total, was 209). Live smoke against personal Worldtree (:8081) returned 12 agents; programmatic picker drive auto-picked lofn and created a real session with `end_user_id="ratatoskr-tui"`.
21 KiB
contract_version, target_module, scope, depends_on, used_by, language, complexity, estimated_loc, confidence, assumptions, open_questions, prd, dependencies
| contract_version | target_module | scope | depends_on | used_by | language | complexity | estimated_loc | confidence | assumptions | open_questions | prd | dependencies | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2.1 | ratatoskr.sessions | Startup agent picker for TUI mode when `--new` is passed without `--agent`. Small surface change distributed across three existing modules via in-place contract amendments: `ratatoskr.sessions` gains `list_agents()` (GET /agents) returning `list[AgentInfo]` (new frozen dataclass with omit-when-null defaults mirroring SessionInfo's INV-001/INV-002 pattern); `ratatoskr.cli` softens `--agent` requirement from absolute to mode-conditional (`--send --new` still requires it; bare `--new` accepts None; `--session` still forbids it); `ratatoskr.tui._resolve_then_run` gains a pre-create branch that, when `args.new and args.agent_id is None`, calls `list_agents(client)` then runs a dedicated tiny `AgentPickerApp` (separate Textual `App` instance, opens before the main `RatatoskrApp`) whose `run_async()` returns the chosen `agent_id` (or `None` on Esc/Ctrl-D for clean exit). No new files; no wire-level surface change beyond the new endpoint hit. Composes naturally with #5 (`--end-user-id`): both thread through `ParsedArgs` before any App opens. |
|
|
python | low | 200 | 0.85 |
|
|
|
|
Startup agent picker — GET /agents when --new without --agent (TUI)
Context
Today, ratatoskr --new requires --agent <id>. If omitted, _parse_args
raises UsageError("--agent is required when --new is passed"). That's
correct for --send --new (non-interactive — can't prompt) but wrong
for the TUI (operator may not know which agents are available, would
prefer to pick from a list at startup).
Worldtree's spec §832 exposes GET /agents. The endpoint returns a flat
JSON array; required fields are agent_id, name, description;
optional fields (version, capabilities, supported_models,
persona_traits, ui_hints) follow omit-when-null/empty rules. No
pagination, no filters, no special scope. Worldtree-dev confirmed
2026-05-23: Tier 1 baseline auth covers it.
This issue threads a small surface change through three existing modules in-place — no new files apart from this contract.
Data flow
Input:
httpx.AsyncClient(caller-owned, base_url + bearer auth on the client).- No request body, no query params.
Output (list_agents):
list[AgentInfo]— one entry per available agent, in server-declared order.
Output (AgentPickerApp.run_async()):
str | None— chosenagent_id, orNoneon Esc/Ctrl-D dismissal.
Public surface (ratatoskr.sessions amendment)
@dataclass(frozen=True)
class AgentInfo:
"""One agent's metadata from GET /agents.
INV-005: Required fields (`agent_id`, `name`, `description`) take the
response value verbatim. Optional fields default to None (`version`)
or an empty container (`capabilities`, `supported_models`,
`persona_traits`, `ui_hints`) when omitted from the server response,
mirroring SessionInfo's INV-001/INV-002 origin-conditional pattern.
"""
agent_id: str
name: str
description: str
version: str | None
capabilities: list[str]
supported_models: list[str]
persona_traits: dict[str, Any]
ui_hints: dict[str, Any]
async def list_agents(client: httpx.AsyncClient) -> list[AgentInfo]:
"""GET /agents → list of available agents. See contract FN list_agents."""
Functions
FN list_agents
FN list_agents(client: httpx.AsyncClient) -> list[AgentInfo]
BRIEF: GET /agents → list of available agents. No pagination, no filters.
PRE-001: client is not None.
STEPS:
1. resp = await client.get("/agents")
2. IF resp.status_code != 200:
raise SessionApiFailed(status=resp.status_code, body=resp.content)
3. body = resp.json() # expected: list[dict]
4. items = [
AgentInfo(
agent_id = item["agent_id"],
name = item["name"],
description = item["description"],
version = item.get("version"),
capabilities = item.get("capabilities") or [],
supported_models = item.get("supported_models") or [],
persona_traits = item.get("persona_traits") or {},
ui_hints = item.get("ui_hints") or {},
)
for item in body
]
5. RETURN items
POST-001: every item in the return list has required fields populated.
POST-002: optional fields default to None / [] / {} when absent from the response.
ERROR_ROUTING:
- 200 with non-list body → KeyError / TypeError propagates (server bug; not handled here).
- non-200 → SessionApiFailed(status=N, body=resp.content)
- httpx.RequestError → propagates (network failure; caller handles).
TESTS:
- test_happy_full_shape: 200 + spec's full-shape mimir example → AgentInfo with all fields populated.
- test_happy_minimum_shape: 200 + spec's minimum-shape "minimal" example → AgentInfo with required + defaulted optional.
- test_happy_multi_agent: 200 + array of 3 agents → list of 3 AgentInfo in order.
- test_happy_empty: 200 + [] → empty list (no error).
- test_omit_capabilities: 200 + agent missing capabilities → AgentInfo.capabilities == [].
- test_omit_persona_traits: 200 + agent missing persona_traits → AgentInfo.persona_traits == {}.
- test_omit_ui_hints: 200 + agent missing ui_hints → AgentInfo.ui_hints == {}.
- test_500_raises: 500 → SessionApiFailed with status=500.
- test_401_raises: 401 → SessionApiFailed with status=401.
CLI surface change (ratatoskr.cli amendment)
_parse_args STEP 3, currently:
if ns.new and not ns.agent:
raise UsageError("--agent is required when --new is passed")
becomes:
if ns.new and not ns.agent:
if ns.send is not None:
# --send --new mode: non-interactive, cannot prompt for choice.
raise UsageError("--agent is required with --new in --send mode")
# else: bare --new (TUI mode) — agent_id stays None, TUI runs picker.
INV-004 (--session + --agent mutual exclusion) is unchanged. Existing
--send --new smoke flows that pass --agent continue to work unchanged.
ERROR_ROUTING (cli):
--send --newwithout--agent→UsageError→ exit 10 (unchanged from today).- bare
--newwithout--agent→ParsedArgs.agent_id=None, TUI handles.
TESTS (additions to test_cli.py):
- test_parse_send_new_without_agent_raises:
--send "hi" --new(no --agent) → UsageError. - test_parse_bare_new_without_agent_accepted:
--new(no --agent, no --send) → ParsedArgs with agent_id=None. - test_parse_bare_new_with_agent_accepted:
--new --agent mimir→ unchanged behavior, agent_id="mimir".
TUI surface change (ratatoskr.tui amendment)
New: AgentPickerApp
class AgentPickerApp(App[str | None]):
"""Single-purpose picker App. Opens before RatatoskrApp.
`run_async()` returns the chosen agent_id (str) or None on Esc/Ctrl-D.
"""
BINDINGS: ClassVar[list[Binding]] = [
Binding("enter", "pick", "Pick", priority=True),
Binding("escape", "dismiss", "Cancel", priority=True),
Binding("ctrl+d", "dismiss", "Cancel", priority=True),
Binding("ctrl+c", "dismiss", "Cancel", priority=True),
]
def __init__(self, agents: list[AgentInfo]) -> None:
super().__init__()
assert agents # PRE-002 — caller guarantees non-empty
self.agents = agents
def compose(self) -> ComposeResult:
yield Header()
yield Static("Pick an agent for the new session:", id="picker-prompt")
yield ListView(
*[
ListItem(Label(f"{a.agent_id} · {a.name} — {a.description}"))
for a in self.agents
],
id="agent-list",
)
yield Footer()
async def on_mount(self) -> None:
self.query_one("#agent-list", ListView).focus()
def action_pick(self) -> None:
lv = self.query_one("#agent-list", ListView)
idx = lv.index
if idx is None:
return # no row highlighted; ignore
self.exit(self.agents[idx].agent_id)
def action_dismiss(self) -> None:
self.exit(None)
Modified: _resolve_then_run
Insert a pre-create branch between the async with httpx.AsyncClient(...)
and the existing if args.new: block:
async def _resolve_then_run(args: ParsedArgs) -> int:
assert isinstance(args, ParsedArgs) and args.send_content is None
async with httpx.AsyncClient(...) as client:
# NEW (issue #8): startup agent picker when --new without --agent.
chosen_agent_id: str | None = args.agent_id
if args.new and args.agent_id is None:
try:
agents = await list_agents(client)
except SessionApiFailed as exc:
sys.stderr.write(
f"[session_api_failed] status={exc.status} body={exc.body!r}\n"
)
return 20
except (httpx.ConnectError, httpx.ReadTimeout, httpx.TransportError) as exc:
sys.stderr.write(f"[network_error] {type(exc).__name__}: {exc}\n")
return 21
if not agents:
sys.stderr.write("[no_agents] server returned empty agent list\n")
return 13
picker = AgentPickerApp(agents)
chosen_agent_id = await picker.run_async()
if chosen_agent_id is None:
return 0 # Esc/Ctrl-D — clean exit, no session created
# EXISTING: create_session OR re-use --session id
if args.new:
assert chosen_agent_id is not None
try:
info = await create_session(
client, chosen_agent_id, end_user_id=args.end_user_id
)
...
else:
...
app = RatatoskrApp(args, session_id=session_id, agent_id=agent_id, client=client)
...
ERROR_ROUTING (tui startup)
| Failure | Stderr label | Exit |
|---|---|---|
list_agents → SessionApiFailed |
[session_api_failed] status=N body=B |
20 |
list_agents → network error |
[network_error] T: M |
21 |
empty agent list (GET /agents returns []) |
[no_agents] server returned empty agent list |
13 (new) |
| picker Esc/Ctrl-D dismissal | (none — clean exit) | 0 |
create_session post-pick → AgentNotFound |
[agent_not_found] agent_id=X |
12 (unchanged from #4) |
INV: exit code 13 is new (no-agents). Previously unused — does not collide
with any existing exit code in _resolve_then_run or _amain.
TESTS (additions to test_tui.py)
- test_picker_happy_path: list_agents returns 2 agents; AgentPickerApp opens; user picks index 0; chosen agent_id flows into create_session; main App opens.
- test_picker_esc_clean_exit: list_agents returns 2 agents; picker opens; user presses Esc; _resolve_then_run returns 0; create_session NOT called; RatatoskrApp NOT opened.
- test_picker_skipped_when_agent_id_provided: bare --new --agent mimir → list_agents NOT called; picker NOT opened; create_session called with "mimir".
- test_picker_skipped_when_session_mode: --session s-1 → list_agents NOT called; picker NOT opened; no create_session.
- test_picker_list_agents_session_api_failed: list_agents raises SessionApiFailed → stderr [session_api_failed]; exit 20; picker NOT opened; create_session NOT called.
- test_picker_list_agents_network_error: list_agents raises ConnectError → stderr [network_error]; exit 21.
- test_picker_empty_list: list_agents returns [] → stderr [no_agents]; exit 13; picker NOT opened; create_session NOT called.
- test_agent_picker_app_renders_rows: AgentPickerApp with 3 agents → ListView has 3 ListItem children with expected text.
- test_agent_picker_app_pick_returns_agent_id: simulate Enter on highlighted row → exit value == agents[idx].agent_id.
- test_agent_picker_app_dismiss_returns_none: simulate Esc → exit value is None.
Invariants
- INV-005:
AgentInfofield defaults are origin-conditional (mirrors INV-001/002 from #2). Required → verbatim; optional → None / [] / {}. - INV-006:
list_agentsfailure modes route throughSessionApiFailedonly — no new exception type introduced. - INV-007: Picker is a separate App, opened by
_resolve_then_runBEFORERatatoskrApp. Preserves issue #6's stderr-error invariant forlist_agentsfailures. - INV-008:
--agentCLI requirement is mode-conditional: required only when--send --new; bare--newaccepts None;--sessionalways forbids it. - INV-009: Picker dismissal (Esc/Ctrl-D) returns clean exit 0; no session created server-side.
- INV-010: Empty agent list is a clean stderr exit (code 13), not an open picker.
- INV-011: Single-agent response still opens the picker — no auto-select.
- INV-012: Two alt-screen cycles (picker + main App) is the explicit architectural tradeoff for preserving INV-007.