Behavior library

robot.behavior_library

Reusable behaviors.

A behavior is a short, named routine that drives both the face and the body. The library ships a few ready-made ones (Greeting, Thinking, Listening, Sleeping, Excited) and provides the building blocks (:class:BehaviorStep) so the user can compose their own.

Behaviors

robot.behavior_library.behavior

Behavior primitives.

A :class:Behavior is a recipe: a list of steps to run, where each step is either a face action, a body-language request, or a wait. The runner walks the steps in order (some can be parallel) and returns when the last step is done.

Behaviors are declarative - they describe what to do, not how. The runner decides how to schedule the steps against the face engine and the body-language engine.

__all__ = ['Behavior', 'BehaviorRunner', 'BehaviorStep', 'BodyStep', 'FaceStep', 'WaitStep', 'body', 'excited', 'face', 'greeting', 'listening', 'sleeping', 'surprised', 'thinking', 'wait'] module-attribute

_log = get_logger('behavior_library.behavior') module-attribute

ArmsOpen dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ArmsOpen(_BaseRequest):
    name: str = "arms_open"
    amount: float = 20.0
    duration_s: float = 0.5

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={
                    SERVO_LEFT_ARM: max(MIN, min(MAX, CENTER - self.amount)),
                    SERVO_RIGHT_ARM: max(MIN, min(MAX, CENTER + self.amount)),
                },
                duration_s=self.duration_s,
            )
        ]

amount = 20.0 class-attribute instance-attribute

duration_s = 0.5 class-attribute instance-attribute

name = 'arms_open' class-attribute instance-attribute

__init__(name='arms_open', amount=20.0, duration_s=0.5)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={
                SERVO_LEFT_ARM: max(MIN, min(MAX, CENTER - self.amount)),
                SERVO_RIGHT_ARM: max(MIN, min(MAX, CENTER + self.amount)),
            },
            duration_s=self.duration_s,
        )
    ]

ArmsRelax dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ArmsRelax(_BaseRequest):
    name: str = "arms_relax"
    duration_s: float = 0.5

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={SERVO_LEFT_ARM: CENTER, SERVO_RIGHT_ARM: CENTER},
                duration_s=self.duration_s,
            )
        ]

duration_s = 0.5 class-attribute instance-attribute

name = 'arms_relax' class-attribute instance-attribute

__init__(name='arms_relax', duration_s=0.5)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={SERVO_LEFT_ARM: CENTER, SERVO_RIGHT_ARM: CENTER},
            duration_s=self.duration_s,
        )
    ]

Behavior dataclass

A named sequence of steps.

Source code in src/robot/behavior_library/behavior.py
@dataclass(slots=True, frozen=True)
class Behavior:
    """A named sequence of steps."""

    name: str
    steps: tuple[BehaviorStep, ...] = ()

name instance-attribute

steps = () class-attribute instance-attribute

__init__(name, steps=())

BehaviorRunner

Run :class:Behavior objects against a face + body engine.

Source code in src/robot/behavior_library/behavior.py
class BehaviorRunner:
    """Run :class:`Behavior` objects against a face + body engine."""

    def __init__(
        self,
        face: FaceAnimator,
        body: BodyLanguageEngine,
        clock: Clock,
    ) -> None:
        self.face = face
        self.body = body
        self.clock = clock

    async def run(self, behavior: Behavior) -> None:
        _log.info("behavior.start", name=behavior.name, steps=len(behavior.steps))
        for step in behavior.steps:
            await self._run_step(step)
        _log.info("behavior.done", name=behavior.name)

    async def _run_step(self, step: BehaviorStep) -> None:
        if step.kind == "face" and step.face is not None:
            method = getattr(self.face, step.face.method, None)
            if method is None:
                _log.warning("behavior.unknown_face_method", method=step.face.method)
                return
            await _maybe_await(method(*step.face.args, **step.face.kwargs))
        elif step.kind == "body" and step.body is not None:
            await self.body.perform(step.body.request)
        elif step.kind == "wait" and step.wait is not None:
            await self.clock.sleep(step.wait.seconds)

body = body instance-attribute

clock = clock instance-attribute

face = face instance-attribute

__init__(face, body, clock)

Source code in src/robot/behavior_library/behavior.py
def __init__(
    self,
    face: FaceAnimator,
    body: BodyLanguageEngine,
    clock: Clock,
) -> None:
    self.face = face
    self.body = body
    self.clock = clock

run(behavior) async

Source code in src/robot/behavior_library/behavior.py
async def run(self, behavior: Behavior) -> None:
    _log.info("behavior.start", name=behavior.name, steps=len(behavior.steps))
    for step in behavior.steps:
        await self._run_step(step)
    _log.info("behavior.done", name=behavior.name)

BehaviorStep dataclass

One entry in a behavior's recipe.

A step is one of: * :class:FaceStep - call a method on the :class:FaceAnimator. * :class:BodyStep - perform a :class:BodyRequest on the body. * :class:WaitStep - sleep.

Source code in src/robot/behavior_library/behavior.py
@dataclass(slots=True, frozen=True)
class BehaviorStep:
    """One entry in a behavior's recipe.

    A step is one of:
    * :class:`FaceStep` - call a method on the :class:`FaceAnimator`.
    * :class:`BodyStep` - perform a :class:`BodyRequest` on the body.
    * :class:`WaitStep` - sleep.
    """

    name: str
    kind: str  # "face" | "body" | "wait"
    face: FaceStep | None = None
    body: BodyStep | None = None
    wait: WaitStep | None = None

body = None class-attribute instance-attribute

face = None class-attribute instance-attribute

kind instance-attribute

name instance-attribute

wait = None class-attribute instance-attribute

__init__(name, kind, face=None, body=None, wait=None)

BodyLanguageEngine dataclass

Drive the four servos with high-level body-language requests.

