Coverage for src/copytrading_engine/control/wire.py: 95%
260 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 versioned request and response contract shared by the CLI, the MCP server and the engine.
3These models are the public face of agent control. They are deliberately separate from the
4engine's internal views, never carry credentials, tokens or broker account identifiers, and
5name Discord text `untrusted_source_text` so no consumer mistakes it for instructions.
6"""
8from decimal import Decimal
9from typing import Annotated, Any, Final, Literal, Self
11from pydantic import (
12 AwareDatetime,
13 BaseModel,
14 ConfigDict,
15 Field,
16 PlainSerializer,
17 SecretStr,
18 TypeAdapter,
19 model_validator,
20)
22SCHEMA_VERSION: Final = 1
23MAX_LINE_BYTES: Final = 64 * 1024
26class Wire(BaseModel):
27 model_config = ConfigDict(frozen=True, extra="forbid", strict=True, hide_input_in_errors=True)
30AccountId = Annotated[str, Field(min_length=1, max_length=64)]
31Identifier = Annotated[str, Field(min_length=1, max_length=256)]
32RequestId = Annotated[str, Field(min_length=1, max_length=128)]
33ProposalId = Annotated[str, Field(pattern=r"^p-[0-9a-f]{12}$")]
34Digest = Annotated[str, Field(pattern=r"^[0-9a-f]{64}$")]
35Limit = Annotated[int, Field(ge=1, le=100)]
36Sequence = Annotated[int, Field(ge=1)]
37RecoveryPreference = Literal["manual", "automatic"]
38CopyingWord = Literal["copying", "sells_only", "paused", "stopped", "not_started"]
39# The five words the owner sees for copying, as the app says them (`control.copying` picks one).
40COPYING_WORDS: Final[dict[CopyingWord, str]] = {
41 "copying": "Copying",
42 "sells_only": "Sells only",
43 "paused": "Paused",
44 "stopped": "Stopped",
45 "not_started": "Not started",
46}
48type Operation = Literal[
49 "get_status",
50 "list_accounts",
51 "list_activity",
52 "list_account_events",
53 "list_manual_commands",
54 "get_manual_command",
55 "preview_manual_order",
56 "list_proposals",
57 "get_proposal",
58 "pause_processing",
59 "pause_account",
60 "propose_resume_account",
61 "propose_recovery_preference",
62 "propose_manual_order",
63 "propose_set_account_limits",
64 "propose_start_processing",
65 "get_setup",
66 "edit_setup_discord",
67 "edit_setup_model",
68 "edit_setup_account",
69 "edit_setup_guru",
70 "edit_setup_alerts",
71 "import_setup",
72 "apply_setup",
73 "discard_setup",
74]
76# The setup operations the app answers itself: their keys go to the Keychain, never the engine.
77type SetupOperation = Literal[
78 "get_setup",
79 "edit_setup_discord",
80 "edit_setup_model",
81 "edit_setup_account",
82 "edit_setup_guru",
83 "edit_setup_alerts",
84 "import_setup",
85 "apply_setup",
86 "discard_setup",
87]
88SETUP_OPERATIONS: Final[frozenset[str]] = frozenset(
89 (
90 "get_setup",
91 "edit_setup_discord",
92 "edit_setup_model",
93 "edit_setup_account",
94 "edit_setup_guru",
95 "edit_setup_alerts",
96 "import_setup",
97 "apply_setup",
98 "discard_setup",
99 )
100)
102type ErrorCode = Literal[
103 "access_off",
104 "locked",
105 "forbidden",
106 "invalid_request",
107 "not_found",
108 "unavailable",
109 "busy",
110 "cooling_down",
111 "proposal_limit",
112 "conflict",
113 "expired",
114 "rejected",
115]
118# Requests
121class RequestHeader(Wire):
122 schema_version: Literal[1] = 1
123 request_id: RequestId
126class GetStatus(RequestHeader):
127 operation: Literal["get_status"] = "get_status"
130class ListAccounts(RequestHeader):
131 operation: Literal["list_accounts"] = "list_accounts"
132 before_account_id: AccountId | None = None
133 limit: Limit = 50
136class ListActivity(RequestHeader):
137 operation: Literal["list_activity"] = "list_activity"
138 before_seq: Sequence | None = None
139 limit: Limit = 50
142class ListAccountEvents(RequestHeader):
143 operation: Literal["list_account_events"] = "list_account_events"
144 account_id: AccountId
145 before_seq: Sequence | None = None
146 limit: Limit = 50
149class ListManualCommands(RequestHeader):
150 operation: Literal["list_manual_commands"] = "list_manual_commands"
151 account_id: AccountId
152 source_id: Identifier
153 before_command_id: Identifier | None = None
154 limit: Limit = 50
157class GetManualCommand(RequestHeader):
158 operation: Literal["get_manual_command"] = "get_manual_command"
159 account_id: AccountId
160 command_id: Identifier
163class PreviewManualOrder(RequestHeader):
164 operation: Literal["preview_manual_order"] = "preview_manual_order"
165 account_id: AccountId
166 correction_id: Identifier
167 instruction_index: Annotated[int, Field(ge=0)]
170class ListProposals(RequestHeader):
171 operation: Literal["list_proposals"] = "list_proposals"
174class GetProposal(RequestHeader):
175 operation: Literal["get_proposal"] = "get_proposal"
176 proposal_id: ProposalId
179class PauseProcessing(RequestHeader):
180 operation: Literal["pause_processing"] = "pause_processing"
183class PauseAccount(RequestHeader):
184 operation: Literal["pause_account"] = "pause_account"
185 account_id: AccountId
188class ProposeResumeAccount(RequestHeader):
189 operation: Literal["propose_resume_account"] = "propose_resume_account"
190 account_id: AccountId
193class ProposeRecoveryPreference(RequestHeader):
194 operation: Literal["propose_recovery_preference"] = "propose_recovery_preference"
195 account_id: AccountId
196 preference: RecoveryPreference
199LIMIT_FIELDS: Final = (
200 "max_order_usd",
201 "max_symbol_usd",
202 "max_total_usd",
203 "daily_loss_cap_usd",
204 "max_entries_per_day",
205 "max_signal_age_seconds",
206 "order_timeout_seconds",
207 "poll_seconds",
208 "extended_hours",
209 "overnight",
210 "copy_exits",
211 "approve_orders",
212 "follow_stops",
213 "max_above_signal_pct",
214 "max_below_signal_pct",
215)
216type LimitField = Literal[
217 "max_order_usd",
218 "max_symbol_usd",
219 "max_total_usd",
220 "daily_loss_cap_usd",
221 "max_entries_per_day",
222 "max_signal_age_seconds",
223 "order_timeout_seconds",
224 "poll_seconds",
225 "extended_hours",
226 "overnight",
227 "copy_exits",
228 "approve_orders",
229 "follow_stops",
230 "max_above_signal_pct",
231 "max_below_signal_pct",
232]
235class LimitChange(Wire):
236 """One account setting and the value it is to take, as the text a person would type."""
238 field: LimitField
239 value: Annotated[str, Field(min_length=1, max_length=32)]
242class ProposeSetAccountLimits(RequestHeader):
243 operation: Literal["propose_set_account_limits"] = "propose_set_account_limits"
244 account_id: AccountId
245 changes: Annotated[tuple[LimitChange, ...], Field(min_length=1, max_length=len(LIMIT_FIELDS))]
248class ProposeStartProcessing(RequestHeader):
249 """Start copying the saved setup, as the app's Start Copying does; the owner approves."""
251 operation: Literal["propose_start_processing"] = "propose_start_processing"
254class ProposeManualOrder(RequestHeader):
255 operation: Literal["propose_manual_order"] = "propose_manual_order"
256 account_id: AccountId
257 preview_id: Identifier
260# Setup: the CLI edits the app's own draft, the same one Connections edits, then applies it.
263def _reveal(value: SecretStr) -> str:
264 return value.get_secret_value()
267# A key, token or secret. It travels only in a request line to the app, which saves it in the
268# Keychain; its repr, errors and Python dumps are masked, and no response ever carries one.
269Secret = Annotated[
270 SecretStr,
271 Field(min_length=1, max_length=4096),
272 PlainSerializer(_reveal, return_type=str, when_used="json"),
273]
274# Discord channel, user and webhook-free identifiers are decimal strings (snowflakes).
275DiscordId = Annotated[str, Field(pattern=r"^[0-9]{1,32}$")]
276AccountName = Annotated[str, Field(pattern=r"^[A-Za-z0-9_-]{1,64}$")]
277GuruRef = Annotated[str, Field(min_length=1, max_length=100)]
278Environment = Literal["paper", "live"]
279type ModelService = Literal[
280 "anthropic",
281 "openai",
282 "google",
283 "deepseek",
284 "openrouter",
285 "groq",
286 "xai",
287 "mistral",
288 "together",
289 "fireworks",
290 "cerebras",
291 "moonshotai",
292 "ollama",
293 "openai_compatible",
294]
295AlertService = Literal["telegram", "discord"]
296PLAYBOOK_MAX_LENGTH: Final = 8_000
297IMPORT_MAX_LENGTH: Final = 60_000
298REPEAT_WINDOW_MAX_MINUTES: Final = 1440
301def _require_a_change(model: BaseModel, fields: tuple[str, ...]) -> None:
302 if all(getattr(model, name) is None for name in fields):
303 raise ValueError("Name at least one thing to change")
306class GetSetup(RequestHeader):
307 """The setup as Connections shows it: saved values plus unsaved edits, keys as saved or not."""
309 operation: Literal["get_setup"] = "get_setup"
312class EditSetupDiscord(RequestHeader):
313 operation: Literal["edit_setup_discord"] = "edit_setup_discord"
314 channel_ids: Annotated[tuple[DiscordId, ...], Field(min_length=1, max_length=50)] | None = None
315 # An empty list copies every author in the channels.
316 author_ids: Annotated[tuple[DiscordId, ...], Field(max_length=50)] | None = None
317 token: Secret | None = None
319 @model_validator(mode="after")
320 def changes_something(self) -> Self:
321 _require_a_change(self, ("channel_ids", "author_ids", "token"))
322 return self
325class EditSetupModel(RequestHeader):
326 operation: Literal["edit_setup_model"] = "edit_setup_model"
327 service: ModelService | None = None
328 model: Annotated[str, Field(min_length=1, max_length=200)] | None = None
329 # Only for ollama and openai_compatible; an empty string clears it.
330 base_url: Annotated[str, Field(max_length=2048)] | None = None
331 key: Secret | None = None
333 @model_validator(mode="after")
334 def changes_something(self) -> Self:
335 _require_a_change(self, ("service", "model", "base_url", "key"))
336 return self
339class EditSetupAccount(RequestHeader):
340 operation: Literal["edit_setup_account"] = "edit_setup_account"
341 action: Literal["add", "edit", "remove"]
342 account_id: AccountName
343 rename: AccountName | None = None
344 environment: Environment | None = None
345 # The Alpaca API key ID and its secret, always together.
346 key: Secret | None = None
347 secret: Secret | None = None
348 limits: Annotated[tuple[LimitChange, ...], Field(max_length=len(LIMIT_FIELDS))] = ()
349 # What the account does after a restart: wait for the owner (manual), or carry on by itself.
350 recovery_preference: RecoveryPreference | None = None
352 @model_validator(mode="after")
353 def consistent(self) -> Self:
354 if (self.key is None) != (self.secret is None):
355 raise ValueError("Give the Alpaca key and its secret together")
356 if len({change.field for change in self.limits}) != len(self.limits): 356 ↛ 357line 356 didn't jump to line 357 because the condition on line 356 was never true
357 raise ValueError("A setting is named twice")
358 changes = (
359 self.rename,
360 self.environment,
361 self.key,
362 self.recovery_preference,
363 ) != (None, None, None, None) or self.limits
364 if self.action == "remove" and changes: 364 ↛ 365line 364 didn't jump to line 365 because the condition on line 364 was never true
365 raise ValueError("Removing an account takes only its name")
366 if self.action == "add" and self.rename is not None: 366 ↛ 367line 366 didn't jump to line 367 because the condition on line 366 was never true
367 raise ValueError("A new account is named once")
368 if self.action == "edit" and not changes:
369 raise ValueError("Name at least one thing to change")
370 return self
373class EditSetupGuru(RequestHeader):
374 operation: Literal["edit_setup_guru"] = "edit_setup_guru"
375 action: Literal["add", "edit", "remove"]
376 # The guru's name, or its ID; for add, the new guru's name.
377 guru: GuruRef
378 rename: GuruRef | None = None
379 # An empty string follows the first source channel.
380 channel_id: DiscordId | Literal[""] | None = None
381 # An empty string copies every author in the channel.
382 author_id: DiscordId | Literal[""] | None = None
383 account_id: AccountName | None = None
384 # The guru's own full position in their account: a 1/6 call buys a sixth of it (ADR-0010).
385 full_position_usd: Annotated[str, Field(min_length=1, max_length=32)] | None = None
386 playbook: Annotated[str, Field(max_length=PLAYBOOK_MAX_LENGTH)] | None = None
387 # Minutes within which the same call again is a re-post; 0 copies every post.
388 repeat_window_minutes: Annotated[int, Field(ge=0, le=REPEAT_WINDOW_MAX_MINUTES)] | None = None
390 @model_validator(mode="after")
391 def consistent(self) -> Self:
392 fields = (
393 "rename",
394 "channel_id",
395 "author_id",
396 "account_id",
397 "full_position_usd",
398 "playbook",
399 "repeat_window_minutes",
400 )
401 changes = any(getattr(self, name) is not None for name in fields)
402 if self.action == "remove" and changes: 402 ↛ 403line 402 didn't jump to line 403 because the condition on line 402 was never true
403 raise ValueError("Removing a guru takes only their name")
404 if self.action == "add" and self.rename is not None: 404 ↛ 405line 404 didn't jump to line 405 because the condition on line 404 was never true
405 raise ValueError("A new guru is named once")
406 if self.action == "edit" and not changes: 406 ↛ 407line 406 didn't jump to line 407 because the condition on line 406 was never true
407 raise ValueError("Name at least one thing to change")
408 return self
411class EditSetupAlerts(RequestHeader):
412 operation: Literal["edit_setup_alerts"] = "edit_setup_alerts"
413 enabled: bool | None = None
414 service: AlertService | None = None
415 # Telegram's chat; a Discord webhook names its own channel.
416 chat_id: Annotated[str, Field(max_length=64)] | None = None
417 # Telegram's bot token, or the Discord webhook URL.
418 token: Secret | None = None
420 @model_validator(mode="after")
421 def changes_something(self) -> Self:
422 _require_a_change(self, ("enabled", "service", "chat_id", "token"))
423 return self
426class ImportSetup(RequestHeader):
427 """A setup file's text, read the way the app's Import Setup reads it."""
429 operation: Literal["import_setup"] = "import_setup"
430 text: Annotated[
431 SecretStr,
432 Field(min_length=1, max_length=IMPORT_MAX_LENGTH),
433 PlainSerializer(_reveal, return_type=str, when_used="json"),
434 ]
437class ApplySetup(RequestHeader):
438 """Check every connection, then save. Copying that runs starts again with the new setup;
439 copying that is paused stays paused unless `start` asks to start it, as Start Copying does."""
441 operation: Literal["apply_setup"] = "apply_setup"
442 start: bool = False
445class DiscardSetup(RequestHeader):
446 """Drop the unsaved edits, as Connections' Discard does."""
448 operation: Literal["discard_setup"] = "discard_setup"
451type Request = Annotated[
452 GetStatus
453 | ListAccounts
454 | ListActivity
455 | ListAccountEvents
456 | ListManualCommands
457 | GetManualCommand
458 | PreviewManualOrder
459 | ListProposals
460 | GetProposal
461 | PauseProcessing
462 | PauseAccount
463 | ProposeResumeAccount
464 | ProposeRecoveryPreference
465 | ProposeManualOrder
466 | ProposeSetAccountLimits
467 | ProposeStartProcessing
468 | GetSetup
469 | EditSetupDiscord
470 | EditSetupModel
471 | EditSetupAccount
472 | EditSetupGuru
473 | EditSetupAlerts
474 | ImportSetup
475 | ApplySetup
476 | DiscardSetup,
477 Field(discriminator="operation"),
478]
479REQUEST: Final = TypeAdapter[Request](Request)
482# Results
485class ProcessingView(Wire):
486 state: str
487 # One of the five words the owner sees, and the code for the line under it.
488 copying: CopyingWord
489 copying_detail: str | None
490 source_connected: bool
491 model_ready: bool
492 pending_source: int
493 pending_signals: int
494 processed_signals: int
495 error_code: str | None
498class AccountStateView(Wire):
499 account_id: str
500 copying: CopyingWord
501 copying_detail: str | None
502 run_state: str
503 entry_permission: str
504 recovery_preference: str
505 readiness: str
506 risk_status: str
507 activity_status: str
508 error_code: str | None
511class StatusView(Wire):
512 type: Literal["status"] = "status"
513 engine_state: str
514 processing: ProcessingView
515 accounts: tuple[AccountStateView, ...]
518class LotView(Wire):
519 """One block of shares the copier bought, and the post that bought it."""
521 lot_id: str
522 source_id: str | None
523 guru_id: str | None
524 posted_at: AwareDatetime | None
525 untrusted_source_text: str | None
526 bought_at: AwareDatetime | None
527 original_qty: Decimal
528 remaining_qty: Decimal
529 average_price: Decimal
532class PositionView(Wire):
533 symbol: str
534 owned_qty: Decimal
535 external_qty: Decimal
536 lots: tuple[LotView, ...]
539class UnavailableAccountView(Wire):
540 account_id: str
541 reason: str
544class BalanceView(Wire):
545 equity: Decimal
546 day_change_usd: Decimal
547 cash: Decimal
548 buying_power: Decimal
549 observed_at: AwareDatetime
552class AccountView(Wire):
553 account_id: str
554 environment: Literal["paper", "live"]
555 copying: CopyingWord
556 copying_detail: str | None
557 entry_permission: str
558 recovery_preference: str
559 readiness: str
560 risk_status: str
561 risk_reason: str | None
562 activity_status: str
563 activity_reason: str | None
564 total_exposure_usd: Decimal | None
565 positions: tuple[PositionView, ...]
566 ownership_incidents: int
567 pending_orders: int | None
568 balance: BalanceView | None
571class AccountsPage(Wire):
572 type: Literal["accounts"] = "accounts"
573 items: tuple[AccountView, ...]
574 next_before_account_id: str | None
575 unavailable: tuple[UnavailableAccountView, ...]
578class OrderView(Wire):
579 client_id: str
580 symbol: str
581 side: str
582 status: str
583 quantity: Decimal
584 filled_quantity: Decimal
585 average_fill_price: Decimal | None
588class DestinationView(Wire):
589 account_id: str
590 environment: str
591 status: str
592 instruction_outcomes: tuple[str, ...]
593 orders: tuple[OrderView, ...]
596class InstructionItem(Wire):
597 action: Literal["buy", "reduce", "close"]
598 symbol: str
599 # None for a sell at the market (ADR-0007).
600 price: Decimal | None
601 fraction: Decimal | None
602 # A buy the post sizes in dollars ("$200 of NFLX").
603 usd_amount: Decimal | None
606class ActivityItem(Wire):
607 sequence: int
608 source_id: str
609 source_at: AwareDatetime
610 captured_at: AwareDatetime
611 parse_status: str
612 delivery_status: str
613 decision: str | None
614 parser_reason: str | None
615 guru_id: str | None
616 untrusted_source_text: str
617 understood_as: tuple[InstructionItem, ...]
618 destinations: tuple[DestinationView, ...]
621class RejectedActivityItem(Wire):
622 source_id: str
623 rejected_at: AwareDatetime
624 reason: str
627class ActivityPage(Wire):
628 type: Literal["activity"] = "activity"
629 items: tuple[ActivityItem, ...]
630 rejected: tuple[RejectedActivityItem, ...]
631 next_before_seq: int | None
632 unavailable: tuple[UnavailableAccountView, ...]
635class AccountEventView(Wire):
636 sequence: int
637 at: AwareDatetime
638 kind: str
639 message_id: str | None
640 order_id: str | None
641 reason: str | None
642 status: str | None
645class AccountEventsPage(Wire):
646 type: Literal["account_events"] = "account_events"
647 account_id: str
648 items: tuple[AccountEventView, ...]
649 next_before_seq: int | None
652class ManualCommandView(Wire):
653 command_id: str
654 account_id: str
655 source_id: str
656 correction_id: str
657 instruction_index: int
658 actor: str
659 confirmed_at: AwareDatetime
660 status: str
661 reason: str | None
662 client_id: str | None
665class ManualCommand(Wire):
666 type: Literal["manual_command"] = "manual_command"
667 command: ManualCommandView
670class ManualCommandsPage(Wire):
671 type: Literal["manual_commands"] = "manual_commands"
672 account_id: str
673 source_id: str
674 items: tuple[ManualCommandView, ...]
675 next_before_command_id: str | None
678class InstructionView(Wire):
679 action: Literal["buy", "reduce", "close"]
680 symbol: str
681 # None for a sell at the market (ADR-0007).
682 price: Decimal | None
683 entry_price: Decimal | None
684 fraction: Decimal | None
687class OrderPlanView(Wire):
688 side: Literal["buy", "sell"]
689 type: Literal["limit", "market", "stop"]
690 quantity: Decimal
691 limit_price: Decimal | None
692 session: str
695class CheckView(Wire):
696 name: str
697 status: Literal["passed", "warning", "blocked"]
698 reason: str | None
701class ManualPreview(Wire):
702 type: Literal["manual_preview"] = "manual_preview"
703 preview_id: str
704 account_id: str
705 environment: Literal["paper", "live"]
706 source_age_seconds: int
707 created_at: AwareDatetime
708 expires_at: AwareDatetime
709 instruction: InstructionView
710 fresh_price: Decimal | None
711 plan: OrderPlanView | None
712 checks: tuple[CheckView, ...]
713 reasons: tuple[str, ...]
716class ResumeAccountSubject(Wire):
717 kind: Literal["resume_account"] = "resume_account"
718 account_id: str
721class RecoverySubject(Wire):
722 kind: Literal["set_recovery"] = "set_recovery"
723 account_id: str
724 preference: RecoveryPreference
727class ManualOrderSubject(Wire):
728 kind: Literal["confirm_manual_order"] = "confirm_manual_order"
729 account_id: str
730 preview_id: str
731 environment: Literal["paper", "live"]
732 symbol: str
733 side: Literal["buy", "sell"]
734 order_type: Literal["limit", "market", "stop"]
735 quantity: Decimal
736 limit_price: Decimal | None
739class LimitsSubject(Wire):
740 kind: Literal["set_account_limits"] = "set_account_limits"
741 account_id: str
742 changes: tuple[LimitChange, ...]
745class StartProcessingSubject(Wire):
746 kind: Literal["start_processing"] = "start_processing"
749class ApplySetupSubject(Wire):
750 """Applying the setup touches real money: what in it does, by account."""
752 kind: Literal["apply_setup"] = "apply_setup"
753 # Accounts the setup makes live, new or switched from paper.
754 made_live: tuple[str, ...]
755 # Live accounts with new Alpaca keys to save.
756 new_live_keys: tuple[str, ...]
757 # Live accounts whose limits or switches change.
758 changed_live: tuple[str, ...]
759 # Live accounts copying starts again with.
760 starts_live: tuple[str, ...]
763type ProposalSubject = Annotated[
764 ResumeAccountSubject
765 | RecoverySubject
766 | ManualOrderSubject
767 | LimitsSubject
768 | StartProcessingSubject
769 | ApplySetupSubject,
770 Field(discriminator="kind"),
771]
774class CallerView(Wire):
775 pid: int | None
776 path: str | None
779class ProposalOutcome(Wire):
780 status: Literal["succeeded", "failed", "outcome_unknown"]
781 code: str | None
782 command_id: str
785class ProposalView(Wire):
786 type: Literal["proposal"] = "proposal"
787 proposal_id: str
788 state: Literal[
789 "pending",
790 "running",
791 "succeeded",
792 "failed",
793 "outcome_unknown",
794 "rejected",
795 "expired",
796 "discarded",
797 ]
798 subject: ProposalSubject
799 digest: Digest
800 command_id: str
801 created_at: AwareDatetime
802 expires_at: AwareDatetime
803 requested_by: CallerView
804 outcome: ProposalOutcome | None
807class ProposalsPage(Wire):
808 type: Literal["proposals"] = "proposals"
809 items: tuple[ProposalView, ...]
812class ProcessingPaused(Wire):
813 type: Literal["processing"] = "processing"
814 processing: ProcessingView
817class AccountControlView(Wire):
818 type: Literal["account_control"] = "account_control"
819 account_id: str
820 entry_permission: str
821 recovery_preference: str
822 applied_at: AwareDatetime
825# Setup results. Keys are only ever "saved", "missing", "entered" (typed, not saved yet), or
826# "not_needed" (a model on the owner's own machine).
827type KeyState = Literal["saved", "missing", "entered", "not_needed"]
830class SetupCheckView(Wire):
831 """A connection's latest check, as its row in Connections reads."""
833 connection: Literal["discord", "model", "account", "alerts", "setup"]
834 subject: str | None = None
835 state: Literal["passed", "failed", "not_configured"]
836 reason: str | None = None
837 # What happened and what to do, in the app's words; set when the check failed.
838 message: str | None = None
841class SetupDiscordView(Wire):
842 channel_ids: tuple[str, ...]
843 author_ids: tuple[str, ...]
844 token: KeyState
845 check: SetupCheckView | None = None
848class SetupModelView(Wire):
849 service: str
850 model: str
851 base_url: str | None = None
852 key: KeyState
853 check: SetupCheckView | None = None
856class SetupAccountView(Wire):
857 account_id: str
858 environment: Environment
859 keys: KeyState
860 limits: tuple[LimitChange, ...]
861 recovery_preference: RecoveryPreference
862 check: SetupCheckView | None = None
865class SetupGuruView(Wire):
866 # The ID the guru's channel gives them (`route_keys.guru_for_channel`); None until they have
867 # a channel.
868 guru_id: str | None = None
869 name: str
870 # The channel the guru is read from; the first source channel when they name none.
871 channel_id: str | None = None
872 author_id: str | None = None
873 account_id: str | None = None
874 full_position_usd: str | None = None
875 repeat_window_minutes: int | None = None
876 playbook_characters: int
879class SetupAlertsView(Wire):
880 enabled: bool
881 service: AlertService
882 chat_id: str | None = None
883 token: KeyState
884 check: SetupCheckView | None = None
887class SetupView(Wire):
888 type: Literal["setup"] = "setup"
889 # A setup has been checked, saved and started at least once.
890 saved: bool
891 # The draft differs from what is saved; `setup apply` checks and saves it.
892 unsaved_changes: bool
893 # One of the five words the owner sees for copying (`COPYING_WORDS`).
894 copying: CopyingWord
895 discord: SetupDiscordView
896 model: SetupModelView
897 accounts: tuple[SetupAccountView, ...]
898 gurus: tuple[SetupGuruView, ...]
899 alerts: SetupAlertsView
902class SetupImported(Wire):
903 type: Literal["setup_imported"] = "setup_imported"
904 # What the file filled and what the setup still needs, by name; never a value.
905 filled: tuple[str, ...]
906 missing: tuple[str, ...]
907 setup: SetupView
910class SetupApplied(Wire):
911 type: Literal["setup_applied"] = "setup_applied"
912 # applied: checked, saved, and copying uses it; unchanged: nothing to apply; failed_checks:
913 # a connection needs attention and nothing was saved; failed: it did not start (see message).
914 status: Literal["applied", "unchanged", "failed_checks", "failed"]
915 message: str | None = None
916 checks: tuple[SetupCheckView, ...] = ()
919type Result = Annotated[
920 StatusView
921 | AccountsPage
922 | ActivityPage
923 | AccountEventsPage
924 | ManualCommandsPage
925 | ManualCommand
926 | ManualPreview
927 | ProposalView
928 | ProposalsPage
929 | ProcessingPaused
930 | AccountControlView
931 | SetupView
932 | SetupImported
933 | SetupApplied,
934 Field(discriminator="type"),
935]
938class ErrorBody(Wire):
939 code: ErrorCode
940 message: str
943class Response(Wire):
944 schema_version: Literal[1] = 1
945 request_id: str
946 ok: Result | None = None
947 error: ErrorBody | None = None
949 @model_validator(mode="after")
950 def one_outcome(self) -> Self:
951 if (self.ok is None) == (self.error is None): 951 ↛ 952line 951 didn't jump to line 952 because the condition on line 951 was never true
952 raise ValueError("A response carries exactly one of ok or error")
953 return self
956def json_schema() -> dict[str, Any]:
957 """The published contract: every request a client may send and every response it may get."""
958 return {
959 "schema_version": SCHEMA_VERSION,
960 "request": REQUEST.json_schema(),
961 "response": Response.model_json_schema(),
962 }