Coverage for src/copytrading_engine/host/pipe/requests.py: 100%

157 statements  

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

1"""The engine pipe's request contract: one model per operation the app may send.""" 

2 

3import datetime as dt 

4from collections.abc import Awaitable, Callable 

5from typing import Annotated, Literal 

6 

7from pydantic import ( 

8 AwareDatetime, 

9 BaseModel, 

10 ConfigDict, 

11 Field, 

12 SecretStr, 

13 StrictInt, 

14 TypeAdapter, 

15 model_validator, 

16) 

17 

18from copytrading_engine.assistant.service import AskContext 

19from copytrading_engine.control.service import ControlContext, SetupAuthorization 

20from copytrading_engine.control.wire import MAX_LINE_BYTES as MAX_CONTROL_LINE_BYTES 

21from copytrading_engine.execution.domain.lifecycle import AccountControlCommand 

22from copytrading_engine.execution.domain.lot_sales import LotSaleConfirmation, LotSalePreviewRequest 

23from copytrading_engine.execution.domain.manual_commands import ( 

24 ManualConfirmationRequest, 

25 ManualCorrectionRequest, 

26 ManualPreviewRequest, 

27) 

28from copytrading_engine.execution.domain.market import DailyRange, HistoryWindow 

29from copytrading_engine.execution.domain.ownership import OwnershipResolutionRequest 

30from copytrading_engine.execution.domain.sizing import RouteConnection 

31from copytrading_engine.shared.symbols import SYMBOL_PATTERN 

32from copytrading_engine.trading.domain.config import ( 

33 BrokerCheck, 

34 ModelCheck, 

35 NotificationCheck, 

36 ProviderConfiguration, 

37 SourceCheck, 

38 TradingConfiguration, 

39 TradingSecrets, 

40) 

41from copytrading_engine.trading.domain.profiles import ProfileRevision 

42 

43 

44class PipeRequest(BaseModel): 

45 model_config = ConfigDict(extra="forbid", strict=True) 

46 

47 version: Literal[1] 

48 request_id: str = Field(min_length=1, max_length=128) 

49 

50 

51class SelfTestCommandBody(BaseModel): 

52 model_config = ConfigDict(extra="forbid", strict=True) 

53 

54 command_id: str = Field(min_length=1, max_length=128) 

55 text: str = Field(min_length=1) 

56 destination_ids: list[str] = Field(min_length=1, max_length=2) 

57 

58 

59class SubmitRequest(PipeRequest): 

60 operation: Literal["submit_self_test"] 

61 command: SelfTestCommandBody 

62 

63 

64class GetStatusRequest(PipeRequest): 

65 operation: Literal["get_status"] 

66 

67 

68class GetWorkflowRequest(PipeRequest): 

69 operation: Literal["get_workflow"] 

70 command_id: str = Field(min_length=1, max_length=128) 

71 

72 

73class StopRequest(PipeRequest): 

74 operation: Literal["stop"] 

75 

76 

77class GetTradingStatusRequest(PipeRequest): 

78 operation: Literal["get_trading_status"] 

79 

80 

81class GetTradingActivationRequest(PipeRequest): 

82 operation: Literal["get_trading_activation"] 

83 activation_id: str = Field(pattern=r"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$") 

84 

85 

86class StartTradingRequest(PipeRequest): 

87 operation: Literal["start_trading"] 

88 configuration: TradingConfiguration 

89 secrets: TradingSecrets 

90 validation_token: str = Field(min_length=1, max_length=128) 

91 activation_id: str = Field(pattern=r"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$") 

92 

93 

94class ValidateTradingRequest(PipeRequest): 

95 operation: Literal["validate_trading"] 

96 configuration: TradingConfiguration 

97 secrets: TradingSecrets 

98 

99 

100class CheckConnectionRequest(PipeRequest): 

101 """One service checked as the owner connects it; saves nothing and grants no start.""" 

102 

103 operation: Literal["check_connection"] 