Source code in src/robot/body_language/engine.py
@dataclass(slots=True)
class BodyLanguageEngine:
    """Drive the four servos with high-level body-language requests."""

    servo_controller: ServoController
    clock: Clock
    calibration: dict[str, ServoCalibration] = field(
        default_factory=lambda: dict(DEFAULT_CALIBRATION)
    )

    _current: Pose = field(default_factory=Pose, init=False)
    _busy: bool = field(default=False, init=False)

    def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
        self.calibration = calibration

    def snapshot(self) -> Pose:
        """Current pose - used by the simulation overlay."""
        return self._current

    def apply_hint(self, hint: object) -> Pose:
        """Translate a :class:`BodyLanguageHint` into a Pose (no servo moves)."""
        pose = hint_to_pose(hint)
        self._current = pose
        return pose

    async def perform(self, request: BodyRequest) -> None:
        """Play a request on the servos."""
        if self._busy:
            # Another request is already in flight - log the dropped request
            # so it's visible rather than silently lost.
            _log.warning(
                "body_language.request_dropped", request=getattr(request, "name", "unknown")
            )
            return
        self._busy = True
        try:
            for frame in request.frames():
                await self._play_frame(frame)
        finally:
            self._busy = False

    def perform_sync(self, request: BodyRequest) -> None:
        """Synchronous version (for tests and the simulation CLI)."""
        for frame in request.frames():
            self._play_frame_sync(frame)

    async def play_frames(self, frames: Iterable[ServoFrame]) -> None:
        async for _ in self._aiter_frames(frames):
            pass

    async def _aiter_frames(self, frames: Iterable[ServoFrame]) -> AsyncIterator[None]:
        for frame in frames:
            await self._play_frame(frame)
            yield

    async def _play_frame(self, frame: ServoFrame) -> None:
        if not frame.targets:
            await self.clock.sleep(frame.duration_s)
            return
        # Compute the per-servo interpolation start positions
        start_targets = {name: self._current.get(name, 90.0) for name in frame.targets}
        steps = max(1, int(frame.duration_s * 30))
        step_s = frame.duration_s / steps
        for step in range(1, steps + 1):
            t = step / steps
            eased = t * t * (3.0 - 2.0 * t)
            targets: dict[str, float] = {}
            for name, target in frame.targets.items():
                start = start_targets[name]
                targets[name] = self._calibrate(name, start + (target - start) * eased)
            # Apply every servo in this slice
            await self._apply_targets(targets)
            self._current = Pose(targets={**self._current.targets, **targets})
            await self.clock.sleep(step_s)

    def _play_frame_sync(self, frame: ServoFrame) -> None:
        if not frame.targets:
            return
        # Apply each servo's calibrated target directly (sync mode jumps
        # to the target without interpolation).
        new_targets = dict(self._current.targets)
        for name, target in frame.targets.items():
            calibrated = self._calibrate(name, target)
            new_targets[name] = calibrated
        self._current = Pose(targets=new_targets)

    async def _apply_targets(self, targets: dict[str, float]) -> None:
        for name, angle in targets.items():
            servo = self._get_servo(name)
            if servo is not None:
                with contextlib.suppress(Exception):
                    await servo.move_to(angle, duration_s=0.0)

    def _apply_targets_sync(self, targets: dict[str, float]) -> None:
        for name, angle in targets.items():
            servo = self._get_servo(name)
            if servo is not None:
                # The sync method is used by the simulator CLI and the tests.
                # It updates the snapshot but does not call the async
                # ``servo.move_to`` (that would require a running loop).
                self._current = Pose(
                    targets={**self._current.targets, name: self._calibrate(name, angle)}
                )

    def _get_servo(self, name: str) -> Servo | None:
        try:
            return self.servo_controller.get(name)
        except Exception:
            return None

    def _calibrate(self, name: str, angle: float) -> float:
        cal = self.calibration.get(name)
        if cal is None:
            return max(0.0, min(180.0, angle))
        return cal.clamp(angle)

calibration = field(default_factory=lambda: dict(DEFAULT_CALIBRATION)) class-attribute instance-attribute

clock instance-attribute

servo_controller instance-attribute

__init__(servo_controller, clock, calibration=(lambda: dict(DEFAULT_CALIBRATION))())

apply_hint(hint)

Translate a :class:BodyLanguageHint into a Pose (no servo moves).

Source code in src/robot/body_language/engine.py
def apply_hint(self, hint: object) -> Pose:
    """Translate a :class:`BodyLanguageHint` into a Pose (no servo moves)."""
    pose = hint_to_pose(hint)
    self._current = pose
    return pose

perform(request) async

Play a request on the servos.

Source code in src/robot/body_language/engine.py
async def perform(self, request: BodyRequest) -> None:
    """Play a request on the servos."""
    if self._busy:
        # Another request is already in flight - log the dropped request
        # so it's visible rather than silently lost.
        _log.warning(
            "body_language.request_dropped", request=getattr(request, "name", "unknown")
        )
        return
    self._busy = True
    try:
        for frame in request.frames():
            await self._play_frame(frame)
    finally:
        self._busy = False

perform_sync(request)

Synchronous version (for tests and the simulation CLI).

Source code in src/robot/body_language/engine.py
def perform_sync(self, request: BodyRequest) -> None:
    """Synchronous version (for tests and the simulation CLI)."""
    for frame in request.frames():
        self._play_frame_sync(frame)

play_frames(frames) async

Source code in src/robot/body_language/engine.py
async def play_frames(self, frames: Iterable[ServoFrame]) -> None:
    async for _ in self._aiter_frames(frames):
        pass

set_calibration(calibration)

Source code in src/robot/body_language/engine.py
def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
    self.calibration = calibration

snapshot()

Current pose - used by the simulation overlay.

Source code in src/robot/body_language/engine.py
def snapshot(self) -> Pose:
    """Current pose - used by the simulation overlay."""
    return self._current

BodyRequest

Bases: Protocol

A high-level body-language request.

