tree: c15f45d7893d315471bb2998a7d26f246f3a2880 [search]
  1. api_extension/
  2. services/
  3. src/
  4. tests/
  5. Android.bp
  6. OWNERS
  7. README.md
  8. safetyevaluator.extension.xml
  9. TEST_MAPPING
libs/safetyevaluator/README.md

Safety Evaluator System Extension Library

The Safety Evaluator System Extension library (com.android.extensions.safetyevaluator) is engineered to provide real-time, non-blocking safety and policy evaluation for autonomous AI agents in Android OS.

In V1, two primary ingress surfaces target integration:

  1. Computer Control: Stream UI tap gestures, display screen frames, and user text prompts.
  2. App Functions: Stream tool execution calls, parameter payloads, and semantic context.

The framework decouples event capture in the Android platform from evaluation logic. The platform acts as a zero-copy two-hop intermediary and queue engine, delegating stateful evaluation policies to the system configured evaluator service via object-oriented Binder IPC streams.


1. Architectural Flow Diagram

The following sequence diagram illustrates the lifecycle and evaluation stream of a sample SafetyEvaluationScope, highlighting two-phase gatekeeping, automated Consume-on-Dispatch memory hand-off, and end-of-scope crash defense:

+-------------------+       +-------------------+       +-------------------+
|  Ingress Client   |       |   system_server   |       | Evaluator Service |
| (ComputerControl) |       | (SafetyEvaluator) |       | (SafetyScopeHost) |
+---------+---------+       +---------+---------+       +---------+---------+
          |                           |                           |
     [1. Open Evaluation Scope]       |                           |
          |--- openScope(token) ----->|                           |
          |                           |--- linkToDeath() & bind ->|
          |<-- Scope Client Handle ---|                           |
          |                                                       |
     [2. Phase 1: Pre-Flight Scope Gatekeeping]                   |
          |--- evaluate(CreateScopeEvent) ----------------------->|
          | (Consume-on-Dispatch: local fds instantly closed)     | (Retain Prompt)
          |<-- onResult(DECISION_ALLOW) --------------------------|
          |                                                       |
     [3. Phase 2: Interactive UI Action Streaming]                |
          |--- evaluate(ComputerControlTapEvent) ---------------->|
          | (Consume-on-Dispatch: local fds instantly closed)     | (Drop GPU frame)
          |<-- onResult(DECISION_ALLOW) --------------------------|
          |                                                       |
     [4. Scope Termination / Crash Protection]                    |
          |--- scope.close() (or Process Crash / Death) --------->|
          |                           |--- Idempotent Sweep ----->|
          |                           |    (closes remaining fds) |
          v                           v                           v

2. Core Architectural Constructs

Client Scopes (SafetyEvaluationScope) & System-Minted Tokens (scopeToken)

  • Client Side (SafetyEvaluationScope): An AutoCloseable handle enabling clean try-with-resources syntax. Tracks client lifecycle and automatically triggers teardown on completion.
  • Platform Intermediary (SystemServerScope): Sits in the middle to enforce Pattern A+B duplicate ID collision defense, system-level side effects, and client crash monitoring via linkToDeath.
  • System-Minted Scope IDs (long scopeId): system_server mints a primitive, monotonically increasing long scopeId per scope. Passing a primitive long across AIDL eliminates kernel Binder driver object allocation and reference counting overhead.

Evaluator Host Service & Evaluation Scopes (SafetyEvaluatorService & SafetyEvaluatorScope)

  • Host Base Service (SafetyEvaluatorService): An abstract android.app.Service implemented by a system-configured evaluator service, OEM system package, or test stub.
    • Manifest Action: com.android.extensions.safetyevaluator.SafetyEvaluatorService.
    • Permission: android.permission.BIND_SAFETY_EVALUATOR_SERVICE (protectionLevel="internal"), ensuring only system_server can bind to the evaluator host.
    • Acts as the single Binder entry point bound to system_server. Automatically manages primitive scopeId scope mapping internally via LongSparseArray, invoking onOpenScope() to instantiate a developer-defined SafetyEvaluatorScope instance per client scope, routing lifecycle events (onOpen, onEvaluateEvent, onClose) directly to the scope instance, and automatically executing an idempotent sweep to tear down all active scopes when onUnbind() or onDestroy() is triggered.
  • Evaluation Scopes (SafetyEvaluatorScope): Abstract Java class extended by host implementors to encapsulate per-scope state, ML model contexts, and evaluation logic (onOpen / onEvaluateEvent / onClose).
  • Platform Discovery & Test Overrides:
    • OEM stack enablement and default backend resolution are controlled via R.string.config_defaultSafetyEvaluatorService (defaults to empty/disabled). Setting a non-empty string in a product or vendor overlay enables the stack.
    • FrameworkResourcesServiceNameResolver reads R.string.config_defaultSafetyEvaluatorService, formatted as either a flattened component name (e.g., com.example.evaluator/.ExampleSafetyEvaluatorService) or a package name (e.g., com.example.evaluator). The target service must extend SafetyEvaluatorService and be guarded by android.permission.BIND_SAFETY_EVALUATOR_SERVICE.
    • Supports dynamic test overrides via ServiceNameResolver (cmd safety_evaluator_manager set temporary-service <user_id> <component> <duration_ms>), allowing CTS and unit tests to stub the backend without image modification or state leaks.

Strongly-Typed Events & Native OS Handles

To prevent mismatched payload types and eliminate unnecessary wrapper levels, the framework embeds native AOSP SDK resources directly inside self-describing events:

  • Strongly-Typed Events (SafetyEvent): Concrete final classes such as ComputerControlTapEvent and AppFunctionExecuteEvent embody system actions and directly hold native OS handles (SharedMemory and HardwareBuffer). The abstract SafetyEvent base class implements Parcelable with package-private constructors and a polymorphic creator, routing events directly over AIDL without intermediate wrappers.

