# Architecture

This document describes how the plugin runtime fits into NextGram Android. It is
deliberately concrete: every layer has one direction of dependency, and upstream
Telegram code is modified only at named seams.

## 1. Constraints

- Base: Telegram for Android 13.4.3, Java 17 source, `minSdk 23`, `compileSdk 36`.
- Package: `app.nextgram.dev`. Upstream code lives in `org.telegram.*`.
- The app is a single Android process. DEX plugins run in that process.
- The upstream project is merged regularly. Plugin integration must not turn every
  upstream file into a merge conflict.
- No Xposed, no hidden API calls, no patching of `org.telegram.*` classes from plugins.
- The public API must remain stable across upstream Telegram updates.
- Plugin code is not allowed to declare Android components. No plugin activities,
  services, receivers or providers. The host owns every component.

## 2. Layers

```
┌────────────────────────────────────────────────────────────────────┐
│ Upstream Telegram UI and core (org.telegram.*)                     │
│   calls only seams                                                 │
└───────────────────────────────┬────────────────────────────────────┘
                                │ one-way
┌───────────────────────────────▼────────────────────────────────────┐
│ Seams (dev.nextgram.plugin.host.*, dev.nextgram.plugin.ui.*)       │
│   snapshot mapping, boolean fast paths, menu/UI/screen adapters     │
└───────────────────────────────┬────────────────────────────────────┘
                                │
┌───────────────────────────────▼────────────────────────────────────┐
│ Kernel (dev.nextgram.plugin.host.*)                                │
│   boot, registry, installer, class loaders, permissions, events,   │
│   contributions, services, storage, recovery                       │
└───────────────┬───────────────────────────────────┬────────────────┘
                │                                   │
┌───────────────▼─────────────────┐   ┌─────────────▼────────────────┐
│ Public SDK                      │   │ Built-in plugins             │
│ dev.nextgram.plugin.v1.*        │   │ dev.nextgram.builtin.*       │
│ (Java, no org.telegram types)   │   │ compiled into the APK        │
└───────────────▲─────────────────┘   └──────────────────────────────┘
                │ implements
┌───────────────┴─────────────────┐
│ External .ngp plugins           │
│ DEX or QuickJS payload          │
└─────────────────────────────────┘
```

Dependency rules:

1. Upstream may call seams. Seams may call the kernel. The kernel may call the SDK.
   Plugins may call the SDK. Nothing calls back into upstream except through a seam.
2. The public SDK must not import `org.telegram.*`, `TLRPC`, `MessageObject`,
   `BaseFragment`, `Activity` internals or any app-internal class.
3. Built-in plugins may use a privileged internal API. External plugins may not.
4. The kernel must not depend on a specific feature plugin.

### Why not Xposed-style hooks

Xposed and reflection hooks are tempting because they can change anything. They are a
bad foundation for a platform:

- they break on every upstream refactor;
- they expose private fields and objects as an API;
- they have no permission model and no stable contracts;
- they make crash attribution and safe mode almost impossible;
- they encourage every plugin to become a fork of the client.

NextGram uses typed seams and snapshots. A plugin can do less, but what it can do keeps
working across Telegram updates. If a capability is missing, it is added to the SDK
deliberately.

## 3. Kernel

The kernel is always present and is not a plugin. It owns:

- Boot and safe mode.
- Installed plugin registry and package store.
- Package verification and installation.
- Class loading for DEX plugins and QuickJS contexts for script plugins.
- Dependency resolution and load order.
- Permission grants and host API guards.
- Contribution registries (settings, menus, toolbar, decorators).
- Appearance runtime and screen/slot overlay registries.
- Event bus and interceptor chains.
- Service registry.
- Plugin storage, logging and scheduling.
- Installer and permission consent UI.
- Crash attribution and recovery.

The plugin manager list and details screen is a locked system plugin that reads kernel
state. The installer and consent screens stay in the kernel because trust UI must not be
provided by a plugin.

