# App Bridge v1 for Android

App Bridge lets one installed app request a named operation from another. The
publisher owns its records and the consent screen. The client sees the operations
and records the owner has granted. Calls run on the Android device using Binder.

This document specifies the Android wire format. Smarter Agent currently lists
verified publishers in **Settings → Apps**. An independently built app can
implement and test v1 with the [reference project](./example.md). Inclusion in a
Smarter Agent release requires separate publisher verification and qualification.

The terms **must** and **should** describe interoperability and safety
requirements. Capability names, business rules, scopes and record shapes belong
to the publisher. For example, a task app could let an owner grant permission to
read one project's tasks and update their due dates. A library could grant
read-only access to one shelf. A notes app could allow a client to open a note
without granting access to its text. All three use the same transport and
consent rules.

## Android registration and identity

The publisher declares an exported ContentProvider with authority
`<publisher application ID>.agentbridge` and with URI permission grants disabled.
It exposes only the protocol calls below. Ordinary content queries, file access
and data mutation methods must not expose records.

```xml
<provider
    android:name=".BridgeProvider"
    android:authorities="${applicationId}.agentbridge"
    android:exported="true"
    android:grantUriPermissions="false" />
<activity
    android:name="com.smarter.bridge.AgentBridgeAccessActivity"
    android:exported="true" />
```

Each side declares narrow Android package visibility for its known peers, by
package name or provider authority. The client resolves the provider and
checks its owning package and current APK signing identity before trusting
metadata or launching consent. Obtain trusted signer fingerprints independently
of the discovered provider. The current signer set can be represented by sorted
lowercase SHA-256 hashes of the signing certificates joined with colons.

The publisher authenticates every Binder call using the OS caller UID and its
package identity. The consent activity authenticates the OS activity-for-result
caller. Each verifies the signers for the authorized client package. Payloads,
intent extras, app labels and unverified package names cannot establish identity.
An untrusted caller should receive a `SecurityException` without metadata,
records or a grant. Replacing an app with a different signing identity invalidates
the prior trust decision and grant.

