PHOS Architecture
For the documentation-only audit and proposed source-aware evolution, see Physical intelligence vision and architecture audit. Its spatial and fusion designs remain proposals. The optional MQTT observation provider and explicitly configured, ESPHome Native API integration are implemented with source isolation.
The physical provider interface records the implemented native-provider foundation: provider lifecycle uses the existing Core behavior registry and awaited observations use the existing event bus. ESPHome Native API observations are now mapped and authorized through the same physical-context projection; distributed history, source fusion and spatial public views remain deferred.
High-level model
Repository ownership
- phos — owns the Raspberry Pi runtime, application services, MCP Streamable HTTP server, REST API, Web Admin, Vision and Voice.
- phos-mcp-bridge — is the Node.js
20+ transport adapter between local MCP
stdioand PHOS Streamable HTTP. It reads bearer auth fromPHOS_MCP_TOKEN, performs no identity or permission decisions, and never automatically retriestools/call. - phos-esp32 — owns the companion
phos-hwv1 firmware: ESP32 sensor acquisition and WS2812B physical execution.
System context and implemented boundaries
PHOS is a local runtime that can operate its configured display, local behaviors,
and available sensors without an external model or agent. It also exposes selected
semantic reads and actions through separate adapters. The AI provider interfaces under
robot.ai are not composed into a conversational agent loop by robot.main.
flowchart TD
user[Local user] -->|touch / voice| local[PHOS runtime<br/>robot.main + robot.runtime]
hw[Pi sensors, camera, display] <-->|configured device I/O| local
ctl[External hardware controller] <-->|phos-hw serial JSONL| local
local -->|semantic rendering / LED commands| hw
admin[Web Admin] <-->|authenticated administration| app[PHOS application services]
rest[REST clients] <-->|authenticated API operations| app
mcp[Optional MCP host and client] -.->|Supported tool request| mserver[PHOS MCP adapter]
mserver -->|Resource data, tool results and URI cues| mcp
mserver --> agent[AgentApplicationService]
agent --> app
app --> local
service[Optional external STT / TTS / expression providers] <-->|provider-specific requests| local
model[External AI model / host reasoning] -. decisions remain external .-> mcp
classDef phos fill:#0F4C5C,stroke:#49E7FF,color:#fff
classDef aiAgent fill:#5B21B6,stroke:#C4B5FD,color:#fff
classDef protocol fill:#312E81,stroke:#818CF8,color:#fff
classDef hardware fill:#334155,stroke:#94A3B8,color:#fff
classDef externalService fill:#78350F,stroke:#FBBF24,color:#fff
classDef interface fill:#1E40AF,stroke:#60A5FA,color:#fff
class user,admin,rest interface
class mcp protocol
class model aiAgent
class local,app,mserver,agent phos
class hw,ctl hardware
class service externalService
style model stroke-dasharray: 5 4
style service stroke-dasharray: 5 4
style mcp stroke-dasharray: 5 4
The system context shows supported categories of interaction, not an assertion that every deployment enables every provider. Local sensor/display operations do not require an external AI service; selected STT, TTS, expression-analysis and remote-client paths can. An external model does not receive a GPIO, driver, renderer or firmware interface. PHOS validates and executes only its implemented semantic operations. See How PHOS works for the user-level context and MCP overview for agent-host responsibilities.
Logical software architecture
The following are responsibility groupings across the implementation, not strict
Python layers. The event bus is used for selected in-process state/observation changes;
ordinary service calls remain direct calls. Dependency direction is mixed by design:
composition in robot.runtime constructs concrete providers and services, while
adapters call application services and providers report typed data to runtime-owned
services.
flowchart TD
adapters["Interface adapters<br/>robot.web / robot.mcp / robot.interaction"]
app["Application services<br/>PhosApplicationService / AgentApplicationService"]
lifecycle["Configuration lifecycle<br/>LifecycleService / ConfigRepository"]
runtime["Runtime composition and coordination<br/>build_runtime / PhosRuntime"]
core["Core state, events and local behavior<br/>RobotCore / EventBus / BehaviorEngine"]
semantic["Typed sensor and semantic services<br/>robot.sensors / robot.services / robot.physical"]
vision[Vision pipeline]
voice[Voice and interaction]
ui["UI and output arbitration<br/>FaceState / EyeRenderLoop / SemanticLedService"]
providers["Hardware and external-provider adapters<br/>robot.hardware / robot.vision / robot.voice"]
external["Physical devices and external services"]
adapters --> app
adapters --> lifecycle
app --> runtime
runtime --> core
runtime --> semantic
runtime --> vision
runtime --> voice
runtime --> ui
providers --> semantic
providers --> vision
providers --> voice
semantic -->|typed observations / selected events| core
core -->|FaceState and semantic intent| ui
ui --> providers
providers <--> external
classDef phos fill:#0F4C5C,stroke:#49E7FF,color:#fff
class adapters,app,lifecycle,runtime,core,semantic,vision,voice,ui,providers phos
robot.runtime.build_runtime() is the main composition root: it validates the typed
RuntimeConfig, creates the Core, behavior engine, services and configured providers,
and returns PhosRuntime. robot.main.async_main() adds application-service, MCP,
lifecycle and optional Web Admin ownership around that runtime. The Web Admin server
runs in a separate process/thread boundary and requests parent-owned runtime state
through the lifecycle/application channel.
Application-service boundaries
PhosApplicationService in robot.services.application supplies semantic operations
and read models over a running PhosRuntime; it is not the transport parser or the
only validation/security boundary. REST request parsing and bearer authentication live
in robot.web.api and robot.web.auth; Web Admin session authentication, CSRF,
form parsing and HTML rendering live in robot.web.app and its domain/template code.
MCP protocol registration and request adaptation live in robot.mcp.server; MCP agent
identity authentication and permission checks wrap the shared semantic service through
AgentApplicationService. Voice has its own transcript, intent-resolution and
execution path in robot.interaction; when execution is enabled its CommandExecutor
delegates supported commands through PhosApplicationService.
The shared service does not make all interfaces identical: authentication, permission profiles, input parsing, error mapping and available operations differ by adapter. The Web Admin also has administration operations which are deliberately not MCP actions. See Remote API, MCP reference, Web Administration, and Voice for those contracts.
State and physical-context flow
There is no single persisted runtime-state store. RobotCore owns the explicit
RobotState state machine and event bus; BehaviorEngine owns evolving presentation
intent; sensor services own current typed snapshots and freshness metadata; PhosRuntime
coordinates subsystem lifecycle and aggregates operational status; configuration is
persisted separately by ConfigRepository; semantic agent identity and activity leases
have their own services. FaceState is UI-neutral output intent, while renderer and
display state remain in robot.ui.
Physical providers produce measurements/events that update their typed services. The application service builds semantic physical-context read models from current snapshots and accepted external observations; it does not expose every raw provider reading. Each sensor section reports its own availability and age/freshness. Missing or stale snapshots can have no current value. Presence, attention, observed facial-expression classification and motion are semantic/derived views with different evidence and retention rules. Temporal history is a separate bounded in-memory service, not durable configuration. See Environmental awareness, Motion awareness, Vision, and the physical observation model.
flowchart LR
physical["Pi devices / camera / configured external providers"] --> adapters["Provider adapters"]
adapters --> typed["Typed snapshots and observations"]
typed --> interpretations["Interpretation / freshness / availability"]
interpretations --> state["Core and subsystem-owned state"]
state --> context["SemanticPhysicalContextService"]
context --> app[PhosApplicationService]
app --> interfaces["Authorized REST / MCP / Web read models"]
External action flow: visual expression
For MCP, robot.mcp.server registers and adapts the tool call. Authentication resolves
an agent identity, then AgentApplicationService checks the operation permission and
delegates to PhosApplicationService. The service validates the expression and submits
semantic intent to the runtime/Core and BehaviorEngine; the resulting FaceState is
consumed by EyeRenderLoop on its render cadence. The adapter returns a semantic result
or a sanitized error; it does not wait for a display write. REST has its own route and
auth wrapper but delegates supported semantic actions to the application service; it
does not use MCP's agent permission adapter. Neither path sends drawing or GPIO commands.
sequenceDiagram
participant C as MCP client
participant M as MCP server adapter
participant A as AgentApplicationService
participant P as PhosApplicationService
participant R as PhosRuntime / Core
participant B as BehaviorEngine
participant D as EyeRenderLoop / EyeRenderer / display
C->>M: semantic expression tool request
M->>M: authenticate identity
M->>A: operation and validated arguments
A->>A: authorize CONTROL_EXPRESSION
A->>P: request expression
P->>R: semantic runtime operation
R->>B: update visual intent
P-->>M: operation result or application error
M-->>C: protocol result
Note over B,D: EyeRenderLoop consumes current FaceState asynchronously at render cadence
B-->>D: FaceState read for next frame
Rendering is scheduled independently of request handling; a successful semantic request is not proof of a physical display write. Detailed operation schemas and result semantics belong to the MCP reference and REST API.
Core principles
External Hardware Controller Protocol v1
PHOS defines a hardware-agnostic USB/serial controller boundary in
robot.hardware.controller_protocol; it is not an ESP32 protocol.
Framing and envelope
It uses UTF-8 JSON Lines, one bounded object per newline, with the envelope:
protocol: "phos-hw"version: 1type- Optional
id - Optional
reply_to - Object
payload
Controllers push semantic sensor/motion events and advertise capabilities; PHOS does not poll them.
Inbound messages and sensor mapping
The v1 source currently specifies the payload only where PHOS consumes it. Strict payload validation applies to:
motion_updateorientation_updateset_led_animation
The serial adapter also maps sensor_update values into existing semantic services:
- Temperature (
c). - Pressure (
hpa). - Humidity (
%). - eCO2 (
ppm). - TVOC (
ppb). - The push proof (
{"sensor":"push","event":"pressed"}).
capabilities remains controller-defined metadata; LED output is available only for the
active serial session when that metadata advertises LED support. Other recognized v1
event types are retained as diagnostics but have no Raspberry semantic mapping yet.
Outbound commands
PHOS currently transmits only:
request_capabilitiesping- Resolved
set_led_animationcommands.
The remaining accepted command names are reserved protocol vocabulary, not Web or API controls.
Bounded LED animations
offsolidblinkpulsebreathechasespinwipe
breathe accepts color, brightness, period/duration and min/max intensity.
Controllers execute timing, but never invent PHOS semantics.
Connection and validation boundaries
Heartbeats use reconnectable transports; a stale peer is unhealthy. PHOS treats LED
output as unavailable for that session; any controller-local LED fallback is
firmware-owned. Unknown top-level fields are ignored, while unknown types and versions
receive bounded protocol errors. Sensor events must still enter existing semantic
services and BehaviorEngine ownership. The Raspberry Pi serial adapter is
reconnectable and configured with a manual device path.
Directional LED semantics
Directional LED fields are protocol semantics, not physical LED indexes.
spin— Is circular and defaults to clockwise; it accepts only clockwise or counterclockwise direction.chaseandwipe— Default to circular/clockwise; their circular form accepts clockwise/counterclockwise direction (wipemay also name a top/bottom/left/right origin). Their symmetric form requires an origin plus outward or inward direction.off— Rejects all directional fields.solid— Rejects all directional fields.blink— Rejects all directional fields.pulse— Rejects all directional fields.breathe— Rejects all directional fields.
Top, bottom, left and right are logical positions: each controller implementation owns its physical index mapping and must preserve these v1 defaults for payloads that omit the new optional fields.
Touch input mapping
For the initial inbound proof, a controller pushes sensor_update with
{"sensor":"push","event":"pressed"}. PHOS maps this to its existing completed
touch/tap semantic boundary; it does not poll the controller or add controller-specific
behavior logic.
Controller-backed provider configuration
For controller-backed sensors:
- Set
hardware_controller.enabled: true. - Set the corresponding canonical provider to
controller: sensors.environmental.providersensors.ens160.provider-
sensors.imu.provider -
Retain
enabled: true.
This prevents local I2C workers from starting while controller sensor_update messages
update the same semantic snapshots used by the application services. The controller is a
generic provider, not a hardware vendor identity. The committed default remains local
and does not enable optional controller hardware.
IMU message contracts
Controller IMU telemetry uses two validated v1 messages:
motion_update has exactly:
{
"state": "stationary|moving|tilt_left|tilt_right|tilt_forward|tilt_backward|shake|impact",
"intensity": "low|medium|high"
}
Intensity is semantic movement intensity, never linear velocity.
orientation_update has exactly:
acceleration_m_s2— Vector with finite numericx,y, andzaxes in m/s².angular_velocity_dps— Vector with finite numericx,y, andzaxes in degrees/second.
Both update the existing IMU service; semantic motion and telemetry remain independent snapshot fields.
Transient semantic overlays
SemanticOverlayService owns bounded, source-scoped presentation requests:
successinfoattentionwarningerrorsensor_alert
Each source owns one request; replacement affects only that source. Requests are plain-text (maximum 120 characters), expire on monotonic time, and resolve by priority from highest to lowest as shown below. Equal-priority requests resolve to the newest request.
flowchart LR
error[error] --> warning[warning] --> sensor[sensor_alert]
sensor --> attention[attention] --> success[success] --> info[info]
style error fill:#991B1B,stroke:#F87171,color:#fff
The renderer receives only an immutable visible intent/message view, never caller-supplied drawing details.
The existing interpreted air-quality warning/bad event is the only automatic v1 sensor
source; it requests sensor_alert without inspecting raw providers.
Overlay boundaries and display order
This system is internal to the application-service boundary in v1: it adds no REST
endpoint. It is independent of RobotState, FaceState, environmental markers, and
state effects. The compact semantic card renders after camera preview but before the
final local administrative layer. Recovery and Admin QR overlays therefore remain
secret-bearing system overlays above it, retain their existing touch behavior, and are
not dismissible by semantic requests.
Semantic Physical Context
The physical-context read model combines canonical semantics through the shared application-service boundary:
flowchart TD
n0["Sensors / Vision / RobotState"]
n1["Canonical semantic services"]
n2["Semantic Physical Context"]
n3["PhosApplicationService"]
n4["Agent / MCP / REST adapters"]
n0 --> n1 --> n2 --> n3 --> n4
classDef phos fill:#0F4C5C,stroke:#49E7FF,color:#fff
class n1,n2,n3,n4 phos
SemanticPhysicalContext is a read-only, build-on-read perception model. It combines
canonical robot, environmental, air-quality, motion, presence, attention, and
observed-expression semantics. Each section preserves its own availability and freshness
state, so partial context remains useful. It exposes no provider/device identity, raw
camera data, identity, renderer state, LED state, or controller health. It adds no REST
endpoint or MCP adapter; /api/v1/status remains the broader operational status
contract.
Minimal Agent Permission Model
Agent operations pass through permission checks before application services:
flowchart TD
n0["External agent"]
n1["Agent permission boundary"]
n2["PhosApplicationService"]
n3["Behavior / Voice / Physical Context / Semantic Signals"]
n0 --> n1 --> n2 --> n3
classDef phos fill:#0F4C5C,stroke:#49E7FF,color:#fff
classDef aiAgent fill:#5B21B6,stroke:#C4B5FD,color:#fff
class n0 aiAgent
class n1,n2,n3 phos
AgentApplicationService is a small, provider-independent facade for future trusted
agent adapters. It checks an immutable AgentAccess set before delegating to the
existing PhosApplicationService; it never grants access to providers, renderers,
controller transports, or configuration internals. The canonical operation mapping is:
| Operation | Permission |
|---|---|
status |
READ_STATUS |
get_physical_context |
READ_PHYSICAL_CONTEXT |
presence |
READ_PERCEPTION |
attention |
READ_PERCEPTION |
observed_expression |
READ_PERCEPTION |
set_expression |
CONTROL_EXPRESSION |
speak |
CONTROL_VOICE |
sleep |
CONTROL_SLEEP |
wake |
CONTROL_SLEEP |
signal_user |
SIGNAL_USER |
set_visual_state |
CONTROL_VISUAL_STATE |
State transitions and visual leases
Sleep and wake remain normal state transitions; a signal remains subject to existing semantic LED arbitration.
An agent visual-state request is an identity-scoped, expiring presentation lease, not a
lifecycle transition: only thinking may be acquired and idle releases the caller's
lease. The effective visual state preserves Core priority for error, sleeping, speaking,
and listening, and never mutates RobotCore.state.
This temporary visual-state lease is distinct from the AgentAppearanceActivityTracker
used by the administrator-selected Follow Active Agent skin mode. The latter records
accepted MCP activity for a configured identity, filters candidates by configured
participation and assigned-skin eligibility, then selects the highest configured
priority; ties retain the previous winner when possible and otherwise use a stable
identity ordering. A configured activity timeout expires the lease. Ordinary MCP client
disconnection and credential revocation do not themselves call the tracker's forget();
agent deletion does. Therefore an existing activity lease may continue to select a skin
until timeout after disconnect or revocation. Neither lease grants additional agent
permissions or extends the agent's MCP authentication.
Permission profiles and excluded controls
The in-code standard profile contains that explicit complete v1 set; the observer
profile contains only the three read permissions. Configured agent identities select a
profile through the canonical agent registry. Raw LED animation, renderer internals,
continuous camera-frame access, serial/controller transport, hardware/configuration
mutation, and administrative/recovery controls are intentionally absent from this
facade.
Permission, capability, and authentication
- Permission — Answers whether an identity may request an operation.
- Capability — Answers whether the delegated application service can currently perform it; validation, availability, lifecycle, and arbitration errors still come from that service after a permission check.
- Authentication — Answers who is calling.
MCP resolves one immutable provider-neutral AgentIdentity per inbound request before
constructing the identity-bound facade. Configured bearer credentials select independent
agents; with no credential references, the compatibility path selects the configured
default identity without credential verification. Authentication modes and the
credential lifecycle are documented in the MCP reference. Network access, TLS,
OS permissions, and deployment isolation remain separate concerns.
MCP Semantic Adapter — Stage 1
The MCP adapter delegates through the existing agent and application boundaries:
flowchart TD
n0["MCP client"]
n1["MCP semantic adapter"]
n2["Agent permission boundary"]
n3["PhosApplicationService"]
n4["PHOS runtime / services"]
n0 --> n1 --> n2 --> n3 --> n4
classDef phos fill:#0F4C5C,stroke:#49E7FF,color:#fff
classDef protocol fill:#312E81,stroke:#818CF8,color:#fff
class n0 protocol
class n1,n2,n3,n4 phos
Stage 1 uses the official Python mcp SDK (the bounded 2.x line) over Streamable HTTP.
PHOS owns the listener lifecycle: normal runtime startup creates one listener over the
existing application services, and normal runtime shutdown closes it.
Request/response tools
It exposes seventeen request/response tools.
Status and physical context
phos_get_statusphos_get_physical_contextphos_get_physical_assessment
Perception and camera
phos_get_presencephos_get_attentionphos_get_observed_expressionphos_get_camera_snapshotphos_capture_camera_snapshotphos_get_visible_objects
Expressions, state, speech, and signals
phos_set_expressionphos_speakphos_sleepphos_wakephos_signal_userphos_set_state
Retained physical history
phos_query_measurementsphos_list_physical_transitions
Every one delegates through AgentApplicationService; MCP owns no permissions,
runtime state, provider, or hardware logic.
Client sessions and deployment boundaries
MCP clients connect to the already-running PHOS instance. Client sessions do not create runtimes, application services, or permission boundaries. The default listener is loopback-only; a non-loopback bind requires explicit configuration and emits a warning. PHOS bearer authentication and operation permissions do not replace network restrictions or TLS deployment policy.
This is for trusted local/integrated execution. Configure credential references for distinct bearer-authenticated agents; the credential-free compatibility path is not transport authentication. Do not expose the endpoint on the public Internet. Raw hardware, controller transport, renderer internals, continuous video, audio-device management, configuration, and administrative/recovery controls are absent. Protected on-demand camera snapshots are available through the semantic facade.
Semantic events and resource updates
Stage 2 begins with a transport-neutral semantic event model. The application service projects meaningful interpreted transitions (robot state, environmental and air-quality conditions, motion, presence, attention, and observed expression) into events with stable fields:
typetimestampsourcepayload
It does not emit raw telemetry, provider/device details, or confidence jitter.
Event filtering and status projection
Consumers may request a validated allow-list of stable event types; each subscription
defensively suppresses only adjacent identical semantic events during a short internal
window, so a real transition from A to B and back to A remain visible. The model is an
internal observer boundary—not the Core event bus and not an MCP feature. It projects
canonical agent-status availability as one compact capability_changed event per
changed capability, and canonical degraded state as system_health_changed. The first
ready-status snapshot establishes a baseline and emits neither startup availability nor
health events; later comparisons use the same availability/degraded projection as
phos_get_status, with health reasons sorted before comparison.
Subscription ownership and cleanup
Each observer owns an explicit SemanticSubscription handle with an opaque
process-local identifier, active state, idempotent close(), and optional
context-manager cleanup. The publisher holds the handler strongly only while the handle
is active; explicit close is the required ownership boundary. A dispatch snapshot
already in progress may complete when a handle is closed, but no later delivery starts
after close() returns.
MCP notification delivery
The MCP adapter may consume this model through its bounded McpSemanticEventBridge:
standard MCP subscriptions/listen clients receive URI-only
notifications/resources/updated cues and re-read the relevant Resource. This remains
separate from the Core event bus; REST/WebSocket delivery and an optional future MCP
Events webhook adapter are not Core responsibilities. Camera resources remain excluded
from semantic push cues.
Agent status projection
phos_get_status is intentionally narrower than /api/v1/status. Its agent status
document contains only:
runningstate- Semantic subsystem
availability. degradeddegraded_reasons
It contains no sensor or perception values (those belong to physical context),
provider/device/model details, controller session data, LED animation resolution,
display state, or administrative diagnostics. The projection is owned by
AgentApplicationService, not the MCP adapter, so future trusted agent adapters share
the same contract.
1. Separation of concerns
Core coordinates lifecycle, state, events and behavior. Subsystems implement capabilities.
2. Hardware abstraction
Business logic depends on interfaces, not GPIO/device-specific code. Ordinary unit tests must not require physical hardware.
3. Events where they reduce coupling
Use events for meaningful asynchronous state changes such as speech recognition, robot-state changes or stable Vision observations. Do not create an event merely to avoid a normal function call.
4. Explicit robot state
The existing state model includes IDLE, LISTENING, THINKING, SPEAKING,
SLEEPING and ERROR. Keep transitions explicit and testable.
5. Incremental verification
PHOS is developed through runnable vertical milestones. Existing code may be ahead of the current verified milestone, but new work should prove one capability before expanding the next major subsystem.
Visual / behavior path
The visual path separates observation, behavior, rendering, and display composition:
flowchart TD
camera[Camera] --> vision[Vision] --> events[Stable observations and events]
events --> core[Robot Core] --> behavior[BehaviorEngine] --> face[FaceState]
face --> renderer[EyeRenderer] --> display[EyeDisplay composition]
vision --> preview[Latest preview snapshot] --> runtime[PhosRuntime] --> display
style behavior fill:#0F4C5C,stroke:#49E7FF,color:#fff
- Vision — Observes.
- Behavior — Interprets observations in the context of PHOS's own
RobotState. EyeRenderer— Consumes onlyFaceStateand handles rendering/animation details.- Display adapter — May compose an optional local diagnostic preview from a
UI-neutral snapshot supplied by
PhosRuntime; it never accesses camera or Vision providers.
The face-rendering frequency is independent from Vision timing so the display can remain smooth while detection/inference runs at a lower rate.
BehaviorEngine currently lives under src/robot/core/, because behavior is part of
Core orchestration in the checked-out implementation.
Visual reaction semantics
Vision classifies an uncertain visible facial expression, not a person's internal
emotional state. BehaviorEngine gives PHOS its own response and produces the
UI-neutral FaceState; Vision never selects renderer geometry or colors directly.
| Stable visible-expression observation | PHOS behavior | FaceExpression |
VisualAccent |
|---|---|---|---|
| neutral | calm acknowledgement | neutral | neutral |
| happiness / happy | warm, friendly response | happy | warm |
| surprise / surprised | alert, open response | surprised | alert |
| unknown (including rejected/negative FER classes) | preserve and decay to baseline | unchanged, then neutral | unchanged, then neutral |
Vision publishes semantic evidence, not individual negative FER labels. UNKNOWN is an
explicit absence of accepted evidence. It is distinct from a positively confirmed
neutral observation; current uncalibrated models abstain on neutral. See
docs/vision.md for thresholds and temporal rules.
Face intent and renderer mapping
FaceState carries these independently:
- Expression.
- Semantic
VisualAccent. reaction_strength.
Its optional signed eye_asymmetry is provider-neutral visual intent:
- Positive — Opens the left eye by that amount and closes the right by the same amount.
- Negative — Mirrors it.
- Zero — Requests equal eyes.
- Absent — The renderer uses the expression profile's ordinary shape.
The renderer maps accents to its own color palette:
| Accent | Color |
|---|---|
| Neutral | Light cyan/white |
| Warm | Turquoise |
| Curious | Cyan/blue |
| Alert | Amber |
| Sleepy | Muted violet |
| Error | Red |
Strength blends the neutral and accent colors, as well as the existing eye-shape profile.
Eye, pupil, and background color transitions interpolate at render cadence rather than jumping at Vision inference cadence.
Environmental overlays
Environmental interpretation also supplies independent, confirmed temperature and
air-quality overlay intents on FaceState. They are composable renderer inputs only:
the single priority-selected EnvironmentalState remains the contract for existing eye
and LED behavior, while the display can show, for example, both a warm-temperature
marker and an air-quality haze without reinterpreting sensor readings or thresholds.
Robot-state priority and reaction timing
Robot state remains higher priority than Vision:
- Listening/thinking — Use a curious accent.
- Speaking — Uses warm.
- Sleeping — Uses sleepy.
- Error — Uses red.
Expression reaction timing
-
Happy reactions — Refresh only from confirmed observations and decay smoothly back to neutral when evidence stops.
-
Surprise — Is temporary, cannot refresh from a sustained pose, and needs confirmed alternative evidence plus a cooldown to rearm.
-
UNKNOWN — Allows normal decay.
-
Face tracking and blink timing — Remain independent from expression inference.
VisualAccent is provider-neutral visual intent for the face. The WS2812B ring in the
PHOS hardware build connects to the ESP32; its output uses the semantic controller path
below rather than a per-pixel renderer feed.
flowchart LR
behavior[BehaviorEngine] --> face[FaceState] --> eyes[EyeRenderer] --> display[Display]
intent[Robot state / environment / user signal] --> arbiter[SemanticLedService]
arbiter --> controller[ControllerService]
controller -->|phos-hw v1 serial JSONL| esp[ESP32 controller]
esp --> ring[WS2812B ring]
classDef phos fill:#0F4C5C,stroke:#49E7FF,color:#fff
classDef hardware fill:#334155,stroke:#94A3B8,color:#fff
classDef interface fill:#1E40AF,stroke:#60A5FA,color:#fff
class behavior,face,eyes,arbiter,controller phos
class display interface
class esp,ring hardware
External-controller semantic LED arbitration
External controller LEDs use a separate semantic path: SemanticLedService owns
source-scoped requests, priority arbitration, expiry, and command deduplication; the
controller executes only the resolved realtime animation. The intent sources are:
RobotState— Contributes one persistent intent.- Environmental context — Contributes a lower-priority ambient intent.
signal_user— Contributes the bounded semantic signals:successwarningerrorattention
Transient signals and persistent errors
All user signals, including signal_user("error"), are transient. In contrast,
RobotState.ERROR contributes the persistent robot_state/error intent until the robot
state changes. Error wins over warning, transient user signals, robot-state intents, and
ambient context.
Animation ownership and capability changes
Neither BehaviorEngine, Web/API adapters, nor firmware choose animation parameters. On
a controller capability report the arbiter reapplies its current winner; when LED
capability is absent it retains logical intent and emits no hardware command.
flowchart LR
n0["RobotState / environment / signal_user"]
n1["SemanticLedService"]
n2["ControllerService"]
n3["ESP32 controller LED executor"]
n4["WS2812B ring"]
n0 --> n1 --> n2 --> n3 --> n4
classDef phos fill:#0F4C5C,stroke:#49E7FF,color:#fff
classDef hardware fill:#334155,stroke:#94A3B8,color:#fff
class n0,n1,n2 phos
class n3,n4 hardware
Runtime
The process entry point is robot.main.main(). It parses the selected YAML path and
deprecated compatibility overrides, loads and validates the canonical RuntimeConfig,
configures logging, creates the optional WebServer (which owns LifecycleService),
then runs async_main() with asyncio.run(). async_main() composes the runtime,
application services and—when enabled and configured—the MCP manager. It registers
runtime/lifecycle callbacks before starting the runtime. The MCP server is started from
the runtime-started callback, after the runtime event loop is available.
build_runtime() validates settings and paths, creates Core, BehaviorEngine,
provider-neutral sensor services, configured hardware and optional subsystem adapters,
and the display/render loop. It constructs but does not start those runtime components.
PhosRuntime.start() starts Core (which starts registered behaviors, including the
render loop and runtime-owned behaviors), then sensor services and optional controller
outputs, followed by Vision when configured and available. It records optional component
readiness as ready or unavailable. Some provider factories (for example STT/TTS) catch
initialization failures and expose an unavailable status; failures escaping required
runtime startup are recorded as failure, move Core to ERROR where possible, trigger
cleanup and propagate.
sequenceDiagram
participant E as robot.main.main
participant C as ConfigRepository / RuntimeConfig
participant W as WebServer / LifecycleService
participant R as build_runtime / PhosRuntime
participant K as RobotCore / behaviors
participant O as optional services and providers
participant M as MCP manager
E->>C: load YAML, validate settings and paths
E->>W: start isolated Web Admin worker
E->>R: asyncio.run(async_main)
R->>K: construct Core and behavior graph
R->>O: construct enabled adapters and services
R->>K: start Core and registered behaviors
R->>O: start sensor, controller, and configured Vision components
R-->>M: runtime-started callback
M->>M: attach to runtime loop and serve if enabled
E->>R: stop signal / supervised failure
R->>O: cancel tasks and stop services/providers
R->>K: stop Core and behaviors
E->>W: stop Web Admin worker
PhosRuntime.run() supervises the required BehaviorEngine and eye-render tasks and the
Vision supervisor when a pipeline exists. A normal stop request cancels supervisor
waits and calls stop(). A supervised task that exits unexpectedly transitions Core to
ERROR and then shuts down. stop() retires external providers, cancels owned tasks,
stops services and Vision, stops Core/behaviors, closes ephemeral leases and unsubscribes
events. Startup cleanup is also attempted after exceptions. Web Admin and MCP have
their own lifecycle managers coordinated by main; they are not display-loop tasks.
The main async runtime is not one blocking loop: Vision, rendering, service freshness,
MCP serving, and selected speech/preview work use asyncio tasks. Some hardware services
use worker threads, MCP/Web Admin span server/process boundaries, speech synthesis and
playback use asyncio.to_thread, and agent presentation expiry uses timers. This is not
a hard real-time or universal thread-safety guarantee. Individual components define
their own locks, queues, cancellation and cleanup behavior.
AI interfaces and implemented agent adapters
robot.ai.provider.LLMProvider, message/tool models, RobotAgent and provider adapter
classes exist in source, but robot.runtime.build_runtime() and robot.main.async_main()
do not construct a conversational RobotAgent or call an LLM provider. The source
therefore contains reusable AI abstractions and provider scaffolding, not an integrated
general-purpose model reasoning loop. External AI hosts decide their own workflow and
invoke PHOS through the authenticated MCP boundary; the configured MCP identity and
permission services are separate from robot.ai.
The OpenAI, Anthropic and local adapter modules should not be read as proof of currently
configured production model access. The AI strategy identifies conversational
composition and model policy as proposed/future work. This distinction also applies to
the presence of modules under robot.ai: repository presence alone does not establish
runtime activation.
Voice architecture
The voice path separates capture, transcription, intent resolution, authorization, and application execution:
flowchart TD
n0["USB microphone"]
n1["AudioCaptureProvider<br/>Native device rate"]
n2["ResamplingAudioCaptureProvider"]
n3["PCM16 mono, 16 kHz"]
n4["VAD"]
n5["Bounded pre-roll"]
n6["VoiceCaptureSession"]
n7["STTProvider"]
n8["TranscriptResult"]
n9["InteractionInput"]
n10["IntentResolver"]
n11["ResolvedIntent or UnresolvedIntent"]
n12["CommandRouter"]
n13["Semantic command route"]
n14["Explicit source-aware authorization"]
n15["CommandExecutor"]
n16["PhosApplicationService"]
n17["InteractionOutcome"]
n18["InteractionResponseRenderer"]
n19["InteractionResponse"]
n0 --> n1 --> n2 --> n3 --> n4 --> n5 --> n6 --> n7 --> n8 --> n9 --> n10 --> n11 --> n12 --> n13 --> n14 --> n15 --> n16 --> n17 --> n18 --> n19
style n0 fill:#334155,stroke:#94A3B8,color:#fff
Capture and processing rates
Capture rate and processing rate are deliberately separate. Raspberry Pi 3 validation uses a USB microphone at 44.1 kHz, followed by the one canonical resampling boundary to the 16 kHz stream consumed by VAD and STT; microphones need not support 16 kHz natively.
The current explicit capture session stops at transcription:
stateDiagram-v2
IDLE --> LISTENING
LISTENING --> THINKING
THINKING --> IDLE
VAD baseline and pre-roll
VAD confirmation takes time, so its bounded 300 ms pre-roll preserves audio preceding speech-start confirmation. The validated baseline is:
| Parameter | Baseline value |
|---|---|
| Threshold | 50 |
| Speech start | 120 ms |
| Silence end | 700 ms |
| Minimum utterance | 300 ms |
| Maximum utterance | 12000 ms |
| Pre-roll | 300 ms |
These are validated baseline values, not universal calibration values.
Transcription providers
STTProvider keeps transcription provider-neutral; VoskSTTProvider is the first
local/offline implementation, not PHOS's architectural identity. The small English Vosk
model validates the local architecture but can have limited accuracy for longer phrases
and non-native English accents.
Intent resolution, routing, and execution
Voice input publishes status/events and uses centralized runtime state transitions. It
does not control GPIO, renderers, LEDs, or BehaviorEngine.
-
robot.interaction— Provides plainTranscriptResult,InteractionInput, and canonical resolved/unresolved intent contracts. -
Async
IntentResolver— Its boundary interprets language only; it has no runtime/hardware access and does not route or execute commands. -
Selectable deterministic resolver — Has a small exact English/Italian catalog for state, expression, temperature, pressure, and air-quality commands; see Voice Commands for the user-facing accepted phrases.
-
Main runtime — When interaction is enabled, observes completed voice transcripts and publishes resolution events/status.
-
CommandRouter— Separately validates a resolved canonical intent and maps it to a semantic command. -
Voice execution — Is opt-in through
interaction.execution_enabled(false by default): the coordinator creates a voice-scoped allowlist, thenCommandExecutorinvokes sleep, wake, expression, and authorized sensor commands throughPhosApplicationService.
Query outcomes and spoken responses
Sensor queries reuse that service's read models and produce an InteractionOutcome with
canonical numeric fields; unavailable snapshots are normal outcomes.
The pure local InteractionResponseRenderer produces deterministic English or Italian
user-facing text from query outcomes.
With interaction.response_tts_enabled (false by default), query responses pass through
the application speech boundary and the existing synthesis/playback path:
flowchart LR
synthesis[TTSProvider] --> playback[AudioOutputProvider]
style synthesis fill:#0F4C5C,stroke:#49E7FF,color:#fff
This includes SPEAKING; actions and unresolved input remain silent.
The current provider-neutral TTS contract accepts text only, so response language is retained as interaction metadata rather than passed as a provider-specific argument.
TTS adapters are implemented for:
- Local Piper.
- Cartesia.
- ElevenLabs.
Deterministic phrase resolution and command routing/execution are implemented through the local interaction path, with execution opt-in. Conversational LLM integration, wake words, continuous listening, and Home Assistant remain future work.
Physical voice validation
Physical validation on Raspberry Pi 3 with a USB microphone confirmed native capture,
resampling from 44.1 kHz to 16 kHz, VAD, preserved speech onset through pre-roll, local
Vosk transcription, and return to IDLE.
Vision architecture
Vision keeps capture, detection, expression classification, and smoothing separate:
flowchart TD
n0["Picamera2CameraProvider"]
n1["FaceDetector"]
n2["ExpressionProvider"]
n3["ExpressionSmoother"]
n4["Provider-neutral Vision result / event"]
n0 --> n1 --> n2 --> n3 --> n4
style n0 fill:#0F4C5C,stroke:#49E7FF,color:#fff
Use lightweight processing appropriate for Raspberry Pi 3. Expression classification describes uncertain visible facial-expression patterns, not a person's true mental/emotional state. No identity recognition or frame persistence by default.
Home Assistant relationship
Home Assistant integration is deferred; PHOS does not currently implement a native Home Assistant integration or expose its actions as robot tools. An external host may connect to PHOS through the documented authenticated APIs, but that is not a PHOS-to-Home-Assistant integration. Any future integration must use PHOS application services and explicit authorization; protocol extensibility alone does not establish a supported feature.
Local/cloud expression boundary
Local and optional cloud providers share the expression-smoothing and behavior path:
flowchart LR
camera[Camera] --> crop[Local detector / selector / square crop]
crop --> provider[ExpressionProvider]
provider --> local[OpenCVExpressionProvider]
provider --> cloud[Optional AWSExpressionProvider]
local --> smoother[ExpressionSmoother]
cloud --> smoother
smoother --> events[Vision events] --> behavior[BehaviorEngine] --> face[FaceState]
style provider fill:#0F4C5C,stroke:#49E7FF,color:#fff
Provider execution and observation provenance
AWS SDK objects remain in its adapter. Cloud requests use a single background asyncio
task plus to_thread, independent of capture/tracking/render cadence. Provider
lifecycle invalidation discards evidence across tracking discontinuity. Cached
ExpressionObservation.sampled_at preserves provenance so reads cannot manufacture
temporal confirmation. Local observations retain their existing cadence and semantics.
See Vision.
Canonical configuration and secrets
config/phos.yaml is the sole supported source of normal runtime settings.
-
The provider-neutral
robot.configmodule validates its required sections and maps them toRuntimeConfigandCloudExpressionConfig, with no hardware, SDK or argparse dependencies. -
The runtime passes only relevant typed values to each subsystem.
-
Startup validates before constructing any camera/display components; paths are relative to the configuration file.
-
Existing constructor fallback values are not consulted by application composition.
The same file/dict validation, serialization and atomic persistence must be used by the optional web configuration interface. Credentials are never fields in application settings.
SecretsService keeps runtime-only provider credentials in an authenticated encrypted
local store; its web facade reports slot status and permits replacement/removal but
deliberately cannot read values.
New ordinary settings must extend this central model/file, not standalone CLI arguments.
Existing CLI settings are deprecated explicit overrides during migration.
Reload, live activation, and restart
- Reload through the lifecycle service — Logging level, display iris appearance, and camera-preview settings.
- Runtime-aware live activation and persistence — Supported Voice & Speech STT/TTS/audio changes.
- Restart — Other subsystem changes require restart. See configuration reference.
Administration adapter
robot.web wraps the canonical configuration service with structured settings forms and
an advanced YAML editor, both backed by the same ConfigRepository.
- Credentials page — Uses the write-only
WebSecretsServicefacade, neverSecretsService.get_secret, so secrets cannot enter page rendering or an administrative response.
Provider integration remains separate from this storage foundation.
Web worker and authentication boundaries
Waitress runs in a separate process owned by the main startup lifecycle, independent of rendering/Vision. It receives startup settings for a saved-versus-startup comparison; runtime-backed pages request semantic status through the bounded application/lifecycle channel rather than reading subsystem internals directly.
Its password-storage service is separate from runtime JSON; Flask sessions and Flask-WTF protect administration actions. Core, providers and the renderer have no web-framework dependency. See the web manual.
Settings domains and persistence
Administration domains select canonical field paths for presentation only. Each page merges its submitted fields into the complete document and calls the same validation/persistence boundary. System / Status is read-only; password changes use the separate credential service. See the manual for the domain-to-field map.
Shared application services for control surfaces
Web, future remote API, MCP and Voice are adapters around PHOS application services. They reuse the same validation, authorization, configuration and behavior-command services; they must not reach into GPIO, hardware adapters, provider objects, renderer state or other subsystem internals. Add an application service when an approved capability needs one, rather than duplicating behavior in each surface.
The configuration, Remote API, supported Voice & Speech, and MCP semantic application services are implemented examples.
Application lifecycle boundary
robot.lifecycle.LifecycleService owns the active-configuration snapshot and
allowed operations:
- Status — Allowed status operation.
- Reload — Validates the full canonical file before applying logging level, iris appearance, and camera preview through their application-service boundaries.
- Restart — Allowed restart operation.
Supported Voice & Speech changes use a separate candidate-activation/persistence transaction; other changes remain pending.
The parent process serves a bounded local process channel to the web worker; adapters cannot submit shell commands, paths or arbitrary configuration payloads. Future API/MCP surfaces must use the same policy service.
Restart ownership and failure recovery
The supplied user systemd service owns process replacement. A confirmed restart follows this sequence:
- Request graceful runtime shutdown and exit code 75.
- systemd restarts the same entry point.
The web adapter neither runs OS commands nor spawns replacements. Runtime subsystem and web-worker failures propagate as nonzero process exits for systemd recovery.
Preview reload and runtime status
Preview reload is acknowledged after camera start/stop acceptance; failed starts release partially acquired camera resources, and shutdown drains preview tasks and supervisor waiters. Manual launches reject browser restart. OS reboot and general remote control remain out of scope. See installation for display-session environment and service permissions. Status distinguishes configured values from runtime active/availability state where that snapshot is available; it does not invent a health-monitoring layer.
Eye appearance
The dedicated Skin Architecture explains catalog loading, active-agent selection, and the shared appearance lifecycle. See the Skins reference for supported presentation fields.
- Display & Appearance configuration — Supplies the validated canonical iris
color to
EyeRendererat startup. EyeRenderer— Still consumes onlyFaceStateand renderer style configuration; expression/provider labels never reach the renderer.- Semantic visual accents — Continue to pass through
BehaviorEngineandFaceState. - Tk — Draws layered eye-body, iris, pupil and highlight primitives without a raster-processing pipeline.
- Live iris appearance — Can be applied through the configuration lifecycle and render-loop queue; display geometry/backend changes still require PHOS restart.
Environmental sensor service
The separately approved BME280/BMP280 addition follows:
flowchart TD
n0["BME280 / BMP280"]
n1["Selected hardware provider"]
n2["EnvironmentalSensorService"]
n3["PhosRuntime.sensor_status"]
n4["LifecycleService status snapshot"]
n5["Existing local process channel"]
n6["Authenticated Web Admin Sensors"]
n0 --> n1 --> n2 --> n3 --> n4 --> n5 --> n6
style n0 fill:#334155,stroke:#94A3B8,color:#fff
-
robot.sensors— Owns the provider-neutral contract, immutable measurements and latest-state service. -
robot.hardwareadapters — Alone know the SMBus/driver APIs. -
hardware.environmental.environmental_provider_type— Centralizes selection and capabilities.
Measurement contracts and interpretation
Both return EnvironmentalReading with temperature/pressure and nullable
humidity_percent; BMP280 must return null, BME280 must supply humidity. The service
validates that invariant using declared available measurements.
The runtime constructs and starts/stops the service and passes only its typed, fresh
snapshots to EnvironmentalInterpreter.
The interpreter publishes confirmed semantic state and independent overlay intents to
BehaviorEngine; raw readings never reach EyeRenderer, LEDRingController or Vision.
Future compatible environmental providers reuse this boundary; other kinds of sensors need their own typed measurements rather than forcing them into temperature/humidity/pressure fields.
Worker lifecycle and freshness
One daemon worker serializes all provider calls; disabled means no worker, provider construction, vendor imports or I2C open. It retries initialization after failures, retains no history and exposes only finite valid current measurements.
Snapshot metadata includes:
- Active sensor type.
- Available measurements.
- Availability/status.
- UTC last success.
- Monotonic age.
- Sanitized error type.
Failed or stale snapshots contain no current values.
A blocked native call cannot stop the render loop or grow a work queue; stop signals the worker and awaits at most one second.
The owner closes the bus when I/O returns; process exit releases it if stuck. No concurrent bus close is used.
Configuration and administration access
All settings are restart-only under existing lifecycle classification. Save and Reload do not restart any subsystem. Only an explicitly requested PHOS restart reinitializes hardware.
The Sensors page reads in-memory state via shared services, never imports a driver or infers availability from saved enabled/address values. The existing authenticated process channel carries the snapshot; no new API or IPC operation is exposed. See ADR-022, hardware and configuration migration.
Controller-backed ENS160 and AHT21
Controller telemetry enters the shared status and interpretation services:
flowchart LR
esp[ESP32 telemetry] --> controller[ControllerService]
controller --> callbacks[Runtime lifecycle callbacks] --> air[AirQualitySensorService]
air --> status[Runtime / application status] --> clients[WebUI / MCP]
style air fill:#0F4C5C,stroke:#49E7FF,color:#fff
The controller acquires measurements and publishes phos-hw v1 records; Pi services own freshness, validity, controller-generation isolation and environmental interpretation. ENS160 provides estimated eCO2, TVOC and AQI-UBA; AHT21 temperature and humidity are independently fresh. Retiring a session immediately makes controller readings unusable until fresh telemetry arrives.
MPU-6050 IMU extension
The IMU provider feeds the existing sensor-service and runtime status boundary:
flowchart LR
provider[hardware.MPU6050Provider] --> service[IMUSensorService]
service --> status[PhosRuntime.sensor_status]
style service fill:#0F4C5C,stroke:#49E7FF,color:#fff
This path uses the same worker, freshness, retry and authenticated status boundary as the other sensors.
-
IMUReadingholds acceleration X/Y/Z in m/s² and angular velocity X/Y/Z in °/s. -
The hardware adapter alone knows MPU-6050 registers and smbus2; Web Admin only reads snapshots and edits canonical
sensors.imusettings. -
No
BehaviorEngine,EyeRendereror Vision component receives IMU readings.
The adapter applies fixed ±2 g / ±250 °/s scale factors only; offset calibration, fusion and orientation are outside this capability.
Motion interpretation extension
Motion interpretation converts readings into provider-neutral semantic observations:
flowchart LR
reading[IMUReading] --> interpreter[MotionInterpreter] --> motion[MotionState / MotionEvent]
style interpreter fill:#0F4C5C,stroke:#49E7FF,color:#fff
Motion interpretation is a pure, provider-neutral layer between IMU state and its
semantic consumers. It never accesses the MPU-6050, GPIO, Web handlers, Vision,
EyeRenderer or BehaviorEngine. The IMU worker supplies timestamped samples and
exposes only the current interpreted state and last event through the existing status
boundary. STILL, MOVING, four tilt directions, SHAKE and IMPACT are semantic
observations consumed by BehaviorEngine through the event bus.
Motion settings reload into the interpreter without reopening the I2C provider.
IMU visual behavior extension
The IMU service publishes stable semantic state changes to Core's local event bus.
BehaviorEngine consumes them and overlays visual intent onto FaceState; the renderer
still receives no IMU object or event.
Motion-specific visual intent
In IDLE:
MOVING— Recenters the pupils, opens the eyes to 1.16 and gives it 0.63 reaction strength.
Tilt reactions move pupils in the corresponding visual direction at 86% of the normalized safe range. All have 0.56 strength and the curious accent.
| Tilt | Eye opening and asymmetry |
|---|---|
| Horizontal | Opening 1.12; mirrored 0.18 signed eye asymmetry. Left tilt opens the left eye and closes the right; right tilt reverses it. |
| Forward | Equal eyes, opening to 1.23. |
| Back | Equal eyes, closing to 0.82. |
SHAKE— Is a 1.18-open, 0.88-strength surprised alert.IMPACT— Is the stronger 1.25-open, 1.0-strength alert.
Both hold for 55% of their configured duration then decay smoothly.
State priority and resumption
ERROR, SLEEPING, LISTENING, THINKING and SPEAKING override IMU intent; motion
then resumes only when Core returns to IDLE. Motion overlays take priority over
lower-priority Vision expression reactions in IDLE, without changing the user-selected
iris theme.
Local Admin Access
NetworkInfoService is parent-process runtime state, not configuration: it selects
the first non-loopback, non-link-local IPv4 address and refreshes its bounded cached
result every 30 seconds.
Web Admin obtains that read model only through RemoteApplicationService and lifecycle.
Physical Admin overlay
The physical Admin overlay is a separate top display layer. It receives only the
effective LAN Admin URL and a cached qrcode matrix; Tk renders individual square
canvas modules, so Pillow and image resampling are unnecessary. A top-right double-tap
20% of the display opens it, and a tap closes it. This never changes FaceState,
RobotState, or BehaviorEngine state.