SDL — Structured Data Layer
SDL — Structured Data Layer: type the meaning of fields so Webbee reads your entities as data, with typed facets and roles instead of field-name guessing.
sdl (Structured Data Layer) is the typed-entity system for @chat.function return values. Instead of returning a plain dict inside ActionResult, you compose sdl.Entity with one or more facets — thin mixins that attach semantically-tagged fields to your entity class. Every facet field carries a standard role (e.g. time.created_at, task.priority) so the platform knows exactly what each field means regardless of your extension's naming conventions.
SDL ships in SDK 5.2.0 and is live in production — the platform reads the SDL entities your extensions return today. SDL is fully additive and opt-in: attach a data_model= that subclasses sdl.Entity and you are using SDL; all existing dict-based data payloads continue to work.
Quick start
Subclass sdl.Entity, mix in the facets that match your entity's semantics, and pass the model class to data_model=. Return an instance of it inside ActionResult.success().
from imperal_sdk import sdl
from imperal_sdk.chat import ChatExtension, ActionResult
chat = ChatExtension(...)
class Task(sdl.Entity, sdl.Schedulable, sdl.Prioritized, sdl.Progress):
estimate_s: int | None = None
@chat.function(
"get_task",
description="Open a task by ID.",
action_type="read",
data_model=Task,
)
async def get_task(ctx, params) -> ActionResult:
return ActionResult.success(
Task(id=7, title="Ship SDL", priority="high", progress=0.5),
summary="Task loaded.",
)The data_model=Task declaration makes the entity's shape visible to the platform and to downstream chain steps — without any changes to how you write the handler body.
Core types
sdl.Entity
The canonical base class. Every SDL entity is a Pydantic model that inherits from sdl.Entity.
Required fields:
| Field | Type | Notes |
|---|---|---|
id | str | int | Stable identifier for this entity. |
title | str | Human-readable name shown in the platform. |
kind | str | Semantic type label. Defaults to the subclass class-name lowercased. class Project(sdl.Entity) → kind "project". |
Optional display fields:
| Field | Type | Notes |
|---|---|---|
subtitle | str | None | Secondary display line (e.g. category, assignee name). |
description | str | None | Longer plain-text description. |
status | str | None | Human-readable status label. |
url | str | None | Deep-link URL into the source application. |
sdl.Entity carries an x-sdl: "entity" schema marker. The platform uses this marker to detect SDL results — you do not need to set it manually.
Subclass sdl.Entity and add your own extension-specific fields alongside any standard facet mixins:
from imperal_sdk import sdl
class Project(sdl.Entity):
repo_url: str | None = None
default_branch: str = "main"
class ProjectWithTiming(sdl.Entity, sdl.Timestamped, sdl.Schedulable):
repo_url: str | None = Nonesdl.Ref
A lightweight reference to another entity. Use it for relations, list items, and cross-app links where you want to name the target without embedding the full entity.
| Field | Type | Notes |
|---|---|---|
id | str | int | ID of the referenced entity. |
kind | str | Entity kind of the target (e.g. "project", "user"). |
title | str | Human-readable name. Included so the platform can render the reference without a second call. |
app_id | str | None | App that owns the referenced entity. Defaults to the current app when omitted. |
from imperal_sdk import sdl
class Task(sdl.Entity, sdl.Assignable):
project: sdl.Ref | None = None
task = Task(
id=42,
title="Fix login bug",
assignee=sdl.Ref(id="u_123", kind="user", title="Alex"),
project=sdl.Ref(id="p_7", kind="project", title="Auth Service"),
)sdl.EntityList[T]
A typed list result that wraps a homogeneous list of entities with pagination metadata.
| Field | Type | Notes |
|---|---|---|
items | list[T] | The entities in this page. |
total | int | None | Total count across all pages, if known. |
page | int | None | Current page number (1-based), if applicable. |
has_more | bool | Whether additional pages are available. |
sdl.EntityList carries an x-sdl: "entity-list" schema marker.
When passing to data_model=, use a concrete subclass rather than the raw generic. Pydantic requires a concrete class at the point of instantiation:
from imperal_sdk import sdl
class Project(sdl.Entity):
repo_url: str | None = None
class ProjectList(sdl.EntityList[Project]):
pass
@chat.function(
"list_projects",
description="List all projects.",
action_type="read",
data_model=ProjectList,
)
async def list_projects(ctx, params) -> ActionResult:
rows = await ctx.store.query("projects")
projects = [Project(id=r.id, title=r.data["name"]) for r in rows.data]
return ActionResult.success(
ProjectList(items=projects, total=len(projects), has_more=False),
summary=f"{len(projects)} project(s).",
)Custom roles — sdl.field
For fields not covered by any standard facet, attach a role with sdl.field(role="...").
from imperal_sdk import sdl
class Invoice(sdl.Entity, sdl.Invoiced):
po_number: str | None = sdl.field(role="billing.po_number")
vendor_code: str | None = sdl.field(role="billing.vendor_code")Role format: dotted lowercase — yourapp.something. Use your app ID or a domain you own as the namespace prefix.
Reserved namespaces are owned by the standard facets and must not be used for custom roles:
core · time · people · content · comm · media · quantity · money · catalog · task · geo · net · metric · event · rating · sec · device
For human descriptions on custom fields, use native Pydantic Field(description=...):
from pydantic import Field
from imperal_sdk import sdl
class Shipment(sdl.Entity):
carrier_code: str | None = sdl.field(
role="logistics.carrier_code",
description="IATA carrier code, e.g. 'UPS', 'FEDEX'.",
)Introspection — sdl.roles_of
sdl.roles_of(model) -> dict[str, str]Returns a {field_name: role} map for an Entity subclass or an instance. This is how tooling reads an entity's semantic shape — for example, to discover which fields carry time-family roles or task-family roles before deciding how to render them.
from imperal_sdk import sdl
class Task(sdl.Entity, sdl.Schedulable, sdl.Prioritized):
pass
print(sdl.roles_of(Task))
# {
# "id": "core.id",
# "title": "core.title",
# "kind": "core.kind",
# "start_at": "time.start_at",
# "end_at": "time.end_at",
# "due_at": "time.due_at",
# "all_day": "time.all_day",
# "timezone": "time.timezone",
# "priority": "task.priority",
# "urgency": "task.urgency",
# "severity": "task.severity",
# ...
# }Facet library
All 17 families and 123 facets. All facet fields are optional — every field defaults to None (or [] for list fields). Mix any combination into the same entity without field-name conflicts.
Identity & Provenance (core.*)
Localization, versioning, iconography, and lifecycle state.
Localized
Multi-language metadata.
Fields: language, languages, text_direction, locale, localized_title, localized_description, available_locales
class Article(sdl.Entity, sdl.Localized):
passVersioned
Release and revision tracking.
Fields: version, semver, revision, revision_of, is_latest, content_hash, channel, released_at
Iconified
Visual identity.
Fields: icon, emoji, color_hex, avatar_url
Lifecycle
Soft-delete, pin, favourite, and visibility state.
Fields: is_archived, is_pinned, is_favorite, is_deleted, visibility
Time (time.*)
Timestamps, schedules, durations, recurrence patterns, and booking windows.
Timestamped
Creation and modification times.
Fields: created_at, updated_at, deleted_at
Schedulable
Start/end/due windows and timezone.
Fields: start_at, end_at, due_at, all_day, timezone
Duration
How long something takes.
Fields: duration_s, duration_display_unit
Recurring
Repeating occurrences.
Fields: recurrence_rule, recurrence_until, recurrence_count, is_recurring_master, next_occurrence_at, recurrence_anchor
Booked
Reservation lifecycle.
Fields: booked_at, check_in_at, check_out_at, cancelled_at, cancellation_deadline
People & Identity (people.*)
Associate people, teams, and contact information with an entity.
Authorship
Who created or owns it.
Fields: creator, author, owner, last_editor, editors, contributors
Assignable
Who is responsible for it.
Fields: assignee, assignees, reviewer, reviewers, team, delegated_by, assigned_at
Participants
Group membership and presence.
Fields: members, admins, host, organizer, participant_count, active_now, typing, join_state
Correspondents
Email/message addressing.
Fields: sender, recipients_to, recipients_cc, recipients_bcc, reply_to, recipient_count
ContactPoints
Contact channels.
Fields: emails, phones, social_handles, website_url, preferred_channel
Presence
Real-time availability.
Fields: online_status, status_message, status_emoji, last_seen_at, active_until
Content & Documents (content.*)
Body text, summaries, categories, attachments, and editorial workflow state.
Bodied
Rich body content.
Fields: body, body_format, raw_body
Excerptable
Preview and readability metadata.
Fields: excerpt, summary, word_count, reading_time_s
Categorized
Tags, categories, topics, and labels.
Fields: tags, categories, topics, keywords, labels
Attached
File and image attachments.
Fields: attachments, attachment_count, has_attachments, inline_images
Editorial
Publishing workflow.
Fields: editorial_state, editorial_is_draft, published_at, first_published_at
Communication (comm.*)
Messaging, conversation threads, delivery state, reactions, calls, and drafts.
Conversational
Conversation-level metadata.
Fields: conversation_ref, conversation_type, channel_name, is_group, conversation_participant_count, last_message_at, last_preview
Threaded
Reply chains and nesting.
Fields: thread_ref, reply_to_message, root, depth
MessageState
Delivery and read state.
Fields: direction, is_read, delivery_state, sent_at, edited_at, is_from_me
Reactable
Emoji reactions.
Fields: reactions, reaction_count, my_reactions
Callable
Voice/video call metadata.
Fields: call_direction, call_type, call_state, answered, end_reason, ring_duration_s
Draftable
Draft and scheduled-send state.
Fields: is_draft, scheduled_send_at, last_saved_at, is_auto_generated
Media & Files (media.*)
Files, images, audio/video tracks, archives, content safety scanning, and transcription.
FileObject
Generic file descriptor.
Fields: filename, extension, mime_type, size_bytes, media_class, path, checksum_sha256, permissions
ImageMedia
Image dimensions and metadata.
Fields: width, height, color_space, exif, blurhash
AudioTrack
Audio encoding properties.
Fields: audio_codec, bitrate_kbps, sample_rate_hz, channels, bit_depth, loudness_lufs
VideoTrack
Video encoding properties.
Fields: video_codec, video_resolution, fps, video_bitrate_kbps, hdr
Archive
Compressed archive metadata.
Fields: archive_format, entry_count, uncompressed_size_bytes, compression_ratio, is_encrypted
ContentSafety
Moderation and virus scan results.
Fields: scan_state, is_nsfw, moderation_labels, virus_name, scanned_at
Transcribable
Speech-to-text output.
Fields: transcript, captions_url, transcript_language
Quantities & Units (quantity.*)
Measured values with units, ranges, physical dimensions, and common physical quantities.
Measured
A generic scalar measurement.
Fields: value, unit, dimension, unit_family, value_type, uncertainty, formatted_value
Range
A bounded numeric range with optional target.
Fields: min_value, max_value, target
Dimensions3D
Physical width/height/depth.
Fields: dim_width, dim_height, dim_depth, dim_unit
Area
Surface area.
Fields: area_m2, area_unit
Angle
Angular measurement.
Fields: angle_deg, angle_unit
Bitrate
Data transfer rate.
Fields: bitrate_bps, bitrate_unit
DataSize
Storage size in bytes.
Fields: bytes, data_size_unit
Temperature
Temperature reading.
Fields: temp_c, temp_unit
Length
Linear measurement.
Fields: length_m, length_unit
Weight
Mass measurement.
Fields: weight_kg, weight_unit
Speed
Velocity measurement.
Fields: speed_mps, speed_unit
Percentage
A fractional percentage value.
Fields: percent
Money & Commerce (money.*)
Monetary values, pricing, discounts, subscriptions, account balances, and invoices.
Monetary
A simple currency amount.
Fields: amount, currency
Priced
Product pricing with list/compare prices.
Fields: unit_price, list_price, compare_at_price, price_currency, price_includes_tax
Discountable
Sale pricing and discount percentage.
Fields: sale_price, discount_pct, is_on_sale
Subscribable
Subscription billing state and intervals.
Fields: subscription_status, billing_interval, billing_interval_count, current_period_start, current_period_end, trial_end, recurring_amount, cancel_at_period_end
Balanced
Account balance breakdown.
Fields: balance, balance_currency, available_balance, pending_balance, credit_limit
Invoiced
Invoice and payment state.
Fields: invoice_number, total, tax, payment_status, paid_at, invoice_due_at
Catalog, Products & Inventory (catalog.*)
Product catalog entities: brand identity, stock levels, bundles, materials, and compliance.
Branded
Brand and manufacturer identity.
Fields: brand, manufacturer, model_name, model_year, country_of_origin
Inventory
Stock availability.
Fields: in_stock, availability, low_stock_threshold, is_low_stock, backorderable, preorder
Bundle
Product bundle composition.
Fields: is_bundle, bundle_items, bundle_type
ColorMaterial
Visual and material attributes.
Fields: color, material_color_hex, material, pattern, finish
ProductCompliance
Regulatory and age-restriction metadata.
Fields: certifications, hs_code, age_restriction, restricted_regions, requires_prescription
Tasks & Workflow (task.*)
Task management: priority, progress, completion, blockers, dependencies, kanban boards, checklists, workflow states, approvals, and time estimates.
Prioritized
Priority, urgency, and severity levels.
Fields: priority, urgency, severity
Progress
Completion percentage and item counts.
Fields: progress, done_count, total_count
Completable
Done state and resolution.
Fields: is_done, completed_at, completed_by, resolution
Blockable
Blocker state and reason.
Fields: is_blocked, blocked_reason, blocked_since, waiting_on
Dependencies
Upstream and downstream task links.
Fields: blocks, blocked_by, related
Boarded
Kanban board and column placement.
Fields: board, column, swimlane, position
Checklist
Subtask checklists.
Fields: checklist_items, checked_count, checklist_total
WorkflowState
State machine position and transitions.
Fields: state, allowed_transitions, entered_state_at
Approvable
Approval workflow.
Fields: approval_status, approver, decided_at, decision_note
Estimable
Time estimates and actuals.
Fields: estimate_s, spent_s, remaining_s
Location & Geo (geo.*)
Geographic coordinates, postal addresses, administrative regions, bounding boxes, geofences, routing, and named places.
Geolocated
GPS/GNSS coordinates with accuracy.
Fields: lat, lon, altitude_m, accuracy_m, heading_deg, geo_speed_mps, located_at
PostalAddress
Mailing address.
Fields: street, city, postal_code, region, country
AdminRegion
Administrative hierarchy.
Fields: country_code, region_code, county, locality, neighborhood, continent
BoundingBox
Geographic bounding rectangle.
Fields: min_lat, min_lon, max_lat, max_lon
Geofence
Circular geofence with trigger conditions.
Fields: center_lat, center_lon, radius_m, trigger, dwell_s
Routed
Origin/destination routing.
Fields: origin, destination, distance_m, route_duration_s, waypoints
Placed
Named place identity.
Fields: place_name, place_type, plus_code
Tech / Infra / Network / Data (net.*)
Infrastructure entities: network assets, API endpoints, hosts, compute specs, containers, service health, TLS certificates, data records, config settings, and backups.
NetAsset
A DNS/IP network resource.
Fields: domain, ip, port, protocol, record_type
ApiEndpoint
An HTTP API operation.
Fields: method, api_path, operation_id, auth_required, deprecated
HostResource
A named host or cloud resource.
Fields: hostname, resource_id, environment, host_region
ComputeSpec
CPU/memory/disk/GPU capacity.
Fields: vcpus, memory_bytes, disk_bytes, gpu_count, arch
Container
A running container or service.
Fields: container_id, container_name, image, image_digest, runtime, compose_project
ServiceHealth
Health check and uptime.
Fields: health, uptime_s, last_check_at
Certificated
TLS/X.509 certificate metadata.
Fields: cert_issuer, cert_subject, not_after, fingerprint, cert_is_valid
DataRecord
A database row or query result.
Fields: table, row_id, query, schema_ref
ConfigSetting
A configuration key/value pair.
Fields: config_key, config_value, config_value_type, is_secret, config_source, default_value
Backup
A point-in-time backup snapshot.
Fields: snapshot_id, source_resource, taken_at, backup_size_bytes, retain_until, backup_kind, backup_is_verified
Analytics & Metrics (metric.*)
Aggregated metrics, time series points, trends, statistical confidence, thresholds, and multi-dimensional data.
Aggregated
A windowed aggregation.
Fields: aggregation, window_start, window_end, granularity, fill_policy
TimeSeriesPoint
A single time series data point.
Fields: ts_timestamp, ts_value
Trended
Delta and trend direction.
Fields: delta, change_pct, trend, trend_period
Confident
Statistical confidence interval.
Fields: confidence_level, ci_lower, ci_upper, margin_of_error, p_value, is_significant
Threshold
Alert threshold and breach state.
Fields: threshold_target, threshold, breached
Dimensioned
Arbitrary dimension labels for a metric.
Fields: dimensions
Events & Tickets (event.*)
Calendar events, venue capacity, RSVPs, tickets, admission policies, agenda slots, cancellations, and calendar feed integration.
Eventful
Event venue and organizer.
Fields: venue, event_organizer, event_host, event_type
Capacity
Attendee capacity and availability.
Fields: capacity_total, capacity_remaining, registered_count, waitlist_count, is_sold_out
RSVP
A person's RSVP and check-in state.
Fields: rsvp_state, checked_in, is_no_show, check_in_method
Ticketed
Ticket and seat assignment.
Fields: ticket_type, seat, barcode, ticket_price
AdmissionPolicy
Entry requirements.
Fields: min_age, dress_code, requires_id, prohibited_items, doors_open_at
AgendaSlot
A session within an event program.
Fields: parent_event, track, session_type, order_index, speakers
Cancellation
Event or booking cancellation and refund policy.
Fields: is_cancelled, refund_policy, refund_deadline, is_refundable
CalendarFeed
iCal/ICS feed integration.
Fields: ical_uid, ics_url, feed_url, calendar_name, calendar_color
Ratings & Feedback (rating.*)
Star ratings, written reviews, sentiment analysis, and voting.
Rated
Aggregate star/score rating.
Fields: rating, max_score, rating_count, distribution
Reviewed
A written review with verification.
Fields: review_body, is_verified, helpfulness, would_recommend
Sentiment
NLP sentiment classification.
Fields: sentiment, sentiment_score, magnitude
Voted
Upvote/downvote counts.
Fields: upvotes, downvotes, score, my_vote
Security / Legal / Compliance / Audit (sec.*)
Access classification, permissions, audit logs, consent records, compliance controls, attestations, digital signatures, retention policies, alerts, case management, and risk scoring.
AccessLeveled
Data classification and access visibility.
Fields: classification, clearance_required, access_visibility, handling_caveats
Permissioned
RBAC and CRUD permission flags.
Fields: sec_permissions, role, can_read, can_write, can_delete, can_share
Auditable
An audit trail entry.
Fields: actor, action, audit_target, occurred_at, outcome, source_ip, changes
Consented
A data consent record.
Fields: consent_purpose, consent_state, consent_subject, granted_at, legal_basis, consent_proof
Compliant
A compliance control assessment.
Fields: framework, control_id, compliance_status, last_assessed_at, assessed_by
Attested
A verification attestation.
Fields: attestation_type, attestation_result, attested_by, attestation_confidence
Signed
A digital signature.
Fields: signature, signer, algorithm, signature_is_valid, signed_at
Retained
Data retention and legal hold.
Fields: retention_class, sec_retain_until, legal_hold
Alertable
A monitoring alert.
Fields: alert_severity, alert_state, fired_at, resolved_at, rule_name, alert_threshold
Caseable
A legal or support case.
Fields: case_number, case_type, case_stage, opened_at, closed_at, case_resolution, jurisdiction
RiskScored
A risk score and level.
Fields: risk_score, risk_level, risk_factors
Devices / IoT / Sensors / Health (device.*)
IoT devices, sensors, actuators, consumables, fitness activity, body composition, vital signs, biometrics, sleep records, and AI provenance.
DeviceIdentity
Device hardware identity.
Fields: device_id, device_model, device_manufacturer, firmware_version, serial
DeviceState
Battery, signal, and connectivity state.
Fields: online, battery_pct, signal_strength, device_last_seen_at
SensorReading
A sensor measurement.
Fields: sensor_type, sensor_value, sensor_unit, measured_at, quality
ActuatorState
The state of a controllable device.
Fields: on, level_pct, mode, locked, actuator_position, color_temp_k, actuator_color_hex
Consumable
A replaceable consumable (ink, filter, battery).
Fields: consumable_type, remaining_pct, replace_after_at, low
ActivityMetrics
Fitness activity summary.
Fields: steps, activity_distance_m, active_calories_kcal, active_minutes, floors_climbed
BodyComposition
Body measurement snapshot.
Fields: body_weight_kg, bmi, body_fat_pct, muscle_mass_kg, body_measured_at
VitalSign
Clinical vital signs.
Fields: heart_rate_bpm, blood_pressure, spo2_pct, body_temp_c, respiratory_rate
Biometric
A biometric measurement.
Fields: biometric_type, biometric_value, biometric_unit, biometric_measured_at, biometric_context, reference_low, reference_high
SleepRecord
A sleep session.
Fields: sleep_duration_s, sleep_stages, sleep_quality_score, in_bed_at, awake_at
AIProvenance
AI generation metadata.
Fields: generated_by_ai, ai_model, ai_confidence, prompt_ref, reviewed_by_human
@chat.function reference
Every kwarg, every behavior — full surface for the LLM-callable handler decorator, including data_model=.
SDK: API surface
Full ctx API — ctx.store, ctx.http, ctx.cache, ctx.user, and every context accessor.
SDK: validators reference
V1-V24 validators: rule codes, severity levels, checks, and fixes.
@chat.function reference
@chat.function reference — every parameter of the decorator that defines an LLM-callable Webbee tool: action_type, typed params, effects, and chain dispatch.
UI actions reference
UI actions reference — panel actions that trigger handlers and refresh surfaces: ui.Call, ui.Navigate, ui.Send, ui.Open, plus the auto_action prop format.