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/config.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Configuration management for ireri."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Dict, Optional
|
|
7
|
+
from pydantic import Field
|
|
8
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# Global config directory
|
|
12
|
+
CONFIG_DIR = Path.home() / ".ireri-code"
|
|
13
|
+
CONFIG_FILE = CONFIG_DIR / "config.json"
|
|
14
|
+
MODELS_CACHE_FILE = CONFIG_DIR / "models.json"
|
|
15
|
+
PROFILES_FILE = CONFIG_DIR / "profiles.json"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AgentConfig(BaseSettings):
|
|
19
|
+
"""Agent configuration loaded from global config file."""
|
|
20
|
+
|
|
21
|
+
model_config = SettingsConfigDict(
|
|
22
|
+
env_file=".env",
|
|
23
|
+
env_file_encoding="utf-8",
|
|
24
|
+
extra="ignore",
|
|
25
|
+
env_ignore_empty=True,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# API Configuration
|
|
29
|
+
openai_api_key: str = Field(default="", description="API key for OpenAI-compatible endpoint")
|
|
30
|
+
openai_base_url: str = Field(
|
|
31
|
+
default="https://api.openai.com/v1",
|
|
32
|
+
description="Base URL for the API endpoint"
|
|
33
|
+
)
|
|
34
|
+
openai_model: str = Field(
|
|
35
|
+
default="gpt-4o-mini",
|
|
36
|
+
description="Model identifier to use"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# Agent Behavior
|
|
40
|
+
max_iterations: int = Field(
|
|
41
|
+
default=1000,
|
|
42
|
+
description="Maximum agent loop iterations per task"
|
|
43
|
+
)
|
|
44
|
+
max_tool_calls: int = Field(
|
|
45
|
+
default=1000,
|
|
46
|
+
description="Maximum tool calls per task"
|
|
47
|
+
)
|
|
48
|
+
command_timeout: int = Field(
|
|
49
|
+
default=60,
|
|
50
|
+
description="Command execution timeout in seconds"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# Logging
|
|
54
|
+
log_level: str = Field(
|
|
55
|
+
default="INFO",
|
|
56
|
+
description="Logging level (DEBUG, INFO, WARNING, ERROR)"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# Tool Access Policies ("allow", "ask", "deny")
|
|
60
|
+
tool_access: Dict[str, str] = Field(
|
|
61
|
+
default_factory=dict,
|
|
62
|
+
description="Per-tool access policies (allow, ask, deny)"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# workspace_root is not a pydantic field - managed via property
|
|
66
|
+
_workspace_root: Optional[Path] = None
|
|
67
|
+
|
|
68
|
+
def get_tool_access(self, tool_name: str, default: str = "ask") -> str:
|
|
69
|
+
"""Get configured access policy for a tool ('allow', 'ask', or 'deny')."""
|
|
70
|
+
policy = self.tool_access.get(tool_name, default)
|
|
71
|
+
if policy in ("allow", "ask", "deny"):
|
|
72
|
+
return policy
|
|
73
|
+
return default
|
|
74
|
+
|
|
75
|
+
def set_tool_access(self, tool_name: str, policy: str) -> None:
|
|
76
|
+
"""Set access policy for a tool ('allow', 'ask', or 'deny')."""
|
|
77
|
+
normalized = policy.strip().lower()
|
|
78
|
+
if normalized not in ("allow", "ask", "deny"):
|
|
79
|
+
raise ValueError(f"Invalid tool access policy '{policy}'. Must be 'allow', 'ask', or 'deny'.")
|
|
80
|
+
self.tool_access[tool_name] = normalized
|
|
81
|
+
|
|
82
|
+
def reset_tool_access(self, tool_name: Optional[str] = None) -> None:
|
|
83
|
+
"""Reset tool access policy override for one tool or all tools."""
|
|
84
|
+
if tool_name is None:
|
|
85
|
+
self.tool_access.clear()
|
|
86
|
+
else:
|
|
87
|
+
self.tool_access.pop(tool_name, None)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def workspace_root(self) -> Path:
|
|
91
|
+
"""Get workspace root - defaults to current working directory at runtime."""
|
|
92
|
+
if self._workspace_root is not None:
|
|
93
|
+
return self._workspace_root.resolve()
|
|
94
|
+
return Path.cwd().resolve()
|
|
95
|
+
|
|
96
|
+
@workspace_root.setter
|
|
97
|
+
def workspace_root(self, value: Path) -> None:
|
|
98
|
+
"""Setter for workspace_root (allows CLI override but not persisted)."""
|
|
99
|
+
self._workspace_root = value
|
|
100
|
+
|
|
101
|
+
def to_dict(self) -> dict:
|
|
102
|
+
"""Export config as dictionary for saving."""
|
|
103
|
+
return {
|
|
104
|
+
"openai_api_key": self.openai_api_key,
|
|
105
|
+
"openai_base_url": self.openai_base_url,
|
|
106
|
+
"openai_model": self.openai_model,
|
|
107
|
+
"max_iterations": self.max_iterations,
|
|
108
|
+
"max_tool_calls": self.max_tool_calls,
|
|
109
|
+
"command_timeout": self.command_timeout,
|
|
110
|
+
"log_level": self.log_level,
|
|
111
|
+
"tool_access": dict(self.tool_access),
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def from_dict(cls, data: dict) -> "AgentConfig":
|
|
116
|
+
"""Create config from dictionary."""
|
|
117
|
+
return cls(**data)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Global config instance
|
|
121
|
+
_config: Optional[AgentConfig] = None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _ensure_config_dir() -> None:
|
|
125
|
+
"""Ensure global config directory exists."""
|
|
126
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _load_global_config() -> dict:
|
|
130
|
+
"""Load configuration from global config file."""
|
|
131
|
+
if CONFIG_FILE.exists():
|
|
132
|
+
try:
|
|
133
|
+
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
|
134
|
+
return json.load(f)
|
|
135
|
+
except (json.JSONDecodeError, OSError):
|
|
136
|
+
return {}
|
|
137
|
+
return {}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _save_global_config(config: AgentConfig) -> None:
|
|
141
|
+
"""Save configuration to global config file."""
|
|
142
|
+
_ensure_config_dir()
|
|
143
|
+
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
144
|
+
json.dump(config.to_dict(), f, indent=2)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _load_profiles() -> dict:
|
|
148
|
+
"""Load API key profiles from file."""
|
|
149
|
+
if PROFILES_FILE.exists():
|
|
150
|
+
try:
|
|
151
|
+
with open(PROFILES_FILE, "r", encoding="utf-8") as f:
|
|
152
|
+
return json.load(f)
|
|
153
|
+
except (json.JSONDecodeError, OSError):
|
|
154
|
+
return {}
|
|
155
|
+
return {}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _save_profiles(profiles: dict) -> None:
|
|
159
|
+
"""Save API key profiles to file."""
|
|
160
|
+
_ensure_config_dir()
|
|
161
|
+
with open(PROFILES_FILE, "w", encoding="utf-8") as f:
|
|
162
|
+
json.dump(profiles, f, indent=2)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def get_profiles() -> dict:
|
|
166
|
+
"""Get all saved API key profiles."""
|
|
167
|
+
return _load_profiles()
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def save_profile(name: str, api_key: str, base_url: str = "https://api.openai.com/v1", model: str = "") -> None:
|
|
171
|
+
"""Save an API key profile."""
|
|
172
|
+
profiles = _load_profiles()
|
|
173
|
+
profiles[name] = {
|
|
174
|
+
"api_key": api_key,
|
|
175
|
+
"base_url": base_url,
|
|
176
|
+
"model": model,
|
|
177
|
+
}
|
|
178
|
+
_save_profiles(profiles)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def delete_profile(name: str) -> bool:
|
|
182
|
+
"""Delete an API key profile."""
|
|
183
|
+
profiles = _load_profiles()
|
|
184
|
+
if name in profiles:
|
|
185
|
+
del profiles[name]
|
|
186
|
+
_save_profiles(profiles)
|
|
187
|
+
return True
|
|
188
|
+
return False
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def get_profile(name: str) -> Optional[dict]:
|
|
192
|
+
"""Get a specific API key profile."""
|
|
193
|
+
profiles = _load_profiles()
|
|
194
|
+
return profiles.get(name)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def load_profile(name: str) -> bool:
|
|
198
|
+
"""Load a profile as the active config."""
|
|
199
|
+
profile = get_profile(name)
|
|
200
|
+
if not profile:
|
|
201
|
+
return False
|
|
202
|
+
update_config(
|
|
203
|
+
openai_api_key=profile["api_key"],
|
|
204
|
+
openai_base_url=profile["base_url"],
|
|
205
|
+
)
|
|
206
|
+
if profile.get("model"):
|
|
207
|
+
update_config(openai_model=profile["model"])
|
|
208
|
+
return True
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _load_dotenv_file() -> dict:
|
|
212
|
+
"""Load .env file and return as dict."""
|
|
213
|
+
from pathlib import Path
|
|
214
|
+
env_path = Path(".env")
|
|
215
|
+
if not env_path.exists():
|
|
216
|
+
env_path = Path.cwd() / ".env"
|
|
217
|
+
if not env_path.exists():
|
|
218
|
+
return {}
|
|
219
|
+
|
|
220
|
+
result = {}
|
|
221
|
+
with open(env_path, "r", encoding="utf-8") as f:
|
|
222
|
+
for line in f:
|
|
223
|
+
line = line.strip()
|
|
224
|
+
if line and not line.startswith("#") and "=" in line:
|
|
225
|
+
key, value = line.split("=", 1)
|
|
226
|
+
result[key.strip()] = value.strip()
|
|
227
|
+
return result
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def get_config() -> AgentConfig:
|
|
231
|
+
"""Get the global configuration instance."""
|
|
232
|
+
global _config
|
|
233
|
+
if _config is None:
|
|
234
|
+
# Priority: global config file > .env file > defaults
|
|
235
|
+
global_values = _load_global_config()
|
|
236
|
+
dotenv_values = _load_dotenv_file()
|
|
237
|
+
|
|
238
|
+
# Merge: global config takes priority, then .env, then defaults
|
|
239
|
+
merged = {}
|
|
240
|
+
merged.update(global_values) # Global config (highest priority)
|
|
241
|
+
for k, v in dotenv_values.items():
|
|
242
|
+
if k not in merged: # Only use .env if not in global config
|
|
243
|
+
merged[k] = v
|
|
244
|
+
|
|
245
|
+
_config = AgentConfig(**merged)
|
|
246
|
+
return _config
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def set_config(config: AgentConfig) -> None:
|
|
250
|
+
"""Set the global configuration instance and save to file."""
|
|
251
|
+
global _config
|
|
252
|
+
_config = config
|
|
253
|
+
_save_global_config(config)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def reset_config() -> None:
|
|
257
|
+
"""Reset the global configuration instance (useful after config changes)."""
|
|
258
|
+
global _config
|
|
259
|
+
_config = None
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def update_config(**kwargs) -> AgentConfig:
|
|
263
|
+
"""Update specific config values and save."""
|
|
264
|
+
config = get_config()
|
|
265
|
+
for key, value in kwargs.items():
|
|
266
|
+
if hasattr(config, key):
|
|
267
|
+
setattr(config, key, value)
|
|
268
|
+
set_config(config)
|
|
269
|
+
return config
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def get_available_models(base_url: str = None, api_key: str = None) -> list[dict]:
|
|
273
|
+
"""Fetch available models from OpenAI-compatible API."""
|
|
274
|
+
import httpx
|
|
275
|
+
config = get_config()
|
|
276
|
+
url = (base_url or config.openai_base_url).rstrip("/") + "/models"
|
|
277
|
+
headers = {"Authorization": f"Bearer {api_key or config.openai_api_key}"}
|
|
278
|
+
|
|
279
|
+
try:
|
|
280
|
+
with httpx.Client(timeout=10.0) as client:
|
|
281
|
+
response = client.get(url, headers=headers)
|
|
282
|
+
response.raise_for_status()
|
|
283
|
+
data = response.json()
|
|
284
|
+
return data.get("data", [])
|
|
285
|
+
except Exception:
|
|
286
|
+
return []
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def cache_models(models: list[dict]) -> None:
|
|
290
|
+
"""Cache model list to file."""
|
|
291
|
+
_ensure_config_dir()
|
|
292
|
+
with open(MODELS_CACHE_FILE, "w", encoding="utf-8") as f:
|
|
293
|
+
json.dump(models, f, indent=2)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def get_cached_models() -> list[dict]:
|
|
297
|
+
"""Get cached model list."""
|
|
298
|
+
if MODELS_CACHE_FILE.exists():
|
|
299
|
+
try:
|
|
300
|
+
with open(MODELS_CACHE_FILE, "r", encoding="utf-8") as f:
|
|
301
|
+
return json.load(f)
|
|
302
|
+
except (json.JSONDecodeError, OSError):
|
|
303
|
+
return []
|
|
304
|
+
return []
|
agent/context.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Context management for ireri."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from agent.config import get_config
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class ContextEntry:
|
|
17
|
+
"""A single entry in the conversation context."""
|
|
18
|
+
role: str # user, assistant, tool
|
|
19
|
+
content: str
|
|
20
|
+
tool_calls: Optional[List[Dict[str, Any]]] = None
|
|
21
|
+
tool_call_id: Optional[str] = None
|
|
22
|
+
name: Optional[str] = None # for tool messages
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ContextManager:
|
|
26
|
+
"""Manages conversation context and project state."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, max_tokens: int = 100_000):
|
|
29
|
+
self.max_tokens = max_tokens
|
|
30
|
+
self.messages: List[ContextEntry] = []
|
|
31
|
+
self.project_summary: str = ""
|
|
32
|
+
self.files_inspected: Dict[str, int] = {} # path -> line count
|
|
33
|
+
self.tool_calls_count = 0
|
|
34
|
+
self.iteration_count = 0
|
|
35
|
+
self.total_prompt_tokens = 0 # Tokens up (sent to model)
|
|
36
|
+
self.total_completion_tokens = 0 # Tokens down (received from model)
|
|
37
|
+
|
|
38
|
+
def add_user_message(self, content: str) -> None:
|
|
39
|
+
"""Add a user message."""
|
|
40
|
+
self.messages.append(ContextEntry(role="user", content=content))
|
|
41
|
+
|
|
42
|
+
def add_assistant_message(
|
|
43
|
+
self,
|
|
44
|
+
content: Optional[str] = None,
|
|
45
|
+
tool_calls: Optional[List[Dict[str, Any]]] = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
"""Add an assistant message."""
|
|
48
|
+
self.messages.append(ContextEntry(
|
|
49
|
+
role="assistant",
|
|
50
|
+
content=content or "",
|
|
51
|
+
tool_calls=tool_calls,
|
|
52
|
+
))
|
|
53
|
+
|
|
54
|
+
def add_tool_result(
|
|
55
|
+
self,
|
|
56
|
+
tool_call_id: str,
|
|
57
|
+
name: str,
|
|
58
|
+
content: str,
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Add a tool result message."""
|
|
61
|
+
self.messages.append(ContextEntry(
|
|
62
|
+
role="tool",
|
|
63
|
+
content=content,
|
|
64
|
+
tool_call_id=tool_call_id,
|
|
65
|
+
name=name,
|
|
66
|
+
))
|
|
67
|
+
self.tool_calls_count += 1
|
|
68
|
+
|
|
69
|
+
def add_system_message(self, content: str) -> None:
|
|
70
|
+
"""Add a system message (inserted at beginning)."""
|
|
71
|
+
self.messages.insert(0, ContextEntry(role="system", content=content))
|
|
72
|
+
|
|
73
|
+
def get_messages_for_model(self) -> List[Dict[str, Any]]:
|
|
74
|
+
"""Get messages formatted for the model API."""
|
|
75
|
+
result = []
|
|
76
|
+
for msg in self.messages:
|
|
77
|
+
if msg.role == "system":
|
|
78
|
+
result.append({"role": "system", "content": msg.content})
|
|
79
|
+
elif msg.role == "user":
|
|
80
|
+
result.append({"role": "user", "content": msg.content})
|
|
81
|
+
elif msg.role == "assistant":
|
|
82
|
+
msg_dict = {"role": "assistant"}
|
|
83
|
+
if msg.content:
|
|
84
|
+
msg_dict["content"] = msg.content
|
|
85
|
+
if msg.tool_calls:
|
|
86
|
+
msg_dict["tool_calls"] = msg.tool_calls
|
|
87
|
+
result.append(msg_dict)
|
|
88
|
+
elif msg.role == "tool":
|
|
89
|
+
result.append({
|
|
90
|
+
"role": "tool",
|
|
91
|
+
"tool_call_id": msg.tool_call_id,
|
|
92
|
+
"name": msg.name,
|
|
93
|
+
"content": msg.content,
|
|
94
|
+
})
|
|
95
|
+
return result
|
|
96
|
+
|
|
97
|
+
def record_file_inspection(self, path: str, line_count: int) -> None:
|
|
98
|
+
"""Record that a file was inspected."""
|
|
99
|
+
self.files_inspected[path] = line_count
|
|
100
|
+
|
|
101
|
+
def get_project_context(self) -> str:
|
|
102
|
+
"""Get a summary of project context for the model."""
|
|
103
|
+
parts = []
|
|
104
|
+
|
|
105
|
+
if self.project_summary:
|
|
106
|
+
parts.append(f"Project Summary:\n{self.project_summary}")
|
|
107
|
+
|
|
108
|
+
if self.files_inspected:
|
|
109
|
+
parts.append("Files inspected this session:")
|
|
110
|
+
for path, lines in sorted(self.files_inspected.items()):
|
|
111
|
+
parts.append(f" - {path} ({lines} lines)")
|
|
112
|
+
|
|
113
|
+
return "\n\n".join(parts) if parts else "No project context yet."
|
|
114
|
+
|
|
115
|
+
def set_project_summary(self, summary: str) -> None:
|
|
116
|
+
"""Set the project summary."""
|
|
117
|
+
self.project_summary = summary
|
|
118
|
+
|
|
119
|
+
def increment_iteration(self) -> int:
|
|
120
|
+
"""Increment and return iteration count."""
|
|
121
|
+
self.iteration_count += 1
|
|
122
|
+
return self.iteration_count
|
|
123
|
+
|
|
124
|
+
def reset_iteration_count(self) -> None:
|
|
125
|
+
"""Reset iteration count for a new task/message generation."""
|
|
126
|
+
self.iteration_count = 0
|
|
127
|
+
|
|
128
|
+
def get_iteration_count(self) -> int:
|
|
129
|
+
"""Get current iteration count."""
|
|
130
|
+
return self.iteration_count
|
|
131
|
+
|
|
132
|
+
def get_tool_calls_count(self) -> int:
|
|
133
|
+
"""Get total tool calls count."""
|
|
134
|
+
return self.tool_calls_count
|
|
135
|
+
|
|
136
|
+
def clear(self) -> None:
|
|
137
|
+
"""Clear context (keep system messages)."""
|
|
138
|
+
system_msgs = [m for m in self.messages if m.role == "system"]
|
|
139
|
+
self.messages = system_msgs
|
|
140
|
+
self.tool_calls_count = 0
|
|
141
|
+
self.iteration_count = 0
|
|
142
|
+
self.total_prompt_tokens = 0
|
|
143
|
+
self.total_completion_tokens = 0
|
|
144
|
+
|
|
145
|
+
def add_token_usage(self, prompt_tokens: int, completion_tokens: int) -> None:
|
|
146
|
+
"""Accumulate token usage for the session."""
|
|
147
|
+
self.total_prompt_tokens += max(0, prompt_tokens)
|
|
148
|
+
self.total_completion_tokens += max(0, completion_tokens)
|
|
149
|
+
|
|
150
|
+
def get_token_stats(self) -> Dict[str, Any]:
|
|
151
|
+
"""Get session token statistics and active context estimation."""
|
|
152
|
+
return {
|
|
153
|
+
"tokens_up": self.total_prompt_tokens,
|
|
154
|
+
"tokens_down": self.total_completion_tokens,
|
|
155
|
+
"total_tokens": self.total_prompt_tokens + self.total_completion_tokens,
|
|
156
|
+
"approx_context_tokens": self.estimate_tokens(),
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
def estimate_tokens(self) -> int:
|
|
160
|
+
"""Rough token estimation."""
|
|
161
|
+
total = 0
|
|
162
|
+
for msg in self.messages:
|
|
163
|
+
total += len(msg.content) // 4 # rough estimate
|
|
164
|
+
if msg.tool_calls:
|
|
165
|
+
total += len(json.dumps(msg.tool_calls)) // 4
|
|
166
|
+
return total
|
|
167
|
+
|
|
168
|
+
def trim_if_needed(self, model_max_tokens: int = 128_000) -> None:
|
|
169
|
+
"""Trim context if it exceeds limits."""
|
|
170
|
+
# Reserve tokens for response and tools
|
|
171
|
+
available = model_max_tokens - 8000
|
|
172
|
+
|
|
173
|
+
while self.estimate_tokens() > available and len(self.messages) > 2:
|
|
174
|
+
# Remove oldest non-system messages
|
|
175
|
+
for i, msg in enumerate(self.messages):
|
|
176
|
+
if msg.role != "system":
|
|
177
|
+
self.messages.pop(i)
|
|
178
|
+
break
|
|
179
|
+
|
|
180
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
181
|
+
"""Serialize context for persistence."""
|
|
182
|
+
return {
|
|
183
|
+
"messages": [
|
|
184
|
+
{
|
|
185
|
+
"role": m.role,
|
|
186
|
+
"content": m.content,
|
|
187
|
+
"tool_calls": m.tool_calls,
|
|
188
|
+
"tool_call_id": m.tool_call_id,
|
|
189
|
+
"name": m.name,
|
|
190
|
+
}
|
|
191
|
+
for m in self.messages
|
|
192
|
+
],
|
|
193
|
+
"project_summary": self.project_summary,
|
|
194
|
+
"files_inspected": self.files_inspected,
|
|
195
|
+
"tool_calls_count": self.tool_calls_count,
|
|
196
|
+
"iteration_count": self.iteration_count,
|
|
197
|
+
"total_prompt_tokens": self.total_prompt_tokens,
|
|
198
|
+
"total_completion_tokens": self.total_completion_tokens,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
@classmethod
|
|
202
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ContextManager":
|
|
203
|
+
"""Deserialize context."""
|
|
204
|
+
ctx = cls()
|
|
205
|
+
ctx.project_summary = data.get("project_summary", "")
|
|
206
|
+
ctx.files_inspected = data.get("files_inspected", {})
|
|
207
|
+
ctx.tool_calls_count = data.get("tool_calls_count", 0)
|
|
208
|
+
ctx.iteration_count = data.get("iteration_count", 0)
|
|
209
|
+
ctx.total_prompt_tokens = data.get("total_prompt_tokens", 0)
|
|
210
|
+
ctx.total_completion_tokens = data.get("total_completion_tokens", 0)
|
|
211
|
+
|
|
212
|
+
for msg_data in data.get("messages", []):
|
|
213
|
+
ctx.messages.append(ContextEntry(**msg_data))
|
|
214
|
+
|
|
215
|
+
return ctx
|