API Layer¶
Litestar REST + WebSocket API -- controllers, authentication, guards, and channels.
App¶
app
¶
Litestar application factory.
Creates and configures the Litestar application with all controllers, middleware, exception handlers, plugins, and lifecycle hooks (startup/shutdown).
create_app
¶
create_app(
*,
config=None,
persistence=None,
message_bus=None,
cost_tracker=None,
approval_store=None,
auth_service=None,
task_engine=None,
coordinator=None,
agent_registry=None,
meeting_orchestrator=None,
meeting_scheduler=None,
performance_tracker=None,
settings_service=None,
provider_registry=None,
provider_health_tracker=None,
tool_invocation_tracker=None,
delegation_record_store=None,
artifact_storage=None,
audit_log=None,
trust_service=None,
coordination_metrics_store=None,
training_service=None,
event_stream_hub=None,
interrupt_store=None,
_skip_lifecycle_shutdown=False,
)
Create and configure the Litestar application.
All parameters are optional for testing -- provide fakes via keyword arguments. Services not explicitly provided are auto-wired from config and environment variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RootConfig | None
|
Root company configuration. |
None
|
persistence
|
PersistenceBackend | None
|
Persistence backend. |
None
|
message_bus
|
MessageBus | None
|
Internal message bus. |
None
|
cost_tracker
|
CostTracker | None
|
Cost tracking service. |
None
|
approval_store
|
ApprovalStoreProtocol | None
|
Approval queue store. |
None
|
auth_service
|
AuthService | None
|
Pre-built auth service (for testing). |
None
|
task_engine
|
TaskEngine | None
|
Centralized task state engine. |
None
|
coordinator
|
MultiAgentCoordinator | None
|
Multi-agent coordinator. |
None
|
agent_registry
|
AgentRegistryService | None
|
Agent registry service. |
None
|
meeting_orchestrator
|
MeetingOrchestrator | None
|
Meeting orchestrator. |
None
|
meeting_scheduler
|
MeetingScheduler | None
|
Meeting scheduler. |
None
|
performance_tracker
|
PerformanceTracker | None
|
Performance tracking service. |
None
|
settings_service
|
SettingsService | None
|
Settings service for runtime config. |
None
|
provider_registry
|
ProviderRegistry | None
|
Provider registry. |
None
|
provider_health_tracker
|
ProviderHealthTracker | None
|
Provider health tracking service. |
None
|
tool_invocation_tracker
|
ToolInvocationTracker | None
|
Tool invocation tracking service. |
None
|
delegation_record_store
|
DelegationRecordStore | None
|
Delegation record store. |
None
|
artifact_storage
|
ArtifactStorageBackend | None
|
Artifact storage backend. |
None
|
audit_log
|
AuditLog | None
|
Pre-built audit log (auto-wired if None). |
None
|
trust_service
|
TrustService | None
|
Pre-built trust service. |
None
|
coordination_metrics_store
|
CoordinationMetricsStore | None
|
Pre-built metrics store (auto-wired if None). |
None
|
training_service
|
TrainingService | None
|
Pre-built training service (auto-wired in startup if None and dependencies are available). |
None
|
event_stream_hub
|
EventStreamHub | None
|
Pre-built event stream hub (auto-created if None). |
None
|
interrupt_store
|
InterruptStore | None
|
Pre-built interrupt store (auto-created if None). |
None
|
_skip_lifecycle_shutdown
|
bool
|
Test-only flag. When |
False
|
Returns:
| Type | Description |
|---|---|
Litestar
|
Configured Litestar application. |
Source code in src/synthorg/api/app.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | |
Config¶
config
¶
API configuration models.
Frozen Pydantic models for CORS, rate limiting, server,
authentication, and the top-level ApiConfig that aggregates
them all.
CorsConfig
pydantic-model
¶
Bases: BaseModel
CORS configuration for the API.
Attributes:
| Name | Type | Description |
|---|---|---|
allowed_origins |
tuple[str, ...]
|
Origins permitted to make cross-origin requests. |
allow_methods |
tuple[str, ...]
|
HTTP methods permitted in cross-origin requests. |
allow_headers |
tuple[str, ...]
|
Headers permitted in cross-origin requests. |
allow_credentials |
bool
|
Whether credentials (cookies, auth) are allowed in cross-origin requests. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
allowed_origins(tuple[str, ...]) -
allow_methods(tuple[str, ...]) -
allow_headers(tuple[str, ...]) -
allow_credentials(bool)
Validators:
-
_validate_wildcard_credentials
allowed_origins
pydantic-field
¶
Origins permitted to make cross-origin requests
allow_methods
pydantic-field
¶
HTTP methods permitted in cross-origin requests
allow_headers
pydantic-field
¶
Headers permitted in cross-origin requests
allow_credentials
pydantic-field
¶
Whether credentials (cookies) are allowed
RateLimitTimeUnit
¶
Bases: StrEnum
Valid time windows for rate limiting.
RateLimitConfig
pydantic-model
¶
Bases: BaseModel
API rate limiting configuration.
Three tiers stacked around the auth middleware:
- IP floor (outermost, un-gated): keyed by client IP, applies to every request -- including ones the auth middleware rejects with 401. Guards against flood attacks that burn auth-validation cycles on protected endpoints with forged tokens.
- Unauthenticated (middle, only when
scope["user"]isNone): keyed by client IP, aggressive cap on brute-force against login/setup/logout. - Authenticated (innermost, only when
scope["user"]is set): keyed by user ID, generous cap for normal dashboard use.
Keying authenticated limits by user ID instead of IP prevents multi-user deployments behind a shared gateway or NAT from collectively exhausting a single per-IP budget.
Attributes:
| Name | Type | Description |
|---|---|---|
floor_max_requests |
int
|
Maximum total requests per time window (by IP) across the whole API. Catches traffic that auth_middleware rejects before the unauth tier sees it. |
unauth_max_requests |
int
|
Maximum unauthenticated requests per time window (by IP). |
auth_max_requests |
int
|
Maximum authenticated requests per time window (by user ID). |
time_unit |
RateLimitTimeUnit
|
Time window ( |
exclude_paths |
tuple[str, ...]
|
Paths excluded from rate limiting. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
floor_max_requests(int) -
unauth_max_requests(int) -
auth_max_requests(int) -
time_unit(RateLimitTimeUnit) -
exclude_paths(tuple[str, ...]) -
max_rpm_default(int)
Validators:
-
_validate_floor_above_user_tiers -
_reject_legacy_max_requests
floor_max_requests
pydantic-field
¶
Maximum total requests per time window (by IP) across the whole API, including requests rejected by the auth middleware. Defense-in-depth against floods of invalid auth attempts on protected endpoints. The floor wraps both user-gated tiers in the middleware stack, so it must be >= auth_max_requests AND >= unauth_max_requests -- a lower floor would silently cap either the authenticated per-user budget or the unauthenticated per-IP budget below its documented value (especially behind a shared NAT where many users share one IP). Enforced by :meth:_validate_floor_above_user_tiers.
unauth_max_requests
pydantic-field
¶
Maximum unauthenticated requests per time window (by IP)
auth_max_requests
pydantic-field
¶
Maximum authenticated requests per time window (by user ID)
exclude_paths
pydantic-field
¶
Paths excluded from rate limiting
max_rpm_default
pydantic-field
¶
Fallback requests-per-minute applied to per-connection coordinators when the catalog does not provide a limiter (mirrors the api.max_rpm_default setting; restart required)
ServerConfig
pydantic-model
¶
Bases: BaseModel
Uvicorn server configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
host |
str
|
Bind address. |
port |
int
|
Bind port. |
reload |
bool
|
Enable auto-reload for development. |
workers |
int
|
Number of worker processes. |
ws_ping_interval |
float
|
WebSocket ping interval in seconds (0 to disable). |
ws_ping_timeout |
float
|
WebSocket pong timeout in seconds. |
ssl_certfile |
str | None
|
Path to SSL certificate file (PEM format). |
ssl_keyfile |
str | None
|
Path to SSL private key file (PEM format). |
ssl_ca_certs |
str | None
|
Path to CA bundle for client cert verification. |
trusted_proxies |
tuple[str, ...]
|
IP addresses/CIDRs trusted as reverse
proxies for |
compression_minimum_size_bytes |
int
|
Minimum response body size
in bytes before brotli compression kicks in. Mirrors the
|
request_max_body_size_bytes |
int
|
Maximum accepted HTTP request
body size in bytes. Mirrors the
|
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
host(str) -
port(int) -
reload(bool) -
workers(int) -
ws_ping_interval(float) -
ws_ping_timeout(float) -
ssl_certfile(str | None) -
ssl_keyfile(str | None) -
ssl_ca_certs(str | None) -
trusted_proxies(tuple[str, ...]) -
compression_minimum_size_bytes(int) -
request_max_body_size_bytes(int)
Validators:
-
_normalize_empty_tls -
_validate_tls_pair
ws_ping_interval
pydantic-field
¶
WebSocket ping interval in seconds (0 to disable)
ssl_ca_certs
pydantic-field
¶
Path to CA bundle for client certificate verification
trusted_proxies
pydantic-field
¶
IP addresses/CIDRs trusted as reverse proxies for X-Forwarded-For/Proto header processing
compression_minimum_size_bytes
pydantic-field
¶
Minimum response body size in bytes before brotli compression is applied (mirrors the api.compression_minimum_size_bytes setting; restart required)
request_max_body_size_bytes
pydantic-field
¶
Maximum accepted HTTP request body size in bytes (mirrors the api.request_max_body_size_bytes setting; restart required)
ApiConfig
pydantic-model
¶
Bases: BaseModel
Top-level API configuration aggregating all sub-configs.
Attributes:
| Name | Type | Description |
|---|---|---|
cors |
CorsConfig
|
CORS configuration. |
rate_limit |
RateLimitConfig
|
Global three-tier rate limiting configuration (IP floor un-gated, unauthenticated by IP, authenticated by user ID). |
per_op_rate_limit |
PerOpRateLimitConfig
|
Per-operation throttling configuration (layered on top of the global three-tier limiter). |
per_op_concurrency |
PerOpConcurrencyConfig
|
Per-operation inflight concurrency capping (layered on top of the sliding-window per-op limiter; caps simultaneous long-running requests per operation per subject). |
server |
ServerConfig
|
Uvicorn server configuration. |
auth |
AuthConfig
|
Authentication configuration. |
api_prefix |
NotBlankStr
|
URL prefix for all API routes. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
cors(CorsConfig) -
rate_limit(RateLimitConfig) -
per_op_rate_limit(PerOpRateLimitConfig) -
per_op_concurrency(PerOpConcurrencyConfig) -
server(ServerConfig) -
auth(AuthConfig) -
api_prefix(NotBlankStr)
rate_limit
pydantic-field
¶
Global three-tier rate limiting configuration: un-gated IP floor, unauthenticated by IP, authenticated by user ID
per_op_rate_limit
pydantic-field
¶
Per-operation throttling (layered on the global limiter)
per_op_concurrency
pydantic-field
¶
Per-operation inflight concurrency capping (layered on the sliding-window per-op limiter; caps simultaneous long-running requests per (operation, subject))
DTOs¶
dto
¶
Request/response DTOs and envelope models.
Response envelopes wrap all API responses in a consistent structure. Request DTOs define write-operation payloads (separate from domain models because they omit server-generated fields).
ErrorDetail
pydantic-model
¶
Bases: BaseModel
Structured error metadata (RFC 9457).
Self-contained so agents can parse it without referencing the parent envelope.
Attributes:
| Name | Type | Description |
|---|---|---|
detail |
NotBlankStr
|
Human-readable occurrence-specific explanation. |
error_code |
ErrorCode
|
Machine-readable error code (by convention, 4-digit
category-grouped; see |
error_category |
ErrorCategory
|
High-level error category. |
retryable |
bool
|
Whether the client should retry the request. |
retry_after |
int | None
|
Seconds to wait before retrying ( |
instance |
NotBlankStr
|
Request correlation ID for log tracing. |
title |
NotBlankStr
|
Static per-category title (e.g. "Authentication Error"). |
type |
NotBlankStr
|
Documentation URI for the error category. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
detail(NotBlankStr) -
error_code(ErrorCode) -
error_category(ErrorCategory) -
retryable(bool) -
retry_after(int | None) -
instance(NotBlankStr) -
title(NotBlankStr) -
type(NotBlankStr)
Validators:
-
_validate_retry_after_consistency
retry_after
pydantic-field
¶
Seconds to wait before retrying (null when not applicable).
ProblemDetail
pydantic-model
¶
Bases: BaseModel
Bare RFC 9457 application/problem+json response body.
Returned when the client sends Accept: application/problem+json.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
NotBlankStr
|
Documentation URI for the error category. |
title |
NotBlankStr
|
Static per-category title. |
status |
int
|
HTTP status code. |
detail |
NotBlankStr
|
Human-readable occurrence-specific explanation. |
instance |
NotBlankStr
|
Request correlation ID for log tracing. |
error_code |
ErrorCode
|
Machine-readable 4-digit error code. |
error_category |
ErrorCategory
|
High-level error category. |
retryable |
bool
|
Whether the client should retry the request. |
retry_after |
int | None
|
Seconds to wait before retrying ( |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
type(NotBlankStr) -
title(NotBlankStr) -
status(int) -
detail(NotBlankStr) -
instance(NotBlankStr) -
error_code(ErrorCode) -
error_category(ErrorCategory) -
retryable(bool) -
retry_after(int | None)
Validators:
-
_validate_retry_after_consistency
retry_after
pydantic-field
¶
Seconds to wait before retrying (null when not applicable).
ApiResponse
pydantic-model
¶
Bases: BaseModel
Standard API response envelope.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
T | None
|
Response payload ( |
error |
str | None
|
Error message ( |
error_detail |
ErrorDetail | None
|
Structured error metadata ( |
success |
bool
|
Whether the request succeeded (computed from |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
data(T | None) -
error(str | None) -
error_detail(ErrorDetail | None)
Validators:
-
_validate_error_detail_consistency
PaginationMeta
pydantic-model
¶
PaginatedResponse
pydantic-model
¶
Bases: BaseModel
Paginated API response envelope.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
tuple[T, ...]
|
Page of items. |
error |
str | None
|
Error message ( |
error_detail |
ErrorDetail | None
|
Structured error metadata ( |
pagination |
PaginationMeta
|
Pagination metadata. |
degraded_sources |
tuple[NotBlankStr, ...]
|
Data sources that failed gracefully, resulting in partial data. Empty when all sources responded normally. |
success |
bool
|
Whether the request succeeded (computed from |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
data(tuple[T, ...]) -
error(str | None) -
error_detail(ErrorDetail | None) -
pagination(PaginationMeta) -
degraded_sources(tuple[NotBlankStr, ...])
Validators:
-
_validate_error_detail_consistency
CreateArtifactRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new artifact.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
ArtifactType
|
Artifact type (code, tests, documentation). |
path |
NotBlankStr
|
Logical file/directory path of the artifact. |
task_id |
NotBlankStr
|
ID of the originating task. |
created_by |
NotBlankStr
|
Agent ID of the creator. |
description |
str
|
Human-readable description. |
content_type |
str
|
MIME content type (empty if no content stored). |
project_id |
NotBlankStr | None
|
Optional project ID to link the artifact to. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
type(ArtifactType) -
path(NotBlankStr) -
task_id(NotBlankStr) -
created_by(NotBlankStr) -
description(str) -
content_type(str) -
project_id(NotBlankStr | None)
content_type
pydantic-field
¶
MIME type of the artifact content (empty when no content is stored).
CreateProjectRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new project.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Project display name. |
description |
str
|
Detailed project description. |
team |
tuple[NotBlankStr, ...]
|
Agent IDs assigned to the project. |
lead |
NotBlankStr | None
|
Agent ID of the project lead. |
deadline |
str | None
|
Optional deadline (ISO 8601 string). |
budget |
float
|
Total budget in base currency. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
description(str) -
team(tuple[NotBlankStr, ...]) -
lead(NotBlankStr | None) -
deadline(str | None) -
budget(float)
Validators:
-
_validate_request
CreateTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new task.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
NotBlankStr
|
Short task title. |
description |
NotBlankStr
|
Detailed task description. |
type |
TaskType
|
Task work type. |
priority |
Priority
|
Task priority level. |
project |
NotBlankStr
|
Project ID. |
created_by |
NotBlankStr
|
Agent name of the creator. |
assigned_to |
NotBlankStr | None
|
Optional assignee agent ID. |
estimated_complexity |
Complexity
|
Complexity estimate. |
budget_limit |
float
|
Maximum spend in base currency. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
title(NotBlankStr) -
description(NotBlankStr) -
type(TaskType) -
priority(Priority) -
project(NotBlankStr) -
created_by(NotBlankStr) -
assigned_to(NotBlankStr | None) -
estimated_complexity(Complexity) -
budget_limit(float)
UpdateTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for updating task fields.
All fields are optional -- only provided fields are updated.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
NotBlankStr | None
|
New title. |
description |
NotBlankStr | None
|
New description. |
priority |
Priority | None
|
New priority. |
assigned_to |
NotBlankStr | None
|
New assignee. |
budget_limit |
float | None
|
New budget limit. |
expected_version |
int | None
|
Optimistic concurrency guard. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
title(NotBlankStr | None) -
description(NotBlankStr | None) -
priority(Priority | None) -
assigned_to(NotBlankStr | None) -
budget_limit(float | None) -
expected_version(int | None)
TransitionTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for a task status transition.
Attributes:
| Name | Type | Description |
|---|---|---|
target_status |
TaskStatus
|
The desired target status. |
assigned_to |
NotBlankStr | None
|
Optional assignee override for the transition. |
expected_version |
int | None
|
Optimistic concurrency guard. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
target_status(TaskStatus) -
assigned_to(NotBlankStr | None) -
expected_version(int | None)
CancelTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for cancelling a task.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
NotBlankStr
|
Reason for cancellation. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
CreateApprovalRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new approval item.
Attributes:
| Name | Type | Description |
|---|---|---|
action_type |
NotBlankStr
|
Kind of action requiring approval
( |
title |
NotBlankStr
|
Short summary. |
description |
NotBlankStr
|
Detailed explanation. |
risk_level |
ApprovalRiskLevel
|
Assessed risk level. |
ttl_seconds |
int | None
|
Optional time-to-live in seconds (min 60, max 604 800 = 7 days). |
task_id |
NotBlankStr | None
|
Optional associated task. |
metadata |
dict[str, str]
|
Additional key-value pairs. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
action_type(NotBlankStr) -
title(NotBlankStr) -
description(NotBlankStr) -
risk_level(ApprovalRiskLevel) -
ttl_seconds(int | None) -
task_id(NotBlankStr | None) -
metadata(dict[str, str])
Validators:
-
_validate_action_type_format→action_type -
_validate_metadata_bounds
action_type
pydantic-field
¶
Kind of action requiring approval in category:action format.
description
pydantic-field
¶
Detailed explanation of the action and why it requires approval.
ttl_seconds
pydantic-field
¶
Optional time-to-live in seconds before the approval auto-expires (minimum 60, maximum 604800 = 7 days).
ApproveRequest
pydantic-model
¶
Bases: BaseModel
Payload for approving an approval item.
Attributes:
| Name | Type | Description |
|---|---|---|
comment |
NotBlankStr | None
|
Optional comment explaining the approval. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
comment(NotBlankStr | None)
RejectRequest
pydantic-model
¶
Bases: BaseModel
Payload for rejecting an approval item.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
NotBlankStr
|
Mandatory reason for rejection. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
reason(NotBlankStr)
CoordinateTaskRequest
pydantic-model
¶
Bases: BaseModel
Payload for triggering multi-agent coordination on a task.
Attributes:
| Name | Type | Description |
|---|---|---|
agent_names |
tuple[NotBlankStr, ...] | None
|
Agent names to coordinate with ( |
max_subtasks |
int
|
Maximum subtasks for decomposition. |
max_concurrency_per_wave |
int | None
|
Override for max concurrency per wave. |
fail_fast |
bool | None
|
Override for fail-fast behaviour ( |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
agent_names(tuple[NotBlankStr, ...] | None) -
max_subtasks(int) -
max_concurrency_per_wave(int | None) -
fail_fast(bool | None)
Validators:
-
_validate_unique_agent_names
CoordinationPhaseResponse
pydantic-model
¶
Bases: BaseModel
Response model for a single coordination phase.
Attributes:
| Name | Type | Description |
|---|---|---|
phase |
NotBlankStr
|
Phase name. |
success |
bool
|
Whether the phase completed successfully. |
duration_seconds |
float
|
Wall-clock duration of the phase. |
error |
NotBlankStr | None
|
Error description if the phase failed. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
phase(NotBlankStr) -
success(bool) -
duration_seconds(float) -
error(NotBlankStr | None)
Validators:
-
_validate_success_error_consistency
CoordinationResultResponse
pydantic-model
¶
Bases: BaseModel
Response model for a complete coordination run.
Attributes:
| Name | Type | Description |
|---|---|---|
parent_task_id |
NotBlankStr
|
ID of the parent task. |
topology |
NotBlankStr
|
Resolved coordination topology. |
total_duration_seconds |
float
|
Total wall-clock duration. |
total_cost |
float
|
Total cost across all waves. |
phases |
tuple[CoordinationPhaseResponse, ...]
|
Phase results in execution order. |
wave_count |
int
|
Number of execution waves. |
is_success |
bool
|
Whether all phases succeeded (computed). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
parent_task_id(NotBlankStr) -
topology(NotBlankStr) -
total_duration_seconds(float) -
total_cost(float) -
currency(str) -
phases(tuple[CoordinationPhaseResponse, ...]) -
wave_count(int)
CreateFromPresetRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a provider from a preset.
Attributes:
| Name | Type | Description |
|---|---|---|
preset_name |
NotBlankStr
|
Name of the preset to create from. |
name |
NotBlankStr
|
Unique provider name (2-64 chars, lowercase + hyphens). |
auth_type |
AuthType | None
|
Override the preset's default auth type (optional). |
subscription_token |
NotBlankStr | None
|
Bearer token for subscription-based auth. |
tos_accepted |
bool
|
Whether the user accepted the subscription ToS. |
base_url |
NotBlankStr | None
|
Override the preset's default base URL (optional). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
preset_name(NotBlankStr) -
name(NotBlankStr) -
auth_type(AuthType | None) -
api_key(NotBlankStr | None) -
subscription_token(NotBlankStr | None) -
tos_accepted(bool) -
base_url(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...] | None)
Validators:
-
_validate_name→name -
_validate_base_url→base_url
CreateProviderRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new provider.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Unique provider name (2-64 chars, lowercase + hyphens). |
driver |
NotBlankStr
|
Driver backend name (default |
litellm_provider |
NotBlankStr | None
|
LiteLLM routing identifier override. |
auth_type |
AuthType
|
Authentication mechanism for this provider. |
api_key |
NotBlankStr | None
|
API key credential (optional, depends on auth_type). |
subscription_token |
NotBlankStr | None
|
Bearer token for subscription-based auth. |
tos_accepted |
bool
|
Whether the user accepted the subscription ToS. |
base_url |
NotBlankStr | None
|
Provider API base URL. |
models |
tuple[ProviderModelConfig, ...]
|
Pre-configured model definitions. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
driver(NotBlankStr) -
litellm_provider(NotBlankStr | None) -
auth_type(AuthType) -
api_key(NotBlankStr | None) -
subscription_token(NotBlankStr | None) -
tos_accepted(bool) -
base_url(NotBlankStr | None) -
oauth_token_url(NotBlankStr | None) -
oauth_client_id(NotBlankStr | None) -
oauth_client_secret(NotBlankStr | None) -
oauth_scope(NotBlankStr | None) -
custom_header_name(NotBlankStr | None) -
custom_header_value(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...]) -
preset_name(NotBlankStr | None)
Validators:
-
_validate_name→name -
_validate_base_url→base_url
DiscoverModelsResponse
pydantic-model
¶
Bases: BaseModel
Result of provider model auto-discovery.
Attributes:
| Name | Type | Description |
|---|---|---|
discovered_models |
tuple[ProviderModelConfig, ...]
|
Models found on the provider endpoint. |
provider_name |
NotBlankStr
|
Name of the provider that was queried. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
discovered_models(tuple[ProviderModelConfig, ...]) -
provider_name(NotBlankStr)
ProbePresetRequest
pydantic-model
¶
Bases: BaseModel
Request to probe a preset's candidate URLs for reachability.
Attributes:
| Name | Type | Description |
|---|---|---|
preset_name |
NotBlankStr
|
Preset identifier to probe. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
preset_name(NotBlankStr)
ProbePresetResponse
pydantic-model
¶
Bases: BaseModel
Result of probing a preset's candidate URLs.
Attributes:
| Name | Type | Description |
|---|---|---|
url |
NotBlankStr | None
|
The first reachable base URL, or |
model_count |
int
|
Number of models discovered at the URL. |
candidates_tried |
int
|
Number of candidate URLs attempted. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
url(NotBlankStr | None) -
model_count(int) -
candidates_tried(int)
ProviderResponse
pydantic-model
¶
Bases: BaseModel
Safe provider config for API responses -- secrets stripped.
Non-secret auth fields are included for frontend edit form UX.
Boolean has_* indicators signal credential presence without
exposing values.
Attributes:
| Name | Type | Description |
|---|---|---|
driver |
NotBlankStr
|
Driver backend name. |
litellm_provider |
NotBlankStr | None
|
LiteLLM routing identifier override. |
auth_type |
AuthType
|
Authentication mechanism. |
base_url |
NotBlankStr | None
|
Provider API base URL. |
models |
tuple[ProviderModelConfig, ...]
|
Configured model definitions. |
has_api_key |
bool
|
Whether an API key is set. |
has_oauth_credentials |
bool
|
Whether OAuth credentials are configured. |
has_custom_header |
bool
|
Whether a custom auth header is configured. |
has_subscription_token |
bool
|
Whether a subscription token is set. |
tos_accepted_at |
str | None
|
ISO timestamp of ToS acceptance (or |
preset_name |
NotBlankStr | None
|
Preset used to create this provider (if any). |
supports_model_pull |
bool
|
Whether pulling models is supported. |
supports_model_delete |
bool
|
Whether deleting models is supported. |
supports_model_config |
bool
|
Whether per-model config is supported. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
driver(NotBlankStr) -
litellm_provider(NotBlankStr | None) -
auth_type(AuthType) -
base_url(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...]) -
has_api_key(bool) -
has_oauth_credentials(bool) -
has_custom_header(bool) -
has_subscription_token(bool) -
tos_accepted_at(str | None) -
oauth_token_url(NotBlankStr | None) -
oauth_client_id(NotBlankStr | None) -
oauth_scope(NotBlankStr | None) -
custom_header_name(NotBlankStr | None) -
preset_name(NotBlankStr | None) -
supports_model_pull(bool) -
supports_model_delete(bool) -
supports_model_config(bool)
TestConnectionRequest
pydantic-model
¶
Bases: BaseModel
Payload for testing a provider connection.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
NotBlankStr | None
|
Model to test (defaults to first model in config). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
model(NotBlankStr | None)
TestConnectionResponse
pydantic-model
¶
Bases: BaseModel
Result of a provider connection test.
Attributes:
| Name | Type | Description |
|---|---|---|
success |
bool
|
Whether the connection test succeeded. |
latency_ms |
float | None
|
Round-trip latency in milliseconds. |
error |
NotBlankStr | None
|
Error message on failure. |
model_tested |
NotBlankStr | None
|
Model ID that was tested. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
success(bool) -
latency_ms(float | None) -
error(NotBlankStr | None) -
model_tested(NotBlankStr | None)
Validators:
-
_validate_success_error_consistency
UpdateProviderRequest
pydantic-model
¶
Bases: BaseModel
Payload for updating a provider (partial update).
All fields are optional -- only provided fields are updated.
tos_accepted: only True re-stamps the timestamp;
False and None are no-ops (cannot be retracted).
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
driver(NotBlankStr | None) -
litellm_provider(NotBlankStr | None) -
auth_type(AuthType | None) -
api_key(NotBlankStr | None) -
clear_api_key(bool) -
subscription_token(NotBlankStr | None) -
clear_subscription_token(bool) -
tos_accepted(bool | None) -
base_url(NotBlankStr | None) -
oauth_token_url(NotBlankStr | None) -
oauth_client_id(NotBlankStr | None) -
oauth_client_secret(NotBlankStr | None) -
oauth_scope(NotBlankStr | None) -
custom_header_name(NotBlankStr | None) -
custom_header_value(NotBlankStr | None) -
models(tuple[ProviderModelConfig, ...] | None)
Validators:
-
_validate_base_url→base_url -
_validate_credential_clear_consistency
ActivateWorkflowRequest
pydantic-model
¶
Bases: BaseModel
Request body for activating a workflow definition.
Attributes:
| Name | Type | Description |
|---|---|---|
project |
NotBlankStr
|
Project ID for all created tasks. |
context |
dict[str, str | int | float | bool | None]
|
Runtime context for condition expression evaluation. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
project(NotBlankStr) -
context(dict[str, str | int | float | bool | None])
BlueprintInfoResponse
pydantic-model
¶
Bases: BaseModel
Response body for a single workflow blueprint entry.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Blueprint identifier. |
display_name |
NotBlankStr
|
Human-readable name. |
description |
str
|
Short description. |
source |
Literal['builtin', 'user']
|
Origin of the blueprint. |
tags |
tuple[NotBlankStr, ...]
|
Categorization tags. |
workflow_type |
WorkflowType
|
Target execution topology. |
node_count |
int
|
Number of nodes in the graph. |
edge_count |
int
|
Number of edges in the graph. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
display_name(NotBlankStr) -
description(str) -
source(Literal['builtin', 'user']) -
tags(tuple[NotBlankStr, ...]) -
workflow_type(WorkflowType) -
node_count(int) -
edge_count(int)
CreateFromBlueprintRequest
pydantic-model
¶
Bases: BaseModel
Request body for creating a workflow from a blueprint.
Attributes:
| Name | Type | Description |
|---|---|---|
blueprint_name |
NotBlankStr
|
Name of the blueprint to instantiate. |
name |
NotBlankStr | None
|
Optional name override (defaults to blueprint display_name). |
description |
str | None
|
Optional description override. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
blueprint_name(NotBlankStr) -
name(NotBlankStr | None) -
description(str | None)
CreateWorkflowDefinitionRequest
pydantic-model
¶
Bases: BaseModel
Payload for creating a new workflow definition.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Workflow name. |
description |
str
|
Optional description. |
workflow_type |
WorkflowType
|
Target execution topology. |
nodes |
tuple[dict[str, object], ...]
|
Nodes in the workflow graph (serialized as dicts). |
edges |
tuple[dict[str, object], ...]
|
Edges connecting nodes (serialized as dicts). |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
description(str) -
workflow_type(WorkflowType) -
version(str) -
inputs(tuple[WorkflowIODeclarationRequest, ...]) -
outputs(tuple[WorkflowIODeclarationRequest, ...]) -
is_subworkflow(bool) -
nodes(tuple[dict[str, object], ...]) -
edges(tuple[dict[str, object], ...])
Validators:
-
_validate_semver→version
is_subworkflow
pydantic-field
¶
Whether this definition is a reusable subworkflow
RollbackWorkflowRequest
pydantic-model
¶
Bases: BaseModel
Request body for rolling back a workflow to a previous version.
Attributes:
| Name | Type | Description |
|---|---|---|
target_version |
int
|
Snapshot version number to restore content from (monotonic counter in the workflow_definition_versions table). |
expected_revision |
int
|
Current definition revision for optimistic concurrency on the live workflow_definitions row. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
target_version(int) -
expected_revision(int)
UpdateWorkflowDefinitionRequest
pydantic-model
¶
Bases: BaseModel
Payload for updating an existing workflow definition.
All fields are optional -- only provided fields are updated.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr | None
|
New name. |
description |
str | None
|
New description. |
workflow_type |
WorkflowType | None
|
New workflow type. |
version |
NotBlankStr | None
|
New semver version string. |
inputs |
tuple[WorkflowIODeclarationRequest, ...] | None
|
New typed input contract. |
outputs |
tuple[WorkflowIODeclarationRequest, ...] | None
|
New typed output contract. |
is_subworkflow |
bool | None
|
New publishing flag. |
nodes |
tuple[dict[str, object], ...] | None
|
New nodes. |
edges |
tuple[dict[str, object], ...] | None
|
New edges. |
expected_revision |
int | None
|
Optimistic concurrency guard. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr | None) -
description(str | None) -
workflow_type(WorkflowType | None) -
version(NotBlankStr | None) -
inputs(tuple[WorkflowIODeclarationRequest, ...] | None) -
outputs(tuple[WorkflowIODeclarationRequest, ...] | None) -
is_subworkflow(bool | None) -
nodes(tuple[dict[str, object], ...] | None) -
edges(tuple[dict[str, object], ...] | None) -
expected_revision(int | None)
Validators:
-
_validate_semver→version
WorkflowIODeclarationRequest
pydantic-model
¶
Bases: BaseModel
Typed input/output declaration for workflow creation/update.
Field names mirror WorkflowIODeclaration so that
model_validate pass-through works without renaming.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
NotBlankStr
|
Identifier for this input or output. |
type |
WorkflowValueType
|
The declared data type. |
required |
bool
|
Whether this declaration is mandatory. |
default |
object
|
Default when not required (must be None when required). |
description |
str
|
Human-readable description. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
name(NotBlankStr) -
type(WorkflowValueType) -
required(bool) -
default(object) -
description(str)
Validators:
-
_validate_default_with_required
RollbackAgentIdentityRequest
pydantic-model
¶
Bases: BaseModel
Request body for rolling back an agent identity to a previous version.
Attributes:
| Name | Type | Description |
|---|---|---|
target_version |
int
|
Snapshot version number to restore content from (monotonic counter in the agent_identity_versions table). |
reason |
NotBlankStr | None
|
Optional human-readable justification recorded alongside the evolution event for audit purposes. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
target_version(int) -
reason(NotBlankStr | None)
to_provider_response
¶
Convert a ProviderConfig to a safe ProviderResponse.
Strips all secrets and provides boolean credential indicators.
Resolves local model management capabilities from the preset
when preset_name is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ProviderConfig
|
Provider configuration (may contain secrets). |
required |
Returns:
| Type | Description |
|---|---|
ProviderResponse
|
Safe response DTO with secrets stripped. |
Source code in src/synthorg/api/dto_providers.py
Errors¶
errors
¶
API error hierarchy and RFC 9457 error taxonomy.
All API-specific errors inherit from ApiError so callers
can catch the entire family with a single except clause.
ErrorCategory and ErrorCode provide machine-readable error
metadata for structured error responses (RFC 9457).
ErrorCategory
¶
Bases: StrEnum
High-level error category for structured error responses.
Values are lowercase strings suitable for JSON serialization.
ErrorCode
¶
Bases: IntEnum
Machine-readable error codes (4-digit, category-grouped).
First digit encodes the category: 1xxx = auth, 2xxx = validation, 3xxx = not_found, 4xxx = conflict, 5xxx = rate_limit, 6xxx = budget_exhausted, 7xxx = provider_error, 8xxx = internal.
ApiError
¶
Bases: Exception
Base exception for API-layer errors.
Class Attributes
default_message: Fallback error message used when none is provided and for 5xx response scrubbing. error_category: RFC 9457 error category. error_code: RFC 9457 machine-readable error code. retryable: Whether the client should retry the request.
Instance Attributes
status_code: HTTP status code (set via __init__, fixed per
subclass).
Source code in src/synthorg/api/errors.py
__init_subclass__
¶
Validate error_code/error_category consistency at class creation.
Source code in src/synthorg/api/errors.py
NotFoundError
¶
ApiValidationError
¶
ConflictError
¶
VersionConflictError
¶
Bases: ApiError
Raised when an ETag/If-Match version check fails (409).
Used for ETag/If-Match optimistic concurrency checks -- currently on settings endpoints.
Source code in src/synthorg/api/errors.py
ForbiddenError
¶
SessionRevokedError
¶
Bases: ApiError
Raised when a revoked session token is used (401).
Gives clients a distinct error code (SESSION_REVOKED) so
they can show a "you were logged out" message instead of a
generic auth failure.
Source code in src/synthorg/api/errors.py
UnauthorizedError
¶
AccountLockedError
¶
Bases: ApiError
Raised when login is blocked by account lockout (429).
Uses HTTP 429 (Too Many Requests) with an optional
Retry-After header indicating when the lockout expires.
Source code in src/synthorg/api/errors.py
ServiceUnavailableError
¶
ArtifactTooLargeApiError
¶
ArtifactStorageFullApiError
¶
PerOperationRateLimitError
¶
Bases: ApiError
Raised when a per-operation rate limit is exceeded (429).
Produced by :func:synthorg.api.rate_limits.guard.per_op_rate_limit
guards. Flows through handle_api_error to produce an RFC 9457
response with Retry-After set.
Source code in src/synthorg/api/errors.py
ConcurrencyLimitExceededError
¶
Bases: PerOperationRateLimitError
Raised when a per-operation concurrency (inflight) cap is hit (429).
Produced by the PerOpConcurrencyMiddleware when a user already
has max_inflight requests running for the guarded operation.
Inherits from :class:PerOperationRateLimitError so the existing
429 / Retry-After / RFC 9457 handling applies unchanged. A
distinct error_code lets clients discriminate concurrency
denials ("you already have one running") from window denials
("try again after the bucket refills").
Source code in src/synthorg/api/errors.py
category_title
¶
Return the RFC 9457 title for a category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cat
|
ErrorCategory
|
Error category. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Human-readable title string. |
category_type_uri
¶
Return the RFC 9457 type URI for a category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cat
|
ErrorCategory
|
Error category. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Documentation URI with fragment anchor for the error category. |
Source code in src/synthorg/api/errors.py
Guards¶
guards
¶
Route guards for access control.
Guards read the authenticated user identity from connection.user
(populated by the auth middleware) and check role-based permissions.
The require_roles factory creates guards for arbitrary role sets.
Pre-built constants cover common patterns::
require_ceo -- CEO only
require_ceo_or_manager -- CEO or Manager
require_approval_roles -- CEO, Manager, or Board Member
require_ceo_or_manager
module-attribute
¶
require_ceo_or_manager = require_roles(CEO, MANAGER)
Guard allowing CEO or Manager roles.
require_approval_roles
module-attribute
¶
require_approval_roles = require_roles(CEO, MANAGER, BOARD_MEMBER)
Guard allowing roles that can approve or reject actions.
HumanRole
¶
Bases: StrEnum
Recognised human roles for access control.
has_write_role
¶
Return True if the role grants write access.
Use this for inline role checks instead of importing _WRITE_ROLES
directly. The write set includes CEO, Manager, and Pair Programmer.
Source code in src/synthorg/api/guards.py
require_write_access
¶
Guard that allows only write-capable human roles.
Checks connection.user.role for ceo, manager,
or pair_programmer. Board members are excluded (they
may only observe and approve). The system role is
intentionally excluded -- use require_roles() with the
desired roles for endpoints the CLI needs to reach.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
ASGIConnection
|
The incoming connection. |
required |
_
|
object
|
Route handler (unused). |
required |
Raises:
| Type | Description |
|---|---|
PermissionDeniedException
|
If the role is not permitted. |
Source code in src/synthorg/api/guards.py
require_read_access
¶
Guard that allows all human roles (excludes SYSTEM).
Checks connection.user.role for any human role
including observer and board_member. The internal
system role is excluded -- use require_roles() for
endpoints the CLI needs to reach.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
ASGIConnection
|
The incoming connection. |
required |
_
|
object
|
Route handler (unused). |
required |
Raises:
| Type | Description |
|---|---|
PermissionDeniedException
|
If the role is not permitted. |
Source code in src/synthorg/api/guards.py
require_roles
¶
Create a guard that allows only the specified roles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*roles
|
HumanRole
|
One or more |
()
|
Returns:
| Type | Description |
|---|---|
Callable[[ASGIConnection, object], None]
|
A guard function compatible with Litestar's guard protocol. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no roles are provided. |
Source code in src/synthorg/api/guards.py
require_org_mutation
¶
Guard factory for org config mutations.
Access is granted if the user has one of:
OrgRole.OWNER-- always allowedOrgRole.EDITOR-- always allowedOrgRole.DEPARTMENT_ADMIN-- allowed only when the target department (read from the path parameter named department_param) is in the user'sscoped_departments
If the user has no org_roles (empty tuple), falls back to
the existing HumanRole write-access check for backward
compatibility with pre-#1082 installations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
department_param
|
str | None
|
Path parameter name containing the target
department (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[ASGIConnection, object], None]
|
A guard function compatible with Litestar's guard protocol. |
Source code in src/synthorg/api/guards.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | |
Middleware¶
middleware
¶
Request middleware and before-send hooks.
Provides ASGI middleware for request logging, and a before_send
hook that injects security headers (CSP, CORP, HSTS, Cache-Control,
etc.) into every HTTP response -- including exception-handler and
unmatched-route (404/405) responses.
Why before_send instead of ASGI middleware?
Litestar's before_send hook wraps the ASGI send callback at
the outermost layer (before the middleware stack), so it fires for
all responses. By contrast, user-defined ASGI middleware only runs
for matched routes -- 404 and 405 responses from the router bypass it.
RequestLoggingMiddleware
¶
ASGI middleware that logs request start and completion.
Uses time.perf_counter() for high-resolution duration
measurement. Only logs HTTP requests (non-HTTP scopes like
WebSocket and lifespan are passed through without logging).
Source code in src/synthorg/api/middleware.py
__call__
async
¶
Process an ASGI request, logging start and completion.
Source code in src/synthorg/api/middleware.py
security_headers_hook
async
¶
Inject security headers into every HTTP response.
Registered as a Litestar before_send hook so it fires for
all HTTP responses -- successful, exception-handler, and
router-level 404/405.
Adds static security headers (CORP, HSTS, X-Content-Type-Options,
etc.) and path-aware Content-Security-Policy (strict for API,
relaxed for /docs/ to allow Scalar UI resources) and
Cache-Control (no-store for API, public, max-age=300
for /docs/ since it serves public, non-user-specific content).
Uses __setitem__ (not add) so that if any handler or
middleware already set a header, the known-good value overwrites
it rather than creating a duplicate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
ASGI message dict (only |
required |
scope
|
Scope
|
ASGI connection scope. |
required |
Source code in src/synthorg/api/middleware.py
Pagination¶
pagination
¶
In-memory pagination helper.
Applies offset/limit slicing to tuples and produces
PaginationMeta for the response envelope.
PaginationOffset
module-attribute
¶
Query parameter type for pagination offset (>= 0).
PaginationLimit
module-attribute
¶
Query parameter type for pagination limit (1-200).
paginate
¶
Slice a tuple and produce pagination metadata.
Clamps offset to [0, len(items)] and limit to
[1, MAX_LIMIT] as a safety net.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
tuple[T, ...]
|
Full collection to paginate. |
required |
offset
|
int
|
Zero-based starting index. |
required |
limit
|
int
|
Maximum items to return. |
required |
total
|
int | None
|
True total count when items has been truncated
upstream (e.g. by a safety cap). Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
tuple[tuple[T, ...], PaginationMeta]
|
A tuple of (page_items, pagination_meta). |
Source code in src/synthorg/api/pagination.py
WebSocket Models¶
ws_models
¶
WebSocket event models for real-time feeds.
Defines event types and the WsEvent payload that is
serialised to JSON and pushed to WebSocket subscribers.
WsEventType
¶
Bases: StrEnum
Types of real-time WebSocket events.
WsEvent
pydantic-model
¶
Bases: BaseModel
A real-time event pushed over WebSocket.
Callers must not mutate the payload dict after construction
-- the dict is a mutable reference inside a frozen model.
Attributes:
| Name | Type | Description |
|---|---|---|
version |
int
|
Wire-protocol version. Clients MUST ignore events whose
version they do not understand. Bump only when introducing a
breaking change to |
event_type |
WsEventType
|
Classification of the event. |
channel |
NotBlankStr
|
Target channel name. |
timestamp |
AwareDatetime
|
When the event occurred. |
payload |
dict[str, object]
|
Event-specific data. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
version(int) -
event_type(WsEventType) -
channel(NotBlankStr) -
timestamp(AwareDatetime) -
payload(dict[str, object])
Validators:
-
_deep_copy_payload
version
pydantic-field
¶
WS wire-protocol version (clients ignore unknown)
Auth¶
config
¶
Authentication configuration.
AuthConfig
pydantic-model
¶
Bases: BaseModel
JWT and authentication configuration.
The jwt_secret is resolved at application startup via a
priority chain:
SYNTHORG_JWT_SECRETenvironment variable (for multi-instance deployments sharing a common secret).- Previously persisted secret in the
settingstable. - Auto-generate a new secret and persist it for future runs.
At construction time the secret may be empty -- it is populated before the first request is served.
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
jwt_secret(str) -
jwt_algorithm(Literal['HS256', 'HS384', 'HS512']) -
jwt_expiry_minutes(int) -
min_password_length(int) -
exclude_paths(tuple[str, ...] | None) -
cookie_name(NotBlankStr) -
cookie_secure(bool) -
cookie_samesite(Literal['strict', 'lax', 'none']) -
cookie_path(NotBlankStr) -
csrf_cookie_path(NotBlankStr) -
cookie_domain(NotBlankStr | None) -
csrf_cookie_name(NotBlankStr) -
csrf_header_name(NotBlankStr) -
max_concurrent_sessions(int) -
jwt_refresh_enabled(bool) -
jwt_refresh_expiry_minutes(int) -
refresh_cookie_name(NotBlankStr) -
refresh_cookie_path(NotBlankStr) -
lockout_threshold(int) -
lockout_window_minutes(int) -
lockout_duration_minutes(int)
Validators:
-
_validate_secret_length -
_validate_refresh_expiry -
_validate_cookie_settings
jwt_secret
pydantic-field
¶
JWT signing secret (resolved at startup). Also used as the HMAC key for API key hash computation -- rotating this secret invalidates all stored API key hashes.
jwt_expiry_minutes
pydantic-field
¶
Token lifetime in minutes (default 24h)
min_password_length
pydantic-field
¶
Minimum password length for setup and password change
exclude_paths
pydantic-field
¶
Regex patterns for paths excluded from authentication. When None (default), paths are auto-derived from the API prefix (health, auth/setup, auth/login, docs, scalar UI). Use ^ to anchor at the start of the path and add $ when an exact match (rather than a prefix match) is required.
csrf_cookie_path
pydantic-field
¶
Path scope for the CSRF cookie (non-HttpOnly). Defaults to / so document.cookie in JavaScript can read it from any SPA route; scoping it under /api (like the session cookie) would hide it from code running on application pages, breaking the double-submit pattern.
cookie_domain
pydantic-field
¶
Domain for session cookies (None = current host)
csrf_cookie_name
pydantic-field
¶
CSRF token cookie name (non-HttpOnly, JS-readable)
csrf_header_name
pydantic-field
¶
Header name for CSRF token submission
max_concurrent_sessions
pydantic-field
¶
Max concurrent sessions per user (0 = unlimited)
jwt_refresh_expiry_minutes
pydantic-field
¶
Refresh token lifetime in minutes (default 7 days)
refresh_cookie_name
pydantic-field
¶
Refresh token cookie name
refresh_cookie_path
pydantic-field
¶
Path scope for refresh token cookie (narrow)
lockout_threshold
pydantic-field
¶
Failed login attempts before account lockout
lockout_window_minutes
pydantic-field
¶
Sliding window for counting failed attempts
lockout_duration_minutes
pydantic-field
¶
Auto-unlock duration after lockout
with_secret
¶
Return a copy with the JWT secret set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
Resolved JWT signing secret. |
required |
Returns:
| Type | Description |
|---|---|
AuthConfig
|
New |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the secret is too short. |
Source code in src/synthorg/api/auth/config.py
models
¶
Authentication domain models.
AuthMethod
¶
Bases: StrEnum
Authentication method used for a request.
OrgRole
¶
Bases: StrEnum
Permission-level role for org configuration access.
Orthogonal to HumanRole (operational persona).
HumanRole controls who you are in the org simulation;
OrgRole controls what you can do to the org config.
User
pydantic-model
¶
Bases: BaseModel
Persisted user account.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
NotBlankStr
|
Unique user identifier. |
username |
NotBlankStr
|
Login username. |
password_hash |
str
|
Argon2id hash (excluded from repr). |
role |
HumanRole
|
Access control role. |
must_change_password |
bool
|
Whether the user must change password. |
org_roles |
tuple[OrgRole, ...]
|
Permission-level roles for org config access. |
scoped_departments |
tuple[NotBlankStr, ...]
|
Departments accessible to dept admins. |
created_at |
AwareDatetime
|
Account creation timestamp. |
updated_at |
AwareDatetime
|
Last modification timestamp. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
id(NotBlankStr) -
username(NotBlankStr) -
password_hash(str) -
role(HumanRole) -
must_change_password(bool) -
org_roles(tuple[OrgRole, ...]) -
scoped_departments(tuple[NotBlankStr, ...]) -
created_at(AwareDatetime) -
updated_at(AwareDatetime)
Validators:
-
_validate_scoped_departments
ApiKey
pydantic-model
¶
Bases: BaseModel
Persisted API key (hash-only storage).
Attributes:
| Name | Type | Description |
|---|---|---|
id |
NotBlankStr
|
Unique key identifier (UUID). |
key_hash |
NotBlankStr
|
HMAC-SHA256 hex digest of the raw key. |
name |
NotBlankStr
|
Human-readable label. |
role |
HumanRole
|
Access control role. |
user_id |
NotBlankStr
|
Owner user ID. |
created_at |
AwareDatetime
|
Key creation timestamp (timezone-aware). |
expires_at |
AwareDatetime | None
|
Optional expiry timestamp (timezone-aware). |
revoked |
bool
|
Whether the key has been revoked. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
id(NotBlankStr) -
key_hash(NotBlankStr) -
name(NotBlankStr) -
role(HumanRole) -
user_id(NotBlankStr) -
created_at(AwareDatetime) -
expires_at(AwareDatetime | None) -
revoked(bool)
AuthenticatedUser
pydantic-model
¶
Bases: BaseModel
Lightweight identity attached to connection.user.
Populated by the auth middleware after successful authentication.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
NotBlankStr
|
User's unique identifier. |
username |
NotBlankStr
|
User's login name. |
role |
HumanRole
|
Access control role. |
auth_method |
AuthMethod
|
How the user authenticated. |
must_change_password |
bool
|
Whether forced password change is pending. |
org_roles |
tuple[OrgRole, ...]
|
Permission-level roles for org config access. |
scoped_departments |
tuple[NotBlankStr, ...]
|
Departments accessible to dept admins. |
Config:
frozen:Trueallow_inf_nan:False
Fields:
-
user_id(NotBlankStr) -
username(NotBlankStr) -
role(HumanRole) -
auth_method(AuthMethod) -
must_change_password(bool) -
org_roles(tuple[OrgRole, ...]) -
scoped_departments(tuple[NotBlankStr, ...])
Validators:
-
_validate_scoped_departments
service
¶
Authentication service -- password hashing, JWT ops, API key hashing.
SecretNotConfiguredError
¶
Bases: RuntimeError
Raised when the JWT secret is required but not configured.
AuthService
¶
Immutable authentication operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AuthConfig
|
Authentication configuration (carries JWT secret). |
required |
Source code in src/synthorg/api/auth/service.py
hash_password
¶
Hash a password with Argon2id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Argon2id hash string. |
verify_password
¶
Verify a password against an Argon2id hash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password to check. |
required |
password_hash
|
str
|
Stored Argon2id hash. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
VerificationError
|
On non-mismatch verification failures (e.g. unsupported parameters). |
InvalidHashError
|
If the stored hash is corrupted or malformed (data integrity issue). |
Source code in src/synthorg/api/auth/service.py
hash_password_async
async
¶
Hash a password with Argon2id in a thread executor.
Offloads the CPU-intensive hashing to avoid blocking the event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Argon2id hash string. |
Source code in src/synthorg/api/auth/service.py
verify_password_async
async
¶
Verify a password against an Argon2id hash in a thread executor.
Offloads the CPU-intensive verification to avoid blocking the event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
Plaintext password to check. |
required |
password_hash
|
str
|
Stored Argon2id hash. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/synthorg/api/auth/service.py
create_token
¶
Create a JWT for the given user.
The token includes a pwd_sig claim -- a 16-character
truncated SHA-256 of the stored password hash. This is
plain SHA-256, not HMAC -- the password hash is already a
high-entropy Argon2id output, and the claim is protected
by the JWT signature. The auth middleware validates this
claim on every request so that tokens issued before a
password change are automatically rejected.
A jti (JWT ID) claim is included for per-token session
tracking and revocation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
User
|
Authenticated user. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, int, str]
|
Tuple of (encoded JWT, expiry seconds, session ID). |
Raises:
| Type | Description |
|---|---|
SecretNotConfiguredError
|
If the JWT secret is empty. |
Source code in src/synthorg/api/auth/service.py
decode_token
¶
Decode and validate a JWT.
Audience (aud) verification is intentionally disabled
here (verify_aud=False) because audience validation is
performed per-role in the auth middleware's
_resolve_jwt_user. System-user tokens require
aud=synthorg-backend; regular user tokens omit aud.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
Encoded JWT string. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Decoded claims dictionary. |
Raises:
| Type | Description |
|---|---|
SecretNotConfiguredError
|
If the JWT secret is empty. |
InvalidTokenError
|
If the token is invalid or expired. |
Source code in src/synthorg/api/auth/service.py
hash_api_key
¶
Compute HMAC-SHA256 hex digest of a raw API key.
Uses the server-side JWT secret as the HMAC key so that an attacker with read access to stored hashes cannot brute-force API keys offline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_key
|
str
|
The plaintext API key. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Lowercase hex digest. |
Raises:
| Type | Description |
|---|---|
SecretNotConfiguredError
|
If the JWT secret is empty. |
Source code in src/synthorg/api/auth/service.py
generate_api_key
staticmethod
¶
Generate a cryptographically secure API key.
Returns:
| Type | Description |
|---|---|
str
|
URL-safe base64 string (43 chars). |
middleware
¶
JWT + API key authentication middleware.
ApiAuthMiddleware
¶
Bases: AbstractAuthenticationMiddleware
Authenticate requests via cookie, JWT header, or API key.
Authentication priority:
- Session cookie -- HttpOnly cookie set by login/setup. Primary auth path for browser sessions.
- Authorization header --
Bearer <token>. Tokens with dots are JWTs (system user CLI tokens). Tokens without dots are API keys (HMAC-SHA256 lookup).
Requires auth_service, persistence backend on
app.state["app_state"].
authenticate_request
async
¶
Validate the session cookie or Authorization header.
Tries the session cookie first. Falls back to the Authorization header for API keys and system user JWTs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
ASGIConnection[Any, Any, Any, Any]
|
Incoming ASGI connection. |
required |
Returns:
| Type | Description |
|---|---|
AuthenticationResult
|
AuthenticationResult with AuthenticatedUser. |
Raises:
| Type | Description |
|---|---|
NotAuthorizedException
|
If authentication fails. |
Source code in src/synthorg/api/auth/middleware.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
create_auth_middleware_class
¶
Create a middleware class with excluded paths baked in.
Litestar's AbstractAuthenticationMiddleware.__init__ takes
exclude as a parameter (default None). We create a
subclass whose __init__ forwards the configured exclude
list to super().__init__.
The middleware is restricted to ScopeType.HTTP only --
WebSocket connections use ticket-based auth handled entirely
inside the WS handler (see controllers/ws.py).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth_config
|
AuthConfig
|
Auth configuration with exclude_paths. |
required |
Returns:
| Type | Description |
|---|---|
type[ApiAuthMiddleware]
|
Middleware class ready for use in the Litestar middleware stack. |