The kernel does **not** own feature logic. If the kernel starts to know about chat
tools, translators or themes as features, the boundary is wrong.

## 4. Plugin model

### 4.1 Kinds

| Kind | Payload | Code | Trust |
| --- | --- | --- | --- |
| `code` | `android/dex/classes.dex` | Kotlin/Java, DEX | Trusted code, signed, not sandboxed |
| `ts` (`script`) | `script/main.js` | TypeScript/JavaScript | Sandboxed QuickJS context |
| `hybrid` | both payloads | TypeScript primary, Java native module | QuickJS plus trusted DEX module |

Each package has exactly one payload. A code plugin can apply a theme through the
appearance API; a code plugin may also create raw views. TypeScript plugins use the
declarative tree and Canvas and cannot create framework views directly. Hybrid packages
combine a TypeScript entry point with an explicit Java native module. Theme packages and the
removed theme payload no longer exist.

### 4.2 Origin

- **System plugin**: compiled into the APK. ID prefix `app.nextgram.builtin.`.
  It is listed in the plugin manager, can be enabled or disabled, and has a
  `core` flag. Core system plugins are locked.
- **External plugin**: loaded from an installed `.ngp`. It can be disabled, updated
  and uninstalled.
- **Developer plugin**: an external plugin installed in developer mode. Unsigned
  packages are accepted only in this mode, with a permanent warning badge.

### 4.3 Identity

- `id` is a reverse-DNS string, lowercase, immutable, for example
  `dev.example.translator`.
- Official IDs are reserved under `app.nextgram.*`.
- The pair `(id, signing certificate)` identifies a plugin across updates.
- A package with an existing ID but a different signing key is a different publisher
  and is rejected as an update. The user must uninstall the old plugin first; plugin
  data is wiped unless the old plugin exported it.
- Version is semver for humans and dependencies; `versionCode` is a monotonic integer
  used for update ordering.

## 5. Boot sequence

```
Application.attachBaseContext
  existing Telegram initialization only

Application.onCreate
  existing Telegram initialization
  PluginRuntime.install(application)
    ├─ read safe-mode state
    ├─ load installed registry (small JSON index)
    ├─ register system plugins
    ├─ resolve dependencies and validate enabled external plugins
    ├─ create class loaders / QuickJS contexts
    ├─ call onLoad for every plugin in dependency order
    ├─ restore the active appearance and screen registrations
    └─ schedule startup performance checkpoint

LaunchActivity.onCreate
  PluginRuntime.onUiAttached(activity)
  build the normal UI, including system plugin contributions

first frame
  PluginRuntime.onFirstFrame()
    ├─ clear the boot-attempt counter
    └─ call onStart for plugins that requested a UI-ready callback
```

`onLoad` runs on the main thread during `Application.onCreate`. It must be fast and
must not touch UI. Plugins that need to do heavy work use `PluginScheduler` and continue
asynchronously.

The startup budget for all external `onLoad` calls is 1.5 seconds on a mid-range
device. Java cannot preempt a running method, so this is a measured target, not a hard
interrupt:

- a plugin whose `onLoad` exceeds 500 ms is disabled after it returns and reported as
  slow;
- if the total exceeds 1.5 s, the kernel stops loading further external plugins and
  continues with the ones already loaded;
- the current plugin still finishes its call, so a pathological plugin can delay
  startup up to its own runtime. Safe mode and the plugin manager make the cause
  visible.

Script plugins are different: QuickJS callbacks can be interrupted at the engine level,
so the script limits are enforced.

## 6. Lifecycle

```
INSTALLED → VERIFIED → ENABLED → LOADED → STARTED → STOPPED → UNLOADED
                                      └───────────────┘
```

Callbacks:

