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
« 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."""
3import datetime as dt
4from collections.abc import Awaitable, Callable
5from typing import Annotated, Literal
7from pydantic import (
8 AwareDatetime,
9 BaseModel,
10 ConfigDict,
11 Field,
12 SecretStr,
13 StrictInt,
14 TypeAdapter,
15 model_validator,
16)
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
44class PipeRequest(BaseModel):
45 model_config = ConfigDict(extra="forbid", strict=True)
47 version: Literal[1]
48 request_id: str = Field(min_length=1, max_length=128)
51class SelfTestCommandBody(BaseModel):
52 model_config = ConfigDict(extra="forbid", strict=True)
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)
59class SubmitRequest(PipeRequest):
60 operation: Literal["submit_self_test"]
61 command: SelfTestCommandBody
64class GetStatusRequest(PipeRequest):
65 operation: Literal["get_status"]
68class GetWorkflowRequest(PipeRequest):
69 operation: Literal["get_workflow"]
70 command_id: str = Field(min_length=1, max_length=128)
73class StopRequest(PipeRequest):
74 operation: Literal["stop"]
77class GetTradingStatusRequest(PipeRequest):
78 operation: Literal["get_trading_status"]
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}$")
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}$")
94class ValidateTradingRequest(PipeRequest):
95 operation: Literal["validate_trading"]
96 configuration: TradingConfiguration
97 secrets: TradingSecrets
100class CheckConnectionRequest(PipeRequest):
101 """One service checked as the owner connects it; saves nothing and grants no start."""
103 operation: Literal["check_connection"]
104 connection: Annotated[
105 SourceCheck | ModelCheck | BrokerCheck | NotificationCheck, Field(discriminator="kind")
106 ]
109class UpdateAccountLimitsRequest(PipeRequest):
110 """The saved setup with changed account limits; copying takes them without a pause."""
112 operation: Literal["update_account_limits"]
113 configuration: TradingConfiguration
116class PauseTradingRequest(PipeRequest):
117 operation: Literal["pause_trading"]
120class CreateBackupRequest(PipeRequest):
121 operation: Literal["create_backup"]
122 destination: str = Field(min_length=1, max_length=4096)
125class PreviewRestoreRequest(PipeRequest):
126 operation: Literal["preview_restore"]
127 archive_path: str = Field(min_length=1, max_length=4096)
130class PrepareRestoreCandidateRequest(PipeRequest):
131 operation: Literal["prepare_restore_candidate"]
132 staging_id: str = Field(pattern=r"^restore-[0-9a-f]{32}$")
135class RestoreCandidateStatusRequest(PipeRequest):
136 operation: Literal["restore_candidate_status"]
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}$")
144class RestorePreflightAccount(BaseModel):
145 model_config = ConfigDict(extra="forbid", strict=True, hide_input_in_errors=True)
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)
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)
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}$")
165class ControlAccountRequest(PipeRequest):
166 operation: Literal["control_account"]
167 command: AccountControlCommand
170class ResolveOwnershipRequest(PipeRequest):
171 operation: Literal["resolve_ownership"]
172 account_id: str = Field(min_length=1, max_length=64)
173 resolution: OwnershipResolutionRequest
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)
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)
188class GetGuruActivityRequest(PipeRequest):
189 """A page of one guru's posts, newest first, for their page."""
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)
197class GetGuruDayStatsRequest(PipeRequest):
198 """Each guru's numbers for the owner's day, from its start up to its end in their zone."""
200 operation: Literal["get_guru_day_stats"]
201 day_start: AwareDatetime
202 day_end: AwareDatetime
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
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)
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
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)
239class AccountReadKeys(BaseModel):
240 """One account's broker keys, for reading it while copying is paused. Never stored or logged."""
242 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
244 account_id: str = Field(min_length=1, max_length=64)
245 environment: Literal["paper", "live"]
246 key: SecretStr
247 secret: SecretStr
250class AttachAccountReadersRequest(PipeRequest):
251 """Sent when the owner unlocks: read these accounts live while copying is paused."""
253 operation: Literal["attach_account_readers"]
254 accounts: tuple[AccountReadKeys, ...] = Field(max_length=20)
257class DetachAccountReadersRequest(PipeRequest):
258 """Sent when the owner locks: forget every read key."""
260 operation: Literal["detach_account_readers"]
263class DeleteAccountRecordRequest(PipeRequest):
264 """The owner deletes the record of an account no longer in the setup, from Settings."""
266 operation: Literal["delete_account_record"]
267 account_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
270class GetEquityHistoryRequest(PipeRequest):
271 operation: Literal["get_equity_history"]
272 account_id: str = Field(min_length=1, max_length=64)
273 window: HistoryWindow
276class GetQuoteRequest(PipeRequest):
277 """The latest quote for a stock, or a coin's pair, the owner typed into the trade sheet."""
279 operation: Literal["get_quote"]
280 account_id: str = Field(min_length=1, max_length=64)
281 symbol: str = Field(pattern=SYMBOL_PATTERN)
284class GetBarsRequest(PipeRequest):
285 """The five-minute bars of the stocks an account holds, for the sparklines in its Positions."""
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 )
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
300class GetDailyBarsRequest(PipeRequest):
301 """A stock's daily bars over a range, for the chart on its page."""
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
309class GetGuruPerformanceRequest(PipeRequest):
310 """What one guru's copied calls made in one account."""
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}$")
317class SaveManualCorrectionRequest(PipeRequest):
318 operation: Literal["save_manual_correction"]
319 correction: ManualCorrectionRequest
322class PreviewManualOrderRequest(PipeRequest):
323 operation: Literal["preview_manual_order"]
324 preview: ManualPreviewRequest
327class PreviewLotSaleRequest(PipeRequest):
328 operation: Literal["preview_lot_sale"]
329 preview: LotSalePreviewRequest
332class ConfirmLotSaleRequest(PipeRequest):
333 operation: Literal["confirm_lot_sale"]
334 sale: LotSaleConfirmation
337class ConfirmManualOrdersRequest(PipeRequest):
338 operation: Literal["confirm_manual_orders"]
339 commands: list[ManualConfirmationRequest] = Field(min_length=1, max_length=20)
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)
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)
356class ControlRequest(PipeRequest):
357 """One agent request line relayed by the app, with what only the app knows."""
359 operation: Literal["control"]
360 line: str = Field(min_length=1, max_length=MAX_CONTROL_LINE_BYTES)
361 context: ControlContext
364class AuthorizeSetupRequest(PipeRequest):
365 """A setup request the app answers itself, without its keys, for the engine to decide."""
367 operation: Literal["authorize_setup"]
368 setup: SetupAuthorization
369 context: ControlContext
372class ListProposalsRequest(PipeRequest):
373 operation: Literal["list_proposals"]
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}$")
382class CompleteProposalRequest(PipeRequest):
383 """The app reporting how an approved app-performed proposal went."""
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}$")
391class RejectProposalRequest(PipeRequest):
392 operation: Literal["reject_proposal"]
393 proposal_id: str = Field(pattern=r"^p-[0-9a-f]{12}$")
396class DiscardProposalsRequest(PipeRequest):
397 operation: Literal["discard_proposals"]
400class AgentAuditRequest(PipeRequest):
401 operation: Literal["agent_audit"]
402 limit: StrictInt = Field(default=50, ge=1, le=100)
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
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)
421class AssistantCancelRequest(PipeRequest):
422 operation: Literal["assistant_cancel"]
423 turn_id: str = Field(pattern=r"^t-[0-9a-f]{12}$")
426class AssistantResetRequest(PipeRequest):
427 operation: Literal["assistant_reset"]
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)
489# A handler answers one request with one contract response line.
490type RequestHandler = Callable[..., Awaitable[bytes]]