Source code in src/robot/body_language/requests.py
@runtime_checkable
class BodyRequest(Protocol):
    """A high-level body-language request."""

    @property
    def name(self) -> str: ...

    def frames(self) -> list[ServoFrame]: ...

name property

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]: ...

BodyStep dataclass

A body-language request.

Source code in src/robot/behavior_library/behavior.py
@dataclass(slots=True, frozen=True)
class BodyStep:
    """A body-language request."""

    request: BodyRequest

request instance-attribute

__init__(request)

Clock

Bases: Protocol

Minimal time abstraction.

Source code in src/robot/utils/clock.py
class Clock(Protocol):
    """Minimal time abstraction."""

    def now(self) -> datetime:
        """Return the current wall-clock time (UTC)."""

    def monotonic(self) -> float:
        """Return a strictly monotonic time in seconds."""

    async def sleep(self, seconds: float) -> None:
        """Sleep for the given number of seconds."""

monotonic()

Return a strictly monotonic time in seconds.

Source code in src/robot/utils/clock.py
def monotonic(self) -> float:
    """Return a strictly monotonic time in seconds."""

now()

Return the current wall-clock time (UTC).

Source code in src/robot/utils/clock.py
def now(self) -> datetime:
    """Return the current wall-clock time (UTC)."""

sleep(seconds) async

Sleep for the given number of seconds.

Source code in src/robot/utils/clock.py
async def sleep(self, seconds: float) -> None:
    """Sleep for the given number of seconds."""

FaceAnimator dataclass

Drive a single circular face display at 30 FPS.

