rb-wf-ag/AGENTS.md

24 KiB
Executable File
Raw Permalink Blame History

Wi‑Fi Event/Command Bridge for wpa_supplicant

Purpose

This document defines:

  • a formal architecture for an application module that uses:
    • D-Bus for the wpa_supplicant D-Bus tree
    • Unix socket for wpa_supplicant ctrl_iface
  • a ready YAML configuration schema
  • API skeleton for models, classes, and functions

The module must:

  • receive events from configured sources
  • apply source-specific filters
  • classify events
  • serialize selected events to stdout as NDJSON
  • trigger commands for selected events
  • execute commands via the appropriate destination
  • distinguish:
    • execution result of the command inside the application
    • data returned by the external destination

The D-Bus methods, signals, and properties listed below are based on the wpa_supplicant D-Bus API documentation. citeturn754241view0
The ctrl_iface commands and unsolicited events listed below are based on the documented wpa_supplicant control interface. citeturn298527view3turn298527view4turn298527view1turn298527view0


Main source assumptions

D-Bus source

The wpa_supplicant D-Bus API exposes:

  • main object interface fi.w1.wpa_supplicant1
  • interface object interface fi.w1.wpa_supplicant1.Interface
  • main object methods:
    • CreateInterface
    • RemoveInterface
    • GetInterface
  • interface object methods including:
    • Scan
    • Disconnect
    • AddNetwork
    • RemoveNetwork
    • RemoveAllNetworks
    • SelectNetwork
    • Reassociate
    • Reattach
    • Reconnect
  • main object signals:
    • InterfaceAdded
    • InterfaceRemoved
    • PropertiesChanged citeturn754241view0

ctrl_iface source and destination

The control interface provides commands including:

  • STATUS
  • STATUS-VERBOSE
  • REASSOCIATE
  • RECONNECT
  • ATTACH
  • DETACH
  • DISCONNECT
  • SCAN
  • SCAN_RESULTS
  • BSS
  • SELECT_NETWORK
  • ENABLE_NETWORK
  • DISABLE_NETWORK
  • RECONFIGURE
  • TERMINATE citeturn298527view3turn298527view4turn298527view1turn298527view0

After ATTACH, unsolicited control interface events can be received, including examples such as:

  • CTRL-EVENT-SCAN-RESULTS
  • CTRL-EVENT-BSS-ADDED
  • CTRL-EVENT-BSS-REMOVED citeturn298527view1turn298527view0

Runtime-generated internal events

The application must also generate and recognize internal runtime events:

  • start
  • reload
  • stop
  • timer_tick

timer_tick is emitted by a built-in service event source with a configurable interval.

Output format

Serialized events are written to stdout in NDJSON / JSON Lines form: one UTF-8 JSON object per line. This is a standard line-oriented streaming format. citeturn754241view0turn298527view0


Architectural principles

  1. Sources and destinations are separate concerns

    • source adapters receive events
    • command clients execute commands
  2. Listeners must not execute commands directly

    • listeners publish source events into the pipeline
    • trigger logic decides whether to create a command
    • dispatcher selects the destination
  3. Runtime events are first-class events

    • they pass through the same filter / classifier / serializer / trigger flow
  4. Serialization target is stdout

    • selected events are serialized to NDJSON only after classification
  5. Execution result and returned data are distinct

    • the application must represent both explicitly

Formal module architecture

Top-level flow

DBus Source -----------\
                        \
Runtime Event Source ----> Source Filters -> Event Normalizer -> Event Classifier -> NDJSON Serializer -> stdout
                        /                                                 |
CtrlIface Source ------/                                                  |
                                                                          |
                                                                          -> Trigger Engine -> Command Dispatcher
                                                                                                 |
                                                                                                 +-> DBus Command Client
                                                                                                 +-> CtrlIface Command Client

Module list

Source adapters

  • DbusEventSource
  • CtrlIfaceEventSource
  • RuntimeEventSource

Event processing

  • SourceFilterChain
  • EventNormalizer
  • EventClassifier
  • NdjsonSerializer
  • StdoutOutputWriter

Trigger and command side

  • TriggerEngine
  • TriggerLoopGuard
  • CommandDispatcher
  • DbusCommandClient
  • CtrlIfaceCommandClient

Shared services

  • Clock
  • CorrelationIdProvider
  • Observability
  • AppLifecycleService
  • ConfigManager

Unified event and command model

Raw source event

class RawSourceEvent:
    event_id: str
    source_type: str          # dbus | ctrl_iface | runtime
    source_id: str            # dbus.wpa, ctrl_iface.wpa, runtime
    observed_at_unix_ms: int
    raw_payload: object

