Coverage for src/copytrading_engine/assistant/conversation.py: 99%
97 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""One conversation's bounded memory and one answer's ordered events; nothing is persisted."""
3from collections import OrderedDict
4from typing import Literal
6from pydantic import BaseModel, ConfigDict
8MAX_TURNS = 20
9MAX_CONVERSATIONS = 4
10MAX_LINKS = 3
12type EventKind = Literal["text", "step", "link", "proposal", "error", "done"]
15class AssistantLink(BaseModel):
16 model_config = ConfigDict(frozen=True, extra="forbid")
18 kind: Literal["post", "account", "guru"]
19 id: str
20 title: str
23class AssistantEvent(BaseModel):
24 model_config = ConfigDict(frozen=True, extra="forbid")
26 seq: int
27 kind: EventKind
28 text: str | None = None
29 link: AssistantLink | None = None
30 proposal_id: str | None = None
31 code: str | None = None
34class Turn:
35 """One answer in progress: an append-only event log the app reads by sequence."""
37 def __init__(self, turn_id: str) -> None:
38 self.turn_id = turn_id
39 self._events: list[AssistantEvent] = []
40 self._links: set[tuple[str, str]] = set()
41 self._text_written = False
42 self.done = False
43 self.cancelled = False
45 def _add(
46 self,
47 kind: EventKind,
48 *,
49 text: str | None = None,
50 link: AssistantLink | None = None,
51 proposal_id: str | None = None,
52 code: str | None = None,
53 ) -> None:
54 if self.done:
55 return
56 self._events.append(
57 AssistantEvent(
58 seq=len(self._events) + 1,
59 kind=kind,
60 text=text,
61 link=link,
62 proposal_id=proposal_id,
63 code=code,
64 )
65 )
67 def add_text(self, chunk: str) -> None:
68 """Text written after a tool call starts a new paragraph instead of running on."""
69 if not chunk:
70 return
71 if self._text_written and self._events[-1].kind != "text":
72 chunk = "\n\n" + chunk.lstrip("\n")
73 self._text_written = True
74 self._add(kind="text", text=chunk)
76 def add_step(self, text: str) -> None:
77 self._add(kind="step", text=text)
79 def add_link(self, link: AssistantLink) -> None:
80 key = (link.kind, link.id)
81 if key in self._links or len(self._links) >= MAX_LINKS:
82 return
83 self._links.add(key)
84 self._add(kind="link", link=link)
86 def add_proposal(self, proposal_id: str) -> None:
87 self._add(kind="proposal", proposal_id=proposal_id)
89 def fail(self, code: str, text: str) -> None:
90 self._add(kind="error", code=code, text=text)
91 self.finish()
93 def finish(self) -> None:
94 self._add(kind="done")
95 self.done = True
97 def cancel(self) -> None:
98 self.cancelled = True
99 self.finish()
101 def events(self, after: int) -> tuple[AssistantEvent, ...]:
102 return tuple(event for event in self._events if event.seq > after)
105class Conversation:
106 def __init__(self, conversation_id: str) -> None:
107 self.conversation_id = conversation_id
108 self.turns: list[list[object]] = []
109 self.running: Turn | None = None
110 self.turn_ids: list[str] = []
112 @property
113 def history(self) -> list[object]:
114 return [message for turn in self.turns for message in turn]
116 def remember(self, messages: list[object]) -> None:
117 self.turns.append(list(messages))
118 del self.turns[:-MAX_TURNS]
121class ConversationBook:
122 def __init__(self) -> None:
123 self._conversations: OrderedDict[str, Conversation] = OrderedDict()
124 self._turns: dict[str, Turn] = {}
126 def get_or_open(self, conversation_id: str) -> Conversation:
127 conversation = self._conversations.pop(conversation_id, None) or Conversation(
128 conversation_id
129 )
130 self._conversations[conversation_id] = conversation
131 while len(self._conversations) > MAX_CONVERSATIONS:
132 _, dropped = self._conversations.popitem(last=False)
133 if dropped.running is not None:
134 dropped.running.cancel()
135 # Remove all turn ids from this conversation
136 for turn_id in dropped.turn_ids:
137 self._turns.pop(turn_id, None)
138 return conversation
140 def existing(self, conversation_id: str) -> Conversation:
141 return self._conversations[conversation_id]
143 def register(self, turn: Turn, conversation: Conversation) -> None:
144 self._turns[turn.turn_id] = turn
145 conversation.turn_ids.append(turn.turn_id)
146 # Remove old turn ids from _turns if the conversation has too many
147 while len(conversation.turn_ids) > MAX_TURNS:
148 old_id = conversation.turn_ids.pop(0)
149 self._turns.pop(old_id, None)
151 def turn(self, turn_id: str) -> Turn:
152 return self._turns[turn_id]
154 def forget_all(self) -> None:
155 for conversation in self._conversations.values():
156 if conversation.running is not None: 156 ↛ 155line 156 didn't jump to line 155 because the condition on line 156 was always true
157 conversation.running.cancel()
158 self._conversations.clear()
159 self._turns.clear()