from langchain_core.messages import HumanMessage, AIMessage, ToolMessage from langgraph.graph import StateGraph, START, END from langgraph.graph.message import add_messages from typing import Annotated, Literal from typing_extensions import TypedDict from langgraph.checkpoint.memory import MemorySaver from rich.console import Console from rich.panel import Panel from rich.markdown import Markdown from ..backend import llm from .todo_prompt import todo_prompt_template, review_todo_prompt_template from core.tools.file_operations import ( read_file, write_file, replace_in_file, delete_in_file, delete_file, copy_file, move_file, create_directory, delete_directory, list_directory, get_file_info, ) # Keep an ordered list and map of tools for binding and dispatching AVAILABLE_TOOLS_LIST = [ read_file, write_file, replace_in_file, delete_in_file, delete_file, copy_file, move_file, create_directory, delete_directory, list_directory, get_file_info, ] TOOLS_MAP = {tool.name: tool for tool in AVAILABLE_TOOLS_LIST} console = Console() # --------------------------------------------------------------------------- # State # --------------------------------------------------------------------------- class AgentState(TypedDict): messages: Annotated[list, add_messages] todo_list: list[str] task: str current_step: int done: bool awaiting_human_feedback: bool # "plan_task" when plan_task triggered the pause; "" otherwise. feedback_source: str # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _parse_todo_list(raw: str) -> list[str]: """ Parse a newline- or numbered-list LLM response into a clean list of steps. Falls back to a single-item list on failure. """ lines = [] for line in raw.splitlines(): line = line.strip() if not line: continue # Skip obvious markdown headers, dividers, and conversational filler if line.startswith("```") or line.startswith("===") or line.startswith("---") or line.lower().replace("*", "") in ["to-do list", "execution"]: continue # Strip bullet prefixes: "- " / "* " for prefix in ("-", "*"): if line.startswith(prefix): line = line[len(prefix):].strip() break else: # Strip numeric prefixes: "1." / "2)" parts = line.split(".", 1) if len(parts) == 2 and parts[0].strip().isdigit(): line = parts[1].strip() else: parts = line.split(")", 1) if len(parts) == 2 and parts[0].strip().isdigit(): line = parts[1].strip() if line: lines.append(line) return lines if lines else [raw.strip()] def _build_history_text(messages: list) -> str: """Render the message list as a readable conversation string.""" return "\n".join( f"{'User' if isinstance(m, HumanMessage) else 'Assistant'}: {m.content}" for m in messages ) # --------------------------------------------------------------------------- # Nodes # --------------------------------------------------------------------------- def plan_task(state: AgentState) -> dict: """ Ask the LLM to produce (or refine) a to-do list for the user's task. The full conversation history is included so that any prior human feedback rounds are visible. If the LLM still needs clarification it responds with: NEEDS_FEEDBACK: which routes the graph to get_human_feedback -> back to plan_task. Only once the LLM is satisfied does the graph proceed to review_plan. """ messages = state["messages"] if not messages: return { "todo_list": ["No task provided"], "task": "", "current_step": 0, "done": True, "awaiting_human_feedback": False, "feedback_source": "", } history_text = _build_history_text(messages) prompt = ( f"{todo_prompt_template}\n\n" f"Conversation so far:\n{history_text}\n\n" "If anything is unclear and you need human clarification before you can " "produce a reliable plan, respond with exactly:\n" " NEEDS_FEEDBACK: \n" "followed by your best-effort partial todo list (one step per line).\n" "Otherwise just return the final todo list, one step per line. " "IMPORTANT: Output ONLY the list items. Do not include markdown headers, bold text, or conversational filler." ) response = llm.invoke(prompt) raw = response.content if hasattr(response, "content") else str(response) awaiting = False feedback_question = "" if raw.lstrip().startswith("NEEDS_FEEDBACK:"): first_line, _, rest = raw.partition("\n") feedback_question = first_line.replace("NEEDS_FEEDBACK:", "").strip() awaiting = True raw = rest todo_list = _parse_todo_list(raw) if raw.strip() else state.get("todo_list", []) # Preserve the original user task from the first human message. task = next((m.content for m in messages if isinstance(m, HumanMessage)), "") todo_str = "\n".join(f"{i+1}. {step}" for i, step in enumerate(todo_list)) console.print(Panel(todo_str, title="[bold cyan]📝 Initial To-Do List[/bold cyan]", border_style="cyan")) if awaiting: console.print(f"[bold red]❓ Needs clarification:[/bold red] {feedback_question}") return { "todo_list": todo_list, "task": task, "current_step": 0, "done": False, "awaiting_human_feedback": awaiting, "feedback_source": "plan_task" if awaiting else "", **( { "messages": [ AIMessage( content=f"I need some clarification before I can plan: {feedback_question}" ) ] } if awaiting else {} ), } def review_plan(state: AgentState) -> dict: """ Enrich and finalise the plan using the todo list, task description, and any human feedback collected during the plan_task loop. This node does NOT trigger another feedback loop — it goes straight to execute_task once done. """ todo_list = state["todo_list"] task = state["task"] history_text = _build_history_text(state["messages"]) prompt = ( f"{review_todo_prompt_template}\n\n" f"Original task: {task}\n\n" f"Conversation history (including any human feedback):\n{history_text}\n\n" f"Current to-do list:\n" + "\n".join(f"{i+1}. {step}" for i, step in enumerate(todo_list)) + "\n\nReview and improve the todo list based on all context above. " "Return ONLY the final todo list, one step per line. Do not include headers like '**To-Do List**'." ) response = llm.invoke(prompt) raw = response.content if hasattr(response, "content") else str(response) updated_todo = _parse_todo_list(raw) if raw.strip() else todo_list todo_str = "\n".join(f"{i+1}. {step}" for i, step in enumerate(updated_todo)) console.print(Panel(todo_str, title="[bold green]📋 Reviewed To-Do List[/bold green]", border_style="green")) return { "todo_list": updated_todo, "awaiting_human_feedback": False, "feedback_source": "", } def get_human_feedback(state: AgentState) -> dict: """ Interrupt node: LangGraph pauses here so the user can reply. When the graph is resumed the new HumanMessage is already in state["messages"] via the interrupt mechanism — we just clear the flag and let routing decide where to go next (back to plan_task). """ messages = state["messages"] last = messages[-1] if messages else None if last and isinstance(last, HumanMessage): console.print(f"[bold green]👤 Human feedback received:[/bold green] {last.content}") return {"awaiting_human_feedback": False} def execute_task(state: AgentState) -> dict: """Execute the current todo step.""" current_step = state["current_step"] todo_list = state["todo_list"] if current_step >= len(todo_list): return {"done": True} step_description = todo_list[current_step] console.print(f"\n[bold magenta]⚙️ Executing Step {current_step + 1}/{len(todo_list)}:[/bold magenta] {step_description}") # Bind tools to the LLM so it can emit structured tool calls instead of plain text llm_with_tools = llm.bind_tools(AVAILABLE_TOOLS_LIST) # Pass the entire conversation history so the LLM has context of previous tool outputs! messages = state["messages"] + [ HumanMessage( content=( f"You are executing step {current_step + 1} of a task plan.\n" f"Step: {step_description}\n\n" f"Full task context: {state['task']}\n\n" "Please perform this step. If a file-operation tool is needed, " "call the appropriate tool with the required arguments." ) ) ] response = llm_with_tools.invoke(messages) raw = response.content if hasattr(response, "content") else "" if raw.strip(): console.print(Panel(Markdown(raw.strip()), title="[blue]🤖 Agent Thoughts[/blue]", border_style="blue")) if hasattr(response, "tool_calls") and response.tool_calls: tools_requested = ", ".join([tc["name"] for tc in response.tool_calls]) console.print(f"[bold yellow]🛠️ Requested Tools:[/bold yellow] {tools_requested}") if hasattr(response, "invalid_tool_calls") and response.invalid_tool_calls: invalid_tools = ", ".join([tc.get("name", "unknown") for tc in response.invalid_tool_calls]) console.print(f"[bold red]⚠️ Invalid Tool Calls Generated:[/bold red] {invalid_tools}") return { "current_step": current_step + 1, "messages": [response], } def call_tools(state: AgentState) -> dict: """ Tool-dispatch node. Extend with real tool-calling logic: parse ToolCall requests from state["messages"] and invoke the appropriate function from core.tools.file_operation. """ current_step = state["current_step"] todo_list = state["todo_list"] if current_step >= len(todo_list): return {"done": True} last_message = state["messages"][-1] valid_calls = getattr(last_message, "tool_calls", []) invalid_calls = getattr(last_message, "invalid_tool_calls", []) if not valid_calls and not invalid_calls: return {} tool_messages = [] for tool_call in valid_calls: tool_name = tool_call["name"] tool_args = tool_call["args"] console.print(f" [cyan]▶ Running[/cyan] [bold]{tool_name}[/bold] [dim]with args: {tool_args}[/dim]") tool = TOOLS_MAP.get(tool_name) if tool: try: result = tool.invoke(tool_args) except Exception as e: result = f"Error: {str(e)}" else: result = f"Error: Tool '{tool_name}' not found." tool_messages.append( ToolMessage(content=str(result), name=tool_name, tool_call_id=tool_call["id"]) ) # Handle malformed tool calls (common with local OSS models) for invalid_call in invalid_calls: tool_name = invalid_call.get("name", "unknown") error_msg = f"Error: Invalid tool call arguments. Please format your tool arguments exactly as required. Details: {invalid_call.get('error', 'unknown error')}" console.print(f" [red]✖ Failed to run[/red] [bold]{tool_name}[/bold]: {error_msg}") tool_messages.append( ToolMessage(content=error_msg, name=tool_name, tool_call_id=invalid_call.get("id", "unknown")) ) return {"messages": tool_messages} def mark_task_done(state: AgentState) -> dict: """ Summarise the just-completed todo step. Sets done=True only when all steps are exhausted so the router knows whether to loop back to execute_task or exit to END. """ todo_list = state["todo_list"] completed_index = state["current_step"] - 1 completed_step = ( todo_list[completed_index] if 0 <= completed_index < len(todo_list) else "unknown step" ) all_done = state["current_step"] >= len(todo_list) response = llm.invoke( f"Todo step {completed_index + 1}/{len(todo_list)} has just been completed.\n" f"Step description: {completed_step}\n\n" f"Overall task: {state['task']}\n\n" "Provide a concise one-paragraph summary of what was accomplished in this step." ) summary = response.content if hasattr(response, "content") else str(response) console.print(f"[bold green]✅ Step {completed_index + 1}/{len(todo_list)} done:[/bold green] {completed_step}") console.print(f"[dim]{summary}[/dim]\n") if all_done: console.print(Panel.fit("[bold green]🎉 All todo steps completed![/bold green]", border_style="green")) return { "done": all_done, "messages": [AIMessage(content=f"Step completed: {summary}")], } # --------------------------------------------------------------------------- # Routing functions # --------------------------------------------------------------------------- def route_after_plan(state: AgentState) -> Literal["get_human_feedback", "review_plan"]: """ After plan_task: - LLM flagged uncertainty -> get_human_feedback -> plan_task (loop) - LLM is satisfied -> review_plan -> execute_task """ if state.get("awaiting_human_feedback"): return "get_human_feedback" return "review_plan" def route_after_execute(state: AgentState) -> Literal["call_tools", "mark_task_done"]: """After each execution step, dispatch tools or summarise.""" if state.get("done") or state["current_step"] >= len(state["todo_list"]): return "mark_task_done" return "call_tools" def route_after_tools(state: AgentState) -> Literal["execute_task", "mark_task_done"]: """After tool dispatch, continue execution or summarise.""" if state.get("done") or state["current_step"] >= len(state["todo_list"]): return "mark_task_done" return "execute_task" def route_after_mark_done(state: AgentState) -> Literal["execute_task", END]: """Loop to the next todo step, or exit when all steps are done.""" if state.get("done"): return END return "execute_task" # --------------------------------------------------------------------------- # Graph factory # --------------------------------------------------------------------------- def create_agent_graph(): """ Graph topology: START │ plan_task <─────────────────────┐ │ │ ┌────┴──────────────┐ │ │ (needs feedback) │ (satisfied) │ ▼ ▼ │ get_human_feedback review_plan │ │ │ │ └──► plan_task execute_task ◄──────────────┐ │ │ call_tools mark_task_done (more steps) │ │ └──────────────────────►┘ (all done) │ END """ graph = StateGraph(AgentState) # Register nodes graph.add_node("plan_task", plan_task) graph.add_node("review_plan", review_plan) graph.add_node("get_human_feedback", get_human_feedback) graph.add_node("execute_task", execute_task) graph.add_node("call_tools", call_tools) graph.add_node("mark_task_done", mark_task_done) # --- Planning stage --- graph.add_edge(START, "plan_task") # plan_task: needs clarification -> human feedback -> re-plan # satisfied -> review_plan graph.add_conditional_edges( "plan_task", route_after_plan, { "get_human_feedback": "get_human_feedback", "review_plan": "review_plan", }, ) graph.add_edge("get_human_feedback", "plan_task") # review_plan always proceeds directly to execution graph.add_edge("review_plan", "execute_task") # --- Execution stage --- graph.add_conditional_edges( "execute_task", route_after_execute, { "call_tools": "call_tools", "mark_task_done": "mark_task_done", }, ) graph.add_conditional_edges( "call_tools", route_after_tools, { "execute_task": "execute_task", "mark_task_done": "mark_task_done", }, ) graph.add_conditional_edges( "mark_task_done", route_after_mark_done, { "execute_task": "execute_task", END: END, }, ) memory = MemorySaver() # Pause before get_human_feedback so the user can type their reply return graph.compile(checkpointer=memory, interrupt_before=["get_human_feedback"])