```java
public interface NextGramPlugin {
    void onLoad(PluginContext context);
    void onStart();
    void onStop();
    void onUnload();
    void onAccountStart(int account);
    void onAccountStop(int account);
    void onAppEvent(AppEvent event);
    void onPermissionRevoked(String permission);
}
```

Optional callbacks have no-op implementations in `AbstractNextGramPlugin`. The
interface itself avoids default methods: a plugin class loaded from a separate DEX
cannot dispatch a default method inherited from the host class loader on API 23.

- `onLoad` — register contributions, services, listeners, read configuration. No UI
  access. Called once per process.
- `onStart` — the app is in the foreground and the account state is ready. Start
  listeners, timers and expensive work.
- `onStop` — the app went to the background. Stop work that should not run there.
- `onUnload` — disable or process shutdown. Release resources. Not guaranteed on a
  process kill.
- `onAccountStart` / `onAccountStop` — Telegram account activation and deactivation.
  Account 0 is not special; plugins must use the account id from context.
- `onAppEvent` — coarse app events for plugins that do not need a dedicated listener.

Rules:

- `onLoad`, `onStart`, `onStop` and `onUnload` run on the main thread.
- Callbacks must not block. A callback that runs longer than 100 ms is logged. A
  plugin that repeatedly blocks the main thread is disabled.
- `onLoad` may be called before any account exists. Do not assume an account.
- `onUnload` is best effort. Persistent state must be written before it.
- Enabling, disabling or updating an external code plugin takes effect after a process
  restart in v1. Disabling unregisters contributions immediately, but the class loader
  stays until the process dies. Built-in plugins toggle live. Appearance and screen
  providers are removed on disable, uninstall, revocation and safe mode; the previous
  theme is restored without a restart.

## 7. Class loading (code plugins)

### 7.1 Package layout

```
android/
  dex/
    classes.dex
```

One DEX in v1. The package verifier checks the DEX magic, version and size. The
installer extracts it to:

```
files/plugins/<id>/<versionCode>/android/dex/classes.dex
```

The extracted file is made read-only before loading. Android 14+ requires dynamically
loaded code to be read-only, and the same rule keeps the installed payload immutable.

### 7.2 Loader

```java
DexClassLoader loader = new DexClassLoader(
    dexPath,
    optimizedDir,
    nativeLibraryDir, // null: native libraries are not supported
    hostClassLoader
);
```

- `optimizedDir` is the app code cache. It is ignored on API 26+ and used on older
  versions.
- The loader is created after package verification, never from the downloaded file
  directly.
- The entry class is loaded from `entrypoints.android`, checked for a public no-arg
  constructor, and instantiated once.
- The entry class must implement `NextGramPlugin` from the public SDK.
- Class loader creation and entry class instantiation are wrapped in `PluginGuard`.

### 7.3 Delegation

`PluginClassLoader` extends `DexClassLoader` and uses:

- **Parent first:** `java.*`, `javax.*`, `android.*`, `dalvik.*`, `org.json.*`,
  `dev.nextgram.plugin.v1.*`. The SDK must be the same classes the host uses.
- **Parent first (no shadowing):** `org.telegram.*`. A plugin cannot replace app
  classes. Referencing them is unsupported but not a security boundary.
- **Child first:** everything else. The plugin's own dependencies, including Kotlin
  stdlib and bundled libraries, are isolated from other plugins.

`findClass` rejects any class name in a reserved package (`java.*`, `android.*`,
`javax.*`, `dalvik.*`, `org.telegram.*`, `dev.nextgram.plugin.*`,
`dev.nextgram.builtin.*`). A plugin cannot define a class in those namespaces even if
the host does not have it.

Consequences:

- The public API uses Java types, not Kotlin stdlib types. A Kotlin plugin can bundle
  any compatible stdlib; nothing crosses the API boundary as a Kotlin type.
- Each plugin gets its own copy of a library. Two plugins can use different versions.
- Plugins cannot share classes through dependencies in v1. Plugin-to-plugin
  communication goes through services with SDK-defined interfaces (see sdk.md).
