|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: MIT-0 |
| 3 | + |
| 4 | +""" |
| 5 | +Chat command for idp-cli. |
| 6 | +
|
| 7 | +Runs the Agent Companion Chat orchestrator locally, providing interactive |
| 8 | +access to Analytics, Error Analyzer, and other agents from the terminal. |
| 9 | +""" |
| 10 | + |
| 11 | +import asyncio |
| 12 | +import logging |
| 13 | +import re |
| 14 | +import uuid |
| 15 | +from typing import Optional |
| 16 | + |
| 17 | +from rich.console import Console |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | +console = Console() |
| 21 | + |
| 22 | + |
| 23 | +def run_chat( |
| 24 | + stack_name: str, |
| 25 | + region: Optional[str] = None, |
| 26 | + prompt: Optional[str] = None, |
| 27 | + enable_code_intelligence: bool = False, |
| 28 | +): |
| 29 | + """ |
| 30 | + Run the chat command — interactive REPL or single-shot. |
| 31 | +
|
| 32 | + Args: |
| 33 | + stack_name: CloudFormation stack name |
| 34 | + region: AWS region |
| 35 | + prompt: If provided, run single-shot and exit |
| 36 | + """ |
| 37 | + console.print("[bold blue]IDP Agent Chat[/bold blue]") |
| 38 | + console.print(f"[dim]Stack: {stack_name}[/dim]") |
| 39 | + console.print() |
| 40 | + |
| 41 | + # Use IDPClient to access chat processor internals |
| 42 | + from idp_sdk import IDPClient |
| 43 | + |
| 44 | + # Suppress all logging — agents are very chatty |
| 45 | + logging.disable(logging.CRITICAL) |
| 46 | + |
| 47 | + try: |
| 48 | + client = IDPClient(stack_name=stack_name, region=region) |
| 49 | + processor = client.chat._get_processor() |
| 50 | + |
| 51 | + with console.status("[bold]Discovering stack resources..."): |
| 52 | + processor._setup_env() |
| 53 | + |
| 54 | + session_id = f"cli-{uuid.uuid4().hex[:12]}" |
| 55 | + |
| 56 | + with console.status("[bold]Initializing agents..."): |
| 57 | + processor._ensure_orchestrator( |
| 58 | + session_id, |
| 59 | + enable_code_intelligence=enable_code_intelligence, |
| 60 | + ) |
| 61 | + |
| 62 | + # Show available agents |
| 63 | + from idp_common.agents.factory import agent_factory |
| 64 | + |
| 65 | + agents = agent_factory.list_available_agents() |
| 66 | + agent_names = [a["agent_name"] for a in agents] |
| 67 | + console.print( |
| 68 | + f"[green]✓ Ready[/green] [dim]Agents: {' · '.join(agent_names)}[/dim]" |
| 69 | + ) |
| 70 | + console.print("[dim]Type /quit to exit[/dim]\n") |
| 71 | + |
| 72 | + if prompt: |
| 73 | + _handle_prompt(processor._orchestrator, prompt) |
| 74 | + return |
| 75 | + |
| 76 | + # Interactive REPL — reuse a single event loop for the session |
| 77 | + loop = asyncio.new_event_loop() |
| 78 | + try: |
| 79 | + while True: |
| 80 | + try: |
| 81 | + user_input = console.input("[bold cyan]You:[/bold cyan] ") |
| 82 | + except (EOFError, KeyboardInterrupt): |
| 83 | + console.print("\n[dim]Goodbye.[/dim]") |
| 84 | + break |
| 85 | + |
| 86 | + text = user_input.strip() |
| 87 | + if not text: |
| 88 | + continue |
| 89 | + if text.lower() in ("/quit", "/exit", "quit", "exit"): |
| 90 | + console.print("[dim]Goodbye.[/dim]") |
| 91 | + break |
| 92 | + |
| 93 | + _handle_prompt(processor._orchestrator, text, loop=loop) |
| 94 | + finally: |
| 95 | + loop.close() |
| 96 | + finally: |
| 97 | + # Restore logging so callers aren't permanently silenced |
| 98 | + logging.disable(logging.NOTSET) |
| 99 | + |
| 100 | + |
| 101 | +def _handle_prompt(orchestrator, prompt: str, loop=None): |
| 102 | + """Send a prompt to the orchestrator and stream the response.""" |
| 103 | + console.print() |
| 104 | + |
| 105 | + if loop is not None: |
| 106 | + # Reuse persistent loop (interactive REPL) |
| 107 | + try: |
| 108 | + loop.run_until_complete(_stream_response(orchestrator, prompt)) |
| 109 | + except Exception as e: |
| 110 | + console.print(f"[red]Error: {e}[/red]") |
| 111 | + else: |
| 112 | + # One-shot mode — create and tear down a loop |
| 113 | + one_shot = asyncio.new_event_loop() |
| 114 | + try: |
| 115 | + one_shot.run_until_complete(_stream_response(orchestrator, prompt)) |
| 116 | + except Exception as e: |
| 117 | + console.print(f"[red]Error: {e}[/red]") |
| 118 | + finally: |
| 119 | + one_shot.close() |
| 120 | + |
| 121 | + console.print() |
| 122 | + |
| 123 | + |
| 124 | +async def _stream_response(orchestrator, prompt: str) -> str: |
| 125 | + """Stream orchestrator response, printing chunks as they arrive.""" |
| 126 | + full_text = "" |
| 127 | + displayed = "" |
| 128 | + current_subagent = None |
| 129 | + |
| 130 | + async for event in orchestrator.stream_async(prompt): |
| 131 | + if "data" in event: |
| 132 | + full_text += event["data"] |
| 133 | + clean = re.sub( |
| 134 | + r"<thinking>.*?</thinking>", "", full_text, flags=re.DOTALL |
| 135 | + ).strip() |
| 136 | + if len(clean) > len(displayed): |
| 137 | + new = clean[len(displayed) :] |
| 138 | + console.print(new, end="", highlight=False) |
| 139 | + displayed = clean |
| 140 | + |
| 141 | + elif "current_tool_use" in event: |
| 142 | + tool_name = event["current_tool_use"].get("name", "") |
| 143 | + if tool_name and tool_name != current_subagent: |
| 144 | + current_subagent = tool_name |
| 145 | + display_name = tool_name.replace("_agent", "").replace("_", " ").title() |
| 146 | + console.print(f"\n[dim]⟶ {display_name}[/dim]", highlight=False) |
| 147 | + |
| 148 | + console.print() |
| 149 | + return displayed |
0 commit comments