Coverage for src/copytrading_engine/control/service.py: 88%

316 statements  

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

1"""Serve agent control requests: decide, then read, pause, or propose, and audit every step.""" 

2 

3import datetime as dt 

4import json 

5from collections import OrderedDict 

6from collections.abc import Callable 

7from decimal import Decimal, InvalidOperation 

8from typing import Final, Literal, Protocol 

9from uuid import uuid4 

10 

11from pydantic import BaseModel, ConfigDict, Field, ValidationError 

12 

13from copytrading_engine.control import views, wire 

14from copytrading_engine.control.audit import Actor, AuditEntry, ControlAudit 

15from copytrading_engine.control.policy import ( 

16 AccessLevel, 

17 Propose, 

18 RateWindow, 

19 Refuse, 

20 Run, 

21 decide, 

22 describe_refusal, 

23 tier, 

24) 

25from copytrading_engine.control.proposals import ( 

26 APP_PERFORMED, 

27 ApplySetup, 

28 Caller, 

29 ConfirmManualOrder, 

30 Finished, 

31 Outcome, 

32 Proposal, 

33 ProposalBook, 

34 ProposalRefused, 

35 ResumeAccount, 

36 SetAccountLimits, 

37 SetRecovery, 

38 StartProcessing, 

39 Subject, 

40) 

41from copytrading_engine.execution.domain.lifecycle import ( 

42 AccountControlCommand, 

43 AccountControlConflict, 

44 AccountControlResult, 

45) 

46from copytrading_engine.execution.domain.manual_commands import ( 

47 ManualCommandPage, 

48 ManualCommandPageRequest, 

49 ManualCommandResult, 

50 ManualCommandsOutcome, 

51 ManualConfirmationRequest, 

52 ManualOrderPreview, 

53 ManualPreviewRequest, 

54) 

55from copytrading_engine.execution.presentation.operator_views import ( 

56 AccountEventPage, 

57 AccountOverviewPage, 

58) 

59from copytrading_engine.trading.domain.config import AccountPolicy 

60from copytrading_engine.trading.domain.status import TradingStatus 

61from copytrading_engine.trading.presentation.operator_models import SourceActivityPage 

62 

63PREVIEW_CACHE_SIZE: Final = 32 

64AGENT_ACTOR: Final = "agent" 

65 

66 

67class ProcessingControl(Protocol): 

68 def status(self) -> TradingStatus: ... 

69 

70 async def pause(self) -> TradingStatus: ... 

71 

72 

73class OperatorQueries(Protocol): 

74 async def account_overviews( 

75 self, before_account_id: str | None, limit: int 

76 ) -> AccountOverviewPage: ... 

77 

78 async def source_activity(self, before_seq: int | None, limit: int) -> SourceActivityPage: ... 

79 

80 async def account_events( 

81 self, account_id: str, before_seq: int | None, limit: int 

82 ) -> AccountEventPage: ... 

83 

84 async def list_manual_commands( 

85 self, request: ManualCommandPageRequest 

86 ) -> ManualCommandPage: ... 

87 

88 

89class ManualControl(Protocol): 

90 async def control_account(self, command: AccountControlCommand) -> AccountControlResult: ... 

91 

92 async def preview_manual_order(self, request: ManualPreviewRequest) -> ManualOrderPreview: ... 

93 

94 async def confirm_manual_orders( 

95 self, requests: tuple[ManualConfirmationRequest, ...] 

96 ) -> ManualCommandsOutcome: ... 

97 

98 async def manual_command_result( 

99 self, account_id: str, command_id: str 

100 ) -> ManualCommandResult: ... 

101 

102 

103class ControlContext(BaseModel): 

104 """What the app knows about a request: the owner's access choice, lock, and caller.""" 

105 

106 model_config = ConfigDict(frozen=True, extra="forbid", strict=True) 

107 

108 access_level: AccessLevel 

109 unlocked: bool 