- Plugin resources are assets, not Android resources. A plugin cannot use `R.*` from
  its own package or from a bundled AndroidX library. UI is built from framework
  views and host components. This is a deliberate limitation: `AssetManager`
  resource injection is hidden API and unreliable across Android versions.

Release builds must not obfuscate or shrink the public SDK. R8/ProGuard keeps
`dev.nextgram.plugin.v1.**` names and members, and a release test loads a sample plugin
against the release APK. Obfuscating the SDK would break every external plugin at
runtime even though the debug build works.

### 7.4 Kotlin

Kotlin plugins are first-class, but the app does not provide the Kotlin runtime.
The plugin packages `kotlin-stdlib` into its DEX. R8 shrinks unused code. The SDK
itself is Java so Java and Kotlin plugins see the same API and no Kotlin version is
forced on the host.

### 7.5 Native code

Native libraries are not allowed in v1. A `.so` in an `.ngp` is rejected. Reasons:
ABI matrix, Android 14 W^X rules, signing complexity and a much larger attack surface.
Pure Java/Kotlin plugins cover the intended feature set. Native code remains a core
feature, not a plugin feature.

## 8. Script runtime

Script plugins exist for small integrations that do not need native UI or deep access.
The runtime is implemented in this tree: QuickJS is compiled into the app, wrapped by
the script adapter and wired to the host bridge. `kind: "script"`/`ts` has been part of
the package format since v1.

- Source is TypeScript, compiled at build time to one JavaScript bundle. The app does
  not ship a TypeScript compiler.
- Each plugin runs in its own QuickJS context. QuickJS is chosen for its small size,
  deterministic sandbox and lack of a JIT. The engine (QuickJS or QuickJS-NG) and its
  Android binding are pinned, reviewed and updated with security patches; the runtime
  is hidden behind a small `ScriptRuntime` interface so the engine can be replaced.
- The context has no Android, Java, filesystem or network bindings. It sees only the
  `nextgram` bridge and standard ECMAScript built-ins.
- The bridge exposes JSON-serializable values and asynchronous host calls.
- Limits: 32 MB heap per plugin, 2 s per background callback, 50 ms per UI callback,
  bounded call queue. The host interrupts and disables a plugin that exceeds limits.
- Script plugins can contribute declarative settings, message actions, chat toolbar
  actions and event listeners. They cannot create arbitrary views.
- The manifest and signature rules are identical to code plugins. `kind: "script"`
  selects `script/main.js`.

The script runtime is a separate implementation of the same contribution and event
contracts. It is not a second plugin system.

## 9. Appearance and screen runtime

### 9.1 Appearance

Appearance is a code-plugin capability, not a package kind:

- A code plugin declares `ui.appearance` and applies an `AppearanceTheme` through
  `AppearanceHost`.
- The builder carries a `LIGHT`, `DARK` or `AMOLED` base, semantic
  `AppearancePalette` tokens, raw upstream `Theme.key_*` values and plugin-scoped custom
  colors.
- `AppearanceRuntime` replaces the old theme runtime. It validates the maps, writes an
  `.attheme` file into the app cache, applies it through `Theme.applyThemeFile`, and
  stores the active plugin id, the previous theme key and the custom colors.
- The previous theme is restored on reset, disable, uninstall, critical revocation,
  safe mode or a failed apply. A failed apply leaves the previous theme intact and
  completes the plugin future exceptionally.
- Only one provider is active. The most recent successful apply wins.
- Raw keys are merged after semantic tokens and override them. Unknown raw keys are
  ignored with a warning. Custom colors never touch upstream `Theme` keys.
- There is no `theme/theme.json`, no theme parser, no preview and no theme catalog.

### 9.2 Screen overlay

The screen contract is a host-owned overlay, not a plugin fragment:

- A code plugin declares `ui.screens` and registers a `PluginScreenFactory` for one of
  the five keys: `CHAT_LIST`, `CHAT`, `SETTINGS`, `PROFILE`, `MAIN_NAVIGATION`.
- `PluginScreenRegistry` keeps a per-key stack. The top provider wins; removing it
  restores the previous provider; removing all restores stock.
- `BaseFragment.performCreateView` calls `PluginScreenSeams.attach` after the stock
  view is created. With no provider, the seam is one boolean check and allocates
  nothing.
- With a provider, `PluginScreenOverlay` adds an opaque `FrameLayout` with
  `MATCH_PARENT` as the last child of the stock root. The stock fragment,
  `fragmentView` identity, parent and navigation stack are unchanged.
- `MainTabsActivity.createView` has the one extra seam for `MAIN_NAVIGATION`. It covers
  the bottom tab bar only; the page content remains stock. There is no drawer key.
- `BaseFragment.onResume`, `onPause`, `onFragmentDestroy` and `onBackPressed` drive the
  plugin lifecycle. `onBackPressed` is offered to the plugin first.
- Screen contexts expose permission-checked `Chats` and `Messages`, navigation,
  insets, density, font scale and appearance access. `ChatScreenContext.sendText`
  requires `messages.send` and rejects secret chats.
- `AndroidHost.openScreen` presents a host-owned full-screen fragment for a
  plugin-owned screen. It requires `ui.custom_screens`; the context has a null
  `screenKey`.
- Slots `CHAT_LIST_HEADER` and `SETTINGS_HEADER` are host insertion points, not screen
  replacements. They require `ui.chatlist` and `ui.settings`.
- `PluginScreenRegistry` resolves no provider when the app is locked, no account is
  active, the surface is protected, or the plugin lacks the permission.
- The kernel-owned **Allow screen replacement plugins** switch disables all overlays
  and slots without uninstalling plugins. Safe mode unloads external plugins and clears
  appearance and screen state.
- The stock screen keeps running under the overlay. The trade-off buys navigation,
  lifecycle and upstream stability; detaching stock children is a future optimization.

The public contract is documented in [screens.md](/screens/); the appearance contract
is in [themes.md](/appearance/).

## 10. Contributions

Contributions are declarative items the host renders. Registration returns a handle
that is removed on disable/unload. Screen replacement and slots are separate view
surfaces; they are not declarative descriptors.

| Contribution | Where it appears | v1 |
| --- | --- | --- |
| `SettingsEntry` | NextGram settings | Yes |
| `SettingsScreen` | Plugin settings | Yes |
| `ChatToolbarAction` | Chat overflow menu | Yes |
| `MessageAction` | Message overflow menu | Yes |
| `ChatListAction` | Chat long-press menu | Phase 2 |
| `ProfileAction` | Profile overflow menu | Phase 2 |
| `DrawerItem` | Main drawer | Reserved; no drawer in this tree |
| `ComposerAction` | Attachment panel | Phase 2 |
| `MessageDecorator` | Message bubble badge/footer | Phase 2, experimental |
| `DialogDecorator` | Chat list badge/subtitle | Phase 2, experimental |
| Screen replacement | Five host screens | Yes (`ui.screens`) |
| Slots | Chat list/settings header | Yes (`ui.chatlist`, `ui.settings`) |

Rules:

- Declarative contributions are descriptors, not raw views. The host owns layout, theme,
  insets, accessibility and RTL.
- Screen replacements and slots are raw framework views hosted inside an opaque overlay
  or a host insertion point. The host still owns lifecycle, navigation and insets.
- A contribution has a stable ID within its plugin. Duplicate IDs are rejected.
- Visibility predicates run only when the containing surface is built, never during
  scroll or draw.
- Plugin actions are grouped under the existing "More" menus where possible. This
  keeps the Telegram UI clean and reduces conflicts with upstream menu changes.