Source code in src/robot/face/animator.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
@dataclass(slots=True)
class FaceAnimator:
    """Drive a single circular face display at 30 FPS."""

    DEFAULT_FPS: ClassVar[int] = 30

    renderer: FaceRenderer
    display: Display
    clock: Clock
    emotions: EmotionEngine
    theme: Theme
    fps: int = DEFAULT_FPS
    bus: InMemoryEventBus | None = None
    width: int = 240
    height: int = 240

    _current: FaceModel = field(init=False)
    _target: FaceModel = field(init=False)
    _eye: EyeAnimator = field(init=False)
    _stopped: bool = field(default=True, init=False)
    _frame_count: int = field(default=0, init=False)
    _anim_time: float = field(default=0.0, init=False)
    _timeline: Timeline | None = field(default=None, init=False)
    _timeline_t: float = field(default=0.0, init=False)
    _timeline_total: float = field(default=0.0, init=False)
    _speaking_animation: SpeakingAnimation | None = field(default=None, init=False)
    _thinking_animation: ThinkingDotsAnimation | None = field(default=None, init=False)
    _wake_animation: WakeAnimation | None = field(default=None, init=False)
    _frame_profiler: FrameProfiler | None = field(default=None, init=False, repr=False)

    def __post_init__(self) -> None:
        if self.fps <= 0:
            raise ValueError("fps must be > 0")
        if self.width <= 0 or self.height <= 0:
            raise ValueError("width and height must be > 0")
        self._eye = EyeAnimator(
            side=EyeSide.LEFT,
            width=self.width,
            height=self.height,
            fps=self.fps,
        )
        self._current = self.emotions.build("neutral")
        self._target = self._current
        if self.bus is not None:
            from robot.events.events import (
                BlinkRequested,
                EmotionChanged,
                LookRequested,
            )

            self.bus.subscribe(EmotionChanged, self._on_emotion)
            self.bus.subscribe(BlinkRequested, self._on_blink)
            self.bus.subscribe(LookRequested, self._on_look)

    # ------------------------------------------------------------------ properties
    @property
    def current(self) -> FaceModel:
        return self._current

    @property
    def frame_count(self) -> int:
        return self._frame_count

    @property
    def is_running(self) -> bool:
        return not self._stopped

    # ------------------------------------------------------------------ public commands
    def set_emotion(self, name: str, intensity: float = 1.0) -> None:
        """Animate to the given emotion over ~0.3s.

        Calling this method clears any running speaking and thinking
        animations (they are interruptible).  The wake animation is
        *not* cleared -- it plays to completion.
        """
        # Clear interruptible animations on emotion change.
        self._speaking_animation = None
        self._thinking_animation = None
        target = self.emotions.build(name)
        # Apply intensity: scale the change in openness, mouth, etc.
        self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
        self._target = target

    def blink(self) -> None:
        self._eye.blink()

    def double_blink(self) -> None:
        self._eye.double_blink()

    def wink(self) -> None:
        self._eye.wink()

    def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
        self._eye.look(x, y, duration_s)

    def look_left(self, duration_s: float = 0.25) -> None:
        self._eye.look_left(duration_s)

    def look_right(self, duration_s: float = 0.25) -> None:
        self._eye.look_right(duration_s)

    def look_up(self, duration_s: float = 0.25) -> None:
        self._eye.look_up(duration_s)

    def look_down(self, duration_s: float = 0.25) -> None:
        self._eye.look_down(duration_s)

    def look_center(self, duration_s: float = 0.25) -> None:
        self._eye.look_center(duration_s)

    def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
        self._eye.drift(amplitude=amplitude, speed=speed)

    def bounce(self) -> None:
        """Run a one-shot bounce animation (squash & stretch)."""
        tl = self._build_bounce_timeline()
        self._timeline = tl

    def smile_grow(self) -> None:
        """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
        target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
        self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

    def mouth_open(self, duration_s: float = 0.3) -> None:
        target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
        self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

    def eyebrow_raise(self, amount: float = 0.6) -> None:
        target = self._current.with_eyebrows(
            left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
            right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        )
        self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

    # ------------------------------------------------------------------ animation slots
    def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
        """Set (or clear) the speaking animation that drives mouth shapes."""
        self._speaking_animation = animation

    def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
        """Set (or clear) the thinking animation that drives gaze shifts."""
        self._thinking_animation = animation

    def set_wake_animation(self, animation: WakeAnimation | None) -> None:
        """Set (or clear) the wake animation (highest priority override)."""
        self._wake_animation = animation

    def reset(self) -> None:
        self._current = self.emotions.build("neutral")
        self._target = self._current
        self._timeline = None
        self._speaking_animation = None
        self._thinking_animation = None
        self._wake_animation = None
        self._eye.reset()

    # ------------------------------------------------------------------ bus
    async def _on_emotion(self, event: object) -> None:
        name = getattr(event, "current", None)
        if name is None:
            return
        # The event's ``current`` can be either an ``EmotionName`` enum or
        # a plain string; normalise to a string before looking it up.
        if hasattr(name, "value"):
            name = name.value
        elif not isinstance(name, str):
            return
        self.set_emotion(name)

    async def _on_blink(self, event: object) -> None:
        self.blink()

    async def _on_look(self, event: object) -> None:
        self.look(
            float(getattr(event, "x", 0.0)),
            float(getattr(event, "y", 0.0)),
            duration_s=float(getattr(event, "duration_s", 0.25)),
        )

    # ------------------------------------------------------------------ frame loop
    def step(self, drift: bool = True) -> EyeFrame:
        """Advance one frame and push to the display.

        The rendering pipeline applies overrides in priority order:

        1. Eye drift + blink state (from :class:`EyeAnimator`).
        2. Thinking animation gaze override.
        3. Timeline-based emotion interpolation.
        4. Speaking animation mouth override.
        5. Wake animation full override (highest priority).
        """
        dt = 1.0 / self.fps
        self._frame_count += 1

        if drift:
            self._eye.drift(amplitude=0.10, speed=0.6)
        # Eye state: pull current gaze from the eye animator
        eye_state = self._eye.step()
        # Translate the eye's (gaze, openness) into left/right Eye components
        new_eyes = self._eyes_from_eye_state(eye_state)

        # Thinking animation: override gaze when active.
        if self._thinking_animation is not None:
            gaze = self._thinking_animation.step(dt)
            new_eyes = (
                Eye(
                    gaze=gaze,
                    openness=new_eyes[0].openness,
                    pupil_dilation=new_eyes[0].pupil_dilation,
                    highlight=new_eyes[0].highlight,
                ),
                Eye(
                    gaze=gaze,
                    openness=new_eyes[1].openness,
                    pupil_dilation=new_eyes[1].pupil_dilation,
                    highlight=new_eyes[1].highlight,
                ),
            )

        # Apply timeline (smile, eyebrows, bounce, …) if any
        if self._timeline is not None:
            self._timeline_t += dt
            progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
            # Invoke the on_update callbacks directly. Each builder
            # registered a single tween whose callback writes to
            # ``self._current`` (interpolation, bounce, …).
            for animation in self._timeline._items:
                if hasattr(animation, "on_update"):
                    animation.on_update(progress)
            if progress >= 1.0:
                self._timeline = None
                self._timeline_t = 0.0
        # Merge eye state + current body
        merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
        # Update the current model so a.current reflects the rendered state.
        self._current = merged

        # Speaking animation: override mouth when active.
        if self._speaking_animation is not None:
            viseme = self._speaking_animation.step(dt)
            mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
            self._current = self._current.with_mouth(
                Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
            )
            if not self._speaking_animation.has_frames:
                self._speaking_animation = None

        # Wake animation: full override (highest priority).
        if self._wake_animation is not None:
            wake_frame = self._wake_animation.step(dt)
            self._current = self._apply_wake_frame(self._current, wake_frame)
            if self._wake_animation.done:
                self._wake_animation = None

        # Apply theme
        themed = self.theme.apply(self._current)
        return self.renderer.render(themed)

    async def _step_async(self, drift: bool = True) -> EyeFrame:
        frame = self.step(drift=drift)
        await self._push(frame)
        return frame

    async def _push(self, frame: EyeFrame) -> None:
        try:
            await self.display.show(frame)
        except Exception:
            _log.exception("face.animator.display_failed")
        if self.bus is not None:
            from robot.events.events import DisplayUpdated

            with contextlib.suppress(Exception):
                await self.bus.publish(DisplayUpdated(display="face"))

    async def run_forever(self) -> None:
        self._stopped = False
        frame_interval = 1.0 / self.fps
        try:
            while not self._stopped:
                start = time.monotonic()
                await self._step_async(drift=True)
                end = time.monotonic()
                if self._frame_profiler is not None and getattr(
                    self._frame_profiler, "enabled", False
                ):
                    self._frame_profiler.record_frame(start, end)
                await self.clock.sleep(frame_interval)
        finally:
            self._stopped = True

    def stop(self) -> None:
        self._stopped = True

    # ------------------------------------------------------------------ timeline helpers
    def _start_timeline(self, timeline: Timeline) -> None:
        self._timeline = timeline
        self._timeline_t = 0.0
        # _timeline_total is set by the builder (so the builder can also do its own work)

    def _build_emotion_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        """Build a timeline that interpolates between two FaceModels.

        We don't yet have a generic FaceModel interpolator, so we use a
        sequence of tween callbacks to lerp scalar fields. The
        renderer is what makes the result look smooth.
        """
        tl = Timeline()
        # Tween the mouth shape change discretely (mid-way)
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_mouth_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_eyebrow_timeline(
        self, start: FaceModel, end: FaceModel, duration_s: float
    ) -> Timeline:
        tl = Timeline()
        tl.tween(
            from_value=0.0,
            to_value=1.0,
            duration_s=duration_s,
            on_update=lambda t: self._set_interp(start, end, t),
        )
        self._timeline_total = duration_s
        return tl

    def _build_bounce_timeline(self) -> Timeline:
        """One-shot bounce: bounce up, squash on landing, settle.

        Uses the model's ``bounce`` and ``squash`` fields and writes a
        per-frame value through a single tween.
        """
        # Build a sequence of keyframes as a list of (t, bounce, squash)
        keyframes: list[tuple[float, float, float]] = [
            (0.00, 0.0, 1.00),
            (0.10, 0.50, 0.92),  # anticipation squash
            (0.30, 0.85, 1.10),  # jump stretch
            (0.55, 0.00, 0.95),  # impact squash
            (0.75, 0.30, 1.04),  # small bounce
            (1.00, 0.0, 1.00),  # settle
        ]
        duration = 0.6

        class _Bounce:
            def __init__(self) -> None:
                pass

        # Use a simple Tween + linear interp through keyframes
        def _sample(t: float) -> tuple[float, float]:
            for i in range(len(keyframes) - 1):
                t0, b0, s0 = keyframes[i]
                t1, b1, s1 = keyframes[i + 1]
                if t0 <= t <= t1:
                    local = (t - t0) / max(1e-6, t1 - t0)
                    local = _ease_in_out(local)
                    return (b0 + (b1 - b0) * local, s0 + (s1 - s0) * local)
            return keyframes[-1][1], keyframes[-1][2]

        def _apply(t: float) -> None:
            bounce, squash = _sample(t)
            # Apply in-place: store the bounce/squash on the model.
            # We achieve this by replacing self._current with a new model
            # that has the transformed bounce/squash.
            self._current = self._current.with_transform(bounce=bounce, squash=squash)

        tl = Timeline()
        tl.tween(from_value=0.0, to_value=1.0, duration_s=duration, on_update=_apply)
        self._timeline_total = duration
        return tl

    def _apply_timeline_at(self, model: FaceModel, t: float) -> FaceModel:
        """Most timelines write to ``self._current`` directly via tween
        callbacks. This method is the fallback for any future timeline
        that wants to be queryable.
        """
        return model

    def _apply_wake_frame(self, model: FaceModel, frame: WakeFrame) -> FaceModel:
        """Apply a :class:`WakeFrame` override to the model.

        The wake animation has the highest priority and overrides
        eyes, eyelids, mouth, and eyebrows.
        """
        return (
            model.with_eyes(
                left_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.left_eye.pupil_dilation,
                    highlight=model.left_eye.highlight,
                ),
                right_eye=Eye(
                    gaze=frame.gaze,
                    openness=frame.eye_openness,
                    pupil_dilation=model.right_eye.pupil_dilation,
                    highlight=model.right_eye.highlight,
                ),
            )
            .with_eyelids(Eyelids(top=frame.eyelid_top, bottom=0.0))
            .with_mouth(
                Mouth(
                    shape=frame.mouth_shape, openness=frame.mouth_openness, width=frame.mouth_width
                )
            )
            .with_eyebrows(
                left=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
                right=Eyebrow(shape=frame.eyebrow_shape, raise_amount=frame.eyebrow_raise),
            )
        )

    def _set_interp(self, start: FaceModel, end: FaceModel, t: float) -> None:
        """Snap-interpolate scalar fields from start to end at progress t."""
        e = _ease_in_out(t)
        left_eye = _interp_eye(start.left_eye, end.left_eye, e)
        right_eye = _interp_eye(start.right_eye, end.right_eye, e)
        eyelids = _interp_eyelids(start.eyelids, end.eyelids, e)
        left_brow = _interp_eyebrow(start.left_eyebrow, end.left_eyebrow, e)
        right_brow = _interp_eyebrow(start.right_eyebrow, end.right_eyebrow, e)
        mouth = _interp_mouth(start.mouth, end.mouth, e)
        cheeks = _interp_cheeks(start.cheeks, end.cheeks, e)
        overlay = end.overlay if e > 0.5 else start.overlay
        body_hint = end.body_hint if e > 0.5 else start.body_hint
        self._current = FaceModel(
            width=start.width,
            height=start.height,
            left_eye=left_eye,
            right_eye=right_eye,
            eyelids=eyelids,
            left_eyebrow=left_brow,
            right_eyebrow=right_brow,
            mouth=mouth,
            cheeks=cheeks,
            overlay=overlay,
            accessory=start.accessory,
            palette=start.palette,
            bounce=start.bounce,
            squash=start.squash,
            body_hint=body_hint,
        )

    def _eyes_from_eye_state(self, state: object) -> tuple[Eye, Eye]:
        """Translate the eye render state into two :class:`Eye` components."""
        # The legacy EyeState has a ``gaze`` field; the new EyeRenderState
        # has separate ``gaze_x`` / ``gaze_y`` floats. Handle both.
        if hasattr(state, "gaze_x"):
            gaze = Gaze(float(getattr(state, "gaze_x", 0.0)), float(getattr(state, "gaze_y", 0.0)))
        else:
            g = getattr(state, "gaze", Gaze())
            gaze = Gaze(float(g.x), float(g.y))
        openness = float(getattr(state, "openness", 1.0))
        dilation = float(getattr(state, "pupil_dilation", 0.5))
        eye = Eye(gaze=gaze, openness=openness, pupil_dilation=dilation, highlight=Gaze(0.3, 0.3))
        return eye, eye

DEFAULT_FPS = 30 class-attribute

bus = None class-attribute instance-attribute

clock instance-attribute

current property

display instance-attribute

emotions instance-attribute

fps = DEFAULT_FPS class-attribute instance-attribute

frame_count property

height = 240 class-attribute instance-attribute

is_running property

renderer instance-attribute

theme instance-attribute

width = 240 class-attribute instance-attribute

__init__(renderer, display, clock, emotions, theme, fps=DEFAULT_FPS, bus=None, width=240, height=240)

__post_init__()

Source code in src/robot/face/animator.py
def __post_init__(self) -> None:
    if self.fps <= 0:
        raise ValueError("fps must be > 0")
    if self.width <= 0 or self.height <= 0:
        raise ValueError("width and height must be > 0")
    self._eye = EyeAnimator(
        side=EyeSide.LEFT,
        width=self.width,
        height=self.height,
        fps=self.fps,
    )
    self._current = self.emotions.build("neutral")
    self._target = self._current
    if self.bus is not None:
        from robot.events.events import (
            BlinkRequested,
            EmotionChanged,
            LookRequested,
        )

        self.bus.subscribe(EmotionChanged, self._on_emotion)
        self.bus.subscribe(BlinkRequested, self._on_blink)
        self.bus.subscribe(LookRequested, self._on_look)
Source code in src/robot/face/animator.py
def blink(self) -> None:
    self._eye.blink()

bounce()

Run a one-shot bounce animation (squash & stretch).

Source code in src/robot/face/animator.py
def bounce(self) -> None:
    """Run a one-shot bounce animation (squash & stretch)."""
    tl = self._build_bounce_timeline()
    self._timeline = tl
Source code in src/robot/face/animator.py
def double_blink(self) -> None:
    self._eye.double_blink()

drift(amplitude=0.1, speed=0.6)

Source code in src/robot/face/animator.py
def drift(self, amplitude: float = 0.10, speed: float = 0.6) -> None:
    self._eye.drift(amplitude=amplitude, speed=speed)

eyebrow_raise(amount=0.6)

Source code in src/robot/face/animator.py
def eyebrow_raise(self, amount: float = 0.6) -> None:
    target = self._current.with_eyebrows(
        left=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
        right=Eyebrow(shape=EyebrowShape.RAISED, raise_amount=amount),
    )
    self._timeline = self._build_eyebrow_timeline(self._current, target, 0.3)

look(x, y, duration_s=0.25)

Source code in src/robot/face/animator.py
def look(self, x: float, y: float, duration_s: float = 0.25) -> None:
    self._eye.look(x, y, duration_s)

look_center(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_center(self, duration_s: float = 0.25) -> None:
    self._eye.look_center(duration_s)

look_down(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_down(self, duration_s: float = 0.25) -> None:
    self._eye.look_down(duration_s)

look_left(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_left(self, duration_s: float = 0.25) -> None:
    self._eye.look_left(duration_s)

look_right(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_right(self, duration_s: float = 0.25) -> None:
    self._eye.look_right(duration_s)

look_up(duration_s=0.25)

Source code in src/robot/face/animator.py
def look_up(self, duration_s: float = 0.25) -> None:
    self._eye.look_up(duration_s)

mouth_open(duration_s=0.3)

Source code in src/robot/face/animator.py
def mouth_open(self, duration_s: float = 0.3) -> None:
    target = self._current.with_mouth(Mouth(shape=MouthShape.OPEN, openness=0.6, width=0.6))
    self._start_timeline(self._build_mouth_timeline(self._current, target, duration_s))

reset()

Source code in src/robot/face/animator.py
def reset(self) -> None:
    self._current = self.emotions.build("neutral")
    self._target = self._current
    self._timeline = None
    self._speaking_animation = None
    self._thinking_animation = None
    self._wake_animation = None
    self._eye.reset()

run_forever() async

Source code in src/robot/face/animator.py
async def run_forever(self) -> None:
    self._stopped = False
    frame_interval = 1.0 / self.fps
    try:
        while not self._stopped:
            start = time.monotonic()
            await self._step_async(drift=True)
            end = time.monotonic()
            if self._frame_profiler is not None and getattr(
                self._frame_profiler, "enabled", False
            ):
                self._frame_profiler.record_frame(start, end)
            await self.clock.sleep(frame_interval)
    finally:
        self._stopped = True

set_emotion(name, intensity=1.0)

Animate to the given emotion over ~0.3s.

Calling this method clears any running speaking and thinking animations (they are interruptible). The wake animation is not cleared -- it plays to completion.

Source code in src/robot/face/animator.py
def set_emotion(self, name: str, intensity: float = 1.0) -> None:
    """Animate to the given emotion over ~0.3s.

    Calling this method clears any running speaking and thinking
    animations (they are interruptible).  The wake animation is
    *not* cleared -- it plays to completion.
    """
    # Clear interruptible animations on emotion change.
    self._speaking_animation = None
    self._thinking_animation = None
    target = self.emotions.build(name)
    # Apply intensity: scale the change in openness, mouth, etc.
    self._timeline = self._build_emotion_timeline(self._current, target, duration_s=0.3)
    self._target = target

set_speaking_animation(animation)

Set (or clear) the speaking animation that drives mouth shapes.

Source code in src/robot/face/animator.py
def set_speaking_animation(self, animation: SpeakingAnimation | None) -> None:
    """Set (or clear) the speaking animation that drives mouth shapes."""
    self._speaking_animation = animation

set_thinking_animation(animation)

Set (or clear) the thinking animation that drives gaze shifts.

Source code in src/robot/face/animator.py
def set_thinking_animation(self, animation: ThinkingDotsAnimation | None) -> None:
    """Set (or clear) the thinking animation that drives gaze shifts."""
    self._thinking_animation = animation

set_wake_animation(animation)

Set (or clear) the wake animation (highest priority override).

Source code in src/robot/face/animator.py
def set_wake_animation(self, animation: WakeAnimation | None) -> None:
    """Set (or clear) the wake animation (highest priority override)."""
    self._wake_animation = animation

smile_grow()

Animate the mouth from NEUTRAL to SMILE over 0.4s.

Source code in src/robot/face/animator.py
def smile_grow(self) -> None:
    """Animate the mouth from NEUTRAL to SMILE over 0.4s."""
    target = self._current.with_mouth(Mouth(shape=MouthShape.SMILE, openness=0.4, width=0.7))
    self._timeline = self._build_mouth_timeline(self._current, target, 0.4)

step(drift=True)

Advance one frame and push to the display.

The rendering pipeline applies overrides in priority order:

  1. Eye drift + blink state (from :class:EyeAnimator).
  2. Thinking animation gaze override.
  3. Timeline-based emotion interpolation.
  4. Speaking animation mouth override.
  5. Wake animation full override (highest priority).
Source code in src/robot/face/animator.py
def step(self, drift: bool = True) -> EyeFrame:
    """Advance one frame and push to the display.

    The rendering pipeline applies overrides in priority order:

    1. Eye drift + blink state (from :class:`EyeAnimator`).
    2. Thinking animation gaze override.
    3. Timeline-based emotion interpolation.
    4. Speaking animation mouth override.
    5. Wake animation full override (highest priority).
    """
    dt = 1.0 / self.fps
    self._frame_count += 1

    if drift:
        self._eye.drift(amplitude=0.10, speed=0.6)
    # Eye state: pull current gaze from the eye animator
    eye_state = self._eye.step()
    # Translate the eye's (gaze, openness) into left/right Eye components
    new_eyes = self._eyes_from_eye_state(eye_state)

    # Thinking animation: override gaze when active.
    if self._thinking_animation is not None:
        gaze = self._thinking_animation.step(dt)
        new_eyes = (
            Eye(
                gaze=gaze,
                openness=new_eyes[0].openness,
                pupil_dilation=new_eyes[0].pupil_dilation,
                highlight=new_eyes[0].highlight,
            ),
            Eye(
                gaze=gaze,
                openness=new_eyes[1].openness,
                pupil_dilation=new_eyes[1].pupil_dilation,
                highlight=new_eyes[1].highlight,
            ),
        )

    # Apply timeline (smile, eyebrows, bounce, …) if any
    if self._timeline is not None:
        self._timeline_t += dt
        progress = min(1.0, self._timeline_t / max(0.001, self._timeline_total))
        # Invoke the on_update callbacks directly. Each builder
        # registered a single tween whose callback writes to
        # ``self._current`` (interpolation, bounce, …).
        for animation in self._timeline._items:
            if hasattr(animation, "on_update"):
                animation.on_update(progress)
        if progress >= 1.0:
            self._timeline = None
            self._timeline_t = 0.0
    # Merge eye state + current body
    merged = self._current.with_eyes(left_eye=new_eyes[0], right_eye=new_eyes[1])
    # Update the current model so a.current reflects the rendered state.
    self._current = merged

    # Speaking animation: override mouth when active.
    if self._speaking_animation is not None:
        viseme = self._speaking_animation.step(dt)
        mouth_shape = MouthShape.OPEN if viseme.openness > 0.1 else MouthShape.NEUTRAL
        self._current = self._current.with_mouth(
            Mouth(shape=mouth_shape, openness=viseme.openness, width=viseme.width)
        )
        if not self._speaking_animation.has_frames:
            self._speaking_animation = None

    # Wake animation: full override (highest priority).
    if self._wake_animation is not None:
        wake_frame = self._wake_animation.step(dt)
        self._current = self._apply_wake_frame(self._current, wake_frame)
        if self._wake_animation.done:
            self._wake_animation = None

    # Apply theme
    themed = self.theme.apply(self._current)
    return self.renderer.render(themed)

stop()

Source code in src/robot/face/animator.py
def stop(self) -> None:
    self._stopped = True

wink()

Source code in src/robot/face/animator.py
def wink(self) -> None:
    self._eye.wink()

FaceStep dataclass

A face command: method(*args, duration_s=...).

Source code in src/robot/behavior_library/behavior.py
@dataclass(slots=True, frozen=True)
class FaceStep:
    """A face command: ``method(*args, duration_s=...)``."""

    method: str
    args: tuple[Any, ...] = ()
    kwargs: dict[str, Any] = field(default_factory=dict)

args = () class-attribute instance-attribute

kwargs = field(default_factory=dict) class-attribute instance-attribute

method instance-attribute

__init__(method, args=(), kwargs=dict())

HeadNod dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class HeadNod(_BaseRequest):
    name: str = "head_nod"
    amplitude: float = 15.0
    duration_s: float = 0.5

    def frames(self) -> list[ServoFrame]:
        fwd = max(MIN, min(MAX, CENTER - self.amplitude))
        return [
            ServoFrame(targets={SERVO_HEAD_TILT: fwd}, duration_s=self.duration_s / 2),
            ServoFrame(targets={SERVO_HEAD_TILT: CENTER}, duration_s=self.duration_s / 2),
        ]

amplitude = 15.0 class-attribute instance-attribute

duration_s = 0.5 class-attribute instance-attribute

name = 'head_nod' class-attribute instance-attribute

__init__(name='head_nod', amplitude=15.0, duration_s=0.5)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    fwd = max(MIN, min(MAX, CENTER - self.amplitude))
    return [
        ServoFrame(targets={SERVO_HEAD_TILT: fwd}, duration_s=self.duration_s / 2),
        ServoFrame(targets={SERVO_HEAD_TILT: CENTER}, duration_s=self.duration_s / 2),
    ]

LookLeft dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class LookLeft(_BaseRequest):
    name: str = "look_left"
    amount: float = 30.0
    duration_s: float = 0.3

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER - self.amount))},
                duration_s=self.duration_s,
            )
        ]

amount = 30.0 class-attribute instance-attribute

duration_s = 0.3 class-attribute instance-attribute

name = 'look_left' class-attribute instance-attribute

__init__(name='look_left', amount=30.0, duration_s=0.3)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER - self.amount))},
            duration_s=self.duration_s,
        )
    ]

LookRight dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class LookRight(_BaseRequest):
    name: str = "look_right"
    amount: float = 30.0
    duration_s: float = 0.3

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER + self.amount))},
                duration_s=self.duration_s,
            )
        ]

amount = 30.0 class-attribute instance-attribute

duration_s = 0.3 class-attribute instance-attribute

name = 'look_right' class-attribute instance-attribute

__init__(name='look_right', amount=30.0, duration_s=0.3)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER + self.amount))},
            duration_s=self.duration_s,
        )
    ]

WaitStep dataclass

A pause (seconds).

Source code in src/robot/behavior_library/behavior.py
@dataclass(slots=True, frozen=True)
class WaitStep:
    """A pause (seconds)."""

    seconds: float

seconds instance-attribute

__init__(seconds)

Wave dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class Wave(_BaseRequest):
    name: str = "wave"
    amplitude: float = 30.0
    duration_s: float = 1.0

    def frames(self) -> list[ServoFrame]:
        up = max(MIN, min(MAX, CENTER - self.amplitude))
        return [
            ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
            ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
            ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
            ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
        ]

amplitude = 30.0 class-attribute instance-attribute

duration_s = 1.0 class-attribute instance-attribute

name = 'wave' class-attribute instance-attribute

__init__(name='wave', amplitude=30.0, duration_s=1.0)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    up = max(MIN, min(MAX, CENTER - self.amplitude))
    return [
        ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
        ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
        ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
        ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
    ]

_maybe_await(value) async

Await value if it is awaitable, otherwise do nothing.

Source code in src/robot/behavior_library/behavior.py
async def _maybe_await(value: Any) -> None:
    """Await ``value`` if it is awaitable, otherwise do nothing."""
    if hasattr(value, "__await__"):
        await value

body(request)

Source code in src/robot/behavior_library/behavior.py
def body(request: BodyRequest) -> BehaviorStep:
    return BehaviorStep(name=request.name, kind="body", body=BodyStep(request=request))

excited()

Wider eyes, quick blink, bounce, small arm movement.

Source code in src/robot/behavior_library/behavior.py
def excited() -> Behavior:
    """Wider eyes, quick blink, bounce, small arm movement."""
    return Behavior(
        name="excited",
        steps=(
            face("set_emotion", "excited"),
            face("bounce"),
            face("blink"),
            body(Wave(amplitude=30.0, duration_s=0.8)),
            face("bounce"),
            face("blink"),
            wait(0.2),
            face("bounce"),
        ),
    )

face(method, *args, **kwargs)

Source code in src/robot/behavior_library/behavior.py
def face(method: str, *args: Any, **kwargs: Any) -> BehaviorStep:
    return BehaviorStep(
        name=method, kind="face", face=FaceStep(method=method, args=args, kwargs=kwargs)
    )

get_logger(name)

Return a bound logger for the given module name.

The name is prefixed with robot. if it doesn't already start with it, so log records naturally form a hierarchy. The name is also bound into the event context as logger_name so :func:_capture_to_ring_buffer can record it; :func:_strip_logger_name removes it before rendering so the stdout JSON output stays unchanged.

Source code in src/robot/logging.py
def get_logger(name: str) -> structlog.stdlib.BoundLogger:
    """Return a bound logger for the given module name.

    The name is prefixed with ``robot.`` if it doesn't already start with it,
    so log records naturally form a hierarchy. The name is also bound into
    the event context as ``logger_name`` so :func:`_capture_to_ring_buffer`
    can record it; :func:`_strip_logger_name` removes it before rendering so
    the stdout JSON output stays unchanged.
    """
    if not name.startswith("robot."):
        name = f"robot.{name}"
    logger = structlog.get_logger(name).bind(logger_name=name)
    return cast("structlog.stdlib.BoundLogger", logger)

greeting()

Smile, blink, raise arms, tilt head.

Source code in src/robot/behavior_library/behavior.py
def greeting() -> Behavior:
    """Smile, blink, raise arms, tilt head."""
    return Behavior(
        name="greeting",
        steps=(
            face("set_emotion", "happy"),
            face("smile_grow"),
            face("blink"),
            body(ArmsOpen(amount=15.0)),
            face("look_left"),
            wait(0.2),
            face("look_center"),
            face("look_right"),
            wait(0.2),
            face("look_center"),
            body(ArmsRelax()),
        ),
    )

listening()

Eyes focused, head tilted slightly, arms relaxed.

Source code in src/robot/behavior_library/behavior.py
def listening() -> Behavior:
    """Eyes focused, head tilted slightly, arms relaxed."""
    return Behavior(
        name="listening",
        steps=(
            face("set_emotion", "curious"),
            face("look_left", 0.1),
            body(HeadNod(amplitude=8.0, duration_s=0.6)),
            wait(0.4),
            face("look_center"),
            face("reset"),
        ),
    )

sleeping()

Eyelids close, breathing animation, head lowers, arms rest.

Source code in src/robot/behavior_library/behavior.py
def sleeping() -> Behavior:
    """Eyelids close, breathing animation, head lowers, arms rest."""
    return Behavior(
        name="sleeping",
        steps=(
            face("set_emotion", "sleepy"),
            body(LookLeft(amount=0.0, duration_s=0.0)),
            wait(0.5),
            face("bounce"),
            wait(0.3),
            face("bounce"),
            wait(0.3),
            face("bounce"),
        ),
    )

surprised()

Wide eyes, open mouth, small jump.

Source code in src/robot/behavior_library/behavior.py
def surprised() -> Behavior:
    """Wide eyes, open mouth, small jump."""
    return Behavior(
        name="surprised",
        steps=(
            face("set_emotion", "surprised"),
            face("bounce"),
            wait(0.5),
            face("reset"),
        ),
    )

thinking()

Look up, brows furrowed, subtle head movement.

Source code in src/robot/behavior_library/behavior.py
def thinking() -> Behavior:
    """Look up, brows furrowed, subtle head movement."""
    return Behavior(
        name="thinking",
        steps=(
            face("set_emotion", "thinking"),
            face("look_up"),
            face("eyebrow_raise", 0.3),
            body(LookLeft(amount=10.0)),
            wait(0.5),
            body(LookRight(amount=10.0)),
            wait(0.5),
            body(LookLeft(amount=10.0)),
            wait(0.3),
            face("look_center"),
            face("reset"),
        ),
    )

wait(seconds)

Source code in src/robot/behavior_library/behavior.py
def wait(seconds: float) -> BehaviorStep:
    return BehaviorStep(name=f"wait_{seconds:.2f}s", kind="wait", wait=WaitStep(seconds=seconds))