Normalized event

class NormalizedEvent:
    event_id: str
    source_type: str
    source_id: str
    event_kind: str
    observed_at_unix_ms: int
    severity: str
    payload_raw: object
    payload_structured: dict
    correlation_id: str | None
    causation_id: str | None

Event disposition

class EventDisposition:
    action: str               # drop | serialize_only | serialize_and_trigger
    classifier_rule_id: str | None
    trigger_rule_ids: list[str]

Logical command request

class CommandRequest:
    command_id: str
    command_kind: str
    destination_hint: str | None    # dbus | ctrl_iface | auto
    arguments: dict
    triggered_by_event_id: str | None
    correlation_id: str | None
    priority: str | None
    not_before_unix_ms: int | None
    expires_at_unix_ms: int | None

Command execution result vs returned data

class CommandExecutionResult:
    execution_status: str     # accepted | sent | succeeded | failed | timed_out | unsupported
    execution_error_code: str | None
    execution_error_message: str | None

class CommandReturnedData:
    data_type: str            # none | text | kv | structured | event_like
    payload: object | None

class CommandResult:
    command_id: str
    destination: str
    execution: CommandExecutionResult
    returned_data: CommandReturnedData

Source behavior model

D-Bus source

Responsibilities:

  • connect to the system bus
  • resolve the root object fi.w1.wpa_supplicant1
  • resolve interface object paths through GetInterface
  • subscribe to relevant signals and/or properties
  • convert source payload into RawSourceEvent

D-Bus method list to reflect in the API skeleton

Main object fi.w1.wpa_supplicant1
  • CreateInterface(args) -> interface
  • RemoveInterface(interface)
  • GetInterface(ifname) -> interface citeturn754241view0
Interface object fi.w1.wpa_supplicant1.Interface
  • Scan(args)
  • Disconnect()
  • AddNetwork(args) -> network
  • RemoveNetwork(network)
  • RemoveAllNetworks()
  • SelectNetwork(network)
  • SignalPoll()
  • SubscribeProbeReq()
  • UnsubscribeProbeReq()
  • Reassociate()
  • Reattach()
  • FlushBSS(args)
  • Reconnect() citeturn754241view0
Main signal examples
  • InterfaceAdded(interface, properties)
  • InterfaceRemoved(interface)
  • PropertiesChanged(properties) citeturn754241view0

ctrl_iface source

Responsibilities:

  • connect to the Unix socket
  • optionally issue ATTACH
  • receive unsolicited event lines
  • convert each unsolicited line into RawSourceEvent

Control interface commands to reflect in the API skeleton

  • STATUS
  • STATUS-VERBOSE
  • REASSOCIATE
  • RECONNECT
  • ATTACH
  • DETACH
  • DISCONNECT
  • SCAN
  • SCAN_RESULTS
  • BSS
  • RECONFIGURE
  • TERMINATE citeturn298527view3turn298527view4turn298527view1turn298527view0

Unsolicited event examples

  • CTRL-EVENT-SCAN-RESULTS
  • CTRL-EVENT-BSS-ADDED
  • CTRL-EVENT-BSS-REMOVED citeturn298527view1turn298527view0

Runtime event source

Responsibilities:

  • emit start
  • emit reload
  • emit stop
  • emit every100ms

The timer_tick event is driven by the application timer source and uses a configurable interval in milliseconds.


Event processing rules

Rule matching semantics

AND/OR logic inside one rule

Inside a single rule:

  • different fields are matched with AND logic;
  • multiple values inside one field are matched with OR logic.

This means that one rule matches only if all specified fields match, while each individual field may match any one value from its configured value list.

D-Bus filter fields

A D-Bus filter rule may contain the following optional fields:

  • Interface
  • Path
  • Member

Each field accepts a list of possible values.

A D-Bus event matches the rule if:

  • Interface matches any configured value, if Interface is present;
  • Path matches any configured value, if Path is present;
  • Member matches any configured value, if Member is present;

and all specified fields match together.

Formally:

(Interface in InterfaceList, if specified)
AND
(Path in PathList, if specified)
AND
(Member in MemberList, if specified)

ctrl_iface filter fields

A ctrl_iface filter rule is matched by the event kind, for example:

  • CTRL-EVENT-SCAN-RESULTS
  • CTRL-EVENT-BSS-ADDED
  • CTRL-EVENT-BSS-REMOVED

If event_kind_in is configured, the rule matches when the received ctrl_iface event kind equals any value from the configured list.

Runtime filter fields