- A plugin cannot remove or reorder core Telegram actions. It can add its own.
- Icons are either a host icon name or a plugin asset. No XML vector drawables.

## 11. Events and interceptors

Events notify plugins about host state. Interceptors let a plugin modify or cancel a
specific operation. They are different mechanisms:

- **Event** — read-only snapshot, asynchronous, cannot change the operation.
- **Interceptor** — synchronous, ordered, can mutate or cancel, used only where the
  host explicitly supports it.

Initial events:

- App start/stop/resume/pause.
- Account start/stop.
- Chat opened/closed.
- Message received, sent, edited, deleted.
- Message send failed.
- Theme changed.
- Plugin enabled/disabled (plugin manager only).

Initial interceptors:

- Outgoing text message before send: modify text/entities or cancel.
- Notification before display: modify or cancel (phase 2).

Interceptor rules:

- Only plugins with the relevant permission are called.
- Order is priority, then registration order.
- An interceptor runs on the thread that performs the operation and must return
  within 50 ms. The host measures the call and disables an interceptor that repeatedly
  exceeds the budget, but it cannot preempt a running method; a slow interceptor delays
  that operation.
- Exceptions disable the interceptor for the session and are reported.
- Secret chats are never passed to third-party interceptors.

## 12. Services

Services are replaceable implementations of host-defined interfaces. They are how a
plugin can change behavior rather than add a button.

```java
ServiceKey<TranslationService> TRANSLATION =
    ServiceKey.create("core.translation", TranslationService.class);
```

- The host defines the interface and a default implementation. Built-in features
  register their default implementation as system plugins.
- A plugin can provide an alternative implementation. The user chooses the active
  provider if more than one exists.
- Only one provider is active per key. The kernel falls back to the default when the
  selected provider fails to load.
- Services are resolved lazily. A plugin may provide a service that another plugin
  consumes; the consumer must not assume the provider is loaded at `onLoad`.
- Service interfaces live in the public SDK. Plugin-defined interfaces for other
  plugins are not supported in v1 because separate class loaders would create
  incompatible class identities.

Initial service keys are defined in [sdk.md](/sdk/). The set is intentionally small.

## 13. Threading and performance

- Main thread: lifecycle, UI contributions, menu clicks, settings.
- Plugin background executor: event delivery, storage, network, heavy work. Each
  plugin has a serial executor, so its callbacks do not race each other.
- Kernel hot paths use boolean flags. If no plugin registered a message action, the
  message menu code does not iterate an empty list or allocate a snapshot.
- Snapshots are created only when a contribution or listener is present.
- No plugin code runs during list scroll, message measure or draw in v1.
- Startup targets on a mid-range device:
  - registry parse: < 50 ms;
  - all external `onLoad`: < 1.5 s;
  - memory per idle code plugin: < 3 MB;
  - no frame time regression when no plugin is installed.
- The plugin manager shows the measured load time per plugin. Measurements are
  approximate but make slow plugins visible.

## 14. Failure isolation and safe mode

Every callback is wrapped:

```java
PluginGuard.call(pluginId, () -> plugin.onLoad(context));
```

The guard:

- catches `Exception` and `LinkageError`;
- logs with the plugin ID and a stack trace;
- increments the plugin's failure counter;
- disables the contribution or the plugin after a threshold;
- never lets a plugin exception escape into upstream code.

`OutOfMemoryError` is not caught. Catching it leaves the process in an unknown state.
The next boot uses safe mode.

Safe mode triggers:

- two consecutive cold starts that crash before the first frame while external plugins
  are enabled;
- a plugin crash during `onLoad` that is attributed to that plugin;
- the user explicitly starts the app in safe mode from the plugin manager or an adb
  intent.

Safe mode:

- disables all external plugins;
- resets the active appearance and removes screen/slot providers;
- keeps system plugins and core UI working;
- shows the last crash summary and the plugin that caused it;
- lets the user re-enable plugins one by one;
- clears the boot counter after a successful start.

