# Cross-Platform Host Permission Abstraction (180.C.29.16)

This guide documents the platform-neutral host runtime contract — the interface
defined in **180.C.26.16** (`libs/bellona/host-runtime`) — and the exact contract
a **Windows** host (`180.C.36`) and a **Linux** host (`180.C.37`) implement to
plug in without forking the adapter or command code that the macOS host already
carries.

The whole point of `@bellona/host-runtime`: adapter and command code must **never
branch on `process.platform`**. Each OS ships one `HostRuntime` (its permission
provider + process launcher + screen-capture descriptor) and registers it; the
rest of the host takes a `HostRuntime`, not a platform switch. Adding a platform
is *a new column in one matrix plus three small implementations*, not a rewrite.

Package: `@bellona/host-runtime` (`libs/bellona/host-runtime/src/index.ts`),
version `0.1.0`.

---

## 1. The three contracts a platform implements

A platform supplies exactly three things, then composes them. All live in
`libs/bellona/host-runtime/src/`.

### 1.1 `HostRuntime` — the aggregate (`host-runtime.ts`)

```ts
export interface HostRuntime {
  readonly platform: HostPlatform;                 // 'macos' | 'linux' | 'windows'
  readonly permissions: HostPermissionProvider;
  readonly processes: HostProcessLauncher;
  screenCapture(): HostScreenCaptureCapability | Promise<HostScreenCaptureCapability>;
  permissionRequirements(): readonly HostPermissionRequirement[];
}
```

You do not implement this by hand — you call the factory
`createHostRuntime(options)` (`host-runtime.ts`), which **validates that every
part agrees on the platform** (a Windows launcher cannot be smuggled into a Linux
runtime — it throws) and wires `permissionRequirements()` to the shared matrix:

```ts
const runtime = createHostRuntime({
  platform: 'linux',
  permissions: createLinuxHostPermissionProvider(),
  processes: createLinuxHostProcessLauncher(),
  screenCapture: () => linuxScreenCaptureCapability(),
});
```

The macOS reference does exactly this in
`apps/bellona/remote-host/src/host-runtime-bridge.ts:createMacHostRuntime`, which
adapts the existing macOS TCC detector to the contract and calls
`createHostRuntime({ platform: 'macos', … })`.

### 1.2 `HostPermissionProvider` — detect + guide (`permission-provider.ts`)

```ts
export interface HostPermissionProvider {
  readonly platform: HostPlatform;
  detect(): HostPermissionReport | Promise<HostPermissionReport>;
  requestGuidance(kind: HostPermissionKind): HostPermissionGuidance;
}
```

- `detect()` probes the OS for the **per-capability** grant state and returns a
  `HostPermissionReport`. You should **not** hand-roll the rollup — build the raw
  per-capability states and call the shared
  `buildHostPermissionReport({ platform, checkedAt, states, reasons })`
  (`permission-provider.ts`), so the `not-applicable` / `missing` / `unknown`
  rollup and the required-count logic are identical on every platform.
- `requestGuidance(kind)` returns the OS-specific step-by-step instructions for
  granting one capability (what the operator clicks in System Settings / a portal
  / a UAC prompt).

A grant state is one of (`HostPermissionState`):

| State | Meaning |
| --- | --- |
| `granted` | The OS has granted the capability. |
| `denied` | A **supported** capability the OS refused. |
| `unknown` | Supported but uncheckable right now (e.g. the probe binary is missing). Distinct from `denied`. |
| `not-applicable` | A capability this platform does not support at all. The matrix forces this — a probe can never make an unsupported capability read as `denied`. |

### 1.3 `HostProcessLauncher` — launch/focus (`process-launcher.ts`)

```ts
export interface HostProcessLauncher {
  readonly platform: HostPlatform;
  launch(request: HostProcessLaunchRequest): HostProcessLaunchResult | Promise<…>;
  focus(request: HostProcessFocusRequest): HostProcessFocusResult | Promise<…>;
}
```

`launch` takes an absolute `target` (executable / `.app` / `.desktop` / `.exe`),
optional `args` / `cwd` / `env`, and an `activateExisting` flag (reuse a running
instance and bring it forward instead of spawning a new one). The result reports
the concrete OS `mechanism` used (`open`, `exec`, `ShellExecute`, …), `launched`,
`focused`, and `processId` when the platform exposes it. This thin launcher is the
*only* per-platform difference in app control — the command layer (which DCC,
which args) is platform-neutral.

### 1.4 `HostScreenCaptureCapability` — describe the backend (`screen-capture.ts`)

`screenCapture()` returns a descriptor of the capture backend (e.g.
ScreenCaptureKit on macOS 12+, PipeWire portal / X11 on Linux, DXGI Desktop
Duplication on Windows). The macOS descriptor is
`host-runtime-bridge.ts:macHostScreenCaptureCapability`.

---

