Coverage for src/copytrading_engine/assistant/tools.py: 97%

98 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""The assistant's hands: each tool is one agent-control request, audited under its caller name.""" 

2 

3import datetime as dt 

4import json 

5import uuid 

6from collections.abc import Callable, Mapping 

7 

8from copytrading_engine.assistant import insights, results 

9from copytrading_engine.assistant.conversation import AssistantLink, Turn 

10from copytrading_engine.assistant.wording import REFUSALS 

11from copytrading_engine.control import wire 

12from copytrading_engine.control.service import ControlContext, ControlService 

13 

14# The audit trail names the caller of every control request; the assistant is one, in process. 

15ASSISTANT_CALLER = "CopyTrading Assistant" 

16# The assistant only runs inside the app, which carries out an approved change to the setup. 

17CONTEXT = ControlContext( 

18 access_level="propose", unlocked=True, caller_path=ASSISTANT_CALLER, app_actions=True 

19) 

20 

21# What each tool did, added once it has done it. 

22STEP = { 

23 "get_status": "Checked whether copying is running", 

24 "list_accounts": "Looked at your accounts", 

25 "list_activity": "Read recent posts", 

26 "list_account_events": "Read {account_id}'s history", 

27 "list_proposals": "Checked what is waiting for you", 

28 "pause_processing": "Paused copying", 

29 "pause_account": "Stopped copying into {account_id}", 

30 "propose_resume_account": "Asked you to approve copying into {account_id}", 

31 "propose_recovery_preference": "Asked you to approve {account_id}'s after-restart setting", 

32 "guru_record": "Added up {guru}'s calls", 

33 "explain_skip": "Looked at that post", 

34} 

35 

36# What each tool tried, when the engine refused it, so a refusal never reads as done. 

37REFUSED_STEP = { 

38 "get_status": "Couldn't check whether copying is running", 

39 "list_accounts": "Couldn't look at your accounts", 

40 "list_activity": "Couldn't read recent posts", 

41 "list_account_events": "Couldn't read {account_id}'s history", 

42 "list_proposals": "Couldn't check what is waiting for you", 

43 "pause_processing": "Couldn't pause copying", 

44 "pause_account": "Couldn't stop copying into {account_id}", 

45 "propose_resume_account": "Couldn't ask you to approve copying into {account_id}", 

46 "propose_recovery_preference": ( 

47 "Couldn't ask you to approve {account_id}'s after-restart setting" 

48 ), 

49 "explain_skip": "Couldn't find that post", 

50} 

51 

52 

53def refused(code: str) -> dict: 

54 """A refusal the model can explain: the code, and what it means in plain words.""" 

55 return {"refused": code, "why": REFUSALS.get(code, code.replace("_", " "))} 

56 

57 

58# A turn the owner cancelled, or that was dropped, must never reach the engine. 

59CANCELLED = refused("cancelled") 

60 

61 

62class AssistantTools: 

63 def __init__( 

64 self, 

65 control: ControlService, 

66 operator: insights.Operator, 

67 turn: Turn, 

68 *, 

69 engine_state: Callable[[], str], 

70 now: Callable[[], dt.datetime], 

71 guru_names: Mapping[str, str] | None = None, 

72 ) -> None: 

73 self._control = control 

74 self._operator = operator 

75 self._turn = turn 

76 self._engine_state = engine_state 

77 self._now = now 

78 self._guru_names = dict(guru_names or {}) 

79 

80 @property 

81 def guru_names(self) -> dict[str, str]: 

82 return dict(self._guru_names) 

83 

84 def knows_guru(self, guru: str) -> bool: 

85 """The guru is one the app named, by id or by name.""" 

86 guru_id, _ = self._guru(guru) 

87 return guru_id in self._guru_names 

88 

89 async def account_ids(self) -> list[str]: 

90 """The engine's accounts, read without a step line, to tell the model which ones exist.""" 

91 line = json.dumps( 

92 { 

93 "schema_version": wire.SCHEMA_VERSION, 

94 "request_id": f"a-{uuid.uuid4().hex[:12]}", 

95 "operation": "get_status", 

96 } 

97 ) 

