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/__init__.py +27 -0
- agent/cli.py +2573 -0
- agent/config.py +304 -0
- agent/context.py +215 -0
- agent/controller.py +633 -0
- agent/model.py +285 -0
- agent/prompts.py +90 -0
- agent/session.py +223 -0
- agent/tools/__init__.py +95 -0
- agent/tools/files.py +322 -0
- agent/tools/search.py +223 -0
- agent/tools/terminal.py +542 -0
- ireri_code-2.0.0.dist-info/METADATA +219 -0
- ireri_code-2.0.0.dist-info/RECORD +17 -0
- ireri_code-2.0.0.dist-info/WHEEL +5 -0
- ireri_code-2.0.0.dist-info/entry_points.txt +2 -0
- ireri_code-2.0.0.dist-info/top_level.txt +1 -0
agent/model.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Model client for ireri."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import asyncio
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any, Callable, Dict, List, Optional, AsyncGenerator
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from openai import AsyncOpenAI
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
from agent.config import get_config
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
# Incremental retry delays in seconds: 1s, 5s, 15s, 30s, 1m (60s), 3m (180s)
|
|
17
|
+
RETRY_DELAYS = [1, 5, 15, 30, 60, 180]
|
|
18
|
+
|
|
19
|
+
# Maximum time to wait for a model response before diagnosing & reloading connection (3 mins = 180s)
|
|
20
|
+
MODEL_CALL_TIMEOUT = 180.0
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def diagnose_connection(base_url: str, api_key: str, timeout: float = 8.0) -> Dict[str, Any]:
|
|
24
|
+
"""Diagnose connectivity to model API endpoint to find out what the problem is."""
|
|
25
|
+
import httpx
|
|
26
|
+
import time
|
|
27
|
+
from urllib.parse import urlparse
|
|
28
|
+
|
|
29
|
+
result = {
|
|
30
|
+
"reachable": False,
|
|
31
|
+
"latency_ms": None,
|
|
32
|
+
"status_code": None,
|
|
33
|
+
"error": None,
|
|
34
|
+
"summary": "",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
parsed = urlparse(base_url)
|
|
38
|
+
hostname = parsed.hostname or base_url
|
|
39
|
+
|
|
40
|
+
start = time.time()
|
|
41
|
+
try:
|
|
42
|
+
test_url = base_url.rstrip("/") + "/models"
|
|
43
|
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
|
44
|
+
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
45
|
+
resp = await client.get(test_url, headers=headers)
|
|
46
|
+
elapsed_ms = int((time.time() - start) * 1000)
|
|
47
|
+
result["reachable"] = True
|
|
48
|
+
result["latency_ms"] = elapsed_ms
|
|
49
|
+
result["status_code"] = resp.status_code
|
|
50
|
+
if resp.status_code == 200:
|
|
51
|
+
result["summary"] = f"Endpoint is reachable and responsive ({elapsed_ms}ms latency). The provider may be experiencing queue delays or high load."
|
|
52
|
+
elif resp.status_code == 401:
|
|
53
|
+
result["summary"] = f"Endpoint is reachable ({elapsed_ms}ms), but returned 401 Unauthorized (Invalid API Key)."
|
|
54
|
+
elif resp.status_code == 429:
|
|
55
|
+
result["summary"] = f"Endpoint is reachable ({elapsed_ms}ms), but rate limit (429) was exceeded."
|
|
56
|
+
else:
|
|
57
|
+
result["summary"] = f"Endpoint is reachable ({elapsed_ms}ms) but returned HTTP status {resp.status_code}."
|
|
58
|
+
except httpx.ConnectTimeout:
|
|
59
|
+
result["error"] = "ConnectTimeout"
|
|
60
|
+
result["summary"] = f"Could not connect to {hostname} within {timeout}s. Check internet connection, proxy, or firewall."
|
|
61
|
+
except httpx.ConnectError as e:
|
|
62
|
+
result["error"] = f"ConnectError: {e}"
|
|
63
|
+
result["summary"] = f"Connection failed to {hostname}. Host unreachable or offline."
|
|
64
|
+
except httpx.ReadTimeout:
|
|
65
|
+
result["error"] = "ReadTimeout"
|
|
66
|
+
result["summary"] = f"Connected to {hostname}, but server timed out without returning response headers."
|
|
67
|
+
except Exception as e:
|
|
68
|
+
result["error"] = str(e)
|
|
69
|
+
result["summary"] = f"Diagnostic probe error: {e}"
|
|
70
|
+
|
|
71
|
+
return result
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class ModelResponse:
|
|
76
|
+
"""Response from the model."""
|
|
77
|
+
content: Optional[str] = None
|
|
78
|
+
tool_calls: Optional[List[Dict[str, Any]]] = None
|
|
79
|
+
finish_reason: Optional[str] = None
|
|
80
|
+
usage: Optional[Dict[str, Any]] = None
|
|
81
|
+
raw: Any = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ModelClient:
|
|
85
|
+
"""Client for interacting with OpenAI-compatible API."""
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
api_key: Optional[str] = None,
|
|
90
|
+
base_url: Optional[str] = None,
|
|
91
|
+
model: Optional[str] = None,
|
|
92
|
+
timeout: float = MODEL_CALL_TIMEOUT,
|
|
93
|
+
):
|
|
94
|
+
config = get_config()
|
|
95
|
+
|
|
96
|
+
self.api_key = api_key or config.openai_api_key
|
|
97
|
+
self.base_url = base_url or config.openai_base_url
|
|
98
|
+
# Use explicitly passed model; caller handles priority resolution
|
|
99
|
+
self.model = model if model is not None else config.openai_model
|
|
100
|
+
self.timeout = timeout
|
|
101
|
+
|
|
102
|
+
if not self.api_key:
|
|
103
|
+
raise ValueError("API key is required. Set OPENAI_API_KEY in .env")
|
|
104
|
+
|
|
105
|
+
self.client = AsyncOpenAI(
|
|
106
|
+
api_key=self.api_key,
|
|
107
|
+
base_url=self.base_url,
|
|
108
|
+
timeout=self.timeout,
|
|
109
|
+
)
|
|
110
|
+
self.progress_callback: Optional[Callable[[str, Dict[str, Any]], None]] = None
|
|
111
|
+
|
|
112
|
+
logger.info(f"Model client initialized: {self.model} @ {self.base_url} (timeout: {self.timeout}s)")
|
|
113
|
+
|
|
114
|
+
def reload_client(self) -> None:
|
|
115
|
+
"""Reload and recreate the AsyncOpenAI client instance (restarts connection pool)."""
|
|
116
|
+
logger.info(f"Reloading AsyncOpenAI client connection pool for {self.model} @ {self.base_url}")
|
|
117
|
+
try:
|
|
118
|
+
self.client = AsyncOpenAI(
|
|
119
|
+
api_key=self.api_key,
|
|
120
|
+
base_url=self.base_url,
|
|
121
|
+
timeout=self.timeout,
|
|
122
|
+
)
|
|
123
|
+
except Exception as e:
|
|
124
|
+
logger.error(f"Failed to reload model client: {e}")
|
|
125
|
+
|
|
126
|
+
async def chat(
|
|
127
|
+
self,
|
|
128
|
+
messages: List[Dict[str, Any]],
|
|
129
|
+
tools: Optional[List[Dict[str, Any]]] = None,
|
|
130
|
+
tool_choice: Optional[str] = None,
|
|
131
|
+
temperature: float = 0.1,
|
|
132
|
+
max_tokens: Optional[int] = None,
|
|
133
|
+
stream: bool = False,
|
|
134
|
+
retry_delays: Optional[List[int]] = None,
|
|
135
|
+
request_timeout: Optional[float] = None,
|
|
136
|
+
progress_callback: Optional[Callable[[str, Dict[str, Any]], None]] = None,
|
|
137
|
+
) -> ModelResponse:
|
|
138
|
+
"""Send a chat completion request with incremental retry delay and 3-min timeout recovery."""
|
|
139
|
+
delays = retry_delays if retry_delays is not None else RETRY_DELAYS
|
|
140
|
+
cb = progress_callback or self.progress_callback
|
|
141
|
+
total_attempts = len(delays) + 1
|
|
142
|
+
call_timeout = request_timeout if request_timeout is not None else self.timeout
|
|
143
|
+
|
|
144
|
+
for attempt_idx in range(total_attempts):
|
|
145
|
+
try:
|
|
146
|
+
kwargs = {
|
|
147
|
+
"model": self.model,
|
|
148
|
+
"messages": messages,
|
|
149
|
+
"temperature": temperature,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if max_tokens:
|
|
153
|
+
kwargs["max_tokens"] = max_tokens
|
|
154
|
+
|
|
155
|
+
if tools:
|
|
156
|
+
kwargs["tools"] = tools
|
|
157
|
+
if tool_choice:
|
|
158
|
+
kwargs["tool_choice"] = tool_choice
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
if stream:
|
|
162
|
+
response = await asyncio.wait_for(
|
|
163
|
+
self._stream_chat(**kwargs),
|
|
164
|
+
timeout=call_timeout,
|
|
165
|
+
)
|
|
166
|
+
else:
|
|
167
|
+
raw_response = await asyncio.wait_for(
|
|
168
|
+
self.client.chat.completions.create(**kwargs),
|
|
169
|
+
timeout=call_timeout,
|
|
170
|
+
)
|
|
171
|
+
response = self._parse_response(raw_response)
|
|
172
|
+
except (asyncio.TimeoutError, TimeoutError):
|
|
173
|
+
# Model did not respond within 3 minutes (or call_timeout)
|
|
174
|
+
logger.warning(
|
|
175
|
+
f"Model did not respond within {int(call_timeout)}s (3 mins). Diagnosing issue..."
|
|
176
|
+
)
|
|
177
|
+
diagnostic = await diagnose_connection(self.base_url, self.api_key)
|
|
178
|
+
self.reload_client()
|
|
179
|
+
if cb:
|
|
180
|
+
cb("model_timeout", {
|
|
181
|
+
"timeout": call_timeout,
|
|
182
|
+
"diagnostic": diagnostic,
|
|
183
|
+
"attempt": attempt_idx + 1,
|
|
184
|
+
"max_attempts": len(delays),
|
|
185
|
+
})
|
|
186
|
+
raise TimeoutError(
|
|
187
|
+
f"No response from model within {int(call_timeout)}s (3 mins). "
|
|
188
|
+
f"Diagnostic: {diagnostic['summary']}"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
if attempt_idx > 0:
|
|
192
|
+
logger.info(f"Model API call recovered on retry {attempt_idx}")
|
|
193
|
+
if cb:
|
|
194
|
+
cb("model_retry_success", {"attempt": attempt_idx})
|
|
195
|
+
|
|
196
|
+
return response
|
|
197
|
+
|
|
198
|
+
except Exception as e:
|
|
199
|
+
if attempt_idx < len(delays):
|
|
200
|
+
delay = delays[attempt_idx]
|
|
201
|
+
retry_num = attempt_idx + 1
|
|
202
|
+
logger.warning(
|
|
203
|
+
f"Model API error: {e}. Retrying in {delay}s (attempt {retry_num}/{len(delays)})..."
|
|
204
|
+
)
|
|
205
|
+
if cb:
|
|
206
|
+
cb("model_retry", {
|
|
207
|
+
"error": str(e),
|
|
208
|
+
"attempt": retry_num,
|
|
209
|
+
"max_attempts": len(delays),
|
|
210
|
+
"delay": delay,
|
|
211
|
+
})
|
|
212
|
+
await asyncio.sleep(delay)
|
|
213
|
+
else:
|
|
214
|
+
logger.error(f"Model API error exhausted all {len(delays)} retries: {e}")
|
|
215
|
+
raise
|
|
216
|
+
|
|
217
|
+
async def _stream_chat(self, **kwargs) -> ModelResponse:
|
|
218
|
+
"""Handle streaming response."""
|
|
219
|
+
# For now, use non-streaming and simulate
|
|
220
|
+
# Full streaming implementation would accumulate chunks
|
|
221
|
+
response = await self.client.chat.completions.create(**kwargs, stream=False)
|
|
222
|
+
return self._parse_response(response)
|
|
223
|
+
|
|
224
|
+
def _parse_response(self, response) -> ModelResponse:
|
|
225
|
+
"""Parse OpenAI response into ModelResponse."""
|
|
226
|
+
choice = response.choices[0]
|
|
227
|
+
message = choice.message
|
|
228
|
+
|
|
229
|
+
tool_calls = None
|
|
230
|
+
if message.tool_calls:
|
|
231
|
+
tool_calls = [
|
|
232
|
+
{
|
|
233
|
+
"id": tc.id,
|
|
234
|
+
"type": tc.type,
|
|
235
|
+
"function": {
|
|
236
|
+
"name": tc.function.name,
|
|
237
|
+
"arguments": tc.function.arguments,
|
|
238
|
+
},
|
|
239
|
+
}
|
|
240
|
+
for tc in message.tool_calls
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
usage = None
|
|
244
|
+
if response.usage:
|
|
245
|
+
usage = {
|
|
246
|
+
"prompt_tokens": response.usage.prompt_tokens,
|
|
247
|
+
"completion_tokens": response.usage.completion_tokens,
|
|
248
|
+
"total_tokens": response.usage.total_tokens,
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return ModelResponse(
|
|
252
|
+
content=message.content,
|
|
253
|
+
tool_calls=tool_calls,
|
|
254
|
+
finish_reason=choice.finish_reason,
|
|
255
|
+
usage=usage,
|
|
256
|
+
raw=response,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
async def close(self):
|
|
260
|
+
"""Close the client."""
|
|
261
|
+
await self.client.close()
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# Global client instance
|
|
265
|
+
_client: Optional[ModelClient] = None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def get_model_client() -> ModelClient:
|
|
269
|
+
"""Get the global model client instance."""
|
|
270
|
+
global _client
|
|
271
|
+
if _client is None:
|
|
272
|
+
_client = ModelClient()
|
|
273
|
+
return _client
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def set_model_client(client: ModelClient) -> None:
|
|
277
|
+
"""Set the global model client instance."""
|
|
278
|
+
global _client
|
|
279
|
+
_client = client
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def reset_model_client() -> None:
|
|
283
|
+
"""Reset the global model client instance (useful after config changes)."""
|
|
284
|
+
global _client
|
|
285
|
+
_client = None
|
agent/prompts.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""System prompts for ireri."""
|
|
2
|
+
|
|
3
|
+
SYSTEM_PROMPT = """You are ireri, an expert AI coding agent that operates in a terminal environment.
|
|
4
|
+
|
|
5
|
+
Your capabilities:
|
|
6
|
+
- Read, write, edit, and delete files
|
|
7
|
+
- Execute terminal commands
|
|
8
|
+
- Search code across the project
|
|
9
|
+
- Navigate and understand project structure
|
|
10
|
+
- Run tests and debug issues
|
|
11
|
+
|
|
12
|
+
Your workflow:
|
|
13
|
+
1. Understand the user's task and the project context
|
|
14
|
+
2. Inspect relevant files to gather information
|
|
15
|
+
3. Plan your approach
|
|
16
|
+
4. Execute the necessary changes using tools
|
|
17
|
+
5. Verify your work by running tests/commands
|
|
18
|
+
6. Report results to the user
|
|
19
|
+
|
|
20
|
+
Guidelines:
|
|
21
|
+
- Make precise, targeted edits rather than rewriting entire files
|
|
22
|
+
- Always test your changes when possible
|
|
23
|
+
- Ask for clarification if the task is ambiguous
|
|
24
|
+
- Report errors honestly - don't claim success without verification
|
|
25
|
+
- Use the tools provided; don't simulate or fake tool execution
|
|
26
|
+
- Preserve existing code style and conventions
|
|
27
|
+
- For long-running processes such as bots, servers, or watchers (e.g., 'python bot.py', 'npm run dev', 'uvicorn ...'), ALWAYS pass background=true to run_command so it starts in the background and returns immediately without blocking. Use get_process_logs or list_processes to inspect ongoing process output.
|
|
28
|
+
|
|
29
|
+
Safety:
|
|
30
|
+
- Never execute dangerous commands without approval
|
|
31
|
+
- Never access files outside the workspace
|
|
32
|
+
- Never expose secrets or credentials
|
|
33
|
+
- Request approval for file modifications and command execution
|
|
34
|
+
|
|
35
|
+
IMPORTANT: Always use RELATIVE paths for file operations and commands. The workspace root is your current working directory (.). Do NOT use absolute paths like /workspace, /c/..., or /home/... - use relative paths like ".", "src/", "tests/", etc.
|
|
36
|
+
|
|
37
|
+
When you need to use a tool, call it through the structured tool calling mechanism. The system will execute it and return the result."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
TASK_PROMPT_TEMPLATE = """The user has given you the following task:
|
|
41
|
+
|
|
42
|
+
{task}
|
|
43
|
+
|
|
44
|
+
Project context:
|
|
45
|
+
{context}
|
|
46
|
+
|
|
47
|
+
Please start by exploring the project to understand the codebase, then implement the requested changes."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
CONTINUATION_PROMPT = """Continue working on the task. Use the available tools to make progress. If you've completed the task, provide a summary of what was done."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
ERROR_RECOVERY_PROMPT = """An error was encountered during execution:
|
|
54
|
+
|
|
55
|
+
{error}
|
|
56
|
+
|
|
57
|
+
Please automatically analyze this error and take appropriate corrective actions:
|
|
58
|
+
1. Determine the root cause of the error.
|
|
59
|
+
2. Apply the necessary fix or corrective measures using your available tools.
|
|
60
|
+
3. If an alternative approach or parameter adjustment is needed, proceed with it automatically.
|
|
61
|
+
4. Report the corrective action taken and verify the resolution."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
APPROVAL_REQUEST_PROMPT = """The following action requires your approval:
|
|
65
|
+
|
|
66
|
+
Tool: {tool_name}
|
|
67
|
+
Arguments: {arguments}
|
|
68
|
+
Reason: {reason}
|
|
69
|
+
|
|
70
|
+
Do you approve? (yes/no)"""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get_system_prompt() -> str:
|
|
74
|
+
"""Get the system prompt."""
|
|
75
|
+
return SYSTEM_PROMPT
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def get_task_prompt(task: str, context: str) -> str:
|
|
79
|
+
"""Get the initial task prompt."""
|
|
80
|
+
return TASK_PROMPT_TEMPLATE.format(task=task, context=context)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def get_continuation_prompt() -> str:
|
|
84
|
+
"""Get the continuation prompt."""
|
|
85
|
+
return CONTINUATION_PROMPT
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def get_error_recovery_prompt(error: str) -> str:
|
|
89
|
+
"""Get the error recovery prompt."""
|
|
90
|
+
return ERROR_RECOVERY_PROMPT.format(error=error)
|
agent/session.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Session and chat history management for ireri."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import json
|
|
5
|
+
import hashlib
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List, Optional
|
|
9
|
+
import logging
|
|
10
|
+
|
|
11
|
+
from agent.context import ContextManager, ContextEntry
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SessionManager:
|
|
17
|
+
"""Manages workspace session persistence and chat history logging."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, workspace_root: Optional[Path] = None):
|
|
20
|
+
self.workspace_root = Path(workspace_root or Path.cwd()).resolve()
|
|
21
|
+
self.session_dir = self._resolve_session_dir()
|
|
22
|
+
self.session_file = self.session_dir / "session.json"
|
|
23
|
+
self.history_file = self.session_dir / "chat_history.log"
|
|
24
|
+
self.error_log_file = self.session_dir / "errors.log"
|
|
25
|
+
self._ensure_dir()
|
|
26
|
+
|
|
27
|
+
def _resolve_session_dir(self) -> Path:
|
|
28
|
+
"""Resolve session directory inside workspace (.ireri/), or in ~/.ireri-code/sessions/ as fallback."""
|
|
29
|
+
try:
|
|
30
|
+
ws_dir = self.workspace_root / ".ireri"
|
|
31
|
+
ws_dir.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
# Test write permission
|
|
33
|
+
test_file = ws_dir / ".test_write"
|
|
34
|
+
test_file.touch()
|
|
35
|
+
test_file.unlink()
|
|
36
|
+
return ws_dir
|
|
37
|
+
except OSError:
|
|
38
|
+
# Fallback to user home directory
|
|
39
|
+
h = hashlib.sha256(str(self.workspace_root).encode()).hexdigest()[:12]
|
|
40
|
+
name = self.workspace_root.name or "root"
|
|
41
|
+
home_dir = Path.home() / ".ireri-code" / "sessions" / f"{name}_{h}"
|
|
42
|
+
home_dir.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
return home_dir
|
|
44
|
+
|
|
45
|
+
def _ensure_dir(self) -> None:
|
|
46
|
+
"""Ensure session directory exists."""
|
|
47
|
+
try:
|
|
48
|
+
self.session_dir.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
except OSError:
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
def save_session(self, context: ContextManager, model: str = "") -> bool:
|
|
53
|
+
"""Save the full ContextManager state to session.json."""
|
|
54
|
+
try:
|
|
55
|
+
self._ensure_dir()
|
|
56
|
+
data = {
|
|
57
|
+
"workspace_root": str(self.workspace_root),
|
|
58
|
+
"saved_at": datetime.now().isoformat(),
|
|
59
|
+
"model": model,
|
|
60
|
+
"context": context.to_dict(),
|
|
61
|
+
}
|
|
62
|
+
with open(self.session_file, "w", encoding="utf-8") as f:
|
|
63
|
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
64
|
+
return True
|
|
65
|
+
except Exception as e:
|
|
66
|
+
logger.error(f"Failed to save session: {e}")
|
|
67
|
+
return False
|
|
68
|
+
|
|
69
|
+
def load_session(self) -> Optional[Dict[str, Any]]:
|
|
70
|
+
"""Load saved session data if present."""
|
|
71
|
+
if not self.session_file.exists():
|
|
72
|
+
return None
|
|
73
|
+
try:
|
|
74
|
+
with open(self.session_file, "r", encoding="utf-8") as f:
|
|
75
|
+
data = json.load(f)
|
|
76
|
+
return data
|
|
77
|
+
except Exception as e:
|
|
78
|
+
logger.warning(f"Could not load session from {self.session_file}: {e}")
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
def has_saved_session(self) -> bool:
|
|
82
|
+
"""Check if a valid session with user/assistant messages exists."""
|
|
83
|
+
if not self.session_file.exists():
|
|
84
|
+
return False
|
|
85
|
+
try:
|
|
86
|
+
data = self.load_session()
|
|
87
|
+
if not data:
|
|
88
|
+
return False
|
|
89
|
+
ctx = data.get("context", {})
|
|
90
|
+
msgs = ctx.get("messages", [])
|
|
91
|
+
# Must have at least one user or assistant message
|
|
92
|
+
return any(m.get("role") in ("user", "assistant") for m in msgs)
|
|
93
|
+
except Exception:
|
|
94
|
+
return False
|
|
95
|
+
|
|
96
|
+
def clear_session(self) -> bool:
|
|
97
|
+
"""Clear the current session.json file while preserving the chat_history.log."""
|
|
98
|
+
try:
|
|
99
|
+
if self.session_file.exists():
|
|
100
|
+
self.session_file.unlink()
|
|
101
|
+
return True
|
|
102
|
+
except Exception as e:
|
|
103
|
+
logger.error(f"Failed to clear session: {e}")
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
def log_message(
|
|
107
|
+
self,
|
|
108
|
+
role: str,
|
|
109
|
+
content: str,
|
|
110
|
+
tool_name: Optional[str] = None,
|
|
111
|
+
tool_args: Optional[Dict[str, Any]] = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
"""Append an entry to the human-readable chat_history.log."""
|
|
114
|
+
try:
|
|
115
|
+
self._ensure_dir()
|
|
116
|
+
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
117
|
+
lines = []
|
|
118
|
+
|
|
119
|
+
if not self.history_file.exists() or self.history_file.stat().st_size == 0:
|
|
120
|
+
header = (
|
|
121
|
+
f"{'='*80}\n"
|
|
122
|
+
f"ireri Chat History Log\n"
|
|
123
|
+
f"Workspace: {self.workspace_root}\n"
|
|
124
|
+
f"Created: {now_str}\n"
|
|
125
|
+
f"{'='*80}\n\n"
|
|
126
|
+
)
|
|
127
|
+
lines.append(header)
|
|
128
|
+
|
|
129
|
+
role_upper = role.upper()
|
|
130
|
+
if role_upper == "TOOL_CALL":
|
|
131
|
+
lines.append(f"[{now_str}] [TOOL_CALL] {tool_name or ''}\n")
|
|
132
|
+
if tool_args:
|
|
133
|
+
lines.append(f"Args: {json.dumps(tool_args, ensure_ascii=False)}\n")
|
|
134
|
+
lines.append(f"Result: {content.strip()}\n\n")
|
|
135
|
+
elif role_upper == "USER":
|
|
136
|
+
lines.append(f"[{now_str}] [USER]\n{content.strip()}\n\n")
|
|
137
|
+
elif role_upper in ("AGENT", "ASSISTANT"):
|
|
138
|
+
lines.append(f"[{now_str}] [AGENT]\n{content.strip()}\n\n")
|
|
139
|
+
else:
|
|
140
|
+
lines.append(f"[{now_str}] [{role_upper}]\n{content.strip()}\n\n")
|
|
141
|
+
|
|
142
|
+
with open(self.history_file, "a", encoding="utf-8") as f:
|
|
143
|
+
f.writelines(lines)
|
|
144
|
+
except Exception as e:
|
|
145
|
+
logger.error(f"Failed to append to chat_history.log: {e}")
|
|
146
|
+
|
|
147
|
+
def get_recent_history(self, limit: int = 20) -> List[Dict[str, Any]]:
|
|
148
|
+
"""Get the recent conversation messages from session."""
|
|
149
|
+
data = self.load_session()
|
|
150
|
+
if not data:
|
|
151
|
+
return []
|
|
152
|
+
msgs = data.get("context", {}).get("messages", [])
|
|
153
|
+
# Filter for user and assistant messages for readable history
|
|
154
|
+
readable = [m for m in msgs if m.get("role") in ("user", "assistant") and m.get("content")]
|
|
155
|
+
return readable[-limit:]
|
|
156
|
+
|
|
157
|
+
def log_error(
|
|
158
|
+
self,
|
|
159
|
+
error_type: str,
|
|
160
|
+
message: str,
|
|
161
|
+
details: Optional[Dict[str, Any]] = None,
|
|
162
|
+
) -> None:
|
|
163
|
+
"""Log an error to .ireri/errors.log for debugging."""
|
|
164
|
+
try:
|
|
165
|
+
self._ensure_dir()
|
|
166
|
+
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
167
|
+
lines = [
|
|
168
|
+
f"[{now_str}] [{error_type.upper()}]\n",
|
|
169
|
+
f"Message: {message.strip()}\n",
|
|
170
|
+
]
|
|
171
|
+
if details:
|
|
172
|
+
lines.append(f"Details: {json.dumps(details, ensure_ascii=False)}\n")
|
|
173
|
+
lines.append("-" * 80 + "\n\n")
|
|
174
|
+
|
|
175
|
+
with open(self.error_log_file, "a", encoding="utf-8") as f:
|
|
176
|
+
f.writelines(lines)
|
|
177
|
+
except Exception as e:
|
|
178
|
+
logger.error(f"Failed to append to errors.log: {e}")
|
|
179
|
+
|
|
180
|
+
def get_recent_errors(self, limit: int = 20) -> List[Dict[str, Any]]:
|
|
181
|
+
"""Get recent logged errors from errors.log."""
|
|
182
|
+
if not self.error_log_file.exists():
|
|
183
|
+
return []
|
|
184
|
+
try:
|
|
185
|
+
with open(self.error_log_file, "r", encoding="utf-8") as f:
|
|
186
|
+
content = f.read()
|
|
187
|
+
blocks = content.strip().split("-" * 80)
|
|
188
|
+
errors = []
|
|
189
|
+
for b in blocks:
|
|
190
|
+
b = b.strip()
|
|
191
|
+
if not b:
|
|
192
|
+
continue
|
|
193
|
+
lines = b.splitlines()
|
|
194
|
+
header = lines[0] if lines else ""
|
|
195
|
+
# Parse [timestamp] [type]
|
|
196
|
+
timestamp = ""
|
|
197
|
+
err_type = "ERROR"
|
|
198
|
+
if header.startswith("[") and "]" in header:
|
|
199
|
+
parts = header.split("] [")
|
|
200
|
+
if len(parts) >= 2:
|
|
201
|
+
timestamp = parts[0].lstrip("[")
|
|
202
|
+
err_type = parts[1].rstrip("]")
|
|
203
|
+
else:
|
|
204
|
+
timestamp = header.strip("[]")
|
|
205
|
+
msg = ""
|
|
206
|
+
details = ""
|
|
207
|
+
for line in lines[1:]:
|
|
208
|
+
if line.startswith("Message: "):
|
|
209
|
+
msg = line[9:]
|
|
210
|
+
elif line.startswith("Details: "):
|
|
211
|
+
details = line[9:]
|
|
212
|
+
errors.append({
|
|
213
|
+
"timestamp": timestamp,
|
|
214
|
+
"type": err_type,
|
|
215
|
+
"message": msg or b,
|
|
216
|
+
"details": details,
|
|
217
|
+
})
|
|
218
|
+
return errors[-limit:]
|
|
219
|
+
except Exception as e:
|
|
220
|
+
logger.error(f"Failed to read errors.log: {e}")
|
|
221
|
+
return []
|
|
222
|
+
|
|
223
|
+
|
agent/tools/__init__.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Tool system base classes and registry."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any, Dict, List, Optional, Type
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
import logging
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ToolResult(BaseModel):
|
|
12
|
+
"""Result of a tool execution."""
|
|
13
|
+
success: bool
|
|
14
|
+
output: Any = None
|
|
15
|
+
error: Optional[str] = None
|
|
16
|
+
metadata: Dict[str, Any] = Field(default_factory=dict)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ToolArgument(BaseModel):
|
|
20
|
+
"""Base class for tool arguments."""
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Tool(ABC):
|
|
25
|
+
"""Base class for all tools."""
|
|
26
|
+
|
|
27
|
+
name: str = ""
|
|
28
|
+
description: str = ""
|
|
29
|
+
args_schema: Type[ToolArgument] = ToolArgument
|
|
30
|
+
requires_approval: bool = False
|
|
31
|
+
dangerous: bool = False
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
async def execute(self, args: ToolArgument) -> ToolResult:
|
|
35
|
+
"""Execute the tool with given arguments."""
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
def format_for_model(self) -> Dict[str, Any]:
|
|
39
|
+
"""Format tool definition for model consumption."""
|
|
40
|
+
return {
|
|
41
|
+
"type": "function",
|
|
42
|
+
"function": {
|
|
43
|
+
"name": self.name,
|
|
44
|
+
"description": self.description,
|
|
45
|
+
"parameters": self.args_schema.model_json_schema(),
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ToolRegistry:
|
|
51
|
+
"""Registry for managing available tools."""
|
|
52
|
+
|
|
53
|
+
def __init__(self):
|
|
54
|
+
self._tools: Dict[str, Tool] = {}
|
|
55
|
+
|
|
56
|
+
def register(self, tool: Tool) -> None:
|
|
57
|
+
"""Register a tool."""
|
|
58
|
+
if tool.name in self._tools:
|
|
59
|
+
logger.warning(f"Tool '{tool.name}' already registered, overwriting")
|
|
60
|
+
self._tools[tool.name] = tool
|
|
61
|
+
logger.debug(f"Registered tool: {tool.name}")
|
|
62
|
+
|
|
63
|
+
def get(self, name: str) -> Optional[Tool]:
|
|
64
|
+
"""Get a tool by name."""
|
|
65
|
+
return self._tools.get(name)
|
|
66
|
+
|
|
67
|
+
def get_all(self) -> List[Tool]:
|
|
68
|
+
"""Get all registered tools."""
|
|
69
|
+
return list(self._tools.values())
|
|
70
|
+
|
|
71
|
+
def get_definitions(self) -> List[Dict[str, Any]]:
|
|
72
|
+
"""Get all tool definitions formatted for the model."""
|
|
73
|
+
return [tool.format_for_model() for tool in self._tools.values()]
|
|
74
|
+
|
|
75
|
+
def has_tool(self, name: str) -> bool:
|
|
76
|
+
"""Check if a tool is registered."""
|
|
77
|
+
return name in self._tools
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# Global registry instance
|
|
81
|
+
_registry = ToolRegistry()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def get_registry() -> ToolRegistry:
|
|
85
|
+
"""Get the global tool registry."""
|
|
86
|
+
return _registry
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def register_tool(tool: Tool) -> None:
|
|
90
|
+
"""Register a tool in the global registry."""
|
|
91
|
+
_registry.register(tool)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# Import tool modules to trigger registration
|
|
95
|
+
from . import files, terminal, search # noqa: F401
|