104 connection: Annotated[ 

105 SourceCheck | ModelCheck | BrokerCheck | NotificationCheck, Field(discriminator="kind") 

106 ] 

107 

108 

109class UpdateAccountLimitsRequest(PipeRequest): 

110 """The saved setup with changed account limits; copying takes them without a pause.""" 

111 

112 operation: Literal["update_account_limits"] 

113 configuration: TradingConfiguration 

114 

115 

116class PauseTradingRequest(PipeRequest): 

117 operation: Literal["pause_trading"] 

118 

119 

120class CreateBackupRequest(PipeRequest): 

121 operation: Literal["create_backup"] 

122 destination: str = Field(min_length=1, max_length=4096) 

123 

124 

125class PreviewRestoreRequest(PipeRequest): 

126 operation: Literal["preview_restore"] 

127 archive_path: str = Field(min_length=1, max_length=4096) 

128 

129 

130class PrepareRestoreCandidateRequest(PipeRequest): 

131 operation: Literal["prepare_restore_candidate"] 

132 staging_id: str = Field(pattern=r"^restore-[0-9a-f]{32}$") 

133 

134 

135class RestoreCandidateStatusRequest(PipeRequest): 

136 operation: Literal["restore_candidate_status"] 

137 

138 

139class AbortRestoreCandidateRequest(PipeRequest): 

140 operation: Literal["abort_restore_candidate"] 

141 candidate_id: str = Field(pattern=r"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$") 

142 

143 

144class RestorePreflightAccount(BaseModel): 

145 model_config = ConfigDict(extra="forbid", strict=True, hide_input_in_errors=True) 

146 

147 account_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$") 

148 environment: Literal["paper", "live"] 

149 key: SecretStr = Field(min_length=1, max_length=512) 

150 secret: SecretStr = Field(min_length=1, max_length=512) 

151 

152 

153class RestorePreflightRequest(PipeRequest): 

154 operation: Literal["restore_preflight"] 

155 candidate_id: str = Field(pattern=r"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$") 

156 accounts: list[RestorePreflightAccount] = Field(min_length=0, max_length=64) 

157 

158 

159class CompleteRestoreCandidateRequest(PipeRequest): 

160 operation: Literal["complete_restore_candidate"] 

161 candidate_id: str = Field(pattern=r"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$") 

162 completion_token: str = Field(pattern=r"^[0-9a-f]{32}$") 

163 

164 

165class ControlAccountRequest(PipeRequest): 

166 operation: Literal["control_account"] 

167 command: AccountControlCommand 

168 

169 

170class ResolveOwnershipRequest(PipeRequest): 

171 operation: Literal["resolve_ownership"] 

172 account_id: str = Field(min_length=1, max_length=64) 

173 resolution: OwnershipResolutionRequest 

174 

175 

176class GetAccountsRequest(PipeRequest): 

177 operation: Literal["get_accounts"] 

178 before_account_id: str | None = Field(default=None, min_length=1, max_length=64) 

179 limit: StrictInt = Field(default=50, ge=1, le=100) 

180 

181 

182class GetSourceActivityRequest(PipeRequest): 

183 operation: Literal["get_source_activity"] 

184 before_seq: StrictInt | None = Field(default=None, ge=1) 

185 limit: StrictInt = Field(default=50, ge=1, le=100) 

186 

187 

188class GetGuruActivityRequest(PipeRequest): 

189 """A page of one guru's posts, newest first, for their page.""" 

190 

191 operation: Literal["get_guru_activity"] 

192 guru_id: str = Field(min_length=1, max_length=64) 

193 before_seq: StrictInt | None = Field(default=None, ge=1) 

194 limit: StrictInt = Field(default=50, ge=1, le=100) 

195 

196 

197class GetGuruDayStatsRequest(PipeRequest): 

198 """Each guru's numbers for the owner's day, from its start up to its end in their zone.""" 

199 

200 operation: Literal["get_guru_day_stats"] 