Crash attribution uses a thread-local plugin frame set by the guard. Uncaught
exceptions in plugin-created raw threads cannot be attributed; plugins should use
`PluginScheduler`, which sets the frame.

## 15. Storage

Each plugin gets private storage:

```
files/plugins/data/<id>/
files/plugins/data/<id>/accounts/<account>/
cache/plugins/<id>/
shared_prefs/nextgram_plugin_<id>.xml
```

- `PluginStorage` provides typed key-value access and a private directory.
- Account-scoped storage is separate from global storage.
- Plugin data is excluded from Android auto-backup by default. Export/import is an
  explicit user action in the plugin manager.
- Uninstall keeps data only if the user chooses "Keep data". Reinstall with a different
  signing key wipes it.
- Plugins must not write to Telegram's own databases or preference files. The API does
  not expose those files, and using them directly is unsupported.
- A future `SecretStorage` API will use the Android Keystore for API keys. In v1,
  plugins that store secrets must warn the user; the private preference file is not
  encrypted.

## 16. Upstream seams

These are the only places where upstream files are modified. Each seam is a small
adapter, not feature logic.

| Upstream file | Seam | Purpose |
| --- | --- | --- |
| `ApplicationLoader` | `PluginRuntime.install`, app lifecycle, crash handler | Boot, safe mode, events |
| `LaunchActivity` | `PluginRuntime` events, `PluginPackageOpener` | UI lifecycle, install intents |
| `NextGramSettingsActivity` | `ContributionRegistry`, `PluginGuard` | NextGram settings and plugin manager entry |
| `ChatActivity` | `PluginChatSeams` | Message menu, toolbar overflow, chat events |
| `AndroidUtilities.openDocument` | `.ngp` detection before generic `ACTION_VIEW` | Install from a chat |
| `AndroidUtilities.openForView` | `.ngp` detection for shared files | Install from a file manager |
| `SendMessagesHelper` | `OutgoingMessageSeam` | Outgoing interceptor |
| `MessagesController` | `PluginMessageEvents` | Message events |
| `UserConfig` | `PluginAccountEvents` | Account activation events |
| `Theme` | `PluginThemeEvents` | Appearance and theme change events |
| `BaseFragment` | `PluginScreenSeams` | Screen overlay attach, lifecycle, back, fast path |
| `MainTabsActivity` | `PluginScreenSeams` | Main navigation tab-bar overlay |
| `NotificationsController` | `NotificationSeams` | Notification interceptor (phase 2) |
| `DialogsActivity` / `ChatsAdapter` | `ChatListSeams` | Chat list actions/decorators (phase 2) |
| `ProfileActivity` | `ProfileSeams` | Profile actions (phase 2) |
| `PasscodeActivity`, `LoginActivity`, `PaymentFormActivity`, secret chat UI | none | Protected surfaces, never resolve a plugin screen |

Seam rules:

- The first line is a static `if (!PluginRuntime.hasX()) return;` check.
- The screen seam is one boolean fast path before any mapping or allocation.
- The seam maps upstream objects to immutable snapshots in the same package; SDK
  never sees `TLRPC` or `MessageObject`.
- The seam catches all plugin exceptions through `PluginGuard`.
- The seam is tested with zero plugins. The no-plugin path must be identical to
  upstream behavior.
- Keep the diff in upstream files to a few lines. Put the logic in
  `dev.nextgram.plugin.host` or `dev.nextgram.plugin.ui` adapters.

## 17. Built-in plugins

Built-in plugins are compiled into the APK but otherwise behave like external plugins:

- They have an ID, a name, a version, permissions and a manifest-equivalent
  descriptor.
- They register contributions and services through the same kernel.
- They are listed in the plugin manager.
- They can be disabled unless marked `core`.
- They may use `dev.nextgram.plugin.host.internal` APIs that external plugins cannot.