110 caller_pid: int | None = Field(default=None, ge=1) 

111 caller_path: str | None = Field(default=None, min_length=1, max_length=4096) 

112 # The app can change the saved setup after the owner approves; a server without one cannot. 

113 app_actions: bool = False 

114 # The owner turned on "Allow setup changes from the command line" in Settings → Agent Access. 

115 setup_changes: bool = False 

116 

117 

118class ApplyFacts(BaseModel): 

119 """What the app found applying its draft would do to live accounts; the engine decides 

120 whether that needs the owner.""" 

121 

122 model_config = ConfigDict(frozen=True, extra="forbid", strict=True) 

123 

124 made_live: tuple[wire.AccountName, ...] = () 

125 new_live_keys: tuple[wire.AccountName, ...] = () 

126 changed_live: tuple[wire.AccountName, ...] = () 

127 starts_live: tuple[wire.AccountName, ...] = () 

128 

129 @property 

130 def touches_live(self) -> bool: 

131 return bool(self.made_live or self.new_live_keys or self.changed_live or self.starts_live) 

132 

133 

134class SetupAuthorization(BaseModel): 

135 """A setup request the app answers itself, without its keys: only the operation, and for an 

136 apply, what it would do to live accounts.""" 

137 

138 model_config = ConfigDict(frozen=True, extra="forbid", strict=True) 

139 

140 operation: wire.SetupOperation 

141 request_id: str = Field(max_length=128) 

142 apply: ApplyFacts | None = None 

143 # The app could not read the request; it is refused, and only recorded here. 

144 invalid: bool = False 

145 

146 

147SETUP_FORBIDDEN: Final = ( 

148 "Agent access allows reading and pausing only. To change the setup from the command line, " 

149 "choose “Read, pause, and ask for approval” in CopyTrading → Settings → Agent Access, then " 

150 "turn on “Allow setup changes from the command line” there." 

151) 

152SETUP_CHANGES_OFF: Final = ( 

153 "Setup changes from the command line are off. Turn on “Allow setup changes from the command " 

154 "line” in CopyTrading → Settings → Agent Access; it asks for Touch ID." 

155) 

156SETUP_IN_APP_ONLY: Final = ( 

157 "This CopyTrading has no app to change its setup: a server is set up in copytrading.toml." 

158) 

159 

160 

161def _validated_limits(changes: tuple[wire.LimitChange, ...]) -> tuple[tuple[str, str], ...]: 

162 """The values as the account's own settings model reads them, in one fixed spelling, or a 

163 ValueError: a number that settings would refuse never reaches the owner's sheet.""" 

164 values: dict[str, object] = {} 

165 for change in changes: 

166 if change.field in values: 

167 raise ValueError("A setting is named twice") 

168 values[change.field] = _typed_limit(change.field, change.value) 

169 AccountPolicy.model_validate(values) 

170 return tuple(sorted((field, _spelled(value)) for field, value in values.items())) 

171 

172 

173_BOOLEAN_LIMITS: Final = { 

174 "extended_hours", 

175 "overnight", 

176 "copy_exits", 

177 "approve_orders", 

178 "follow_stops", 

179} 

180_WHOLE_LIMITS: Final = {"max_entries_per_day", "max_signal_age_seconds", "order_timeout_seconds"} 

181 

182 

183def _typed_limit(field: str, text: str) -> object: 

184 value = text.strip().lower() 

185 if field in _BOOLEAN_LIMITS: 

186 if value not in {"true", "false"}: 

187 raise ValueError("A switch is true or false") 

188 return value == "true" 

189 if field in _WHOLE_LIMITS: 

190 if not value.isascii() or not value.isdigit(): 

191 raise ValueError("A whole number is digits only") 

192 return int(value) 

193 if field == "poll_seconds": 

194 return float(value) 

195 try: 

196 return Decimal(value) 

197 except InvalidOperation: 