A runtime filter rule is matched by the runtime event kind, for example:

  • start
  • reload
  • stop
  • timer_tick

Per-source filters

Per-source filters are applied before normalization.

Examples:

  • suppress low-value D-Bus property changes
  • keep only selected ctrl_iface unsolicited events
  • enable or disable timer_tick

Event classifier

Classifier decisions:

  • drop
  • serialize_only
  • serialize_and_trigger

Trigger rules

A trigger rule must define:

  • event match conditions
  • logical command kind
  • destination
  • arguments
  • cooldown / debounce policy

Loop guard

The application must prevent loops such as:

  • event -> command -> event -> command
  • repeated timer_tick triggers
  • repeated disconnect/reassociate oscillation

NDJSON serialization contract

Each serialized event is written to stdout as one JSON object per line.

Example:

{"event_id":"e-1001","source_type":"dbus","source_id":"dbus.wpa","event_kind":"state_changed","observed_at_unix_ms":1760000000000,"severity":"info","payload":{"state":"completed"}}

Runtime event example:

{"event_id":"e-1002","source_type":"runtime","source_id":"runtime","event_kind":"start","observed_at_unix_ms":1760000000100,"severity":"info","payload":{}}

No JSON arrays are used for streaming output.


Ready YAML configuration schema

version: 1

runtime:
  generate_events:
    start: true
    reload: true
    stop: true
    timer_tick: true
  timers:
    timer_tick_interval_ms: 100

sources:
  dbus:
    enabled: true
    bus: system
    service: fi.w1.wpa_supplicant1
    root_path: /fi/w1/wpa_supplicant1
    interface_name: fi.w1.wpa_supplicant1.Interface
    filters:
      - id: dbus-drop-debug-properties
        enabled: true
        match:
          event_kind: properties_changed
          payload_has_any_key:
            - DebugLevel
            - DebugTimestamp
            - DebugShowKeys
        action: drop

      - id: dbus-keep-core-events
        enabled: true
        match:
          event_kind_in:
            - interface_added
            - interface_removed
            - properties_changed
        action: keep

  ctrl_iface:
    enabled: true
    socket_path: /var/run/wpa_supplicant/wlan0
    attach_for_events: true
    filters:
      - id: ctrl-keep-core-events
        enabled: true
        match:
          event_kind_in:
            - CTRL-EVENT-SCAN-RESULTS
            - CTRL-EVENT-BSS-ADDED
            - CTRL-EVENT-BSS-REMOVED
        action: keep

      - id: ctrl-drop-unmatched
        enabled: true
        match:
          any: true
        action: drop

  runtime:
    enabled: true
    filters:
      - id: runtime-keep-core
        enabled: true
        match:
          event_kind_in:
            - start
            - reload
            - stop
            - timer_tick
        action: keep

classifier:
  rules:
    - id: serialize-runtime-start
      enabled: true
      match:
        source_type: runtime
        event_kind: start
      disposition: serialize_only

    - id: serialize-runtime-reload
      enabled: true
      match:
        source_type: runtime
        event_kind: reload
      disposition: serialize_only

    - id: serialize-runtime-stop
      enabled: true
      match:
        source_type: runtime
        event_kind: stop
      disposition: serialize_only

    - id: serialize-runtime-timer-tick
      enabled: true
      match:
        source_type: runtime
        event_kind: timer_tick
      disposition: serialize_only

    - id: serialize-dbus-properties
      enabled: true
      match:
        source_type: dbus
        event_kind: properties_changed
      disposition: serialize_only

    - id: serialize-and-trigger-scan-results
      enabled: true
      match:
        source_type: ctrl_iface
        event_kind: CTRL-EVENT-SCAN-RESULTS
      disposition: serialize_and_trigger

triggers:
  rules:
    - id: on-start-request-status
      enabled: true
      match:
        source_type: runtime
        event_kind: start
      command:
        command_kind: get_status
        destination: ctrl_iface
        arguments: {}
      cooldown_ms: 2000
      max_retries: 0

    - id: on-scan-results-fetch-bss
      enabled: true
      match:
        source_type: ctrl_iface
        event_kind: CTRL-EVENT-SCAN-RESULTS
      command:
        command_kind: bss_dump
        destination: ctrl_iface
        arguments:
          mode: iterative
      cooldown_ms: 5000
      max_retries: 0

    - id: periodic-scan
      enabled: false
      match:
        source_type: runtime
        event_kind: timer_tick
      command:
        command_kind: scan
        destination: ctrl_iface
        arguments: {}
      cooldown_ms: 30000
      max_retries: 0