The first implementations are `app.nextgram.builtin.pluginmanager` and
`app.nextgram.builtin.community`. Their descriptors are declared in `BuiltInPlugins`,
their entry classes are loaded through the app class loader instead of a
`DexClassLoader`, and they contribute settings entries through the public context.
Plugin Manager is core and locked; Community is a normal feature plugin and can be
disabled. Non-core built-ins toggle at runtime and re-register their contributions
without a restart. Built-ins load in safe mode; safe mode and the external-code switch
only skip external packages.

They are compiled in rather than shipped as preinstalled `.ngp` files for startup
speed and to avoid loading executable packages from read-only app assets. The contracts
are the same, so a future build can ship optional built-ins as preinstalled packages
without changing the plugin API.

The first migration targets:

1. NextGram settings screen and plugin manager entry.
2. Appearance reset and `.attheme` import.
3. Privacy and chat utility toggles that currently live as direct code.
4. Translation and other replaceable services.

Locked system plugins (they use the plugin contracts but cannot be disabled):

- Plugin manager list and details.

Kernel services (not plugins, not replaceable):

- Safe mode and recovery.
- Base navigation and settings shell.
- Authentication and account lifecycle.
- MTProto, storage, crypto, calls and media pipeline.
- Passcode, payments and secret chat surfaces.

This is the honest meaning of "everything is a plugin": every feature is registered
through the same contracts and can be replaced or disabled, while the kernel remains a
small, stable core. The kernel is not a plugin and pretending otherwise would add
failure modes without user value.

## 18. Multi-account

- Every event and snapshot carries an account id.
- Contributions are global by default and may filter by account in their visibility
  predicate.
- Storage has global and per-account scopes.
- Settings are global by default; a plugin may expose per-account settings.
- Background work must specify the account it acts on. There is no implicit "current
  account" in the API.
- Secret chats are excluded for every account.

## 19. Desktop readiness

The container and manifest are platform-neutral:

- `platforms` lists supported platforms.
- `entrypoints` is a map keyed by platform: `android`, later `desktop`.
- Payloads live in platform directories: `android/`, later `desktop/`.
- Shared assets live at the package root.

The v1 SDK is Android-first. Core contracts (identity, lifecycle, events, storage,
permissions) avoid Android types. UI contracts live in an Android subpackage. A
desktop client will add a desktop UI package and a desktop entrypoint; it will not need
a new package format.

## 20. What is not a plugin

- The kernel and its recovery path.
- Authentication, MTProto, storage, crypto, calls, media decoding.
- Android components: activities, services, receivers, providers.
- The plugin installer, permission consent UI and catalog trust UI.
- Secret chats, passcode, payments and Telegram Passport.
- The plugin manager and safe mode.
- Native libraries.
- Theme packages: themes are a code-plugin capability through `ui.appearance`.
- Plugin-owned `BaseFragment` classes, routes or navigation stacks.
- Script and desktop screen replacement.

Anything in this list can still call plugin services, but cannot be replaced by a
plugin in v1.

## 21. Design invariants

1. A plugin can always be disabled without reinstalling the app.
2. A broken plugin must never prevent the app from starting twice in a row.
3. A plugin update cannot change its signing key silently.
4. No plugin code runs in a protected surface.
5. The no-plugin path is unchanged from upstream behavior at the seam level; the screen
   seam allocates nothing when no provider exists.
6. The public SDK never exposes upstream objects.
7. Every SDK breaking change requires a new API major version.
8. A plugin cannot declare an Android component.
9. A plugin cannot add native code.
10. Secret chats never reach third-party plugin views, contexts, events or actions.
11. Missing, disabled, revoked or unloaded plugins cannot keep a theme or a screen.
12. The previous theme is restored on reset, disable, uninstall, revocation and safe
    mode.
13. The stock screen remains the fallback for every screen key and every failure.