198 raise ValueError("A number is digits and one decimal point") from None 

199 

200 

201def _spelled(value: object) -> str: 

202 if isinstance(value, bool): 

203 return "true" if value else "false" 

204 if isinstance(value, Decimal): 

205 return format(value.normalize(), "f") 

206 return str(value) 

207 

208 

209def _utc_now() -> dt.datetime: 

210 return dt.datetime.now(dt.UTC) 

211 

212 

213class ControlService: 

214 def __init__( 

215 self, 

216 processing: ProcessingControl, 

217 operator: OperatorQueries, 

218 manual: ManualControl, 

219 audit: ControlAudit, 

220 *, 

221 clock: Callable[[], dt.datetime] = _utc_now, 

222 book: ProposalBook | None = None, 

223 rate: RateWindow | None = None, 

224 ) -> None: 

225 self._processing = processing 

226 self._operator = operator 

227 self._manual = manual 

228 self._audit = audit 

229 self._clock = clock 

230 self._book = book if book is not None else ProposalBook(clock) 

231 self._rate = rate if rate is not None else RateWindow() 

232 self._previews: OrderedDict[str, ManualOrderPreview] = OrderedDict() 

233 

234 async def handle( 

235 self, line: str, context: ControlContext, *, engine_state: str 

236 ) -> wire.Response: 

237 """Answer one agent request line with exactly one contract response.""" 

238 caller = Caller(context.caller_pid, context.caller_path) 

239 request_id = _request_id(line) 

240 if len(line.encode()) > wire.MAX_LINE_BYTES: 240 ↛ 241line 240 didn't jump to line 241 because the condition on line 240 was never true

241 return await self._refused(request_id, caller, "invalid", None, "invalid_request") 

242 try: 

243 request = wire.REQUEST.validate_json(line) 

244 except ValidationError: 

245 return await self._refused(request_id, caller, "invalid", None, "invalid_request") 

246 operation = request.operation 

247 kind = tier(operation) 

248 if operation in wire.SETUP_OPERATIONS: 

249 # The app answers setup requests itself so their keys never reach the engine; one that 

250 # arrives here came through a server, which has no app setup to change. 

251 return await self._refused( 

252 request_id, caller, operation, kind, "unavailable", SETUP_IN_APP_ONLY 

253 ) 

254 # Pausing only reduces risk, so a flood of other requests never blocks it. 

255 if kind != "safer" and not self._rate.admit(self._clock()): 

256 return await self._refused(request_id, caller, operation, kind, "busy") 

257 

258 decision = decide(operation, context.access_level, unlocked=context.unlocked) 

259 try: 

260 match decision: 

261 case Refuse(code=code): 

262 return await self._refused(request_id, caller, operation, kind, code) 

263 case Run(): 

264 result = await self._run(request, engine_state) 

265 outcome = "ok" 

266 proposal_id = None 

267 case Propose(): 267 ↛ 282line 267 didn't jump to line 282 because the pattern on line 267 always matched

268 proposal = self._propose(request, caller, app_actions=context.app_actions) 

269 result = views.proposal(proposal) 

270 outcome = "proposed" 

271 proposal_id = proposal.proposal_id 

272 except ProposalRefused as refused: 

273 return await self._refused(request_id, caller, operation, kind, refused.code) 

274 except KeyError: 

275 return await self._refused(request_id, caller, operation, kind, "not_found") 

276 except AccountControlConflict: 

277 return await self._refused(request_id, caller, operation, kind, "conflict") 

278 except ValueError: 

279 return await self._refused(request_id, caller, operation, kind, "invalid_request") 

280 except Exception: # noqa: BLE001 - an engine failure becomes a contract error, never a crash 

281 return await self._refused(request_id, caller, operation, kind, "unavailable") 

282 await self._record("agent", caller, operation, kind, outcome, proposal_id) 

283 return wire.Response(request_id=request_id, ok=result) 