Consume-on-Dispatch & Zero-Leak Streaming Defense

Because events carry underlying native Linux file descriptors, retaining items during high-frequency navigation loops quickly depletes VRAM and fd tables:

  • Consume-on-Dispatch Default: SafetyEvaluationScope executes an automatic idempotent .close() locally the instant Binder IPC file descriptor duplication completes. Clients streaming hundreds of screen frames per second accumulate zero pinned RAM or open file descriptors automatically!
  • Opt-Out Retention (FLAG_RETAIN_LOCAL): Clients rendering memory locally after dispatch can attach FLAG_RETAIN_LOCAL to bypass auto-closing.
  • Evaluator Memory Sovereignty: The system configured evaluator service retains full sovereignty over destination file descriptors, preserving prompt RAM across multi-turn sessions while dropping heavy GPU frames instantly via idempotent helper methods (tapEvent.closeScreenshot()).

3. Capability Discovery & Availability

The Safety Evaluator stack is gated by whether an OEM or product overlay configures a default service string (R.string.config_defaultSafetyEvaluatorService). When configured and running, clients acquire an instance via SafetyEvaluatorExtensions.getInstance(context):

SafetyEvaluatorExtensions safetyExtensions = SafetyEvaluatorExtensions.getInstance(context);
if (safetyExtensions == null) {
    // Safety Evaluator service is disabled or unavailable on this device.
    return;
}

4. End-to-End Two-Phase Gatekeeping Workflow

To protect against prompt injection and unsafe autonomous objectives before any screen streaming takes place, a two-phase workflow is prescribed:

  1. Phase 1 (Pre-Flight Gatekeeping): Upon opening a SafetyEvaluationScope, clients dispatch a CreateScopeEvent enclosing initial user prompt and agent plan SharedMemory buffers directly. If evaluation denies this event, the session is blocked before initiating screen capture.
  2. Phase 2 (Action Streaming): Once permitted, clients stream sequential UI actions (such as ComputerControlTapEvent) hosting live zero-copy display captures as the agent executes its plan.

Complete Code Walkthrough

// 1. Acquire extensions instance (returns null if disabled on device)
SafetyEvaluatorExtensions safetyExtensions = SafetyEvaluatorExtensions.getInstance(context);

if (safetyExtensions != null) {
    // 3. Open evaluation scope asynchronously via OutcomeReceiver
    safetyExtensions.openEvaluationScope(executor, new OutcomeReceiver<SafetyEvaluationScope, SafetyEvaluatorException>() {
        @Override
        public void onResult(@NonNull SafetyEvaluationScope scope) {
            try (scope) {
                // 4. Phase 1: Pre-flight evaluation passing native OS handles!
                CreateScopeEvent createEvent = new CreateScopeEvent.Builder()
                        .setUserPrompt(readOnlyPromptAshmem)
                        .setAgentPlan(readOnlyPlanAshmem)
                        .build();

                // Consume-on-Dispatch: local FDs auto-closed upon hand-off! Zero leaks!
                scope.evaluateEvent(createEvent, executor, new OutcomeReceiver<SafetyEvaluationResult, SafetyEvaluatorException>() {
                    @Override
                    public void onResult(@NonNull SafetyEvaluationResult createResult) {
                        if (createResult.getDecisionCode() != SafetyEvaluationResult.DECISION_ALLOW) {
                            // Scope creation denied (e.g. prompt injection detected)
                            return;
                        }

                        // 5. Phase 2: Session permitted; stream subsequent UI actions
                        ComputerControlTapEvent tapEvent = new ComputerControlTapEvent.Builder()
                                .setX(450)
                                .setY(1280)
                                .setScreenshot(image.getHardwareBuffer()) // 0ms copy
                                .build();

                        scope.evaluateEvent(tapEvent, executor, new OutcomeReceiver<SafetyEvaluationResult, SafetyEvaluatorException>() {
                            @Override
                            public void onResult(@NonNull SafetyEvaluationResult actionResult) {
                                if (actionResult.getDecisionCode() == SafetyEvaluationResult.DECISION_ALLOW) {
                                    // Safe to execute touch gesture on display screen
                                } else if (actionResult.getDecisionCode() == SafetyEvaluationResult.DECISION_DENY) {
                                    // Action blocked by policy: abort touch gesture
                                }
                            }

                            @Override
                            public void onError(@NonNull SafetyEvaluatorException error) {
                                // Pipeline evaluation error
                            }
                        });
                    }

                    @Override
                    public void onError(@NonNull SafetyEvaluatorException error) {
                        // Scope creation error
                    }
                });
            }
        }

        @Override
        public void onError(@NonNull SafetyEvaluatorException error) {
            // Failed to open scope
        }
    });
}

5. Developer Tools & Reference Implementation

The tools/debug_evaluator/ directory provides a reference implementation and interactive Jetpack Compose dashboard:

  • Service (DebugSafetyEvaluatorService): Extends SafetyEvaluatorService to receive scope requests and evaluate safety events.
  • Compose UI (DebugEvaluatorActivity):
    • Live inspection of CreateScopeEvent (prompts/plans), ComputerControlTapEvent (screenshot preview + coordinate reticle), and AppFunctionExecuteEvent.
    • Manual interactive decisions (Allow, Deny).
    • Configurable policy toggles (Interactive, Auto Allow, Auto Deny) for automated test stubbing.
  • Testing Override Command:
    adb shell cmd safety_evaluator set temporary-service 0 com.android.safetyevaluator.debug/.DebugSafetyEvaluatorService 30000