201 day_start: AwareDatetime 

202 day_end: AwareDatetime 

203 

204 @model_validator(mode="after") 

205 def _one_day(self) -> GetGuruDayStatsRequest: 

206 # A day is at most 25 hours, on the night the clocks go back. 

207 if not dt.timedelta(0) < self.day_end - self.day_start <= dt.timedelta(hours=25): 

208 raise ValueError("The day must end after it starts, within a day") 

209 return self 

210 

211 

212class EvaluateHistoricalProfileRequest(PipeRequest): 

213 operation: Literal["evaluate_historical_profile"] 

214 source_id: str = Field(min_length=1, max_length=256) 

215 profile: ProfileRevision 

216 provider: ProviderConfiguration 

217 # Empty for a model on this Mac or a custom address; ProviderConfiguration.reader() decides. 

218 provider_api_key: SecretStr 

219 destinations: list[RouteConnection] = Field(min_length=1, max_length=20) 

220 

221 

222class LearnGuruPlaybookRequest(PipeRequest): 

223 operation: Literal["learn_guru_playbook"] 

224 channel_id: str = Field(pattern=r"^[0-9]{1,32}$") 

225 author_id: str | None = Field(default=None, pattern=r"^[0-9]{1,32}$") 

226 discord_token: SecretStr = Field(min_length=1) 

227 provider: ProviderConfiguration 

228 # Empty for a model on this Mac or a custom address; ProviderConfiguration.reader() decides. 

229 provider_api_key: SecretStr 

230 

231 

232class GetAccountFeedRequest(PipeRequest): 

233 operation: Literal["get_account_feed"] 

234 account_id: str = Field(min_length=1, max_length=64) 

235 before_seq: StrictInt | None = Field(default=None, ge=1) 

236 limit: StrictInt = Field(default=50, ge=1, le=100) 

237 

238 

239class AccountReadKeys(BaseModel): 

240 """One account's broker keys, for reading it while copying is paused. Never stored or logged.""" 

241 

242 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

243 

244 account_id: str = Field(min_length=1, max_length=64) 

245 environment: Literal["paper", "live"] 

246 key: SecretStr 

247 secret: SecretStr 

248 

249 

250class AttachAccountReadersRequest(PipeRequest): 

251 """Sent when the owner unlocks: read these accounts live while copying is paused.""" 

252 

253 operation: Literal["attach_account_readers"] 

254 accounts: tuple[AccountReadKeys, ...] = Field(max_length=20) 

255 

256 

257class DetachAccountReadersRequest(PipeRequest): 

258 """Sent when the owner locks: forget every read key.""" 

259 

260 operation: Literal["detach_account_readers"] 

261 

262 

263class DeleteAccountRecordRequest(PipeRequest): 

264 """The owner deletes the record of an account no longer in the setup, from Settings.""" 

265 

266 operation: Literal["delete_account_record"] 

267 account_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") 

268 

269 

270class GetEquityHistoryRequest(PipeRequest): 

271 operation: Literal["get_equity_history"] 

272 account_id: str = Field(min_length=1, max_length=64) 

273 window: HistoryWindow 

274 

275 

276class GetQuoteRequest(PipeRequest): 

277 """The latest quote for a stock, or a coin's pair, the owner typed into the trade sheet.""" 

278 

279 operation: Literal["get_quote"] 

280 account_id: str = Field(min_length=1, max_length=64) 

281 symbol: str = Field(pattern=SYMBOL_PATTERN) 

282 

283 

284class GetBarsRequest(PipeRequest): 

285 """The five-minute bars of the stocks an account holds, for the sparklines in its Positions.""" 

286 

287 operation: Literal["get_bars"] 

288 account_id: str = Field(min_length=1, max_length=64) 

289 symbols: tuple[Annotated[str, Field(pattern=SYMBOL_PATTERN)], ...] = Field( 

290 min_length=1, max_length=50 

291 ) 

292 