284 

285 async def authorize_setup( 

286 self, authorization: SetupAuthorization, context: ControlContext 

287 ) -> wire.Response | None: 

288 """Decide a setup request the app answers itself: None lets the app run it now; otherwise 

289 the response the caller gets, a refusal or a proposal the owner approves in the app.""" 

290 caller = Caller(context.caller_pid, context.caller_path) 

291 operation = authorization.operation 

292 request_id = authorization.request_id 

293 kind = tier(operation) 

294 if not self._rate.admit(self._clock()): 

295 return await self._refused(request_id, caller, operation, kind, "busy") 

296 facts = authorization.apply 

297 # An app that could not read the line refuses it; the trail still records who sent it. 

298 if authorization.invalid or (facts is None) == (operation == "apply_setup"): 

299 return await self._refused(request_id, caller, operation, kind, "invalid_request") 

300 decision = decide( 

301 operation, 

302 context.access_level, 

303 unlocked=context.unlocked, 

304 owner_needed=facts is not None and facts.touches_live, 

305 setup_changes=context.setup_changes, 

306 ) 

307 match decision: 

308 case Refuse(code=code): 

309 message = None 

310 if code == "forbidden": 

311 message = ( 

312 SETUP_CHANGES_OFF if context.access_level == "propose" else SETUP_FORBIDDEN 

313 ) 

314 return await self._refused(request_id, caller, operation, kind, code, message) 

315 case Run(): 

316 await self._record("agent", caller, operation, kind, "ok", None) 

317 return None 

318 case Propose(): 318 ↛ exitline 318 didn't return from function 'authorize_setup' because the pattern on line 318 always matched

319 if facts is None or not context.app_actions: 

320 return await self._refused(request_id, caller, operation, kind, "unavailable") 

321 subject = ApplySetup( 

322 made_live=facts.made_live, 

323 new_live_keys=facts.new_live_keys, 

324 changed_live=facts.changed_live, 

325 starts_live=facts.starts_live, 

326 ) 

327 try: 

328 proposal = self._book.propose(subject, caller) 

329 except ProposalRefused as refused: 

330 return await self._refused(request_id, caller, operation, kind, refused.code) 

331 await self._record( 

332 "agent", caller, operation, kind, "proposed", proposal.proposal_id 

333 ) 

334 return wire.Response(request_id=request_id, ok=views.proposal(proposal)) 

335 

336 async def approve(self, proposal_id: str, approved_digest: str) -> wire.ProposalView: 

337 """Perform an approved proposal exactly once; called only by the app after owner auth.""" 

338 proposal = self._book.begin(proposal_id, approved_digest) 

339 owner = Caller(None, None) 

340 await self._record("owner", owner, "approve_proposal", "approval", "approved", proposal_id) 

341 if proposal.kind in APP_PERFORMED: 

342 # The app changes its own saved setup, then reports how it went (`complete`). 

343 return views.proposal(proposal) 

344 result: Outcome 

345 code: str | None 

346 try: 

347 result, code = await self._perform(proposal) 

348 except KeyError: 

349 result, code = "failed", "not_found" 

350 except AccountControlConflict: 

351 result, code = "failed", "conflict" 

352 except ValueError: 

353 result, code = "failed", "invalid_request" 

354 except Exception: # noqa: BLE001 - an unconfirmed broker effect is reported as unknown 

355 result, code = "outcome_unknown", None 

356 finished = self._book.finish(proposal_id, result, code) 

357 await self._record("owner", owner, "perform_proposal", "approval", result, proposal_id) 

358 return views.proposal(finished) 

359 

360 async def complete( 

361 self, proposal_id: str, outcome: Literal["succeeded", "failed"], code: str | None 

362 ) -> wire.ProposalView: 

363 """Record how the app's own action went; only an approved app-performed proposal.""" 

364 proposal = self._book.get(proposal_id) 