commands:
  dispatch:
    strategy: explicit_destination_only

  dbus:
    enabled: true
    methods:
      create_interface:
        object: fi.w1.wpa_supplicant1
        method: CreateInterface
      remove_interface:
        object: fi.w1.wpa_supplicant1
        method: RemoveInterface
      get_interface:
        object: fi.w1.wpa_supplicant1
        method: GetInterface
      scan:
        object: fi.w1.wpa_supplicant1.Interface
        method: Scan
      disconnect:
        object: fi.w1.wpa_supplicant1.Interface
        method: Disconnect
      add_network:
        object: fi.w1.wpa_supplicant1.Interface
        method: AddNetwork
      remove_network:
        object: fi.w1.wpa_supplicant1.Interface
        method: RemoveNetwork
      remove_all_networks:
        object: fi.w1.wpa_supplicant1.Interface
        method: RemoveAllNetworks
      select_network:
        object: fi.w1.wpa_supplicant1.Interface
        method: SelectNetwork
      reassociate:
        object: fi.w1.wpa_supplicant1.Interface
        method: Reassociate
      reattach:
        object: fi.w1.wpa_supplicant1.Interface
        method: Reattach
      reconnect:
        object: fi.w1.wpa_supplicant1.Interface
        method: Reconnect

  ctrl_iface:
    enabled: true
    commands:
      get_status: STATUS
      get_status_verbose: STATUS-VERBOSE
      disconnect: DISCONNECT
      scan: SCAN
      scan_results: SCAN_RESULTS
      bss_dump: BSS
      reassociate: REASSOCIATE
      reconnect: RECONNECT
      attach: ATTACH
      detach: DETACH
      reconfigure: RECONFIGURE
      terminate: TERMINATE

output:
  format: ndjson
  target: stdout
  flush_every_event: true

observability:
  emit_internal_metrics: true
  log_level: info

guards:
  trigger_loop_guard:
    enabled: true
    default_cooldown_ms: 5000
    dedup_window_ms: 3000

API skeleton

Configuration models

class RuntimeConfig:
    generate_start: bool
    generate_reload: bool
    generate_stop: bool
    generate_timer_tick: bool
    timer_tick_interval_ms: int

class SourceFilterRule:
    rule_id: str
    enabled: bool
    match: dict
    action: str             # keep | drop

class DbusSourceConfig:
    enabled: bool
    bus: str
    service: str
    root_path: str
    interface_name: str
    filters: list[SourceFilterRule]

class CtrlIfaceSourceConfig:
    enabled: bool
    socket_path: str
    attach_for_events: bool
    filters: list[SourceFilterRule]

class RuntimeSourceConfig:
    enabled: bool
    filters: list[SourceFilterRule]

class EventClassifierRule:
    rule_id: str
    enabled: bool
    match: dict
    disposition: str        # drop | serialize_only | serialize_and_trigger

class TriggerRule:
    rule_id: str
    enabled: bool
    match: dict
    command: dict
    cooldown_ms: int
    max_retries: int

class OutputConfig:
    format: str             # ndjson
    target: str             # stdout
    flush_every_event: bool

class AppConfig:
    version: int
    runtime: RuntimeConfig
    dbus: DbusSourceConfig
    ctrl_iface: CtrlIfaceSourceConfig
    runtime_source: RuntimeSourceConfig
    classifier_rules: list[EventClassifierRule]
    trigger_rules: list[TriggerRule]
    output: OutputConfig

Source adapter interfaces

class EventSource:
    async def start(self) -> None: ...
    async def stop(self) -> None: ...
    async def read_event(self) -> RawSourceEvent | None: ...

class DbusEventSource(EventSource):
    async def connect(self) -> None: ...
    async def resolve_root_proxy(self) -> None: ...
    async def resolve_interface_proxy(self, ifname: str) -> None: ...
    async def subscribe_signals(self) -> None: ...
    async def read_event(self) -> RawSourceEvent | None: ...

class CtrlIfaceEventSource(EventSource):
    async def connect(self) -> None: ...
    async def attach(self) -> None: ...
    async def detach(self) -> None: ...
    async def read_event(self) -> RawSourceEvent | None: ...

class RuntimeEventSource(EventSource):
    async def emit_start(self) -> RawSourceEvent: ...
    async def emit_reload(self) -> RawSourceEvent: ...
    async def emit_stop(self) -> RawSourceEvent: ...
    async def emit_timer_tick(self) -> RawSourceEvent: ...

Source filter chain

class SourceFilterChain:
    def apply(self, event: RawSourceEvent, source_type: str) -> bool:
        ...

