From 9606899b10e992ee895a2308ffbbf86b52dad65a Mon Sep 17 00:00:00 2001 From: kimi Date: Fri, 20 Mar 2026 23:17:09 -0400 Subject: [PATCH] refactor: extract _read_message_input and _resolve_session_id from chat() Break up the 72-line chat() command into a thin orchestrator that delegates stdin reading to _read_message_input() and session ID resolution to _resolve_session_id(). Fixes #627 Co-Authored-By: Claude Opus 4.6 --- src/timmy/cli.py | 58 +++++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 23 deletions(-) diff --git a/src/timmy/cli.py b/src/timmy/cli.py index 51051128..fd4268c9 100644 --- a/src/timmy/cli.py +++ b/src/timmy/cli.py @@ -37,6 +37,39 @@ def _is_interactive() -> bool: return hasattr(sys.stdin, "isatty") and sys.stdin.isatty() +def _read_message_input(message: list[str]) -> str: + """Join CLI args into a message, reading from stdin when requested. + + Returns the final message string. Raises ``typer.Exit(1)`` when + stdin is explicitly requested (``-``) but empty. + """ + message_str = " ".join(message) + + if message_str == "-" or not _is_interactive(): + try: + stdin_content = sys.stdin.read().strip() + except (KeyboardInterrupt, EOFError): + stdin_content = "" + if stdin_content: + message_str = stdin_content + elif message_str == "-": + typer.echo("No input provided via stdin.", err=True) + raise typer.Exit(1) + + return message_str + + +def _resolve_session_id(session_id: str | None, new_session: bool) -> str: + """Return the effective session ID for a chat invocation.""" + import uuid + + if session_id is not None: + return session_id + if new_session: + return str(uuid.uuid4()) + return _CLI_SESSION_ID + + def _prompt_interactive(req, tool_name: str, tool_args: dict) -> None: """Display tool details and prompt the human for approval.""" description = format_action_description(tool_name, tool_args) @@ -179,29 +212,8 @@ def chat( Read from stdin by passing "-" as the message or piping input. """ - import uuid - - # Join multiple arguments into a single message string - message_str = " ".join(message) - - # Handle stdin input if "-" is passed or stdin is not a tty - if message_str == "-" or not _is_interactive(): - try: - stdin_content = sys.stdin.read().strip() - except (KeyboardInterrupt, EOFError): - stdin_content = "" - if stdin_content: - message_str = stdin_content - elif message_str == "-": - typer.echo("No input provided via stdin.", err=True) - raise typer.Exit(1) - - if session_id is not None: - pass # use the provided value - elif new_session: - session_id = str(uuid.uuid4()) - else: - session_id = _CLI_SESSION_ID + message_str = _read_message_input(message) + session_id = _resolve_session_id(session_id, new_session) timmy = create_timmy(backend=backend, session_id=session_id) # Use agent.run() so we can intercept paused runs for tool confirmation. -- 2.43.0