365 if proposal.kind not in APP_PERFORMED: 

366 raise ProposalRefused("conflict") 

367 state = proposal.state 

368 if isinstance(state, Finished): 

369 if state.result == outcome: 

370 return views.proposal(proposal) # the app said it twice 

371 raise ProposalRefused("conflict") 

372 finished = self._book.finish(proposal_id, outcome, code) 

373 await self._record( 

374 "owner", Caller(None, None), "perform_proposal", "approval", outcome, proposal_id 

375 ) 

376 return views.proposal(finished) 

377 

378 async def reject(self, proposal_id: str) -> wire.ProposalView: 

379 rejected = self._book.reject(proposal_id) 

380 await self._record( 

381 "owner", Caller(None, None), "reject_proposal", "approval", "rejected", proposal_id 

382 ) 

383 return views.proposal(rejected) 

384 

385 async def audit_entries(self, limit: int) -> tuple[AuditEntry, ...]: 

386 """The newest decisions, for the owner's audit list in the app.""" 

387 return await self._audit.recent(limit) 

388 

389 def proposals(self) -> tuple[wire.ProposalView, ...]: 

390 return tuple(views.proposal(item) for item in self._book.all()) 

391 

392 async def discard_pending(self) -> int: 

393 count = self._book.discard_pending() 

394 if count: 394 ↛ 398line 394 didn't jump to line 398 because the condition on line 394 was always true

395 await self._record( 

396 "owner", Caller(None, None), "discard_proposals", None, f"discarded:{count}", None 

397 ) 

398 return count 

399 

400 async def _run(self, request: wire.Request, engine_state: str) -> wire.Result: 

401 match request: 

402 case wire.GetStatus(): 

403 return views.status(engine_state, self._processing.status()) 

404 case wire.ListAccounts(before_account_id=before, limit=limit): 

405 return views.accounts(await self._operator.account_overviews(before, limit)) 

406 case wire.ListActivity(before_seq=before, limit=limit): 

407 return views.activity(await self._operator.source_activity(before, limit)) 

408 case wire.ListAccountEvents(account_id=account_id, before_seq=before, limit=limit): 

409 return views.account_events( 

410 await self._operator.account_events(account_id, before, limit) 

411 ) 

412 case wire.ListManualCommands() as page: 412 ↛ 413line 412 didn't jump to line 413 because the pattern on line 412 never matched

413 return views.manual_commands( 

414 await self._operator.list_manual_commands( 

415 ManualCommandPageRequest( 

416 account_id=page.account_id, 

417 source_id=page.source_id, 

418 before_command_id=page.before_command_id, 

419 limit=page.limit, 

420 ) 

421 ) 

422 ) 

423 case wire.GetManualCommand(account_id=account_id, command_id=command_id): 423 ↛ 424line 423 didn't jump to line 424 because the pattern on line 423 never matched

424 result = await self._manual.manual_command_result(account_id, command_id) 

425 return wire.ManualCommand(command=views.manual_command(result)) 

426 case wire.PreviewManualOrder() as ask: 

427 preview = await self._manual.preview_manual_order( 

428 ManualPreviewRequest( 

429 preview_id=f"agent-{uuid4().hex}", 

430 account_id=ask.account_id, 

431 correction_id=ask.correction_id, 

432 instruction_index=ask.instruction_index, 

433 ) 

434 ) 

435 self._remember(preview) 

436 return views.manual_preview(preview) 

437 case wire.ListProposals(): 

438 return wire.ProposalsPage(items=self.proposals()) 

439 case wire.GetProposal(proposal_id=proposal_id): 

440 return views.proposal(self._book.get(proposal_id)) 

441 case wire.PauseProcessing(): 

442 return wire.ProcessingPaused( 

443 processing=views.processing(await self._processing.pause()) 

444 ) 

445 case wire.PauseAccount(account_id=account_id): 445 ↛ 452line 445 didn't jump to line 452 because the pattern on line 445 always matched

