-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.py
More file actions
407 lines (317 loc) · 12.3 KB
/
logger.py
File metadata and controls
407 lines (317 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
"""
Agent Logger Module
Provides deterministic logging for agent spawns and results.
Updates IAC.md (Inter Agent Context) automatically.
This module ensures all agent interactions are logged consistently,
without relying on agents to update documentation themselves.
All log files are created in the same directory as mcp_server.py,
keeping PowerSpawn self-contained with no external dependencies.
v0.5.14.1: Added file locking for concurrent agent safety
v0.5.25.1: Newest entries first, limit to 15 entries
v0.5.26.1: Simplified - always write to script directory
v1.6.0: Merged CONTEXT.md into IAC.md (Inter Agent Context pattern)
v1.6.1: Added agent_type (CLI/API) to IAC.md logging
v1.6.2: Increased MAX_IAC_ENTRIES from 15 to 50
v1.6.3: Increased MAX_IAC_ENTRIES from 50 to 200
"""
import re
import uuid
import threading
from datetime import datetime
from pathlib import Path
from typing import Optional
from dataclasses import dataclass
# Global lock for file operations (thread-safe within process)
_file_lock = threading.Lock()
# Maximum number of entries to keep in IAC.md
MAX_IAC_ENTRIES = 200
# IAC.md header template (with active agents placeholder)
IAC_HEADER_TEMPLATE = """# Inter Agent Context (IAC)
> Auto-generated by PowerSpawn. Do not edit manually.
**Last Updated:** {timestamp} UTC
---
## Active Agents
{active_agents_table}
---
## Interaction History
> Newest entries first. Limited to last 200 entries.
"""
def get_output_dir() -> Path:
"""Get the output directory for IAC.md.
Always returns the same directory as mcp_server.py (powerspawn/).
This keeps PowerSpawn self-contained with no external dependencies.
"""
return Path(__file__).parent
def get_agents_dir() -> Path:
"""Get the agents directory path (alias for get_output_dir for backwards compat)."""
return get_output_dir()
def generate_spawn_id() -> str:
"""Generate a short unique ID for a spawn."""
return uuid.uuid4().hex[:8]
def now_iso() -> str:
"""Get current timestamp in ISO format (UTC)."""
return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
def now_time() -> str:
"""Get current time only (UTC)."""
return datetime.utcnow().strftime("%H:%M:%S")
def now_date() -> str:
"""Get current date only (UTC)."""
return datetime.utcnow().strftime("%Y-%m-%d")
def sanitize_for_table(text: str, max_len: int = 60) -> str:
"""Sanitize text for markdown table display (remove newlines, truncate)."""
if not text:
return ""
# Replace newlines with spaces, collapse multiple spaces
clean = ' '.join(text.split())
if len(clean) > max_len:
return clean[:max_len-3] + "..."
return clean
@dataclass
class SpawnRecord:
"""Record of an agent spawn for logging."""
spawn_id: str
agent: str
model: str
agent_type: str # "CLI" or "API"
task_summary: str
prompt: str
tools: list[str]
started_at: str
completed_at: Optional[str] = None
duration_seconds: Optional[float] = None
success: Optional[bool] = None
cost_usd: Optional[float] = None
result_summary: Optional[str] = None
error: Optional[str] = None
class AgentLogger:
"""
Logger for agent spawns and results.
Manages IAC.md (Inter Agent Context) - a single file containing:
- Active agents status (top section)
- Interaction history (below, newest first)
"""
def __init__(self):
self.agents_dir = get_agents_dir()
self.iac_path = self.agents_dir / "IAC.md"
self.active_spawns: dict[str, SpawnRecord] = {}
self.max_recent_runs = 10
def _build_active_agents_table(self) -> str:
"""Build markdown table of active agents."""
table = "| ID | Agent | Type | Model | Task | Started |\n|-----|-------|------|-------|------|--------|\n"
if self.active_spawns:
for sid, rec in self.active_spawns.items():
task_clean = sanitize_for_table(rec.task_summary, 50)
table += f"| `{sid}` | {rec.agent} | {rec.agent_type} | {rec.model} | {task_clean} | {rec.started_at} |\n"
else:
table += "| - | - | - | - | *No active agents* | - |\n"
return table
def _build_header(self) -> str:
"""Build the IAC.md header with active agents table."""
return IAC_HEADER_TEMPLATE.format(
timestamp=now_iso(),
active_agents_table=self._build_active_agents_table()
)
def _ensure_iac_exists(self):
"""Ensure IAC.md exists with proper header."""
if not self.iac_path.exists():
self.iac_path.write_text(self._build_header(), encoding='utf-8')
def _read_iac(self) -> str:
"""Read IAC.md content."""
self._ensure_iac_exists()
return self.iac_path.read_text(encoding='utf-8')
def _parse_iac_entries(self, content: str) -> list[str]:
"""Parse IAC.md content into individual entries.
Each entry starts with '### 🤖' and includes everything until the next entry or EOF.
"""
# Split by entry marker, keeping the marker
parts = re.split(r'(### 🤖)', content)
entries = []
i = 1 # Skip first part (header)
while i < len(parts):
if parts[i] == '### 🤖' and i + 1 < len(parts):
# Combine marker with content
entry = parts[i] + parts[i + 1]
entries.append(entry.strip())
i += 2
else:
i += 1
return entries
def _write_iac(self, entries: list[str]):
"""Write IAC.md with header (including active agents) and entries."""
content = self._build_header()
for entry in entries:
content += entry + "\n\n"
self.iac_path.write_text(content, encoding='utf-8')
def _prepend_iac(self, new_entry: str):
"""Prepend a new entry to IAC.md, keeping only MAX_IAC_ENTRIES (thread-safe)."""
with _file_lock:
self._ensure_iac_exists()
content = self._read_iac()
# Parse existing entries
entries = self._parse_iac_entries(content)
# Prepend new entry
entries.insert(0, new_entry.strip())
# Limit to MAX_IAC_ENTRIES
entries = entries[:MAX_IAC_ENTRIES]
# Write back
self._write_iac(entries)
def _update_iac_entry(
self,
spawn_id: str,
success: bool,
result_text: str,
duration_seconds: float,
cost_usd: float,
error: Optional[str] = None,
):
"""Update an existing IAC entry with completion data (thread-safe)."""
with _file_lock:
content = self._read_iac()
# Build status string for checkbox line
if success:
new_checkbox = f"- [x] ✅ **Done** ({duration_seconds:.1f}s, ${cost_usd:.4f})"
else:
new_checkbox = f"- [x] ❌ **Failed**: {error or 'Unknown'} ({duration_seconds:.1f}s)"
# Find and update the running checkbox line for this spawn
import re
# Match: - [ ] ⏳ **Running** | `#spawn_id` | rest of line
old_pattern = rf"- \[ \] ⏳ \*\*Running\*\* \| `#{spawn_id}` \| ([^\n]+)"
new_line = f"{new_checkbox} | `#{spawn_id}` | \\1"
content = re.sub(old_pattern, new_line, content)
# Replace result placeholder with actual result
result_placeholder = f"<!-- RESULT_{spawn_id} -->"
# Truncate very long results for display but keep essential info
display_result = result_text
if len(result_text) > 50000:
display_result = result_text[:25000] + "\n\n... [truncated] ...\n\n" + result_text[-25000:]
# Use 4 backticks as fence if result contains triple backticks
fence = "````" if "```" in display_result else "```"
result_block = f"""<details>
<summary>📤 Output ({len(result_text)} chars)</summary>
{fence}
{display_result}
{fence}
</details>"""
content = content.replace(result_placeholder, result_block)
# Write back
self.iac_path.write_text(content, encoding='utf-8')
def log_spawn_start(
self,
agent: str,
model: str,
prompt: str,
tools: list[str],
task_summary: Optional[str] = None,
agent_type: str = "CLI",
) -> str:
"""
Log the start of an agent spawn.
Returns the spawn_id for tracking.
"""
spawn_id = generate_spawn_id()
started_at = now_iso()
# Create task summary from first line of prompt if not provided
if not task_summary:
first_line = prompt.split('\n')[0][:80]
task_summary = first_line + ('...' if len(prompt.split('\n')[0]) > 80 else '')
record = SpawnRecord(
spawn_id=spawn_id,
agent=agent,
model=model,
agent_type=agent_type,
task_summary=task_summary,
prompt=prompt,
tools=tools,
started_at=started_at,
)
self.active_spawns[spawn_id] = record
# Write to IAC.md - unified entry format (will be updated on completion)
tools_str = ', '.join(tools) if tools else 'None'
# Escape backticks in prompt to prevent breaking markdown code fences
# Use 4 backticks as fence if prompt contains triple backticks
fence = "````" if "```" in prompt else "```"
iac_entry = f"""### 🤖 {task_summary}
- [ ] ⏳ **Running** | `#{spawn_id}` | {agent} ({model}) [{agent_type}] | {now_time()} | Tools: {tools_str}
<details>
<summary>📥 Input ({len(prompt)} chars)</summary>
{fence}
{prompt}
{fence}
</details>
<!-- RESULT_{spawn_id} -->
---"""
self._prepend_iac(iac_entry)
# Active agents table is updated via _write_iac in _prepend_iac
return spawn_id
def log_spawn_complete(
self,
spawn_id: str,
success: bool,
result_text: str,
duration_seconds: float,
cost_usd: float = 0.0,
error: Optional[str] = None,
):
"""Log the completion of an agent spawn."""
record = self.active_spawns.get(spawn_id)
if not record:
# Spawn wasn't tracked, create minimal record
record = SpawnRecord(
spawn_id=spawn_id,
agent="unknown",
model="unknown",
task_summary="Unknown task",
prompt="",
tools=[],
started_at=now_iso(),
)
record.completed_at = now_iso()
record.duration_seconds = duration_seconds
record.success = success
record.cost_usd = cost_usd
record.error = error
# Store full result (not truncated)
record.result_summary = result_text
# Update existing entry in IAC.md instead of appending
self._update_iac_entry(spawn_id, success, result_text, duration_seconds, cost_usd, error)
# Remove from active spawns
if spawn_id in self.active_spawns:
del self.active_spawns[spawn_id]
# Refresh IAC.md header to update active agents table
self._refresh_iac_header()
def _refresh_iac_header(self):
"""Refresh the IAC.md header (active agents table) without touching entries."""
with _file_lock:
content = self._read_iac()
entries = self._parse_iac_entries(content)
self._write_iac(entries)
# Global logger instance
_logger: Optional[AgentLogger] = None
def get_logger() -> AgentLogger:
"""Get or create the global logger instance."""
global _logger
if _logger is None:
_logger = AgentLogger()
return _logger
def log_spawn_start(
agent: str,
model: str,
prompt: str,
tools: list[str],
task_summary: Optional[str] = None,
agent_type: str = "CLI",
) -> str:
"""Log the start of an agent spawn. Returns spawn_id."""
return get_logger().log_spawn_start(agent, model, prompt, tools, task_summary, agent_type)
def log_spawn_complete(
spawn_id: str,
success: bool,
result_text: str,
duration_seconds: float,
cost_usd: float = 0.0,
error: Optional[str] = None,
):
"""Log the completion of an agent spawn."""
get_logger().log_spawn_complete(
spawn_id, success, result_text, duration_seconds, cost_usd, error
)