ireri-code 2.0.0__py3-none-any.whl

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.
agent/controller.py ADDED
@@ -0,0 +1,633 @@
1
+ """Main agent controller for ireri."""
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ from pathlib import Path
7
+ from typing import Any, Callable, Dict, List, Optional
8
+
9
+ from agent.config import get_config
10
+ from agent.model import get_model_client, ModelClient, ModelResponse
11
+ from agent.context import ContextManager, ContextEntry
12
+ from agent.prompts import get_system_prompt, get_task_prompt, get_continuation_prompt, get_error_recovery_prompt
13
+ from agent.tools import get_registry, ToolRegistry, ToolResult
14
+ from agent.session import SessionManager
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Progress callback type
19
+ ProgressCallback = Callable[[str, Dict[str, Any]], None]
20
+
21
+ # Approval callback type
22
+ ApprovalCallback = Callable[[str, Dict[str, Any], bool], bool]
23
+
24
+
25
+ class AgentController:
26
+ """Main agent control loop."""
27
+
28
+ def __init__(
29
+ self,
30
+ model_client: Optional[ModelClient] = None,
31
+ tool_registry: Optional[ToolRegistry] = None,
32
+ context: Optional[ContextManager] = None,
33
+ session_manager: Optional[SessionManager] = None,
34
+ model: Optional[str] = None,
35
+ progress_callback: Optional[ProgressCallback] = None,
36
+ approval_callback: Optional[ApprovalCallback] = None,
37
+ ):
38
+ from agent.config import reset_config
39
+ from agent.model import reset_model_client, ModelClient
40
+
41
+ reset_config()
42
+ reset_model_client()
43
+ self.config = get_config()
44
+
45
+ # Use provided model or config model (avoids shell env var override)
46
+ effective_model = model or self.config.openai_model
47
+ self.model_client = model_client or ModelClient(model=effective_model)
48
+ self.tool_registry = tool_registry or get_registry()
49
+ self.context = context or ContextManager()
50
+ self.progress_callback = progress_callback
51
+ self.approval_callback = approval_callback
52
+
53
+ if self.progress_callback:
54
+ self.model_client.progress_callback = self.progress_callback
55
+
56
+ self.session_manager = session_manager or SessionManager(workspace_root=self.config.workspace_root)
57
+
58
+ # Add system prompt
59
+ self.context.add_system_message(get_system_prompt())
60
+
61
+ # State
62
+ self.running = False
63
+ self.cancelled = False
64
+ self.last_error: Optional[str] = None
65
+ self.message_queue: List[str] = []
66
+ self.active_approval: Optional[asyncio.Future] = None
67
+
68
+ # Approval state
69
+ self._approve_all = False
70
+ self._deny_all = False
71
+
72
+ def load_session(self) -> bool:
73
+ """Load saved session into context if available."""
74
+ data = self.session_manager.load_session()
75
+ if not data:
76
+ return False
77
+ ctx_data = data.get("context", {})
78
+ saved_messages = ctx_data.get("messages", [])
79
+ non_system = [m for m in saved_messages if m.get("role") != "system"]
80
+ if not non_system:
81
+ return False
82
+
83
+ # Keep existing system message, append saved conversation messages
84
+ system_msgs = [m for m in self.context.messages if m.role == "system"]
85
+ self.context.messages = system_msgs + [ContextEntry(**m) for m in non_system]
86
+ self.context.files_inspected = ctx_data.get("files_inspected", {})
87
+ self.context.project_summary = ctx_data.get("project_summary", "")
88
+ self.context.tool_calls_count = ctx_data.get("tool_calls_count", 0)
89
+ self.context.total_prompt_tokens = ctx_data.get("total_prompt_tokens", 0)
90
+ self.context.total_completion_tokens = ctx_data.get("total_completion_tokens", 0)
91
+ logger.info(f"Loaded saved session: {len(non_system)} messages restored")
92
+ return True
93
+
94
+ def save_session(self) -> bool:
95
+ """Save current context to session file."""
96
+ return self.session_manager.save_session(self.context, model=self.model_client.model)
97
+
98
+ def has_saved_session(self) -> bool:
99
+ """Check if a saved session exists."""
100
+ return self.session_manager.has_saved_session()
101
+
102
+ def clear_saved_session(self) -> bool:
103
+ """Clear saved session file."""
104
+ return self.session_manager.clear_session()
105
+
106
+ def reset(self) -> None:
107
+ """Reset the controller state for a new session."""
108
+ self.context.clear()
109
+ self.context.add_system_message(get_system_prompt())
110
+ self.clear_saved_session()
111
+ self.clear_message_queue()
112
+ self.active_approval = None
113
+ self.running = False
114
+ self.cancelled = False
115
+ self.last_error = None
116
+ self._approve_all = False
117
+ self._deny_all = False
118
+
119
+ async def run_task(self, task: str, project_context: str = "", progress_callback: Optional[ProgressCallback] = None) -> str:
120
+ """Run a complete task and return the result."""
121
+ self.running = True
122
+ self.cancelled = False
123
+ if progress_callback:
124
+ self.progress_callback = progress_callback
125
+ self.model_client.progress_callback = progress_callback
126
+
127
+ # Reset iteration count for each message generation
128
+ self.context.reset_iteration_count()
129
+
130
+ # Log user task to history
131
+ self.session_manager.log_message("USER", task)
132
+
133
+ # Add task to context
134
+ prompt = get_task_prompt(task, project_context)
135
+ self.context.add_user_message(prompt)
136
+
137
+ try:
138
+ result = await self._agent_loop()
139
+ # Log agent result to history
140
+ self.session_manager.log_message("AGENT", result)
141
+ self.save_session()
142
+ return result
143
+ finally:
144
+ self.running = False
145
+ self.context.reset_iteration_count()
146
+ self.save_session()
147
+
148
+ async def recover_from_error(
149
+ self,
150
+ error: str,
151
+ progress_callback: Optional[ProgressCallback] = None,
152
+ ) -> str:
153
+ """Send an encountered error to the model automatically so it can take corrective actions."""
154
+ self.running = True
155
+ self.cancelled = False
156
+ if progress_callback:
157
+ self.progress_callback = progress_callback
158
+ self.model_client.progress_callback = progress_callback
159
+
160
+ self.last_error = error
161
+ self.session_manager.log_error("AUTO_RECOVERY", error)
162
+ if self.progress_callback:
163
+ self.progress_callback("error_encountered", {"error": error})
164
+
165
+ # Add error recovery prompt directly to context
166
+ prompt = get_error_recovery_prompt(error)
167
+ self.context.add_user_message(prompt)
168
+
169
+ try:
170
+ result = await self._agent_loop()
171
+ self.session_manager.log_message("AGENT", result)
172
+ self.save_session()
173
+ return result
174
+ finally:
175
+ self.running = False
176
+ self.context.reset_iteration_count()
177
+ self.save_session()
178
+
179
+ async def _agent_loop(self) -> str:
180
+ """Main agent loop."""
181
+ config = self.config
182
+ max_iterations = config.max_iterations
183
+ max_tool_calls = config.max_tool_calls
184
+
185
+ while self.running and not self.cancelled:
186
+ # Check limits
187
+ if self.context.get_iteration_count() >= max_iterations:
188
+ return f"Stopped: Maximum iterations ({max_iterations}) reached"
189
+
190
+ if self.context.get_tool_calls_count() >= max_tool_calls:
191
+ return f"Stopped: Maximum tool calls ({max_tool_calls}) reached"
192
+
193
+ # Increment iteration
194
+ iteration = self.context.increment_iteration()
195
+ logger.info(f"Agent iteration {iteration}/{max_iterations}")
196
+
197
+ # Emit progress: iteration started
198
+ if self.progress_callback:
199
+ self.progress_callback("iteration_start", {
200
+ "iteration": iteration,
201
+ "max_iterations": max_iterations,
202
+ })
203
+
204
+ try:
205
+ # Get messages for model
206
+ messages = self.context.get_messages_for_model()
207
+
208
+ # Get tool definitions
209
+ tools = self.tool_registry.get_definitions()
210
+
211
+ # Call model
212
+ try:
213
+ response = await self.model_client.chat(
214
+ messages=messages,
215
+ tools=tools,
216
+ tool_choice="auto",
217
+ temperature=0.1,
218
+ progress_callback=self.progress_callback,
219
+ )
220
+ except Exception as e:
221
+ logger.error(f"Model call failed: {e}")
222
+ self.last_error = str(e)
223
+ self.session_manager.log_error(
224
+ "MODEL_ERROR",
225
+ str(e),
226
+ {"model": self.model_client.model, "iteration": iteration},
227
+ )
228
+ if self.progress_callback:
229
+ self.progress_callback("model_error", {"error": str(e)})
230
+ # Try to recover by sending error to model
231
+ error_prompt = get_error_recovery_prompt(str(e))
232
+ self.context.add_user_message(error_prompt)
233
+ continue
234
+
235
+ # Track token usage from model response
236
+ p_tokens = 0
237
+ c_tokens = 0
238
+ if response.usage:
239
+ p_tokens = response.usage.get("prompt_tokens", 0) or 0
240
+ c_tokens = response.usage.get("completion_tokens", 0) or 0
241
+ if not p_tokens:
242
+ p_tokens = self.context.estimate_tokens()
243
+ if not c_tokens and response.content:
244
+ c_tokens = max(1, len(response.content) // 4)
245
+
246
+ self.context.add_token_usage(p_tokens, c_tokens)
247
+
248
+ logger.info(f"Model response: tokens=(↑{p_tokens}, ↓{c_tokens}), content={response.content[:100] if response.content else None}, tool_calls={len(response.tool_calls) if response.tool_calls else 0}")
249
+
250
+ # Emit progress: model response with tokens up/down and approx context
251
+ if self.progress_callback:
252
+ self.progress_callback("model_response", {
253
+ "has_content": bool(response.content),
254
+ "tool_calls_count": len(response.tool_calls) if response.tool_calls else 0,
255
+ "finish_reason": response.finish_reason,
256
+ "tokens_up": p_tokens,
257
+ "tokens_down": c_tokens,
258
+ "total_tokens_up": self.context.total_prompt_tokens,
259
+ "total_tokens_down": self.context.total_completion_tokens,
260
+ "approx_context_tokens": self.context.estimate_tokens(),
261
+ })
262
+
263
+ # Handle response
264
+ if response.tool_calls:
265
+ # Add assistant message with tool calls
266
+ self.context.add_assistant_message(
267
+ content=response.content,
268
+ tool_calls=response.tool_calls,
269
+ )
270
+
271
+ # Execute tool calls
272
+ for tool_call in response.tool_calls:
273
+ if self.cancelled:
274
+ break
275
+
276
+ result = await self._execute_tool_call(tool_call)
277
+
278
+ # Extract tool args for logging
279
+ args_data = tool_call.get("function", {}).get("arguments")
280
+ if isinstance(args_data, str):
281
+ try:
282
+ args_data = json.loads(args_data)
283
+ except Exception:
284
+ pass
285
+
286
+ # Check if tool failed and prepare content
287
+ if not result.success:
288
+ self.last_error = result.error or "Tool execution failed"
289
+ self.session_manager.log_error(
290
+ "TOOL_ERROR",
291
+ self.last_error,
292
+ {
293
+ "tool": tool_call["function"]["name"],
294
+ "args": args_data if isinstance(args_data, dict) else {},
295
+ },
296
+ )
297
+ logger.warning(f"Tool {tool_call['function']['name']} failed: {result.error}")
298
+
299
+ # Build comprehensive error report so the model can take appropriate corrective actions
300
+ diag_parts = [f"[TOOL ERROR in {tool_call['function']['name']}]: {self.last_error}"]
301
+ if isinstance(result.output, dict):
302
+ if result.output.get("stdout") and result.output.get("stdout").strip() != self.last_error.strip():
303
+ diag_parts.append(f"Command stdout:\n{result.output['stdout'].strip()}")
304
+ if result.output.get("stderr") and result.output.get("stderr").strip() != self.last_error.strip():
305
+ diag_parts.append(f"Command stderr:\n{result.output['stderr'].strip()}")
306
+ if "returncode" in result.output and result.output["returncode"] != 0:
307
+ diag_parts.append(f"Exit code: {result.output['returncode']}")
308
+ elif result.output:
309
+ diag_parts.append(f"Output: {result.output}")
310
+
311
+ diag_parts.append(
312
+ "AUTOMATIC ACTION REQUIRED: An error occurred during this action. "
313
+ "Analyze this error, identify the root cause, and take appropriate corrective actions "
314
+ "automatically (e.g. fix parameters, correct code syntax/logic, inspect files, or try an alternative approach)."
315
+ )
316
+ tool_out_str = "\n\n".join(diag_parts)
317
+ else:
318
+ tool_out_str = json.dumps(result.output) if isinstance(result.output, (dict, list)) else str(result.output)
319
+
320
+ # Add tool result to context
321
+ self.context.add_tool_result(
322
+ tool_call_id=tool_call["id"],
323
+ name=tool_call["function"]["name"],
324
+ content=tool_out_str,
325
+ )
326
+
327
+ # Log tool call to history
328
+ self.session_manager.log_message(
329
+ "TOOL_CALL",
330
+ content=tool_out_str,
331
+ tool_name=tool_call["function"]["name"],
332
+ tool_args=args_data if isinstance(args_data, dict) else {},
333
+ )
334
+
335
+ self.save_session()
336
+
337
+ elif response.content:
338
+ # Regular response - add to context and continue
339
+ self.context.add_assistant_message(content=response.content)
340
+
341
+ # Check if task seems complete
342
+ if self._is_task_complete(response.content):
343
+ return response.content
344
+
345
+ # Continue with continuation prompt
346
+ self.context.add_user_message(get_continuation_prompt())
347
+ else:
348
+ # Empty response
349
+ logger.warning("Empty response from model")
350
+ self.context.add_user_message(get_continuation_prompt())
351
+
352
+ except asyncio.CancelledError:
353
+ raise
354
+ except Exception as e:
355
+ logger.error(f"Error in agent iteration {iteration}: {e}")
356
+ self.last_error = str(e)
357
+ self.session_manager.log_error(
358
+ "ITERATION_ERROR",
359
+ str(e),
360
+ {"iteration": iteration},
361
+ )
362
+ if self.progress_callback:
363
+ self.progress_callback("error_encountered", {"error": str(e), "iteration": iteration})
364
+
365
+ # Automatically send error to model for recovery
366
+ error_prompt = get_error_recovery_prompt(f"Runtime execution error: {e}")
367
+ self.context.add_user_message(error_prompt)
368
+ continue
369
+
370
+ if self.cancelled:
371
+ return "Task cancelled by user"
372
+
373
+ return "Agent loop ended without completion"
374
+
375
+ async def _execute_tool_call(self, tool_call: Dict[str, Any]) -> ToolResult:
376
+ """Execute a single tool call."""
377
+ tool_name = tool_call["function"]["name"]
378
+ tool = self.tool_registry.get(tool_name)
379
+
380
+ if not tool:
381
+ return ToolResult(
382
+ success=False,
383
+ error=f"Unknown tool: {tool_name}"
384
+ )
385
+
386
+ # Parse arguments
387
+ try:
388
+ args_json = tool_call["function"]["arguments"]
389
+ if isinstance(args_json, str):
390
+ args_dict = json.loads(args_json)
391
+ else:
392
+ args_dict = args_json
393
+ args = tool.args_schema(**args_dict)
394
+ except Exception as e:
395
+ return ToolResult(
396
+ success=False,
397
+ error=f"Invalid tool arguments: {e}"
398
+ )
399
+
400
+ # Emit progress: tool started
401
+ if self.progress_callback:
402
+ self.progress_callback("tool_start", {
403
+ "tool": tool_name,
404
+ "args": args_dict,
405
+ })
406
+
407
+ # Check configured tool access policy ("allow", "ask", or "deny")
408
+ default_policy = "ask" if tool.requires_approval else "allow"
409
+ policy = self.config.get_tool_access(tool_name, default=default_policy)
410
+
411
+ if policy == "deny":
412
+ if self.progress_callback:
413
+ self.progress_callback("tool_denied", {"tool": tool_name, "reason": "policy"})
414
+ return ToolResult(
415
+ success=False,
416
+ error=f"Tool '{tool_name}' is denied by tool access settings (/settings tools)."
417
+ )
418
+
419
+ if policy == "ask":
420
+ approved = await self._request_approval(tool_name, args_dict, tool.dangerous)
421
+ if not approved:
422
+ if self.progress_callback:
423
+ self.progress_callback("tool_denied", {"tool": tool_name})
424
+ return ToolResult(
425
+ success=False,
426
+ error="User denied approval"
427
+ )
428
+
429
+ # Execute tool
430
+ logger.info(f"Executing tool: {tool_name} with args: {args_dict}")
431
+ try:
432
+ result = await tool.execute(args)
433
+ logger.info(f"Tool {tool_name} result: success={result.success}")
434
+
435
+ # Emit progress: tool completed
436
+ if self.progress_callback:
437
+ self.progress_callback("tool_complete", {
438
+ "tool": tool_name,
439
+ "success": result.success,
440
+ "output": result.output,
441
+ "error": result.error,
442
+ "metadata": result.metadata,
443
+ })
444
+
445
+ return result
446
+ except Exception as e:
447
+ logger.error(f"Tool {tool_name} execution error: {e}")
448
+ self.session_manager.log_error(
449
+ "TOOL_EXCEPTION",
450
+ str(e),
451
+ {"tool": tool_name, "args": args_dict},
452
+ )
453
+ if self.progress_callback:
454
+ self.progress_callback("tool_error", {
455
+ "tool": tool_name,
456
+ "error": str(e),
457
+ })
458
+ return ToolResult(success=False, error=str(e))
459
+
460
+ async def _request_approval(self, tool_name: str, args: Dict[str, Any], dangerous: bool = False) -> bool:
461
+ """Request user approval for a tool call."""
462
+ # Check session-level approvals first
463
+ if self._approve_all:
464
+ return True
465
+ if self._deny_all:
466
+ return False
467
+
468
+ # If we have an approval callback, use it
469
+ if self.approval_callback:
470
+ return await self.approval_callback(tool_name, args, dangerous)
471
+
472
+ # Fallback: auto-approve in non-interactive mode
473
+ logger.info(f"Approval requested for {tool_name}: {args}")
474
+ return True # Auto-approve for now
475
+
476
+ def set_approve_all(self, value: bool) -> None:
477
+ """Set approve-all mode for the session."""
478
+ self._approve_all = value
479
+
480
+ def set_deny_all(self, value: bool) -> None:
481
+ """Set deny-all mode for the session."""
482
+ self._deny_all = value
483
+
484
+ def _is_task_complete(self, response: str) -> bool:
485
+ """Heuristic to detect if task is complete."""
486
+ completion_indicators = [
487
+ "task complete",
488
+ "completed successfully",
489
+ "finished",
490
+ "done",
491
+ "all done",
492
+ "is complete",
493
+ "has been completed",
494
+ "complete.",
495
+ "resolved",
496
+ "fixed",
497
+ ]
498
+ response_lower = response.lower()
499
+ return any(indicator in response_lower for indicator in completion_indicators)
500
+
501
+ def _is_conversational(self, message: str) -> bool:
502
+ """Check if message is a simple conversational input (not a coding task)."""
503
+ msg = message.strip().lower()
504
+ conversational_patterns = [
505
+ "hi", "hello", "hey", "hi there", "hello there",
506
+ "thanks", "thank you", "thx", "ty",
507
+ "bye", "goodbye", "see you", "cya",
508
+ "how are you", "how's it going", "what's up",
509
+ "ok", "okay", "sure", "yeah", "yep", "yup",
510
+ "no", "nope", "nah",
511
+ "lol", "haha", "hehe",
512
+ ]
513
+ # Exact match or very short message
514
+ return msg in conversational_patterns or (len(msg) < 30 and msg in ["hi", "hello", "hey", "thanks", "bye", "ok"])
515
+
516
+ def queue_message(self, message: str) -> int:
517
+ """Queue a user message for upcoming run(s). Returns total queued count."""
518
+ cleaned = message.strip()
519
+ if cleaned:
520
+ self.message_queue.append(cleaned)
521
+ logger.info(f"Queued message (position {len(self.message_queue)}): '{cleaned[:50]}'")
522
+ return len(self.message_queue)
523
+
524
+ def has_queued_messages(self) -> bool:
525
+ """Check if any messages are waiting in queue."""
526
+ return len(self.message_queue) > 0
527
+
528
+ def pop_queued_message(self) -> Optional[str]:
529
+ """Pop and return next queued message, or None if empty."""
530
+ if self.message_queue:
531
+ return self.message_queue.pop(0)
532
+ return None
533
+
534
+ def get_queued_messages(self) -> List[str]:
535
+ """Get copy of all queued messages."""
536
+ return list(self.message_queue)
537
+
538
+ def clear_message_queue(self) -> int:
539
+ """Clear all queued messages. Returns number of cleared messages."""
540
+ count = len(self.message_queue)
541
+ self.message_queue.clear()
542
+ return count
543
+
544
+ def enlighten(self, question: str, answer: str) -> None:
545
+ """Inject /btw question and direct answer into agent context so ongoing/future steps are enlightened."""
546
+ self.context.add_user_message(f"[Side Note / BTW from User]: {question}")
547
+ self.context.add_assistant_message(f"[Direct Answer / Guidance]: {answer}")
548
+ self.session_manager.log_message("BTW_USER", question)
549
+ self.session_manager.log_message("BTW_AGENT", answer)
550
+ self.save_session()
551
+ logger.info(f"Agent enlightened with /btw note: '{question[:50]}'")
552
+
553
+ async def ask_direct(self, question: str) -> str:
554
+ """Directly query the model for a quick answer without executing tools,
555
+ and inject the clarification into the running context to guide the agent."""
556
+ recent_msgs = self.context.get_messages_for_model()
557
+ # Keep up to last 8 non-system messages for context
558
+ trimmed = [m for m in recent_msgs[-8:] if m.get("role") != "system"]
559
+
560
+ system_msg = {
561
+ "role": "system",
562
+ "content": (
563
+ "You are an AI coding assistant (ireri). The user is asking a direct, "
564
+ "side question or giving advice ('by the way') while an ongoing task may be in progress. "
565
+ "Answer clearly, concisely, and helpfully. Do not attempt to call tools. "
566
+ "Your answer will be directly shown to the user and immediately recorded into the "
567
+ "running agent's context to enlighten and guide its subsequent steps."
568
+ ),
569
+ }
570
+
571
+ messages = [system_msg] + trimmed + [{"role": "user", "content": question}]
572
+
573
+ try:
574
+ response = await self.model_client.chat(
575
+ messages=messages,
576
+ tools=None,
577
+ temperature=0.2,
578
+ )
579
+ answer = response.content or "(No response from model)"
580
+
581
+ # Track token usage from /btw response
582
+ p_tokens = 0
583
+ c_tokens = 0
584
+ if response.usage:
585
+ p_tokens = response.usage.get("prompt_tokens", 0) or 0
586
+ c_tokens = response.usage.get("completion_tokens", 0) or 0
587
+ if not p_tokens:
588
+ p_tokens = sum(len(m.get("content", "")) for m in messages) // 4
589
+ if not c_tokens and response.content:
590
+ c_tokens = max(1, len(response.content) // 4)
591
+ self.context.add_token_usage(p_tokens, c_tokens)
592
+ except Exception as e:
593
+ logger.error(f"/btw direct model call failed: {e}")
594
+ self.session_manager.log_error("BTW_ERROR", str(e), {"question": question})
595
+ return f"Error contacting model: {e}"
596
+
597
+ self.enlighten(question, answer)
598
+ return answer
599
+
600
+ def cancel(self) -> None:
601
+ """Cancel the current task."""
602
+ self.cancelled = True
603
+ self.running = False
604
+
605
+ def get_status(self) -> Dict[str, Any]:
606
+ """Get current agent status."""
607
+ stats = self.context.get_token_stats()
608
+ return {
609
+ "running": self.running,
610
+ "cancelled": self.cancelled,
611
+ "iteration": self.context.get_iteration_count(),
612
+ "tool_calls": self.context.get_tool_calls_count(),
613
+ "last_error": self.last_error,
614
+ "queued_messages": len(self.message_queue),
615
+ "tokens_up": stats["tokens_up"],
616
+ "tokens_down": stats["tokens_down"],
617
+ "total_tokens": stats["total_tokens"],
618
+ "approx_context_tokens": stats["approx_context_tokens"],
619
+ }
620
+
621
+
622
+ async def run_agent_task(task: str, project_path: Optional[str] = None) -> str:
623
+ """Convenience function to run a single task."""
624
+ from agent.model import reset_model_client
625
+
626
+ reset_model_client()
627
+ config = get_config()
628
+
629
+ if project_path:
630
+ config.workspace_root = Path(project_path).resolve()
631
+
632
+ controller = AgentController()
633
+ return await controller.run_task(task)