446 result = await self._manual.control_account( 

447 AccountControlCommand( 

448 command_id=f"agent-{uuid4().hex}", account_id=account_id, action="pause" 

449 ) 

450 ) 

451 return views.account_control(result) 

452 case ( 

453 wire.ProposeResumeAccount() 

454 | wire.ProposeRecoveryPreference() 

455 | wire.ProposeManualOrder() 

456 | wire.ProposeSetAccountLimits() 

457 | wire.ProposeStartProcessing() 

458 ): 

459 raise ValueError("Approval-tier requests are proposed, never run directly") 

460 case ( 

461 wire.GetSetup() 

462 | wire.EditSetupDiscord() 

463 | wire.EditSetupModel() 

464 | wire.EditSetupAccount() 

465 | wire.EditSetupGuru() 

466 | wire.EditSetupAlerts() 

467 | wire.ImportSetup() 

468 | wire.ApplySetup() 

469 | wire.DiscardSetup() 

470 ): 

471 raise ValueError("The app answers setup requests itself") 

472 

473 def _propose(self, request: wire.Request, caller: Caller, *, app_actions: bool) -> Proposal: 

474 subject: Subject 

475 expires_by = None 

476 match request: 

477 case wire.ProposeResumeAccount(account_id=account_id): 

478 self._require_account(account_id) 

479 subject = ResumeAccount(account_id) 

480 case wire.ProposeRecoveryPreference(account_id=account_id, preference=preference): 

481 # Recovery is part of the saved setup, which only the app changes. 

482 if not app_actions: 

483 raise ProposalRefused("unavailable") 

484 self._require_account(account_id) 

485 subject = SetRecovery(account_id, preference) 

486 case wire.ProposeManualOrder(account_id=account_id, preview_id=preview_id): 

487 preview = self._previews.get(preview_id) 

488 if preview is None or preview.request.account_id != account_id: 

489 raise KeyError(preview_id) 

490 if preview.plan is None: 490 ↛ 491line 490 didn't jump to line 491 because the condition on line 490 was never true

491 raise ValueError("A blocked preview cannot be proposed") 

492 subject = ConfirmManualOrder( 

493 account_id=account_id, 

494 preview_id=preview_id, 

495 environment=preview.environment, 

496 symbol=preview.plan.symbol, 

497 side=preview.plan.side, 

498 order_type=preview.plan.type, 

499 quantity=preview.plan.qty, 

500 limit_price=preview.plan.limit_price, 

501 ) 

502 expires_by = preview.expires_at 

503 case wire.ProposeSetAccountLimits(account_id=account_id, changes=changes): 

504 if not app_actions: 

505 raise ProposalRefused("unavailable") 

506 self._require_account(account_id) 

507 subject = SetAccountLimits(account_id, _validated_limits(changes)) 

508 case wire.ProposeStartProcessing(): 508 ↛ 514line 508 didn't jump to line 514 because the pattern on line 508 always matched

509 if not app_actions: 

510 raise ProposalRefused("unavailable") 

511 if self._processing.status().state in ("starting", "running", "degraded"): 

512 raise ProposalRefused("conflict") # already copying 

513 subject = StartProcessing() 

514 case _: 

515 raise ValueError("Only approval-tier requests become proposals") 

516 return self._book.propose(subject, caller, expires_by=expires_by) 

517 

518 async def _perform(self, proposal: Proposal) -> tuple[Outcome, str | None]: 

519 match proposal.subject: 

520 case ResumeAccount(account_id=account_id): 

521 await self._manual.control_account( 

522 AccountControlCommand( 

523 command_id=proposal.command_id, account_id=account_id, action="resume" 

524 ) 

525 ) 

526 return "succeeded", None 

527 case ConfirmManualOrder(account_id=account_id, preview_id=preview_id): 527 ↛ 539line 527 didn't jump to line 539 because the pattern on line 527 always matched

