66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
|
|
def build_subagent_event(
|
|
phase: str,
|
|
room_id: str,
|
|
thread_root: str,
|
|
subagent_id: str = "",
|
|
metadata: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
return {
|
|
"phase": phase,
|
|
"room_id": room_id,
|
|
"thread_root": thread_root,
|
|
"subagent_id": subagent_id,
|
|
"metadata": metadata or {},
|
|
}
|
|
|
|
|
|
class SubagentLifecycle:
|
|
PHASE_SPAWNING = "spawning"
|
|
PHASE_ENDED = "ended"
|
|
PHASE_DELIVERY_TARGET = "delivery_target"
|
|
|
|
def __init__(self):
|
|
self._hooks: dict[str, list] = {
|
|
self.PHASE_SPAWNING: [],
|
|
self.PHASE_ENDED: [],
|
|
self.PHASE_DELIVERY_TARGET: [],
|
|
}
|
|
|
|
def on(self, phase: str, callback) -> None:
|
|
if phase in self._hooks:
|
|
self._hooks[phase].append(callback)
|
|
|
|
async def trigger(
|
|
self, phase: str, room_id: str, thread_root: str, subagent_id: str = "", metadata: dict[str, Any] | None = None
|
|
) -> list[Any]:
|
|
event = build_subagent_event(phase, room_id, thread_root, subagent_id, metadata)
|
|
results = []
|
|
for cb in self._hooks.get(phase, []):
|
|
try:
|
|
result = await cb(event)
|
|
results.append(result)
|
|
except Exception:
|
|
pass
|
|
return results
|
|
|
|
def _create_session(self, room_id: str, thread_root: str) -> dict[str, Any]:
|
|
return {
|
|
"session_id": f"subagent_{room_id}_{thread_root}",
|
|
"room_id": room_id,
|
|
"thread_root": thread_root,
|
|
"status": "spawning",
|
|
}
|
|
|
|
def resolve_delivery_target(self, event: dict[str, Any]) -> dict[str, str]:
|
|
metadata = event.get("metadata", {})
|
|
return {
|
|
"room_id": event.get("room_id", ""),
|
|
"thread_root": event.get("thread_root", ""),
|
|
"delivery_type": metadata.get("delivery_type", "thread"),
|
|
}
|