Event normalization

class EventNormalizer:
    def normalize(self, event: RawSourceEvent) -> NormalizedEvent: ...

Event classifier

class EventClassifier:
    def classify(self, event: NormalizedEvent) -> EventDisposition: ...

NDJSON serializer and stdout writer

class NdjsonSerializer:
    def serialize(self, event: NormalizedEvent) -> str: ...

class StdoutOutputWriter:
    def write_line(self, line: str) -> None: ...

Trigger engine and loop guard

class TriggerLoopGuard:
    def allow(self, event: NormalizedEvent, trigger_rule_id: str) -> bool: ...

class TriggerEngine:
    def evaluate(self, event: NormalizedEvent, disposition: EventDisposition) -> list[CommandRequest]:
        ...

Command dispatcher

class CommandDispatcher:
    async def dispatch(self, request: CommandRequest) -> CommandResult: ...
    def select_destination(self, request: CommandRequest) -> str: ...

D-Bus command client skeleton

class DbusCommandClient:
    async def create_interface(self, args: dict) -> CommandResult: ...
    async def remove_interface(self, interface_path: str) -> CommandResult: ...
    async def get_interface(self, ifname: str) -> CommandResult: ...

    async def scan(self, args: dict) -> CommandResult: ...
    async def disconnect(self) -> CommandResult: ...
    async def add_network(self, args: dict) -> CommandResult: ...
    async def remove_network(self, network_path: str) -> CommandResult: ...
    async def remove_all_networks(self) -> CommandResult: ...
    async def select_network(self, network_path: str) -> CommandResult: ...
    async def reassociate(self) -> CommandResult: ...
    async def reattach(self) -> CommandResult: ...
    async def reconnect(self) -> CommandResult: ...

These methods reflect the documented D-Bus API surface used by this module. citeturn754241view0

ctrl_iface command client skeleton

class CtrlIfaceCommandClient:
    async def status(self) -> CommandResult: ...
    async def status_verbose(self) -> CommandResult: ...
    async def reassociate(self) -> CommandResult: ...
    async def reconnect(self) -> CommandResult: ...
    async def disconnect(self) -> CommandResult: ...
    async def scan(self) -> CommandResult: ...
    async def scan_results(self) -> CommandResult: ...
    async def bss(self, selector: str | None = None) -> CommandResult: ...
    async def attach(self) -> CommandResult: ...
    async def detach(self) -> CommandResult: ...
    async def reconfigure(self) -> CommandResult: ...
    async def terminate(self) -> CommandResult: ...

These methods reflect the documented control interface command set used by this module. citeturn298527view3turn298527view4turn298527view1turn298527view0

Lifecycle and orchestration skeleton

class AppLifecycleService:
    async def start(self) -> None: ...
    async def reload(self) -> None: ...
    async def stop(self) -> None: ...

class EventPipeline:
    async def ingest(self, event: RawSourceEvent) -> None: ...
    async def process(self, event: RawSourceEvent) -> None: ...

class ApplicationRuntime:
    async def run(self) -> None: ...
    async def handle_event(self, event: RawSourceEvent) -> None: ...
    async def handle_command_result(self, result: CommandResult) -> None: ...

Commands should be issued to an explicitly configured destination without fallback.

Recommended practical split:

  • D-Bus
    • interface discovery
    • structured object/path resolution
    • selected state/property calls
    • selected interface methods
  • ctrl_iface
    • status text retrieval
    • scan triggering
    • scan result text retrieval
    • detailed BSS dumping
    • reassociation/reconnect/disconnect commands
    • attach/detach for unsolicited text events

This split follows the documented command families and their strengths. Destination selection is defined by trigger rules or explicit command requests; the dispatcher does not apply fallback routing. citeturn754241view0turn298527view3turn298527view4turn298527view1turn298527view0


Implementation rule

The module should follow this rule:

  • source adapters are transport-specific and lightweight
  • all events, including runtime events, pass through one unified event pipeline
  • source-specific filters are applied before normalization
  • classifier and trigger rules are configuration-driven
  • NDJSON serialization is performed only after classification
  • commands are executed through a dedicated dispatcher
  • each command request targets an explicit destination without fallback
  • application-side execution status is always separated from destination-returned data
  • stdout is the only event serialization target in this module
  • Python, dbus-next, virtual-environment

References

  • D-Bus API reference: https://w1.fi/wpa_supplicant/devel/dbus.html
  • ctrl_iface reference: https://w1.fi/wpa_supplicant/devel/ctrl_iface_page.html