528 outcome = await self._manual.confirm_manual_orders( 

529 ( 

530 ManualConfirmationRequest( 

531 command_id=proposal.command_id, 

532 preview_id=preview_id, 

533 account_id=account_id, 

534 actor=AGENT_ACTOR, 

535 ), 

536 ) 

537 ) 

538 return _manual_outcome(outcome, account_id, proposal.command_id) 

539 case SetRecovery() | SetAccountLimits() | StartProcessing() | ApplySetup(): 

540 raise ValueError("The app performs this change; the engine does not") 

541 

542 def _require_account(self, account_id: str) -> None: 

543 if all(account.id != account_id for account in self._processing.status().accounts): 

544 raise KeyError(account_id) 

545 

546 def _remember(self, preview: ManualOrderPreview) -> None: 

547 now = self._clock() 

548 for key in [key for key, item in self._previews.items() if item.expires_at <= now]: 548 ↛ 549line 548 didn't jump to line 549 because the loop on line 548 never started

549 del self._previews[key] 

550 self._previews[preview.request.preview_id] = preview 

551 while len(self._previews) > PREVIEW_CACHE_SIZE: 551 ↛ 552line 551 didn't jump to line 552 because the condition on line 551 was never true

552 self._previews.popitem(last=False) 

553 

554 async def _refused( 

555 self, 

556 request_id: str, 

557 caller: Caller, 

558 operation: str, 

559 kind: str | None, 

560 code: wire.ErrorCode, 

561 message: str | None = None, 

562 ) -> wire.Response: 

563 await self._record("agent", caller, operation, kind, code, None) 

564 return wire.Response( 

565 request_id=request_id, 

566 error=wire.ErrorBody(code=code, message=message or describe_refusal(code)), 

567 ) 

568 

569 async def _record( 

570 self, 

571 actor: Actor, 

572 caller: Caller, 

573 operation: str, 

574 kind: str | None, 

575 outcome: str, 

576 proposal_id: str | None, 

577 ) -> None: 

578 await self._audit.record( 

579 AuditEntry( 

580 at=self._clock(), 

581 actor=actor, 

582 caller_pid=caller.pid, 

583 caller_path=caller.path, 

584 operation=operation, 

585 tier=kind if kind in ("read", "safer", "approval") else None, 

586 outcome=outcome, 

587 proposal_id=proposal_id, 

588 ) 

589 ) 

590 

591 

592def _manual_outcome( 

593 outcome: ManualCommandsOutcome, account_id: str, command_id: str 

594) -> tuple[Outcome, str | None]: 

595 matching = [ 

596 item 

597 for item in outcome.outcomes 

598 if item.account_id == account_id and item.command_id == command_id 

599 ] 

600 if len(matching) != 1: 600 ↛ 601line 600 didn't jump to line 601 because the condition on line 600 was never true

601 return "outcome_unknown", None 

602 item = matching[0] 

603 if item.result is None: 603 ↛ 604line 603 didn't jump to line 604 because the condition on line 603 was never true

604 return "failed", item.error 

605 match item.result.status: 

606 case "prepared" | "accepted" | "partially_filled" | "filled": 606 ↛ 608line 606 didn't jump to line 608 because the pattern on line 606 always matched

607 return "succeeded", item.result.status 

608 case "uncertain": 

609 return "outcome_unknown", item.result.status 

610 case "rejected" | "broker_rejected" | "cancelled" | "expired": 

611 return "failed", item.result.reason or item.result.status 

612 

613 

614def _request_id(line: str) -> str: 

615 """Echo a well-formed request ID even when the rest of the request is invalid.""" 

616 try: 

617 payload = json.loads(line) 

618 except ValueError, RecursionError: 

619 return "" 

620 value = payload.get("request_id") if isinstance(payload, dict) else None 

621 return value if isinstance(value, str) and 0 < len(value) <= 128 else ""