293 @model_validator(mode="after") 

294 def _distinct(self) -> GetBarsRequest: 

295 if len(set(self.symbols)) != len(self.symbols): 

296 raise ValueError("Each symbol is asked for once") 

297 return self 

298 

299 

300class GetDailyBarsRequest(PipeRequest): 

301 """A stock's daily bars over a range, for the chart on its page.""" 

302 

303 operation: Literal["get_daily_bars"] 

304 account_id: str = Field(min_length=1, max_length=64) 

305 symbol: str = Field(pattern=SYMBOL_PATTERN) 

306 range: DailyRange 

307 

308 

309class GetGuruPerformanceRequest(PipeRequest): 

310 """What one guru's copied calls made in one account.""" 

311 

312 operation: Literal["get_guru_performance"] 

313 account_id: str = Field(min_length=1, max_length=64) 

314 guru_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") 

315 

316 

317class SaveManualCorrectionRequest(PipeRequest): 

318 operation: Literal["save_manual_correction"] 

319 correction: ManualCorrectionRequest 

320 

321 

322class PreviewManualOrderRequest(PipeRequest): 

323 operation: Literal["preview_manual_order"] 

324 preview: ManualPreviewRequest 

325 

326 

327class PreviewLotSaleRequest(PipeRequest): 

328 operation: Literal["preview_lot_sale"] 

329 preview: LotSalePreviewRequest 

330 

331 

332class ConfirmLotSaleRequest(PipeRequest): 

333 operation: Literal["confirm_lot_sale"] 

334 sale: LotSaleConfirmation 

335 

336 

337class ConfirmManualOrdersRequest(PipeRequest): 

338 operation: Literal["confirm_manual_orders"] 

339 commands: list[ManualConfirmationRequest] = Field(min_length=1, max_length=20) 

340 

341 

342class GetManualCommandRequest(PipeRequest): 

343 operation: Literal["get_manual_command"] 

344 account_id: str = Field(min_length=1, max_length=64) 

345 command_id: str = Field(min_length=1, max_length=128) 

346 

347 

348class ListManualCommandsRequest(PipeRequest): 

349 operation: Literal["list_manual_commands"] 

350 account_id: str = Field(min_length=1, max_length=64) 

351 source_id: str = Field(min_length=1, max_length=256) 

352 before_command_id: str | None = Field(default=None, min_length=1, max_length=128) 

353 limit: StrictInt = Field(default=50, ge=1, le=100) 

354 

355 

356class ControlRequest(PipeRequest): 

357 """One agent request line relayed by the app, with what only the app knows.""" 

358 

359 operation: Literal["control"] 

360 line: str = Field(min_length=1, max_length=MAX_CONTROL_LINE_BYTES) 

361 context: ControlContext 

362 

363 

364class AuthorizeSetupRequest(PipeRequest): 

365 """A setup request the app answers itself, without its keys, for the engine to decide.""" 

366 

367 operation: Literal["authorize_setup"] 

368 setup: SetupAuthorization 

369 context: ControlContext 

370 

371 

372class ListProposalsRequest(PipeRequest): 

373 operation: Literal["list_proposals"] 

374 

375 

376class ApproveProposalRequest(PipeRequest): 

377 operation: Literal["approve_proposal"] 

378 proposal_id: str = Field(pattern=r"^p-[0-9a-f]{12}$") 

379 digest: str = Field(pattern=r"^[0-9a-f]{64}$") 

380 

381 

382class CompleteProposalRequest(PipeRequest): 

383 """The app reporting how an approved app-performed proposal went.""" 

384 

385 operation: Literal["complete_proposal"] 

386 proposal_id: str = Field(pattern=r"^p-[0-9a-f]{12}$") 

387 outcome: Literal["succeeded", "failed"] 

388 code: str | None = Field(default=None, pattern=r"^[a-z_]{1,48}$") 

389 

390 

391class RejectProposalRequest(PipeRequest): 

