Autodoc — critical public symbols (subset)¶
Generated signatures via mkdocstrings for the primary public surface used in
Learn / Adopt paths. This page is intentionally a subset of every name in
hedron.__all__ — prefer hand-maintained contract pages for narrative, errors, and
adopter guidance; use Autodoc to verify parameter lists against installed sources.
Coverage map for the full export set: Coverage map. Stability levels: Stability. Overview: API overview.
Narrative companions: Inference · Hedron · Interaction.
Inference and model demos (0.18)¶
hedron_core.model_demo.ActionRegistry
dataclass
¶
hedron_core.model_demo.InferenceInterface
dataclass
¶
Reviewable input/result surface derived from a registered action or adapter.
hedron_core.model_demo.ModelDemo
dataclass
¶
Composition layer that builds InferenceInterface only from the registry.
build_from_action(action_id, *, interface_id=None, inputs=None, outputs=None, live_mode=False, debounce_ms=0, component_overrides=None)
¶
build_from_adapter(adapter_id, *, interface_id=None, inputs=None, outputs=None, live_mode=False, debounce_ms=0, component_overrides=None)
¶
build_from_callable(fn, **_)
¶
Fail closed — bare callables are never auto-published.
hedron_core.inference.InferencePolicy
dataclass
¶
Admission and scheduling policy layered on a durable JobBackend.
admit(*, job_type, payload, group, priority=InferencePriority.NORMAL, tenant_id=None, auth_subject=None, correlation_id='', shape_key='default', backend=None)
¶
Admit an inference request: run immediately, queue, or reject on overload.
request_cancel(request_id, *, backend=None)
¶
drain_ready(*, backend=None)
¶
Promote queued items into free concurrency slots (fair within group).
form_batch(items, *, now=None)
¶
Group compatible shapes within the configured batch window.
Flushes when max_size is reached, when the oldest member has waited
at least max_wait_ms (only when enqueued_at is set), or when
flushing the trailing remainder of a one-shot call.
release(group, *, count=1)
¶
hedron_core.inference_workflow.InferenceWorkflow
dataclass
¶
Typed, versioned inference DAG with separate read/run/edit/publish authority.
hedron.recorder.InteractionRecorder
dataclass
¶
Dashboards (0.17)¶
hedron_core.dashboard.DashboardBinding
dataclass
¶
Page-local binding: triggers → action → targets.
hedron_core.dashboard.InteractionGraph
dataclass
¶
Finite, inspectable page-local interaction graph.
hedron_core.dashboard.TriggerContext
dataclass
¶
Typed context for a firing dashboard binding edge.
Application and routing¶
hedron.app.Hedron
¶
Bases: FastAPI
Batteries-included FastAPI application with Hedron defaults.
Installs session middleware (when enabled), CSRF-aware security profiles,
security headers, bundled HTMX static assets, and a root HedronRouter for
@page / @component / @action routes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
security
|
SecurityProfileName | str | SecurityPolicy
|
Built-in profile name ( |
'standard'
|
explorer
|
ExplorerMode | str | None
|
Component Explorer mode ( |
None
|
session_secret
|
str
|
Secret for Starlette session cookies. Replace the development
default before production; |
_DEFAULT_SESSION_SECRET
|
enable_sessions
|
bool
|
When |
True
|
explorer_dependencies
|
Sequence[Depends] | None
|
FastAPI dependencies required for |
None
|
theme
|
str | None
|
Registered theme name ( |
'default'
|
default_styles
|
bool
|
When |
True
|
build_dir
|
str | Path | None
|
Optional precompiled asset manifest directory for production. |
None
|
production
|
bool | None
|
Force production gate behavior; |
None
|
*args
|
Any
|
Forwarded to |
()
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Examples:
>>> app = Hedron(title="Demo", security="standard", session_secret="replace-me")
>>> @app.page("/")
... def home() -> Page:
... return Page(Text("Hello"), title="Home")
page(path, *, fragment_regions=None, **kwargs)
¶
Register a navigable PAGE route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
URL path (FastAPI path syntax). |
required |
fragment_regions
|
Sequence[FragmentRegion | str] | None
|
Declared HTMX fragment regions authorized for this route. |
None
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, R]], Callable[P, R]]
|
Decorator that registers the handler and returns it unchanged. |
component(path, *, fragment_regions=None, **kwargs)
¶
Register an addressable component / fragment route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
URL path (FastAPI path syntax). |
required |
fragment_regions
|
Sequence[FragmentRegion | str] | None
|
Declared HTMX fragment regions authorized for this route. |
None
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, R]], Callable[P, R]]
|
Decorator that registers the handler and returns it unchanged. |
action(path, **kwargs)
¶
Register a mutation endpoint (typically POST) with CSRF when profiles require it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
URL path (FastAPI path syntax). |
required |
**kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, R]], Callable[P, R]]
|
Decorator that registers the action handler. |
region(id, *, selector=None, description='')
¶
Declare a fragment region (default selector #{id}).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Stable region identifier used in markup and allowlists. |
required |
selector
|
str | None
|
CSS selector for the swap target; defaults to |
None
|
description
|
str
|
Human-readable description for Explorer / diagnostics. |
''
|
Returns:
| Type | Description |
|---|---|
FragmentRegion
|
A |
fragment(path, *, region=None, regions=None, fragment_regions=None, **kwargs)
¶
Alias of :meth:component that merges region / regions into the allowlist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
URL path (FastAPI path syntax). |
required |
region
|
FragmentRegion | str | None
|
Single authorized region. |
None
|
regions
|
Sequence[FragmentRegion | str] | None
|
Additional authorized regions. |
None
|
fragment_regions
|
Sequence[FragmentRegion | str] | None
|
Explicit allowlist merged with |
None
|
**kwargs
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, R]], Callable[P, R]]
|
Decorator that registers the fragment handler. |
include_component(descriptor, *, path, **kwargs)
¶
include_router(router, *args, **kwargs)
¶
hedron.routing.router.HedronRouter
¶
Bases: APIRouter
APIRouter with Hedron page/component/action decorators.
page(path, *, methods=None, name=None, include_in_schema=True, dependencies=None, tags=None, fragment_regions=None, **kwargs)
¶
component(path, *, methods=None, name=None, include_in_schema=False, dependencies=None, tags=None, fragment_regions=None, **kwargs)
¶
action(path, *, method='POST', methods=None, name=None, include_in_schema=True, dependencies=None, tags=None, fragment_regions=None, **kwargs)
¶
include_component(descriptor, *, path, name=None, dependencies=None, include_in_schema=None, methods=None, tags=None, **kwargs)
¶
hedron.app.mount_hedron_static(app, *, path='/hedron-static')
¶
Mount bundled Hedron static assets (HTMX, disclose) on any FastAPI app.
hedron.responses.HTML
¶
Explicit HTML intent wrapper for plain FastAPI routes.
hedron.responses.PageResponse
¶
Bases: ComponentResponse
hedron.responses.FragmentResponse
¶
Bases: ComponentResponse
hedron.responses.ComponentResponse
¶
Bases: HTMLResponse
hedron.responses.hedron_response(component_type=None)
¶
OpenAPI metadata for plain FastAPI component routes.
Interaction¶
hedron_core.interaction.InteractionResult
dataclass
¶
Primary content plus validated HTMX mechanics (headers stay inspectable).
Prefer returning InteractionResult (or helpers such as swap(...)) from
fragment and action handlers when you need explicit HTMX headers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
NodeLike | None
|
Node tree rendered for the response body (may be |
None
|
status_code
|
int
|
HTTP status for the response. |
200
|
target
|
str | None
|
Optional |
None
|
swap
|
str | None
|
Optional |
None
|
oob
|
tuple[OobUpdate, ...]
|
Out-of-band updates applied alongside the primary swap. |
()
|
trigger
|
str | Mapping[str, JsonValue] | None
|
|
None
|
trigger_after_swap
|
str | Mapping[str, JsonValue] | None
|
|
None
|
trigger_after_settle
|
str | Mapping[str, JsonValue] | None
|
|
None
|
push_url
|
str | bool | None
|
|
None
|
replace_url
|
str | bool | None
|
|
None
|
redirect
|
str | None
|
|
None
|
refresh
|
bool
|
When |
False
|
retarget
|
str | None
|
Alternate spelling forwarded as retarget header when set. |
None
|
reswap
|
str | None
|
Alternate spelling forwarded as reswap header when set. |
None
|
reselect
|
str | None
|
|
None
|
location
|
str | HxLocation | Mapping[str, JsonValue] | None
|
|
None
|
history
|
HistoryMode
|
History mode for the interaction ( |
'none'
|
cache
|
CacheHint | None
|
Cache hint for response headers ( |
'vary-htmx'
|
concurrency
|
str | None
|
Optional concurrency token / key for adaptive controls. |
None
|
region_id
|
str | None
|
Declared fragment region id this result targets. |
None
|
policy
|
InteractionPolicy | None
|
Interaction policy including declared regions and OOB rules. |
None
|
headers
|
Mapping[str, str]
|
Extra response headers (must pass HTMX allowlist validation). |
dict()
|
explanation
|
str
|
Optional human-readable note for diagnostics / Explorer. |
''
|
Raises:
| Type | Description |
|---|---|
FragmentRegionError
|
When resolving a request target that is not an
authorized declared region (via |
Examples:
>>> from hedron_core.interaction import InteractionResult
>>> InteractionResult(content=None, status_code=200, refresh=True)
InteractionResult(...)
hedron_core.interaction.FragmentRegion
dataclass
¶
Authorized fragment region declared on a route.
hedron_core.interaction.InteractionPolicy
dataclass
¶
Defaults for sync, indicators, CSRF, focus, and error retarget.
hedron_core.interaction.OobUpdate
dataclass
¶
hedron.interaction.swap(content, *, toast=None, oob=(), **kwargs)
¶
Build a primary-fragment :class:InteractionResult (optional toast / OOB).
hedron.interaction.swap_oob(content, *oob, **kwargs)
¶
Primary fragment plus one or more out-of-band updates.
hedron.interaction.retarget(content, region, **kwargs)
¶
Return content with an approved HX-Retarget selector.
hedron.interaction.redirect_htmx(url)
¶
Issue an HTMX HX-Redirect via :class:InteractionResult.
hedron.builtins.RefreshButton
¶
Security¶
hedron.security.policy.SecurityPolicy
dataclass
¶
hedron.security.policy.SecurityProfile
¶
Bases: StrEnum
hedron.security.csrf.csrf_token_for_request(request, policy)
¶
Return a single CSRF token for this request (cookie or request-scoped cache).
Pages and ensure_csrf_cookie must share this value so form / hx-headers
tokens match the Set-Cookie value on first load.
hedron_core.security.SafeUrl
¶
Validated URL for a declared purpose; still subject to final render policy.
hedron_core.security.TrustedHtml
¶
Immutable raw-markup value created only at an explicit trust boundary.
nh3(value, *, tags=None)
classmethod
¶
Sanitize HTML with nh3 and record policy provenance.
Requires the optional nh3 dependency (pip install "hedron[sanitize]"
or pip install "hedron[markdown]").
hedron_core.security.Secret
¶
Bases: Generic[T]
Typed sensitive value that never appears in public representations.
OIDC helpers (optional hedron[auth])¶
hedron.oidc.OidcClientConfig
dataclass
¶
hedron.oidc.generate_pkce(*, nbytes=64)
¶
Generate a PKCE verifier/challenge pair (S256).
hedron.oidc.generate_state(*, nbytes=32)
¶
hedron.oidc.store_oidc_handshake(session, *, state, nonce=None, code_verifier=None)
¶
Persist handshake secrets on the host session (not an identity DB).
hedron.oidc.normalize_claims(claims)
¶
hedron.oidc.redact_claims(claims)
¶
Explorer-safe claim view: keep sub, mask email, scrub token-like raw keys.
hedron.oidc.login_url(config, *, state, nonce=None, code_challenge=None, code_challenge_method='S256', extra_params=None)
¶
Build an OIDC authorization URL via Authlib URL helpers.
Raises HED-AUTH-0001 when Authlib is not installed
(pip install "hedron[auth]").
hedron.oidc.logout_url(config, *, id_token_hint=None, post_logout_redirect_uri=None, state=None, extra_params=None)
¶
Build an OIDC end-session / logout URL via Authlib URL helpers.
Raises HED-AUTH-0001 when Authlib is not installed
(pip install "hedron[auth]").
Page, component, and rendering¶
hedron_core.component.Component
¶
Field(default=..., *, default_factory=None, minimum=None, maximum=None, min_length=None, max_length=None, pattern=None, choices=None, required=None, label=None, help=None, placeholder=None, display=None, autocomplete=None, format=None, read_only=False, hidden=False, secret=False, writable_policy=None, key=None, sortable=False, filterable=False, editor=None, width=None, identity=False, accessible_label=None, accessible_description=None, accessible_error=None, **extra)
¶
Declare validation, presentation, access, data, and a11y metadata.
hedron_core.rendering.render(value, *, context=None, mode=RenderMode.FRAGMENT)
¶
Framework-neutral entry point producing a RenderResult.
hedron_core.rendering.RenderMode
¶
Bases: StrEnum
hedron_core.rendering.RenderResult
dataclass
¶
hedron_core.html.html = _HtmlNamespace()
module-attribute
¶
State and cache¶
hedron.state.SessionState
¶
Bases: Generic[T]
Thin typed facade over the host framework session.
hedron.state.session_state(key, annotation)
¶
hedron_core.cache.invalidate_tags(*tags)
¶
hedron.cache.cache_component(fn=None, /, *, ttl=30, scope='private', version='1', tags=(), vary_on=())
¶
Common built-ins used in guides¶
hedron.builtins.RefreshButton
¶
Color mode¶
hedron_core.color_mode.ColorMode
¶
Bases: StrEnum
hedron_core.color_mode.resolve_color_mode(preference, *, system_dark=False)
¶
Resolve stored preference against system preference.
hedron.color_mode.apply_color_mode_cookie(response, preference, *, max_age=60 * 60 * 24 * 365)
¶
hedron.color_mode.read_color_mode_preference(request)
¶
Live helpers¶
hedron.sse.sse_response(events)
¶
hedron.sse.job_status_sse_response(job_id, *, backend=None, request=None, html_message=None, poll_interval_seconds=None, auth_subject=None, tenant_id=None)
¶
Stream job status events until terminal; polling remains a Supported fallback.
Honors Last-Event-ID by skipping already-delivered event ids. Emits only when
state / updated_at change. Stops when the job is terminal or missing.
When the stored job has auth_subject / tenant_id set, the matching kwargs
must be provided and equal or the helper raises 404 (same as missing) to avoid
job-id enumeration. Unscoped jobs (no scope on the record) are never readable
over HTTP. Missing jobs raise 404.
hedron.sse.SseResponse
¶
Bases: StreamingResponse
hedron.jobs.enqueue_durable(job_type, payload, *, idempotency_key=None, tenant_id=None, auth_subject=None)
¶
hedron.jobs.job_status_response(job_status, *, auth_subject=None, tenant_id=None)
¶
hedron.jobs.schedule_post_response(tasks, fn, *args)
¶
Schedule small non-durable post-response work (NOT a JobBackend).
hedron_core.jobs.JobBackend
¶
Bases: Protocol
Durable job store used by status polling and inference admission.
Implementations must scope observation and cancel by auth_subject /
tenant_id when those values are present. In-memory backends do not span
processes — use Redis (or Celery/RQ bridges) for multi-worker deployments.
Methods:
| Name | Description |
|---|---|
submit |
Enqueue work and return a |
get |
Fetch status when authorized; return |
request_cancel |
Request cancellation; return whether the request was accepted. |
cleanup_expired |
Drop stale records; return the number removed. |
mark |
Update lifecycle state / result payload for an existing job. |
submit(job_type, payload, *, idempotency_key=None, tenant_id=None, auth_subject=None)
¶
Enqueue a job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_type
|
str
|
Application-defined job type string. |
required |
payload
|
Mapping[str, JsonValue]
|
JSON-compatible job payload. |
required |
idempotency_key
|
str | None
|
Optional deduplication key. |
None
|
tenant_id
|
str | None
|
Optional tenant scope for authorization. |
None
|
auth_subject
|
str | None
|
Optional subject scope for authorization. |
None
|
Returns:
| Type | Description |
|---|---|
JobHandle
|
Handle containing the assigned |
get(job_id, *, auth_subject=None, tenant_id=None)
¶
Return job status when the caller is authorized to observe it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Job identifier. |
required |
auth_subject
|
str | None
|
Optional subject scope; fail closed when mismatched. |
None
|
tenant_id
|
str | None
|
Optional tenant scope; fail closed when mismatched. |
None
|
Returns:
| Type | Description |
|---|---|
JobStatus | None
|
|
request_cancel(job_id, *, auth_subject=None, tenant_id=None)
¶
Request cancellation for a job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Job identifier. |
required |
auth_subject
|
str | None
|
Optional subject scope. |
None
|
tenant_id
|
str | None
|
Optional tenant scope. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
cleanup_expired(*, older_than_seconds=86400)
¶
Remove expired job records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
older_than_seconds
|
float
|
Age threshold for cleanup. |
86400
|
Returns:
| Type | Description |
|---|---|
int
|
Number of records removed. |
mark(job_id, state, *, result=None, error=None)
¶
Update lifecycle state for an existing job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Job identifier. |
required |
state
|
JobState
|
New |
required |
result
|
object
|
Optional successful result payload. |
None
|
error
|
str | None
|
Optional failure message. |
None
|
Returns:
| Type | Description |
|---|---|
JobStatus | None
|
Updated |
hedron_core.jobs.InMemoryJobBackend
¶
hedron_core.jobs.set_job_backend(backend)
¶
hedron.streaming.StreamingComponentResponse
¶
Bases: StreamingResponse
Stream focused HTML chunks for an addressable region.
hedron.streaming.stream_tokens(source)
¶
hedron.streaming.stream_chunked_list(source)
¶
hedron.streaming.stream_document(source)
¶
hedron.websocket_channel.accept_page_session_channel(websocket, channel, *, allowed_origins=None, allow_missing_origin=False, on_client_state=None, producer=None)
async
¶
hedron.websocket_channel.send_region_update(websocket, channel, update)
async
¶
hedron_core.preload.NavigationPreloadPolicy
dataclass
¶
Safe-GET speculative preload controls. Disabled by default.
hedron_core.builtins.live_ui.Dialog
¶
hedron_core.builtins.live_ui.ChatMessage
¶
Bases: Component[ChatMessageProps]
Typed chat transcript item. History ownership stays with the application.
hedron.builtins.chat.ChatInput
¶
Bases: Component[ChatInputProps]
Explicit chat submit control. Transcript history is application-owned.
Framework adapters¶
Signatures for hedron-flask and hedron-django public exports. Narrative matrix:
Adapters.
hedron_flask.app.HedronFlask
¶
Native Flask extension with Hedron render and interaction helpers.
Construct with an import_name to own a Flask app (legacy), or construct
without an app and call :meth:init_app for application-factory composition.
hedron_flask.routing.hedron_route(app, rule, *, endpoint=None, methods=None, csrf_protect=True, csrf_cookie_name=DEFAULT_CSRF_COOKIE, fragment_regions=None, allow_undeclared_targets=False, **options)
¶
Register a view that may return a component, InteractionResult, or Response.
hedron_flask.responses.interaction_response(result, *, context=None, mode=None, extra_headers=None, headers_map=None, authenticated=False, fragment_regions=None)
¶
hedron_flask.responses.component_response(value, *, status_code=200, context=None, mode=None, extra_headers=None, headers_map=None, authenticated=False, fragment_regions=None, allow_undeclared_targets=False)
¶
hedron_flask.routing.FlaskUrlReverser
¶
Reverse endpoint names via Flask url_for.
hedron_django.app.HedronDjango
¶
Native Django integration with Hedron render and interaction helpers.
hedron_django.routing.hedron_view(view=None, *, fragment_regions=None, allow_undeclared_targets=False)
¶
Wrap a view so components and InteractionResult values become HttpResponse.
hedron_django.responses.interaction_response(result, *, request=None, context=None, mode=None, extra_headers=None, authenticated=False, fragment_regions=None)
¶
hedron_django.responses.component_response(value, *, request=None, status_code=200, context=None, mode=None, extra_headers=None, authenticated=False, fragment_regions=None, allow_undeclared_targets=False)
¶
hedron_django.routing.DjangoUrlReverser
¶
Reverse named URL patterns via Django reverse.
Prepare lifecycle (0.13)¶
hedron_core.prepare.PrepareContext
dataclass
¶
Request-owned context for Component.prepare.
hedron_core.prepare.PartialFailurePolicy
¶
Bases: StrEnum
How sibling prepare failures interact.
Security audit (0.13)¶
hedron_core.audit.SecurityAuditEvent
dataclass
¶
hedron_core.audit.set_security_audit_sink(sink)
¶
hedron_core.audit.emit_security_audit(event_type, message, *, attributes=None)
¶
Tracing (0.13)¶
hedron.tracing.configure_tracing(*, enabled=True, sample_rate=1.0, service_name='hedron')
¶
hedron.tracing.span(name, /, **attributes)
¶
Open a redacted span; no-op when tracing is disabled.
Async helpers¶
hedron.async_utils.await_if_needed(value)
async
¶
hedron.async_utils.gather(*aws, return_exceptions=False)
async
¶
Gather sibling awaitables with ContextVar propagation via task creation.
When return_exceptions is False, the first exception cancels remaining
siblings (asyncio.gather default behavior).
hedron.async_utils.run_sync(fn, /, *args, **kwargs)
async
¶
Run a sync callable in a bounded thread pool with ContextVar copy.
Callables marked with mark_cpu_heavy are rejected — apps should use a
durable job backend for CPU-heavy work (D-020 / D-037).
Diagnostics¶
hedron_core.diagnostics.Diagnostic
dataclass
¶
Immutable diagnostic record with a stable HED-<AREA>-<NNNN> code.
See also¶
- Hedron contract · Router · Interaction
- Prepare · Audit · Tracing
- Component · Field · SSE · Diagnostics
- CLI · Page · Adapters · Public API coverage map
- Component catalog (props/examples): Components