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 | class StateManager:
"""Manages conversation snapshots, task state, and runtime session data."""
def __init__(
self,
event_stream_manager: EventStreamManager,
*,
summarize_at: int = 30,
tail_keep_after_summarize: int = 15,
):
# We have two types of state, persistant and session state
# Persistant state are state that will not be changed frequently,
# e.g. agent properties
# Session state are states that is short-termed, one time used
# e.g. current conversation, conversation state, action state
self.task: Optional[Task] = None
self.event_stream_manager = event_stream_manager
self._conversation: List[ConversationMessage] = []
self.head_summary: Optional[str] = None
self.summarize_at = summarize_at
self.tail_keep_after_summarize = tail_keep_after_summarize
self._summarize_task: Optional[asyncio.Task] = None
self._lock = threading.RLock()
MINIMUM_BUFFER_BEFORE_NEXT_SUMMARIZATION = 10
if tail_keep_after_summarize + MINIMUM_BUFFER_BEFORE_NEXT_SUMMARIZATION > summarize_at:
logger.warning(
f"[CONVERSATION SUMMARIZATION] Value for tail_keep_after_summarize ({tail_keep_after_summarize}) "
f"is too large relative to summarize_at ({summarize_at}). "
f"Resetting tail_keep_after_summarize to {summarize_at - MINIMUM_BUFFER_BEFORE_NEXT_SUMMARIZATION}"
)
self.tail_keep_after_summarize = summarize_at - MINIMUM_BUFFER_BEFORE_NEXT_SUMMARIZATION
async def start_session(self, gui_mode: bool = False):
conversation_state = await self.get_conversation_state()
event_stream = self.get_event_stream_snapshot()
current_task: Optional[Task] = self.get_current_task_state()
logger.debug(f"[CURRENT TASK]: this is the current_task: {current_task}")
STATE.refresh(
conversation_state=conversation_state,
current_task=current_task,
event_stream=event_stream,
gui_mode=gui_mode
)
def clean_state(self):
"""
End the session, clearing session context so the next user input starts fresh.
"""
STATE.refresh()
def clear_conversation_history(self) -> None:
"""Drop all stored conversation messages for the active user."""
with self._lock:
self._conversation.clear()
self.head_summary = None
self._update_session_conversation_state()
def reset(self) -> None:
"""Fully reset runtime state, including tasks and session context."""
self.task = None
STATE.agent_properties: AgentProperties = AgentProperties(current_task_id="", action_count=0, current_step_index=0)
self.clear_conversation_history()
if self.event_stream_manager:
self.event_stream_manager.clear_all()
self.clean_state()
def _format_conversation_state(self) -> str:
with self._lock:
lines: List[str] = []
# Include summary if available
if self.head_summary:
lines.append("Summary of previous conversation:")
lines.append(self.head_summary)
lines.append("")
# Include recent messages
if self._conversation:
lines.append("Recent conversation:")
for message in self._conversation[-25:]:
timestamp = message["timestamp"]
role = message["role"]
content = message["content"]
lines.append(f"{timestamp}: {role}: \"{content}\"")
return "\n".join(lines) if lines else ""
async def get_conversation_state(self) -> str:
return self._format_conversation_state()
def _append_conversation_message(self, role: Literal["user", "agent"], content: str) -> None:
with self._lock:
self._conversation.append(
{
"role": role,
"content": content,
"timestamp": datetime.utcnow().isoformat(),
}
)
def _update_session_conversation_state(self) -> None:
STATE.update_conversation_state(self._format_conversation_state())
def record_user_message(self, content: str) -> None:
self._append_conversation_message("user", content)
self._update_session_conversation_state()
self.summarize_if_needed()
def record_agent_message(self, content: str) -> None:
self._append_conversation_message("agent", content)
self._update_session_conversation_state()
self.summarize_if_needed()
def get_current_step(self) -> Optional[Step]:
wf: Optional[Task] = self.task
if not wf:
return None
return wf.get_current_step()
def get_event_stream_snapshot(self) -> str:
return self.event_stream_manager.snapshot()
def get_current_task_state(self) -> Optional[Task]:
task: Optional[Task] = self.task
logger.debug(f"[TASK] task in StateManager: {task}")
if not task:
logger.debug("[TASK] task not found in StateManager")
return None
# Build minimal per-step representation
steps_list: List[Step] = []
for step in task.steps:
item: Dict[str, Any] = {}
item = {
"step_index": step.step_index,
"step_name": step.step_name,
"description": step.description,
"action_instruction": step.action_instruction,
"validation_instruction": step.validation_instruction,
"status": step.status,
}
if step.failure_message:
item["failure_message"] = step.failure_message
steps_list.append(Step(**item, action_id=step.action_id))
task: Task = Task(
id=task.id,
name=task.name,
instruction=task.instruction,
goal=task.goal,
inputs_params=task.inputs_params,
context=task.context,
steps=steps_list
)
return task
def bump_task_state(self) -> None:
STATE.update_current_task(
self.get_current_task_state()
)
def bump_event_stream(self) -> None:
STATE.update_event_stream(self.get_event_stream_snapshot())
def is_running_task(self) -> bool:
if self.task:
return True
else:
return False
def add_to_active_task(self, task: Optional[Task]) -> None:
if task is None:
self.task = None
STATE.update_current_task(None)
else:
self.task = task
self.bump_task_state()
def remove_active_task(self) -> None:
self.task = None
STATE.update_current_task(None)
# ───────────────────── summarization & pruning ───────────────────────
def summarize_if_needed(self) -> None:
"""
Trigger summarization when the conversation exceeds the configured threshold.
Uses asyncio.create_task to schedule summarize_by_LLM() without requiring
callers of record_*_message() to be async/await.
"""
with self._lock:
if len(self._conversation) < self.summarize_at:
return
if self._summarize_task is not None and not self._summarize_task.done():
return
try:
loop = asyncio.get_running_loop()
except RuntimeError:
logger.warning("[StateManager] No running event loop; cannot schedule summarization.")
return
self._summarize_task = loop.create_task(self.summarize_by_LLM(), name="conversation_summarize")
self._summarize_task.add_done_callback(self._on_summarize_done)
def _on_summarize_done(self, task: asyncio.Task) -> None:
try:
task.result()
except asyncio.CancelledError:
return
except Exception:
logger.exception("[StateManager] summarize_by_LLM task crashed unexpectedly")
async def summarize_by_LLM(self) -> None:
"""
Summarize the oldest conversation messages using the language model.
This version is concurrency-safe with synchronous record_*_message() calls:
- Snapshot the chunk under a lock
- Release lock while awaiting the LLM
- Re-acquire lock to apply summary + prune using the *current* conversation
so messages appended during the await are not lost.
"""
with self._lock:
if not self._conversation:
return
cutoff = max(0, len(self._conversation) - self.tail_keep_after_summarize)
if cutoff <= 0:
# Nothing old enough to summarize
return
chunk = list(self._conversation[:cutoff])
first_ts = chunk[0]["timestamp"] if chunk else None
last_ts = chunk[-1]["timestamp"] if chunk else None
window = ""
if first_ts and last_ts:
window = f"{first_ts} to {last_ts}"
compact_lines = "\n".join(
f"{msg['timestamp']}: {msg['role']}: \"{msg['content']}\""
for msg in chunk
)
previous_summary = self.head_summary or "(none)"
prompt = CONVERSATION_SUMMARIZATION_PROMPT.format(
window=window,
previous_summary=previous_summary,
compact_lines=compact_lines
)
try:
llm = self.event_stream_manager.llm
llm_output = await llm.generate_response_async(user_prompt=prompt)
new_summary = (llm_output or "").strip()
logger.debug(f"[CONVERSATION SUMMARIZATION] llm_output_len={len(llm_output or '')}")
if not new_summary:
logger.warning("[CONVERSATION SUMMARIZATION] LLM returned empty summary; not updating.")
return
# Apply + prune under lock
# Remove exactly the messages we summarized (first 'cutoff' messages)
# New messages added during await will remain at the end
with self._lock:
self.head_summary = new_summary
if cutoff >= len(self._conversation):
# All messages were summarized, clear everything
self._conversation = []
else:
# Remove the summarized messages, keep the rest (including any new ones)
self._conversation = self._conversation[cutoff:]
self._update_session_conversation_state()
except Exception:
logger.exception("[StateManager] LLM summarization failed. Keeping all messages without summarization.")
return
|