## 2. The permission matrix (`host-platform.ts`) — the single source of truth

`host-platform.ts` is where 180.C.36 and 180.C.37 actually "plug in". It defines:

- The platforms: `HOST_PLATFORM_VALUES = ['macos', 'linux', 'windows']`.
- The capability superset (`HOST_PERMISSION_KIND_VALUES`):
  `screen-recording`, `accessibility`, `automation`, `files-and-folders`,
  `local-network`.
- The capability → protocol-scope + label binding (`HOST_PERMISSION_DEFINITIONS`)
  — **platform-neutral**: only the support/required/authority columns vary.
- `PLATFORM_PERMISSION_MATRIX` — the per-platform `(supported, required,
  authority)` for each capability. **This is the one place you add a platform.**

The capability-to-scope binding (stable across all platforms):

| Capability (`HostPermissionKind`) | Protocol scope (`RemotePermissionScope`) | Label |
| --- | --- | --- |
| `screen-recording` | `desktop.observe` | Screen Recording / Capture |
| `accessibility` | `desktop.input` | Accessibility / Synthetic Input |
| `automation` | `process.launch` | Application Automation |
| `files-and-folders` | `file.read` | Files & Folders Access |
| `local-network` | `browser.profile.isolated` | Local Network Access |

### 2.1 What each platform supports / requires (the live matrix)

Transcribed directly from `PLATFORM_PERMISSION_MATRIX` in `host-platform.ts`.
`req` = required for core remote-control function; `sup` = the platform can
detect/grant it at all.

| Capability | macOS | Linux | Windows |
| --- | --- | --- | --- |
| `screen-recording` | sup ✓, **req** ✓ — *macOS TCC* | sup ✓, **req** ✓ — *PipeWire / X11* | sup ✓, **req** ✓ — *DXGI Desktop Duplication* |
| `accessibility` | sup ✓, **req** ✓ — *macOS TCC* | sup ✓, req ✗ — *compositor session* | **sup ✗** — *n/a* |
| `automation` | sup ✓, req ✗ — *macOS TCC (Automation)* | **sup ✗** — *n/a* (app control is process exec) | sup ✓, req ✗ — *Windows UAC* |
| `files-and-folders` | sup ✓, req ✗ — *macOS TCC (Files)* | sup ✓, req ✗ — *POSIX permissions* | sup ✓, req ✗ — *NTFS ACLs* |
| `local-network` | sup ✓, req ✗ — *macOS Local Network* | sup ✓, req ✗ — *firewall (iptables/nft)* | sup ✓, req ✗ — *Windows Defender Firewall* |

Read the differences carefully — they encode real OS behaviour:

- **macOS** gates capture *and* synthetic input behind TCC, and treats app
  control as a separate Automation grant. Capture + input are both required.
- **Linux** mediates capture/input through the compositor (a PipeWire portal on
  Wayland, X11 otherwise) — there is no separate Accessibility OS grant the way
  macOS has, so `accessibility` is *supported but not required* (it is part of the
  same compositor session), and there is **no** OS-level per-app Automation gate,
  so `automation` is **not supported** (`not-applicable`, not "denied").
- **Windows** captures via DXGI with no per-app prompt, and has **no**
  Accessibility-style synthetic-input grant (`not-applicable`); elevation (UAC)
  gates privileged automation.

### 2.2 Helpers a provider uses

- `resolveHostPermissionRequirements(platform)` → the full requirement list for a
  platform (drives the detection set and operator guidance).
- `resolveHostPermissionRequirement(platform, kind)` → one capability's
  requirement.
- `hostPermissionScope(kind)` → the stable protocol scope a capability maps onto.

---

## 3. How a report becomes gateway-visible permissions

Written **once** in `permission-provider.ts`, reused by every platform — a new
host never re-derives this:

- `buildHostPermissionReport(...)` rolls raw per-capability states into a
  `HostPermissionReport` with `missingRequiredCount` and an overall `state`
  (`granted | missing | unknown | not-applicable`). The rollup rules:
  required-denied ⇒ `missing`; required-unknown ⇒ `unknown`; an unsupported-only
  platform ⇒ `not-applicable`; a *non-required* denial is still surfaced as
  `missing`, but a non-required *unknown* never drags an otherwise-granted host
  below `granted`.
- `hostPermissionReportToRemotePermissions(report)` projects the report onto the
  protocol's `RemotePermission[]`. **Granted capabilities become
  `requires-approval`, never auto-`allowed`** — the host still gates each command;
  denied/unknown become `denied`; `not-applicable` capabilities are omitted.
- `applyHostPermissionReportToDevice(device, report)` merges those permissions
  into a `RemoteDevice`, replacing prior host-permission entries (matched by
  scope) and stamping rollup metadata (`hostPermissionState`,
  `hostPermissionMissingRequiredCount`, …) so the gateway sees a consistent shape
  across macOS/Linux/Windows.