392 operation: Literal["reject_proposal"] 

393 proposal_id: str = Field(pattern=r"^p-[0-9a-f]{12}$") 

394 

395 

396class DiscardProposalsRequest(PipeRequest): 

397 operation: Literal["discard_proposals"] 

398 

399 

400class AgentAuditRequest(PipeRequest): 

401 operation: Literal["agent_audit"] 

402 limit: StrictInt = Field(default=50, ge=1, le=100) 

403 

404 

405class AssistantAskRequest(PipeRequest): 

406 operation: Literal["assistant_ask"] 

407 conversation_id: str = Field(pattern=r"^c-[0-9a-f]{12}$") 

408 text: str = Field(min_length=1, max_length=2000) 

409 context: AskContext 

410 provider: ProviderConfiguration 

411 # Empty for a model on this Mac or a custom address; ProviderConfiguration.reader() decides. 

412 provider_api_key: SecretStr 

413 

414 

415class AssistantTurnRequest(PipeRequest): 

416 operation: Literal["assistant_turn"] 

417 turn_id: str = Field(pattern=r"^t-[0-9a-f]{12}$") 

418 after: StrictInt = Field(ge=0) 

419 

420 

421class AssistantCancelRequest(PipeRequest): 

422 operation: Literal["assistant_cancel"] 

423 turn_id: str = Field(pattern=r"^t-[0-9a-f]{12}$") 

424 

425 

426class AssistantResetRequest(PipeRequest): 

427 operation: Literal["assistant_reset"] 

428 

429 

430RequestType = Annotated[ 

431 SubmitRequest 

432 | GetStatusRequest 

433 | GetWorkflowRequest 

434 | GetTradingStatusRequest 

435 | GetTradingActivationRequest 

436 | StartTradingRequest 

437 | ValidateTradingRequest 

438 | CheckConnectionRequest 

439 | PauseTradingRequest 

440 | UpdateAccountLimitsRequest 

441 | CreateBackupRequest 

442 | PreviewRestoreRequest 

443 | PrepareRestoreCandidateRequest 

444 | RestoreCandidateStatusRequest 

445 | AbortRestoreCandidateRequest 

446 | RestorePreflightRequest 

447 | CompleteRestoreCandidateRequest 

448 | ControlAccountRequest 

449 | ResolveOwnershipRequest 

450 | GetAccountsRequest 

451 | GetSourceActivityRequest 

452 | GetGuruActivityRequest 

453 | GetGuruDayStatsRequest 

454 | EvaluateHistoricalProfileRequest 

455 | LearnGuruPlaybookRequest 

456 | GetAccountFeedRequest 

457 | GetEquityHistoryRequest 

458 | GetQuoteRequest 

459 | GetBarsRequest 

460 | GetDailyBarsRequest 

461 | GetGuruPerformanceRequest 

462 | AttachAccountReadersRequest 

463 | DetachAccountReadersRequest 

464 | DeleteAccountRecordRequest 

465 | SaveManualCorrectionRequest 

466 | PreviewManualOrderRequest 

467 | ConfirmManualOrdersRequest 

468 | PreviewLotSaleRequest 

469 | ConfirmLotSaleRequest 

470 | GetManualCommandRequest 

471 | ListManualCommandsRequest 

472 | ControlRequest 

473 | AuthorizeSetupRequest 

474 | ListProposalsRequest 

475 | ApproveProposalRequest 

476 | CompleteProposalRequest 

477 | RejectProposalRequest 

478 | DiscardProposalsRequest 

479 | AgentAuditRequest 

480 | AssistantAskRequest 

481 | AssistantTurnRequest 

482 | AssistantCancelRequest 

483 | AssistantResetRequest 

484 | StopRequest, 

485 Field(discriminator="operation"), 

486] 

487REQUEST_ADAPTER = TypeAdapter(RequestType) 

488 

489# A handler answers one request with one contract response line. 

490type RequestHandler = Callable[..., Awaitable[bytes]]