98 response = await self._control.handle(line, CONTEXT, engine_state=self._engine_state()) 

99 if not isinstance(response.ok, wire.StatusView): 99 ↛ 100line 99 didn't jump to line 100 because the condition on line 99 was never true

100 return [] 

101 return [account.account_id for account in response.ok.accounts] 

102 

103 def _guru(self, guru: str) -> tuple[str, str]: 

104 """The guru's id and display name, whether the model passed the id or the name.""" 

105 if guru in self._guru_names: 

106 return guru, self._guru_names[guru] 

107 wanted = guru.strip().casefold() 

108 for guru_id, name in self._guru_names.items(): 

109 if name.strip().casefold() == wanted: 

110 return guru_id, name 

111 return guru, guru 

112 

113 async def _ask(self, operation: str, **values: object) -> dict: 

114 if self._turn.cancelled: 

115 return CANCELLED 

116 line = json.dumps( 

117 { 

118 "schema_version": wire.SCHEMA_VERSION, 

119 "request_id": f"a-{uuid.uuid4().hex[:12]}", 

120 "operation": operation, 

121 **values, 

122 } 

123 ) 

124 response = await self._control.handle(line, CONTEXT, engine_state=self._engine_state()) 

125 if response.error is not None: 

126 self._turn.add_step(REFUSED_STEP[operation].format(**values)) 

127 return refused(response.error.code) 

128 assert response.ok is not None 

129 self._turn.add_step(STEP[operation].format(**values)) 

130 result = results.result(response.ok, self._guru_names) 

131 if isinstance(response.ok, wire.ProposalView): 

132 # The proposal card already names the account, so it carries no extra link. 

133 self._turn.add_proposal(response.ok.proposal_id) 

134 elif "account_id" in values: 

135 account_id = str(values["account_id"]) 

136 self._turn.add_link(AssistantLink(kind="account", id=account_id, title=account_id)) 

137 return result 

138 

139 async def get_status(self) -> dict: 

140 return await self._ask("get_status") 

141 

142 async def list_accounts(self) -> dict: 

143 return await self._ask("list_accounts") 

144 

145 async def list_activity(self, limit: int = 25) -> dict: 

146 return await self._ask("list_activity", limit=limit) 

147 

148 async def list_account_events(self, account_id: str, limit: int = 25) -> dict: 

149 return await self._ask("list_account_events", account_id=account_id, limit=limit) 

150 

151 async def list_proposals(self) -> dict: 

152 return await self._ask("list_proposals") 

153 

154 async def pause_processing(self) -> dict: 

155 return await self._ask("pause_processing") 

156 

157 async def pause_account(self, account_id: str) -> dict: 

158 return await self._ask("pause_account", account_id=account_id) 

159 

160 async def propose_resume_account(self, account_id: str) -> dict: 

161 return await self._ask("propose_resume_account", account_id=account_id) 

162 

163 async def propose_recovery_preference(self, account_id: str, preference: str) -> dict: 

164 return await self._ask( 

165 "propose_recovery_preference", account_id=account_id, preference=preference 

166 ) 

167 

168 async def guru_record(self, guru_id: str, days: int = 7) -> dict: 

169 if self._turn.cancelled: 

170 return CANCELLED 

171 guru_id, name = self._guru(guru_id) 

172 record = await insights.guru_record(self._operator, guru_id, days, self._now()) 

173 self._turn.add_step(STEP["guru_record"].format(guru=name)) 

174 self._turn.add_link(AssistantLink(kind="guru", id=guru_id, title=name)) 

175 return results.guru_record(record, name) | {"guru_id": guru_id} 

176 

177 async def explain_skip(self, source_id: str) -> dict: 

178 if self._turn.cancelled: 

179 return CANCELLED 

180 try: 

181 explanation = await insights.explain_skip(self._operator, source_id) 

182 except KeyError: 

183 self._turn.add_step(REFUSED_STEP["explain_skip"]) 

184 return refused("not_found") 

185 self._turn.add_step(STEP["explain_skip"]) 

186 self._turn.add_link(AssistantLink(kind="post", id=source_id, title="Open in Activity")) 

187 return results.skip(explanation)