This is why a Linux host is **never** falsely reported as "missing a macOS TCC
grant": the unsupported capabilities resolve to `not-applicable` and are dropped
from the projection entirely.

---

## 4. The fail-loud default: `NullHostRuntime`

Before a platform is wired, the honest representation of "real but absent" is
`createNullHostRuntime(platform)` (`host-runtime.ts`). It does **not** fabricate:

- `detect()` reports every *supported* capability as `unknown` ("can't check"),
  never `granted`.
- `requestGuidance()` says the runtime is unconfigured.
- `launch()` / `focus()` / `screenCapture()` **throw**
  `HostRuntimeNotConfiguredError` rather than silently no-op.

This is the correct pattern for an unwired Windows/Linux host today: fail loud,
never fake a grant or a launch. It is the opposite of a stub.

---

## 5. Step-by-step: implementing a new host (180.C.36 Windows / 180.C.37 Linux)

The macOS host is the worked reference
(`apps/bellona/remote-host/src/host-runtime-bridge.ts`). To add a platform:

1. **Confirm the matrix column.** `PLATFORM_PERMISSION_MATRIX[<platform>]` in
   `host-platform.ts` already has Windows and Linux columns (above). If your OS
   behaves differently from what is encoded, *that table* is the single edit — not
   adapter code.

2. **Implement `HostPermissionProvider`.** For each `supported` capability, probe
   the OS and produce a raw `HostPermissionState`; pass the map to
   `buildHostPermissionReport({ platform, checkedAt, states, reasons })`. Do not
   reproduce the rollup. Implement `requestGuidance(kind)` with the real OS steps:
   - *Linux:* check a working PipeWire portal / X11 capture path for
     `screen-recording`; POSIX perms for `files-and-folders`; firewall reachability
     for `local-network`. `automation` is `not-applicable` (the matrix forces it).
   - *Windows:* DXGI availability for `screen-recording`; a UAC/elevation check for
     `automation`; NTFS ACLs for `files-and-folders`; Defender Firewall for
     `local-network`. `accessibility` is `not-applicable`.

3. **Implement `HostProcessLauncher`.** Map `launch`/`focus` onto the OS
   mechanism — Linux: `exec` / `gtk-launch` / freedesktop activation; Windows:
   `ShellExecute` / `start` / activate-existing. Report the real `mechanism`
   string and honour `activateExisting` (fall back to launching with
   `focused: false` if you can't).

4. **Describe `screenCapture()`** — return the backend descriptor (PipeWire/X11
   or DXGI).

5. **Compose with `createHostRuntime({ platform, permissions, processes,
   screenCapture })`** and register it where the macOS bridge is registered. The
   factory's platform-agreement check is your safety net.

Adapter code, the command executor, and the gateway projection need **zero**
changes — they already consume `HostRuntime` and the protocol `RemotePermission[]`
the shared projection produces.

> **Honest scope note.** The macOS provider/launcher are real
> (`host-runtime-bridge.ts` + the macOS TCC detector). Windows (180.C.36) and
> Linux (180.C.37) host *implementations* of these interfaces are the remaining
> work; the **contract, the matrix columns, the shared rollup/projection, and the
> fail-loud `NullHostRuntime`** are all implemented and tested today. Authoring +
> running a real Windows/Linux capture+input path requires the respective OS and
> hardware and is not exercised on the Linux CI box.

---

## 6. Module map

| Concern | File | Key symbols |
| --- | --- | --- |
| Platforms + permission matrix | `host-platform.ts` | `HOST_PLATFORM_VALUES`, `HOST_PERMISSION_KIND_VALUES`, `PLATFORM_PERMISSION_MATRIX`, `resolveHostPermissionRequirements`, `hostPermissionScope` |
| Permission provider + projection | `permission-provider.ts` | `HostPermissionProvider`, `HostPermissionReport`, `buildHostPermissionReport`, `hostPermissionReportToRemotePermissions`, `applyHostPermissionReportToDevice` |
| Process launch/focus | `process-launcher.ts` | `HostProcessLauncher`, `HostProcessLaunchRequest`, `HostProcessLaunchResult` |
| Screen capture descriptor | `screen-capture.ts` | `HostScreenCaptureCapability` |
| Aggregate + factory + fail-loud default | `host-runtime.ts` | `HostRuntime`, `createHostRuntime`, `createNullHostRuntime`, `HostRuntimeNotConfiguredError` |
| macOS reference wiring | `apps/bellona/remote-host/src/host-runtime-bridge.ts` | `createMacHostRuntime`, `createMacHostPermissionProvider`, `createMacHostProcessLauncher`, `macHostScreenCaptureCapability` |

See also: [Architecture §3.1–3.2](./architecture.md) for where host permissions
sit in the trust model, and the
[cross-platform scope ADR](./adr/ADR-0004-cross-platform-remote-host-scope.md).
