-
-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathsession_engine.py
More file actions
343 lines (280 loc) · 12.8 KB
/
session_engine.py
File metadata and controls
343 lines (280 loc) · 12.8 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
"""Session engine — orchestrates structured multi-agent sessions."""
import logging
import threading
import time
log = logging.getLogger(__name__)
# Dissent mandate injected for review/critique roles
_DISSENT_LINE = "Provide your own independent analysis. Do not repeat or defer to other participants."
# Roles that get the dissent mandate
_DISSENT_ROLES = {"reviewer", "red_team", "critic", "challenger", "against"}
class SessionEngine:
"""Orchestrates session turn flow on top of existing chat infrastructure.
Listens to message store callbacks, advances session state, and triggers
agents via the AgentTrigger system.
"""
def __init__(self, session_store, message_store, agent_trigger, registry=None):
self._store = session_store
self._messages = message_store
self._trigger = agent_trigger
self._registry = registry
self._lock = threading.Lock()
# Hook into message stream
self._messages.on_message(self._on_message)
# --- Public API ---
def start_session(self, template_id: str, channel: str, cast: dict,
started_by: str, goal: str = "") -> dict | None:
"""Start a new session. Returns the session dict or None on failure."""
session = self._store.create(
template_id=template_id,
channel=channel,
cast=cast,
started_by=started_by,
goal=goal,
)
if not session:
return None
log.info("Session %d started: %s in #%s", session["id"],
session["template_name"], channel)
# Trigger the first participant
self._trigger_current(session)
return session
def emit_current_phase_banner(self, session: dict):
"""Post the banner for the session's current phase."""
tmpl = self._store.get_template(session.get("template_id", ""))
if not tmpl:
return
phases = tmpl.get("phases", [])
phase_idx = session.get("current_phase", 0)
if phase_idx >= len(phases):
return
phase = phases[phase_idx]
self._messages.add(
sender="system",
text=f"Phase: {phase['name']}",
msg_type="session_phase",
channel=session.get("channel", "general"),
metadata={
"session_id": session["id"],
"phase": phase_idx,
"phase_name": phase["name"],
},
)
def end_session(self, session_id: int, reason: str = "ended by user") -> dict | None:
"""End a session early."""
session = self._store.interrupt(session_id, reason)
if session:
log.info("Session %d interrupted: %s", session_id, reason)
return session
def get_active(self, channel: str) -> dict | None:
"""Get the active session for a channel, enriched with phase info."""
session = self._store.get_active(channel)
if not session:
return None
return self._enrich(session)
def get_allowed_agent(self, channel: str) -> str | None:
"""If a session is active on this channel, return the agent whose turn it is.
Returns None if no session is active (meaning all agents are allowed)."""
session = self._store.get_active(channel)
if not session or session.get("state") not in ("active", "waiting"):
return None
return self._get_expected_agent(session)
def list_active(self) -> list[dict]:
"""List all active/waiting/paused sessions, enriched for the frontend."""
active = []
for session in self._store.list_all():
if session.get("state") in ("active", "waiting", "paused"):
active.append(self._enrich(session))
return active
def resume_active_sessions(self):
"""On server restart, resume any sessions that were in progress.
Only re-trigger 'active' sessions. 'waiting' sessions already had
their trigger sent before the restart — re-triggering would
double-queue the same participant.
"""
for session in self._store.list_all():
if session.get("state") == "active":
log.info("Resuming session %d (%s) from phase %d, turn %d",
session["id"], session.get("template_name", "?"),
session["current_phase"], session["current_turn"])
self._trigger_current(session)
def _is_agent(self, name: str) -> bool:
"""Check if name belongs to a registered agent (not a human)."""
if self._registry:
return self._registry.is_registered(name)
return False
# --- Message callback ---
def _on_message(self, msg: dict):
"""Called on every new chat message. Checks if it advances a session."""
channel = msg.get("channel", "general")
sender = msg.get("sender", "")
# Ignore system-generated messages (banners, phase markers, etc.)
if sender == "system" or msg.get("type", "chat") != "chat":
return
session = self._store.get_active(channel)
if not session:
return
expected_agent = self._get_expected_agent(session)
if not expected_agent:
return
cast_agents = set(session.get("cast", {}).values())
sender_is_agent = self._is_agent(sender)
# Agent not in this session's cast — ignore
if sender_is_agent and sender not in cast_agents:
return
# Human spoke but it's not their turn — pause if an agent is expected
if not sender_is_agent and sender != expected_agent and self._is_agent(expected_agent):
self._store.pause(session["id"])
log.info("Session %d paused: human interruption by %s", session["id"], sender)
return
if sender == expected_agent:
# Auto-resume if paused
if session["state"] == "paused":
self._store.resume(session["id"])
# Defer advance slightly so the triggering message broadcasts
# before phase/completion banners are added
threading.Timer(0.3, self._advance, args=(session, msg["id"])).start()
return
# Wrong agent spoke - ignore
return
# --- Engine core ---
def _advance(self, session: dict, message_id: int):
"""Advance session after the expected agent has responded."""
tmpl = self._store.get_template(session["template_id"])
if not tmpl:
self._store.interrupt(session["id"], "template not found")
return
phases = tmpl.get("phases", [])
phase_idx = session["current_phase"]
turn_idx = session["current_turn"]
if phase_idx >= len(phases):
self._store.complete(session["id"], message_id)
return
phase = phases[phase_idx]
participants = phase.get("participants", [])
next_turn = turn_idx + 1
if next_turn < len(participants):
# More turns in this phase
session = self._store.advance_turn(session["id"], message_id)
if session:
self._trigger_current(session)
else:
# Phase complete
next_phase = phase_idx + 1
if next_phase < len(phases):
# More phases
session = self._store.advance_phase(session["id"], message_id)
if session:
next_phase_obj = phases[next_phase]
self._messages.add(
sender="system",
text=f"Phase: {next_phase_obj['name']}",
msg_type="session_phase",
channel=session.get("channel", "general"),
metadata={"session_id": session["id"],
"phase": next_phase, "phase_name": next_phase_obj["name"]},
)
self._trigger_current(session)
else:
# Session complete - check if this was the output phase
is_output = phase.get("is_output", False)
self._store.complete(session["id"],
message_id if is_output else None)
log.info("Session %d complete", session["id"])
def _trigger_current(self, session: dict):
"""Trigger the agent whose turn it is."""
tmpl = self._store.get_template(session["template_id"])
if not tmpl:
return
phases = tmpl.get("phases", [])
phase_idx = session["current_phase"]
turn_idx = session["current_turn"]
if phase_idx >= len(phases):
return
phase = phases[phase_idx]
participants = phase.get("participants", [])
if turn_idx >= len(participants):
return
role = participants[turn_idx]
cast = session.get("cast", {})
agent = cast.get(role)
if not agent:
log.warning("Session %d: no agent cast for role '%s'", session["id"], role)
self._store.interrupt(session["id"], f"no agent for role '{role}'")
return
if not self._is_agent(agent):
# Human's turn - just mark as waiting, don't trigger
self._store.set_waiting(session["id"], agent)
return
# Mark waiting
self._store.set_waiting(session["id"], agent)
# Assemble the prompt
prompt = self._assemble_prompt(session, tmpl, phase, role)
# Trigger the agent
channel = session.get("channel", "general")
log.info("Session %d: triggering %s (%s) for phase '%s'",
session["id"], agent, role, phase["name"])
try:
self._trigger.trigger_sync(agent, channel=channel, prompt=prompt)
except Exception as exc:
log.error("Session %d: failed to trigger %s: %s",
session["id"], agent, exc)
def _assemble_prompt(self, session: dict, tmpl: dict, phase: dict,
role: str) -> str:
"""Build the session-aware prompt for an agent."""
phases = tmpl.get("phases", [])
phase_idx = session["current_phase"]
total_phases = len(phases)
channel = session.get("channel", "general")
lines = [
f"SESSION: {tmpl.get('name', '?')}",
]
if session.get("goal"):
lines.append(f"GOAL: {session['goal']}")
lines.append(f"PHASE: {phase['name']} ({phase_idx + 1}/{total_phases})")
lines.append(f"YOUR ROLE: {role}")
lines.append(f"INSTRUCTION: {phase.get('prompt', '')}")
# Dissent mandate for review/critique roles
if role.lower() in _DISSENT_ROLES:
lines.append(f"\n{_DISSENT_LINE}")
lines.append("")
lines.append(f"IMPORTANT: You MUST respond using the 'chat_send' tool in the #{channel} channel. "
"The session flow is blocked until your message appears in the chat. "
"Do NOT respond only in your terminal.")
lines.append("Read recent messages in the channel for context (use 'chat_read' or 'mcp read'), "
"then post your response. Stay focused on the session goal.")
# Use double newlines to ensure separation in TUIs that might collapse single newlines
return "\n\n".join(lines)
def _get_expected_agent(self, session: dict) -> str | None:
"""Get the agent name expected to respond next."""
tmpl = self._store.get_template(session["template_id"])
if not tmpl:
return None
phases = tmpl.get("phases", [])
phase_idx = session["current_phase"]
turn_idx = session["current_turn"]
if phase_idx >= len(phases):
return None
phase = phases[phase_idx]
participants = phase.get("participants", [])
if turn_idx >= len(participants):
return None
role = participants[turn_idx]
cast = session.get("cast", {})
return cast.get(role)
def _enrich(self, session: dict) -> dict:
"""Add computed fields to a session dict for the frontend."""
tmpl = self._store.get_template(session["template_id"])
if tmpl:
phases = tmpl.get("phases", [])
session["total_phases"] = len(phases)
phase_idx = session["current_phase"]
if phase_idx < len(phases):
phase = phases[phase_idx]
session["phase_name"] = phase["name"]
participants = phase.get("participants", [])
turn_idx = session["current_turn"]
if turn_idx < len(participants):
role = participants[turn_idx]
session["current_role"] = role
session["current_agent"] = session.get("cast", {}).get(role)
return session