[Android package visibility](https://developer.android.com/training/package-visibility/declaring) ·
[ContentProvider.call](https://developer.android.com/reference/android/content/ContentProvider#call(java.lang.String,%20java.lang.String,%20android.os.Bundle))

## Request and response

Call `ContentResolver.call` off the main thread using
`content://<publisher application ID>.agentbridge`, the method name, a null
method argument, and a Bundle whose string `request` contains a JSON object.
The returned Bundle has a string `response` containing a JSON object. Only an
open result may carry an additional `openIntent` Parcelable.

Send the integer `version: 1` in every request and require it in every response.
An unsupported version receives a v1 failure with `error: "unsupported"`.
For compatibility with existing bridges, allow a request of up to 65,536 UTF-8
bytes and keep each reply within 262,144 UTF-8 bytes. Page large result sets.

| Method | Request fields besides `version` | Successful response |
| --- | --- | --- |
| `manifest` | Optional correlation `id` | Publisher identity and current capabilities |
| `invoke` | `id`, `capability`, `arguments` | Operation result or a receipt |
| `status` | Original `invoke` ID in `id` | Receipt without record contents |
| `revoke` | Optional correlation `id` | `{"version":1,"state":"revoked"}` |
| `changes` (optional) | `id`, optional opaque `cursor` | A scoped page of current record snapshots |

`changes` is an optional v1 extension advertised by `manifest.changeFeed` below.
Publishers implementing the original four methods remain compatible. Clients
must discover extension support before calling it; absence means unsupported,
not permission to simulate a background grant using ordinary read access.

An `invoke` or `status` ID is an opaque string matching
`[A-Za-z0-9_-]{8,100}`. Use a fresh ID for each new operation. For an exact
retry or a status lookup, reuse the original ID. The current Agent client also
sends `limit` at the top level of an invoke. Treat that as a legacy hint. Use
only fields declared in the capability schema to interpret `arguments`, including
any page size. Clients should ignore response fields they do not recognize.

## Discover and grant access

```json
{
  "version": 1,
  "appId": "app.example.notebook",
  "appVersion": "1.0",
  "grantActivity": "com.smarter.bridge.AgentBridgeAccessActivity",
  "processing": "localOnly",
  "capabilities": [
    {
      "id": "notebook.notes.read",
      "description": "Read a note from a permitted notebook.",
      "effect": "read",
      "inputSchema": {
        "type": "object",
        "properties": {"noteId": {"type": "string"}},
        "required": ["noteId"],
        "additionalProperties": false
      },
      "granted": false
    }
  ]
}
```

`appId` is the verified provider package. Capability IDs must be stable and
unique within the publisher. Use a publisher-specific prefix to avoid collisions
in clients that combine multiple tool sets. Each effect is `read`, `write`,
or `open`. Capability descriptions must be static and free of personal data.
The interoperable input schema uses an object with `properties`,
optional `required`, and `additionalProperties: false`. Property types are
`string`, `integer`, and `boolean`. Reject unknown keys, missing required
fields and incorrectly typed values. Describe domain constraints in the schema
and enforce them in the publisher.

The initial manifest advertises capabilities without exposing private scopes or
records. Only actively granted capabilities have `granted: true`. Launch the
explicit publisher activity in the foreground using the activity-for-result API.
The Boolean extras `requestRead`, `requestWrite` and `requestExternal` express
the client's request. They convey no authority. Present actions and any record
or collection scope inside the publisher's screen. Commit only the owner's
confirmed selections. Cancel and Back must leave saved access unchanged. Return
`RESULT_OK` only after saving the owner's decision. The client rechecks the
publisher identity and reads a fresh manifest to learn the actual grant.

Store grants privately outside backup, bound to the caller's package and
signers, the publisher's active account or profile, allowed capabilities, and
the owner's selected scope. Recheck the grant, account and applicable record
scope for every operation. Revoke must remove that caller's active grant and
invalidate any outstanding open handoff. The owner must be able to end access
without deleting records.

`localOnly` prohibits off-device processing by the client. A publisher can
instead declare `ownerApprovedExternal` for data that may be processed
externally after the owner's separate, explicit consent in the client. A
publisher grant or request extra is insufficient. Keep receipts and logs within
the same data boundary.

## Optional background checks and change snapshots

A publisher may add this object to its manifest:

```json
{
  "changeFeed": {
    "version": 1,
    "supported": true,
    "backgroundGranted": false,
    "grantRevision": "opaque-effective-grant-revision"
  }
}
```

The owner must separately approve background reads in the publisher's consent
screen. A foreground read grant, an app update or the client's
`requestBackground: true` activity extra must not select or save that permission
automatically. The extra is a request hint only. The publisher should explain
whether background checks can read selected records while the screen is locked.
The current extension permits that only with explicit background consent; it
does not authorize writes, open handoffs or UI launches while locked. A publisher
whose protected storage is unavailable must fail safely instead of weakening
device security. Consent itself still requires the owner to unlock the device.

Bind this grant to the verified client package/signers, current publisher account,
read capabilities and selected collections or records. Recheck all of these on
every page. `backgroundGranted` is true only while a background grant and an
eligible scoped read are both effective. The opaque `grantRevision` must change
when the effective grant or account changes. Revoking access also removes
background permission and invalidates previous cursors. Existing grants without
a background choice default to false.

The client starts a full scan without a cursor:

```json
{"version":1,"id":"scan_f71ba92c"}
```

Call the optional `changes` method. A successful response has this shape:

```json
{
  "version": 1,
  "id": "scan_f71ba92c",
  "state": "read",
  "events": [{
    "eventId": "opaque-grant-resource-revision-identity",
    "resourceId": "notebook:welcome",
    "revision": "opaque-content-revision",
    "occurredAt": 1794326400000,
    "title": "Launch notes",
    "sourceUrl": null,
    "content": {"id":"welcome","title":"Launch notes","sourceRef":"notebook:welcome"},
    "kind": "snapshot"
  }],
  "nextCursor": "opaque-continuation",
  "complete": false,
  "consistency": "bestEffort",
  "grantRevision": "opaque-effective-grant-revision",
  "processing": "localOnly",
  "asOf": 1794326400000
}
```

Continue with the returned opaque `cursor` and a fresh request ID until
`complete: true` and `nextCursor: null`. A page size or transport byte budget is
not a total-record limit: include every eligible record across all pages. Reject
a cursor from a different effective grant with `error: "revoked"`; reject an
invalid cursor without revealing records outside the grant. A cursor must make
progress. It is not a permanent incremental-sync token.

These are **current snapshots of native app storage**, including edits made
inside the publisher, not a journal of Agent invocations. `resourceId` identifies
the record; `revision` changes when relevant content changes and excludes
read-time fields such as `asOf`, `freshness` and cache timestamps. `eventId` is
stable for the same effective grant, resource and revision. `occurredAt` uses an
available source timestamp; when only observation time exists, it must not be
represented as a verified modification time. `sourceUrl` is a real source link
or null, not an internal ID disguised as a URL.

The current publishers use `kind: "snapshot"` and `consistency: "bestEffort"`.
They do not promise a change journal, deletion tombstones, an atomic database
snapshot or realtime push. Clients keep scoped revision state, establish a
baseline, compare complete subsequent scans and deduplicate persisted updates.
Do not infer deletion from a partial scan or assume a best-effort cursor cannot
move while native data changes. Schedule local checks honestly under the host
platform's background-execution constraints.

To respect Binder limits, a publisher may reduce a page and, for an individually
oversized record, send identifying metadata with
`contentOmittedForTransport: true` inside `content`. Its revision must still
represent the complete record. This must not prevent later records from being
paged. Clients must treat omitted text as unavailable evidence, rather than
claiming to have read it.

Every page repeats `processing`. Background permission does not override
`localOnly`, authorize external AI processing or authorize notifications. For
`ownerApprovedExternal`, the client still needs the owner's separate source and
processing consent. Stop background access promptly on opt-out, scope change,
account switch, signer change or revocation; do not silently restore the grant.

## Invoke, page and reconcile

```json
{
  "version": 1,
  "id": "attempt_a092dcec",
  "capability": "notebook.notes.read",
  "arguments": {"noteId": "welcome"}
}
```

A successful read returns `state: "read"` and a capability-specific `result`.
For the note above, the result might be:

```json
{
  "version": 1,
  "id": "attempt_a092dcec",
  "receipt": "attempt_a092dcec",
  "state": "read",
  "processing": "localOnly",
  "result": {
    "id": "welcome",
    "revision": "rev_23",
    "title": "Launch notes",
    "sourceRef": "notebook:welcome"
  }
}
```

Paged reads should include an opaque `nextCursor` or null, `complete`, and
a `consistency` label such as `bestEffort`. A result may include
`sourceRef`, `sourceRefs`, Unix epoch milliseconds in `asOf`, and a
`freshness` label. Clients follow the cursor until the response marks the
result complete. They must not assume a best-effort cursor is a snapshot.

A confirmed write returns `state: "applied"`. Edits should include the last
observed `expectedRevision` and return `conflict` if it is stale. The
client would send `expectedRevision: "rev_23"` along with a new title for this
note, if it also had a grant for that edit capability. The publisher must
serialize competing writes. Commit a local write and its receipt in the same
transaction, or reserve the request ID durably before dispatching a write
that cannot share the transaction. Associate the ID with the caller identity and a
canonical representation of the request, such as SHA-256 of recursively
sorted JSON object keys. Preserve array order. A different request with the
same ID returns `conflict`. Keep the duplicate protection across scope changes.

For an exact write replay, return a receipt and never apply the write again.
`status` returns the same receipt after checking the current grant, caller
signer, and the account and record scope that produced it. It may
include an opaque record ID, kind, revision or source reference when still in
scope. Exclude full `result` contents and any open intent. An interrupted write
can remain `unknown`; resolve it through a scoped read or owner review before
attempting a fresh write. Reads and opens may run again under current access.

```json
{
  "version": 1,
  "id": "attempt_a092dcec",
  "receipt": "attempt_a092dcec",
  "state": "unknown"
}
```

An open capability returns `state: "requiresApp"` and an immutable,
publisher-created `PendingIntent` as the Bundle's `openIntent`. The client
verifies its creator and opens it only in the foreground. The publisher
should use a short-lived, single-use handoff to a non-exported activity that
rechecks the grant and record scope at launch. Issuing a handoff does not
confirm that the record opened.

## Failures

Protocol failures return `state: "failed"` and a machine-readable `error`.
Common codes are `denied`, `revoked`, `invalidInput`, `unsupported`, `conflict`,
`notFound`, `locked`, `tooLarge`, and `unavailable`. A failure before
the request ID is validated may omit it or return an empty string. Otherwise
echo the ID. Clients reject a response with a different nonempty ID. When a
write may have happened but the publisher cannot confirm it, return `unknown`
instead of a definite failure or success. For calls that cannot complete while
the device is locked, return `locked` without touching records.

## Compatibility checks

Run the [reference project's test client](./example.md) on a disposable Android
emulator. Use separate publisher and client signing keys. Before distributing
an integration, run the same checks against your own release-signed build with
synthetic data. Exercise rejected callers and signers, initial access, consent
cancellation, scope, input validation, read/write/open, write replay, status,
and revocation. Confirm the optimized APK retains the provider, consent
activity, and permission labels.

For the optional extension, also test default-off background access, cancelled
consent and ignored request hints, scope and grant changes between pages,
complete scans larger than a page, native record edits, stable revisions across
ordinary reads, local-only processing and revocation. Test locked-device behavior
against the exact consent and storage policy of your publisher. The reference
fixture includes 123 synthetic notes to exercise complete pagination; its tests
do not establish a production device's scheduling or notification latency.

For Smarter Agent qualification, provide the publisher package ID, the signing
certificate SHA-256 fingerprint of the distributed APK, the supported bridge
version, and the compatibility test results. A signing certificate change
requires a new trust decision. Each installation still requires its owner's
grant.
