# AGENTS.md — NextGram plugin authoring

Instructions for AI coding agents that build, sign or submit NextGram plugins. Follow
the names and limits exactly: the installer is strict and rejects a package with a clear
`E_*` error instead of guessing.

Read this file before writing code. The full reference is in the NextGram repository:

- [Package format](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/package-format.md)
- [SDK and extension points](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/sdk.md)
- [Appearance API](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/themes.md)
- [Screen replacement and slots](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/screens.md)
- [TypeScript plugins](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/typescript.md)
- [Declarative UI](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/declarative-ui.md)
- [Capabilities](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/capabilities.md)
- [Resources](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/resources.md)
- [Automation](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/automation.md)
- [Internal API](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/internal-api.md)
- [Security model](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/security.md)
- [Distribution and updates](https://github.com/gitwelk/NextGram/blob/main/docs/plugins/distribution.md)

## 1. What you produce

A plugin is one signed `.ngp` package. TypeScript is the primary language.

| Kind | Payload | Author writes | Trust |
| --- | --- | --- | --- |
| `ts` (`script`) | `script/main.js` | TypeScript compiled to one IIFE | QuickJS sandbox |
| `java` (`code`) | `android/dex/classes.dex` | Java or Kotlin compiled to DEX | Trusted code |
| `hybrid` | both payloads | TypeScript entry point plus a Java native module | Trusted code for the DEX part |

`java` is an alias of `code`; `ts` is an alias of `script`. New packages use the new
names. All three kinds install, enable, disable and update. TypeScript-only packages
reload live; hybrid and Java packages need a restart when their DEX changes.

A Java package can apply a color theme with `ui.appearance`, override resources and
replace app screens with `ui.screens`. There is no theme package kind and no
`theme/theme.json`. A package with `kind: "theme"` is rejected with
`E_UNSUPPORTED_KIND` and:
`Theme packages are no longer supported. Ship a code plugin with the ui.appearance permission.`

For a catalog submission you also produce `plugins/<id>/entry.json`, an icon and
optional screenshots in this repository. Never commit a `.ngp`, a keystore or a private
key here.

Target host: NextGram Android 13.4.0, SDK API `1`, `minSdk 23`, `compileSdk 36`.

## 2. Non-negotiable rules

- `id` is lowercase reverse-DNS, 3-128 characters, at least two segments, immutable:
  `^[a-z][a-z0-9]*(\.[a-z0-9][a-z0-9_-]*)+$`. `app.nextgram.*` is reserved.
- `format` is `"ngp"`, `formatVersion` is `1`, `api` is `1`.
- `version` is semver. `versionCode` is a positive integer that must increase on every
  update. The catalog entry and the package manifest must carry the same values.
- A Java package must list `android` in `platforms` and provide `entrypoints.android`.
  A TypeScript package lists `android` or `*` and may omit `entrypoints`.
- A hybrid package provides both payloads; `entrypoints.android` implements
  `NextGramNativeModule` and `nativeMethods` lists every callable method.
- Only one `classes.dex`. No `classes2.dex`, no native libraries, no nested archives,
  no executable scripts.
- Limits: package 64 MB, uncompressed total 192 MB, 4096 entries, `classes.dex` 32 MB,
  `script/main.js` 8 MB, `plugin.json` 256 KB, 200:1 compression ratio per entry.
- `script`/`ts`/`hybrid` and every new permission or resource declaration require
  `minHost`.
- Do not bundle `dev.nextgram.plugin.v1.*` classes. The SDK is `compileOnly`; the host
  provides it at runtime.
- Do not define classes in `java.*`, `javax.*`, `android.*`, `dalvik.*`,
  `org.telegram.*`, `dev.nextgram.plugin.*` or `dev.nextgram.builtin.*`.
- Do not declare Android components: no `Activity`, `Service`, `BroadcastReceiver` or
  `ContentProvider` subclasses. The host owns every component.
- Do not use Android resources or `R.*`. Assets are files under `assets/`, not compiled
  resources. Do not bundle AndroidX for resources; framework views only.
- The entry class must be public, have a public no-arg constructor and extend
  `AbstractNextGramPlugin` (or implement `NextGramPlugin` and all of its methods).
- Request the minimum permissions. Unknown or blocked permissions reject the package.
- `ui.screens` is high risk. Declare it only when the plugin really replaces a screen,
  and never try to render login, passcode, payments, secret chats, the installer, the
  plugin manager or safe mode.
- Code plugins run as trusted code, not in a sandbox. Never add reflection escapes,
  hidden APIs or dynamic code download.

## 3. Source layout

Code plugin:

```text
my-plugin/
  plugin.json
  assets/
    icon.png
    screenshots/
      main.png
  src/
    com/example/myplugin/
      MyPlugin.java
      MySettings.java
  LICENSE
  README.md
```

The official shell builder copies `plugin.json`, `assets/`, the kind payload and the
optional root `LICENSE`, `CHANGELOG.md`, `README.md` and `i18n/`. Other files in the
source directory are not packaged.

## 4. Manifest

Minimal code plugin:

```json
{
  "format": "ngp",
  "formatVersion": 1,
  "id": "com.example.hello",
  "name": "Hello",
  "version": "1.0.0",
  "versionCode": 1,
  "kind": "code",
  "api": 1,
  "minHost": ">=13.4.0",
  "platforms": ["android"],
  "entrypoints": {
    "android": "com.example.hello.HelloPlugin"
  },
  "description": "Adds a settings screen and a message action.",
  "author": {
    "name": "Example Author"
  },
  "license": "MIT",
  "icon": "assets/icon.png",
  "permissions": ["ui.settings", "ui.chat", "messages.read"]
}
```

Rules that are easy to miss:

- `icon` must be a PNG or WebP under `assets/`, at most 2 MB and 1024x1024. Every
  catalog plugin must ship an icon: the manager shows it in the plugin list and the
  plugin must reuse it with `IconRef.asset("assets/icon.png")` in its settings entry.
- `screenshots` is optional, at most 6 paths, each at most 4 MB.
- `homepage`, `source` and `support` must start with `https://`.
- `update` is accepted but ignored. The catalog index is the update source.
- `localization` is validated but the manager does not display it yet.
- `i18n/<locale>.json` is accepted in the package, but the host does not resolve those
  strings yet. Use plain `LocalizedText.of(...)` text.
- `dependencies` and `conflicts` are enforced at install. A required dependency must be
  installed, enabled and inside its semver range; a conflict with an installed plugin
  blocks installation. `provides` is metadata only.
- JSON duplicate keys are rejected. Unknown fields are ignored.

### Permissions

Request only what the plugin uses. Unknown or blocked permissions reject the package.

| Permission | Risk | Unlocks |
| --- | --- | --- |
| `ui.settings` | low | Settings entry |
| `ui.appearance` | low | Blur, avatar shape, theme colors |
| `ui.resources` | high | Fonts, sounds, wallpaper, icons, haptics, motion, chrome |
| `ui.strings` | high | Allowlisted string overrides |
| `ui.chat` | medium | Message actions, chat toolbar actions, chat slots |
| `ui.chatlist` | medium | Chat list slots |
| `ui.screens` | high | Replace a catalogue screen |
| `ui.custom_screens` | low | Open a plugin-owned full-screen view |
| `messages.read` | high | Message text, snapshots and events |
| `messages.send` | high | Send text and media, outgoing interceptor |
| `messages.modify` | high | Edit and delete |
| `messages.react` | medium | Add and remove reactions |
| `messages.automation` | critical | Background automation rules |
| `chats.read` | medium | Dialog snapshots and permissions |
| `chats.members.read` | high | Member lists |
| `chats.join` | medium | Join and leave public chats |
| `chats.create` | high | Create groups and channels |
| `chats.admin` | critical | Ban, mute, promote, pin, edit info, delete for all |
| `notifications.read` | medium | Notification snapshots |
| `notifications.manage` | high | Cancel, update and intercept notifications |
| `network` | medium | HTTPS HTTP client |
| `media.read` | medium | Pick files and read packaged assets |
| `media.write` | high | Send photos, documents, voice and stickers |
| `telegram.actions` | low | Mark read and similar account actions |
| `internal.access` | critical | Typed unstable host facade; `java`/`hybrid` only |
| `clipboard.write` | low | Copy text |
| `accounts.list` | low | Account snapshots |

`messages.background` is accepted for old packages but is inert and never grants
automation. `ui.screens` and the critical permissions are off by default at install.
Blocked and rejected: `secret_chats`, `passcode`, `payments`, `calls`.

Every mutating call checks the signed-in account's Telegram rights. The host never
bypasses a server restriction. Secret chats and protected surfaces are filtered.

## 5. Code API

Entry point:

```java
package com.example.hello;

import dev.nextgram.plugin.v1.AbstractNextGramPlugin;
import dev.nextgram.plugin.v1.Permissions;
import dev.nextgram.plugin.v1.PluginContext;
import dev.nextgram.plugin.v1.ui.IconRef;
import dev.nextgram.plugin.v1.ui.LocalizedText;
import dev.nextgram.plugin.v1.ui.MessageAction;
import dev.nextgram.plugin.v1.ui.SettingsEntry;

public final class HelloPlugin extends AbstractNextGramPlugin {

    @Override
    public void onLoad(PluginContext context) {
        context.contributions().addSettingsEntry(
                SettingsEntry.builder("main")
                        .title(LocalizedText.of("Hello"))
                        .subtitle(LocalizedText.of("Greeting options"))
                        .icon(IconRef.asset("assets/icon.png"))
                        .screen(HelloSettings::new)
                        .build()
        );

        context.contributions().addMessageAction(
                MessageAction.builder("hello")
                        .title(LocalizedText.of("Say hello"))
                        .icon(IconRef.host("msg_info"))
                        .permission(Permissions.MESSAGES_READ)
                        .handler((action, message) ->
                                action.ui().showToast("Hello, " + message.senderName()))
                        .build()
        );
    }
}
```

Settings screen:

```java
package com.example.hello;

import dev.nextgram.plugin.v1.ui.AbstractSettingsScreen;
import dev.nextgram.plugin.v1.ui.SettingsContext;
import dev.nextgram.plugin.v1.ui.SettingsSpec;

public final class HelloSettings extends AbstractSettingsScreen {

    @Override
    public CharSequence title() {
        return "Hello";
    }

    @Override
    public SettingsSpec build(SettingsContext context) {
        return SettingsSpec.builder()
                .section("general", "Greeting")
                .textRow("greeting", "Greeting text", "Hello")
                .switchRow("include_name", "Include sender name", true)
                .sliderRow("scale", "Scale", 1, 50, 100)
                .buttonRow("preview", "Preview", settings ->
                        settings.ui().showToast(settings.preferences()
                                .getString("greeting", "Hello") + ", NextGram!"))
                .infoRow("Built with the NextGram plugin SDK.")
                .build();
    }
}
```

Available context services:

- `info()`, `host()`, `storage()`, `scheduler()`, `logger()`, `ui()`, `permissions()`;
- `accounts()`, `chats()`, `messages()` with read, send, edit, delete, forward and
  reaction methods;
- `chatAdmin()`, `automation()`, `http()`, `media()`, `notifications()`;
- `contributions()`, `events()`, `interceptors()`, `services()`.

`require(AppearanceHost.class)` requires `ui.appearance`.
`require(ResourcesHost.class)` requires `ui.resources`.
`require(AndroidHost.class)` comes from `nextgram-plugin-sdk-android`.
`require(InternalHost.class)` requires `internal.access`, kind `java` or `hybrid`, and
the kernel switch. Use it only when the public API cannot express the task; it is
unstable and may change between host builds.

`AppearanceHost` controls:

- blur: `blurStrength()`, `setBlurStrength(int)`, `resetBlurStrength()`;
- avatar shape: `avatarShape()`, `setAvatarShape(int)`, `resetAvatarShape()` with
  `AVATAR_SHAPE_CIRCLE`, `AVATAR_SHAPE_SQUIRCLE`, `AVATAR_SHAPE_ROUNDED` and
  `AVATAR_SHAPE_SQUARE`;
- theme: `applyTheme(AppearanceTheme)`, `resetTheme()`, `hasTheme()`,
  `themeColor(String, int)` and `customColor(String, int)`. Build a theme from
  `AppearanceTheme.Base.LIGHT`, `DARK` or `AMOLED`, semantic
  `AppearancePalette` tokens, raw `Theme.key_*` values and plugin-scoped custom colors.
  Limits: 256 entries per map, 128-character keys;
- palette compatibility: `applyPalette(AppearancePalette)`, `resetPalette()`,
  `hasPalette()` are wrappers over the same appearance runtime. The most recent
  successful apply wins.

Snapshots are plain Java objects:

- `MessageSnapshot`: `account()`, `dialogId()`, `messageId()`, `date()`, `senderId()`,
  `senderName()`, `outgoing()`, `kind()`, `text()`, `caption()`, `entities()`,
  `secret()`. `text()` and `caption()` are nullable and require `messages.read`.
- `DialogSnapshot`: `account()`, `dialogId()`, `title()`, `group()`, `channel()`,
  `secret()`.
- `AccountSnapshot`: `id()`, `displayName()`, `active()`.

Read methods are `chats().getDialog(...)`, `chats().getDialogs(account, limit)`,
`messages().getMessage(...)`, `messages().getMessages(...)` and
`messages().searchMessages(...)`. Limits are clamped: dialogs and messages 100, search
50. Reads are in-memory only and never trigger a network history load.

Contributions:

- `addSettingsEntry(SettingsEntry)` requires `ui.settings`;
- `addMessageAction(MessageAction)` and `addChatToolbarAction(ChatToolbarAction)`
  require `ui.chat`, plus the action's own `permission` when set;
- `Registration.close()` removes the contribution immediately.

Events:

- `AppLifecycleEvent`, `AccountEvent`, `ChatOpenedEvent`, `ChatClosedEvent`,
  `MessageEvent`, `MessageSendFailedEvent`, `ThemeChangedEvent`, `PluginStateEvent`.
- `subscribe(MessageEvent.class, ...)` requires `messages.read`.
- Listeners run on the plugin's serial background executor. Use
  `scheduler().runOnMain(...)` before touching UI.
- Events are read-only. Secret chats are filtered out.

Outgoing interceptor:

```java
context.interceptors().addOutgoingMessageInterceptor(message -> {
    if (message.text().contains("foo")) {
        message.setText(message.text().replace("foo", "bar"));
    }
});
```

It requires `messages.send`, runs synchronously and must return within 50 ms. Only plain
text is covered. Secret chats are excluded.

Storage and scheduling:

- `storage().global()` and `storage().account(account)` return `PluginPreferences`.
- `storage().filesDir()` and `cacheDir()` are plugin-private.
- `scheduler().runOnMain(...)`, `runOnBackground(...)`, `schedule(...)`,
  `schedulePeriodic(...)`; the minimum period is 15 minutes. Tasks stop when the plugin
  is disabled.

Threading and budgets:

- `onLoad`, `onStart`, `onStop`, `onUnload`, settings callbacks and action handlers run
  on the main thread.
- `onLoad` must finish within 500 ms; other lifecycle callbacks within 100 ms.
- UI calls off the main thread throw `WrongThreadException`.
- Do not log message contents, phone numbers or tokens. Log tag is `ngp/<plugin-id>`.

Not available in this release: contacts, account switching, calls, payments,
secret-chat access, arbitrary WebView or HTML screens, native `.so` plugins and the test
SDK. Do not work around missing APIs with reflection or `org.telegram.*` imports unless
the package is `java`/`hybrid` and the task explicitly needs the internal facade.

## 6. Appearance and screen replacement

### 6.1 Appearance

`ui.appearance` unlocks `require(AppearanceHost.class)`:

```java
AppearanceHost host = context.require(AppearanceHost.class);

host.applyTheme(
        AppearanceTheme.builder(AppearanceTheme.Base.DARK)
                .color(AppearancePalette.WINDOW_BACKGROUND, 0xFF0E1117)
                .color(AppearancePalette.TEXT_PRIMARY, 0xFFF5F7FA)
                .color(AppearancePalette.ACCENT, 0xFF6D8BFF)
                .rawColor("windowBackgroundWhite", 0xFF0E1117)
                .customColor("surfaceRaised", 0xFF1B1E24)
                .build()
).exceptionally(error -> null);

int accent = host.themeColor(AppearancePalette.ACCENT, 0xFF6D8BFF);
int surface = host.customColor("surfaceRaised", 0xFF1B1E24);
host.resetTheme();
```

- Base is `LIGHT`, `DARK` or `AMOLED`; it supplies defaults for missing tokens.
- Semantic tokens are `AppearancePalette.WINDOW_BACKGROUND`,
  `CHAT_BUBBLE_IN`, `ACCENT` and the rest of the constants. Unknown tokens throw
  `IllegalArgumentException`.
- Raw keys are the bare `Theme.key_*` names (`windowBackgroundWhite`, not
  `Theme.key_windowBackgroundWhite`). Unknown keys are dropped with a warning; raw
  keys override semantic mappings.
- Custom keys match `[a-zA-Z0-9._-]{1,128}` and are scoped to the plugin.
- Limits: 256 entries per map and 128-character keys.
- `applyTheme` runs on the main thread and returns a `CompletableFuture<Void>`.
- `applyPalette`, `resetPalette` and `hasPalette` are compatibility wrappers.
- One appearance provider is active. Reset, disable, uninstall, revocation, safe mode or
  a failed apply restores the previous theme.
- There is no `theme/theme.json` and no `kind: "theme"`. Do not ship theme packages.

### 6.2 Screen replacement and slots

`ui.screens` unlocks `Screens.replace` for exactly `CHAT_LIST`, `CHAT`, `SETTINGS`,
`PROFILE` and `MAIN_NAVIGATION`. `ui.custom_screens` unlocks
`AndroidHost.openScreen`. Slots require `ui.chatlist` for `CHAT_LIST_HEADER` and
`ui.settings` for `SETTINGS_HEADER`.

```java
AndroidHost host = context.require(AndroidHost.class);

Registration chatList = host.screens().replace(ScreenKey.CHAT_LIST, ChatListScreen::new);
Registration header = host.screens().addSlot(SlotKey.CHAT_LIST_HEADER, new HeaderContribution());
```

- The plugin returns a normal framework `View` from `PluginScreen.onCreateView`.
- The stock fragment, navigation stack, insets, back handling and lifecycle stay
  host-owned. The stock screen still runs under the overlay.
- `MAIN_NAVIGATION` covers only the tab bar. There is no drawer key.
- The five contexts expose `Chats`, `Messages`, navigation, insets, density, font scale
  and appearance access. `ChatScreenContext.sendText` requires `messages.send`.
- Theme changes call `PluginScreen.onThemeChanged`.
- Rotation recreates the view through the factory; save state in storage or the view's
  saved state.
- `ScreenContext.screenKey()` is `null` for screens opened with `openScreen`.
- Registrations are removed on disable, uninstall, revocation and safe mode.

Protected surfaces never receive plugin views or contexts: login, passcode, payments,
secret chats, installer, consent, safe mode, plugin manager, calls and inactive accounts.
`SharedConfig.appLocked` also resolves to stock. Do not imitate these surfaces. The user
can disable all screen replacement plugins with the kernel switch **Allow screen
replacement plugins**, and safe mode resets appearance and screens.

A plugin cannot provide a `BaseFragment`, `Activity`, `Service`, `BroadcastReceiver` or
`ContentProvider`. It cannot change the navigation stack or another plugin's screen.

## 6.3 TypeScript plugins

Use `nextgram-plugin-ts` from the NextGram repository. A TypeScript package has
`plugin.json`, `script/main.js` after the build and optional `assets/`, `i18n/`:

```bash
cd nextgram-plugin-ts
pnpm install
pnpm --filter @nextgram/cli build
node packages/cli/dist/index.js build path/to/my-plugin
node packages/cli/dist/index.js pack path/to/my-plugin out/my-plugin-1.0.0.ngp
```

The bundle is a single IIFE that assigns `globalThis.__ngp_plugin__`. No CommonJS, no
runtime ESM import, no `node:*`, no `fetch`, no `eval` escape. The host provides
`ctx.storage`, `ctx.ui`, `ctx.screens`, `ctx.messages()`, `ctx.chats()`,
`ctx.chatAdmin()`, `ctx.automation()`, `ctx.http()`, `ctx.media()`,
`ctx.notifications()`, `ctx.resources` and `ctx.native.call`.

Declarative nodes are plain objects from `@nextgram/plugin`:

```ts
import { definePlugin, column, text, button } from "@nextgram/plugin";

export default definePlugin({
  async onLoad(ctx) {
    ctx.screens.replace("chat_list", {
      create: () => column({
        style: { padding: 16, gap: 8 },
        children: [
          text("Chats"),
          button("Refresh", { onPress: "refresh" }),
        ],
      }),
      onAction(action) {
        if (action === "refresh") ctx.ui.invalidate();
      },
    });
  },
});
```

A hybrid package adds a Java module:

```java
public final class MyNativeModule implements NextGramNativeModule {
    @Override public void onLoad(NativeModuleContext context) {}
    @Override public void onUnload() {}
    @Override public Map<String, NativeMethod> methods() {
        return Collections.singletonMap("applyPatch", arguments -> patch(arguments));
    }
}
```

`plugin.json` declares `kind: "hybrid"`, both payloads, `entrypoints.android` and
`nativeMethods: ["applyPatch"]`. TypeScript calls
`await ctx.native.call("applyPatch", { value: 1 })`. A method present in only one list is
unavailable. The call limit is 5 s.

## 6.4 Resources, automation and admin

- `ui.resources` unlocks `require(ResourcesHost.class).apply(appResources)`. Limits:
  font 8 MB each/8 files, sound 5 MB/16 files/60 s, wallpaper 10 MB/4096x4096, icon
  1 MB/512x512/128, string 2,000 chars/200, 32 MB copied assets total. Apply is atomic;
  a failed apply changes nothing.
- `messages.automation` unlocks `ctx.automation()`. Automation is off until the user
  enables the global switch and the per-plugin toggle. Destructive actions need a
  one-time confirmation. Rules run only while the app process is alive in v1.
- `chats.admin` unlocks `ctx.chatAdmin()`. Ban, mute, promote, pin, edit and delete for
  all check the account's real Telegram rights and return `E_TELEGRAM` when the server
  denies the action.

## 7. Build and sign

From the NextGram repository root:

```bash
./gradlew :nextgram-plugin-sdk:compileJava :nextgram-plugin-sdk-android:assembleDebug
docs/plugins/tools/build-ngp.sh path/to/my-plugin out/my-plugin-1.0.0.ngp
```

- The shell builder compiles Java sources only. For Kotlin, use your own Gradle build
  that runs D8 with `--min-api 23`, bundles `kotlin-stdlib` and produces exactly
  `android/dex/classes.dex`, then sign the ZIP as JAR.
- TypeScript, hybrid and CLI packaging use `@nextgram/cli`; see section 6.3.
- The builder uses the newest Android build-tools and `platforms/android-36/android.jar`.
- Without `NGP_KEYSTORE` it creates a temporary development key under the source
  directory. That key must not be used for a catalog release.
- Sign a release with a stable author key:

```bash
NGP_KEYSTORE=/secure/author.p12 \
NGP_KEY_ALIAS=author \
NGP_STORE_PASS=... \
NGP_KEY_PASS=... \
docs/plugins/tools/build-ngp.sh path/to/my-plugin out/my-plugin-1.0.0.ngp
```

- The verifier accepts RSA 2048+ or EC P-256+ with SHA-256, exactly one signer. The
  shell builder signs RSA with `jarsigner`.
- Verify before publishing:

```bash
jarsigner -verify out/my-plugin-1.0.0.ngp
```

- `--unsigned` is for developer-mode testing only. Release builds reject unsigned
  packages outside developer mode.
- First-party `dev.nextgram.*` plugins are released by the `release-plugin` workflow.
  It compiles the SDK, signs with the `FIRSTPARTY_KEYSTORE_BASE64` secret, commits the
  version bump, creates the GitHub Release and rebuilds the index. A merged
  `versionCode` increase is detected by `auto-release-plugin`, and a pushed
  `dev.nextgram.<id>-v<version>` tag is handled by `tag-release-plugin`; both
  dispatch the same workflow automatically. Do not sign a first-party release with a
  local temporary key.

## 8. Test on a device

1. Build and install the debug app.
2. Open the `.ngp` from **Plugins → Install from file** or a file manager.
3. Check the preview: id, version, permissions, signing key fingerprint, icon.
4. Install, restart NextGram when the code plugin asks for it, then check settings and
   actions.
5. Disable and re-enable, uninstall with and without keeping data, and deny a permission
   to confirm the plugin handles `PermissionDeniedException`.
6. Inspect logs: `adb logcat -s 'ngp/<plugin-id>'`.
7. Confirm secret chats never show the contributions.

Common causes of a failed load: missing public no-arg constructor, class name mismatch
with `entrypoints.android`, a bundled SDK class, a bundled Android resource, or DEX built
for the wrong API level.

## 9. Submit to the catalog

1. Copy `templates/entry.json` to `plugins/<id>/entry.json`.
2. Set the same `id`, `name`, `version` and `versionCode` as `plugin.json`.
3. Add `icon.png` or `icon.webp` and optional screenshots under `plugins/<id>/`.
4. Set `source` to the HTTPS repository at the released commit and keep a valid SPDX
   `license`.
5. Add the release:

```json
{
  "version": "1.0.0",
  "versionCode": 1,
  "tag": "com.example.hello-v1.0.0",
  "asset": "com.example.hello-1.0.0.ngp"
}
```

6. Run:

```bash
python3 tools/validate_catalog.py
```

7. Open a pull request with the template. Do not attach the `.ngp` to the pull request.
8. After merge, publish the GitHub Release in this repository with the exact tag and
   asset name. The `publish-index` workflow downloads assets from this repository, not
   from your fork, and rebuilds `catalog/index.json` and `catalog/index.sig`.
   First-party `dev.nextgram.*` plugins use the `release-plugin` workflow instead; it
   bumps the version, builds and signs the package, creates the release and runs
   `publish-index` in one run.

Catalog entry limits: `name` 1-64, `summary` 1-200, at most 10 tags, at most 10 authors,
icon at most 2 MB, screenshots at most 6 and 4 MB each, `presentation.accent` is
`#RRGGBB`, `presentation.cover` is PNG or WebP. Unknown entry fields fail validation.

Updates: publish a new release with a higher `versionCode`, the same plugin `id` and the
same signing key. A different key is rejected as `E_KEY_MISMATCH`; the user must
uninstall first. The app shows the permission diff and never installs silently.

## 10. Rejection codes

| Code | Usual cause |
| --- | --- |
| `E_MANIFEST` | Missing field, wrong type, invalid ID, duplicate permission |
| `E_FORMAT` | `formatVersion` is not `1` |
| `E_PERMISSION` | Unknown or blocked permission |
| `E_PLATFORM` | Code plugin without `android` in `platforms` |
| `E_PAYLOAD` | Missing `classes.dex` or `script/main.js` |
| `E_DEX` | Bad DEX magic, version outside `035`-`039`, more than one DEX |
| `E_SIGNATURE` | Missing, invalid or cross-key signature |
| `E_UNSIGNED` | Unsigned package outside developer mode |
| `E_KEY_MISMATCH` | Update signed by a different key |
| `E_DOWNGRADE` | `versionCode` is not higher than the installed one |
| `E_TOO_LARGE` | Package, entry, asset or ratio limit exceeded |
| `E_UNSAFE_PATH` | `..`, absolute path, backslash, symlink, duplicate or non-NFC name |
| `E_DUPLICATE_ENTRY` | The same ZIP entry appears twice |
| `E_UNSUPPORTED` | A capability removed from this host build |
| `E_UNSUPPORTED_KIND` | `kind: "theme"` was removed; ship a code plugin with `ui.appearance` |
| `E_UNSUPPORTED_API` | `api` is not `1`, `minHost` excludes the host, or the host lacks the capability |

## 11. Definition of done

- [ ] `plugin.json` matches the schema and the catalog entry exactly.
- [ ] The entry class is public, has a no-arg constructor and extends
      `AbstractNextGramPlugin`.
- [ ] Only implemented APIs and permissions are used.
- [ ] Appearance is applied with `AppearanceTheme`; the package has no `theme/` payload.
- [ ] Screen replacement handles rotation, back, insets, RTL and the protected-surface
      rules; it never imitates login, passcode, payments, secret chats, the installer,
      the plugin manager or safe mode.
- [ ] The dashboard, settings and actions work after a restart.
- [ ] Permission denial is handled without a crash.
- [ ] No secret chats, no Android components, no resources, no native code.
- [ ] The package is signed with the author key and `jarsigner -verify` passes.
- [ ] `python3 tools/validate_catalog.py` passes.
- [ ] The release tag and asset name match `entry.json`, and the asset is attached to a
      release in this repository.
- [ ] No keys, keystores or `.ngp` files are committed.
