NextGram/plugins Build a plugin SDK & extension points

SDK and Extension Points

The public API: lifecycle, context, permissions, events, contributions and services.

The public SDK is the only supported way for a plugin to touch NextGram. It is versioned, typed and deliberately smaller than the app's internal API. If a feature is not in the SDK, a plugin cannot use it; adding a new capability is a deliberate API change, not a reflection trick.

0. Implementation status#

This document describes the shipped v1 API. The maximum-capability slice is present in the tree:

  • lifecycle callbacks, plugin info, host info, storage, scheduler, logger, permissions, declarative settings, message actions, chat toolbar actions and services;
  • accounts(), chats() and messages() with read, send, edit, delete, forward, reaction, typing and draft methods;
  • chatAdmin(), automation(), http(), media() and notifications();
  • require(AppearanceHost.class), require(ResourcesHost.class), require(AndroidHost.class) and, for trusted kinds only, require(InternalHost.class);
  • declarative UI trees, Canvas, screens, slots and the expanded screen catalogue;
  • outgoing message and notification interceptors;
  • the TypeScript SDK (@nextgram/plugin), CLI (@nextgram/cli) and QuickJS bridge.

The source of truth for the actual surface is nextgram-plugin-sdk/, nextgram-plugin-sdk-android/, nextgram-plugin-sdk-internal/, nextgram-plugin-ts/ and TMessagesProj/src/main/java/dev/nextgram/plugin/.

See capabilities.md, resources.md, automation.md, declarative-ui.md, typescript.md and internal-api.md for the new surfaces. The stable formatVersion and api stay 1.

1. Artifact and packages#

ArtifactContentsStatus
dev.nextgram:plugin-sdk-v1Core contracts, data snapshots, permissions, settings specAvailable as nextgram-plugin-sdk
dev.nextgram:plugin-sdk-v1-androidAndroid host, screen/slot contracts, view creationAvailable as nextgram-plugin-sdk-android
dev.nextgram:plugin-sdk-v1-internalUnstable typed facade for trusted Java and hybrid packagesAvailable as nextgram-plugin-sdk-internal
dev.nextgram:plugin-sdk-v1-testFake host, JUnit rules, snapshot fixturesPlanned
@nextgram/pluginTypeScript types and helpers for script pluginsAvailable in nextgram-plugin-ts/packages/plugin
@nextgram/cliTypeScript build and .ngp packagingAvailable in nextgram-plugin-ts/packages/cli

The repository modules today are nextgram-plugin-sdk, nextgram-plugin-sdk-android and nextgram-plugin-sdk-internal. The TypeScript packages live in nextgram-plugin-ts/packages. The test module is still planned.

Packages:

text
dev.nextgram.plugin.v1              core, platform-neutral
dev.nextgram.plugin.v1.events       event types
dev.nextgram.plugin.v1.services     service types
dev.nextgram.plugin.v1.ui           declarative settings and actions
dev.nextgram.plugin.v1.android      Android views, screens and slots
dev.nextgram.plugin.v1.test         test host (planned)

The SDK modules are compileOnly for plugins. The host provides the classes at runtime. A plugin must not bundle dev.nextgram.plugin.v1.* classes.

Plugin builds use compileSdk 36, minSdk 23, Java 17 source and core library desugaring, matching the host. The Gradle plugin configures D8 with --min-api 23. Plugin authors must test on API 23; the SDK does not guarantee APIs that are missing from the oldest supported Android version.

The SDK is Java-first. Kotlin plugins use the same interfaces and may bundle their own Kotlin runtime. No Kotlin-specific type crosses the API boundary, so two plugins can use different Kotlin versions without conflicts.

2. Entry point#

java
package dev.example.hello;

import dev.nextgram.plugin.v1.AbstractNextGramPlugin;
import dev.nextgram.plugin.v1.PluginContext;

public final class HelloPlugin extends AbstractNextGramPlugin {
    @Override
    public void onLoad(PluginContext context) {
        // register contributions
    }
}

Rules:

  • public class;
  • public no-arg constructor;
  • implements NextGramPlugin or extends AbstractNextGramPlugin;
  • referenced by entrypoints.android in the manifest;
  • no static initialization that does heavy work or touches Android UI;
  • no Android Application, Activity, Service, BroadcastReceiver or ContentProvider subclasses.

3. Lifecycle#

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. Extend it instead of implementing every method:

java
public abstract class AbstractNextGramPlugin implements NextGramPlugin {
    @Override public void onStart() {}
    @Override public void onStop() {}
    @Override public void onUnload() {}
    // ...
}

The SDK avoids interface default methods because plugins compile to a separate DEX. On API 23 the platform cannot dispatch a default method inherited from the host class loader, so default methods would fail at runtime.

CallbackThreadWhen
onLoadmainOnce per process, after verification and class loading
onStartmainApp foreground, account state ready
onStopmainApp background
onUnloadmainDisable or process shutdown, best effort
onAccountStartmainA Telegram account becomes active
onAccountStopmainA Telegram account becomes inactive
onAppEventmainCoarse app lifecycle events
onPermissionRevokedmainThe user revoked a permission; stop using the API

onLoad must complete within 500 ms. Register contributions and return; use PluginScheduler for anything heavier. onStart, onStop and onUnload have a 100 ms budget. The host measures these callbacks and disables a plugin after repeated violations. It cannot preempt a running method, so a slow callback delays its caller; code plugins are expected to cooperate, while script plugins are interrupted by the engine.

4. Context#

java
public interface PluginContext {
    PluginInfo info();
    HostInfo host();

    PluginStorage storage();
    PluginScheduler scheduler();
    PluginLogger logger();
    PluginUi ui();

    PluginPermissions permissions();
    Contributions contributions();
    Events events();
    Interceptors interceptors();
    Services services();

    Accounts accounts();
    Chats chats();
    Messages messages();
    Contacts contacts();
    Media media();
    Notifications notifications();
    TelegramActions telegram();

    <T extends PlatformHost> T require(Class<T> type);
}

The current PluginContext exposes accounts(), chats() and messages() read-only. contacts(), media(), notifications() and telegram() do not exist in the SDK yet. require(...) currently supports AppearanceHost and AndroidHost; any other platform host throws UnsupportedOperationException. Plugin code must not call the target-only methods.

The current context is:

java
public interface PluginContext {
    PluginInfo info();
    HostInfo host();
    PluginStorage storage();
    PluginScheduler scheduler();
    PluginLogger logger();
    PluginUi ui();
    PluginPermissions permissions();
    Accounts accounts();
    Chats chats();
    Messages messages();
    Contributions contributions();
    Events events();
    Interceptors interceptors();
    Services services();
    <T extends PlatformHost> T require(Class<T> type);
}

PluginContext is valid until onUnload. Do not store it in static fields of the plugin beyond the plugin's own lifetime; the host may create a new context after a restart.

5. Data snapshots#

Plugins never receive TLRPC.*, MessageObject, TLObject, BaseFragment, ChatActivity or any other upstream class. The host maps data to immutable snapshots. This keeps the public API stable when Telegram changes its internals.

Current snapshots: AccountSnapshot, DialogSnapshot and MessageSnapshot. UserSnapshot exists as a type but is not produced by the host, and media/reply snapshots are design targets.

java
public interface MessageSnapshot {
    int account();
    long dialogId();
    int messageId();
    long date();
    long senderId();
    String senderName();         // nullable, resolved display name
    boolean outgoing();
    MessageKind kind();          // TEXT, PHOTO, VIDEO, FILE, VOICE, STICKER, ...
    String text();               // nullable; requires messages.read
    String caption();            // nullable
    List<MessageEntity> entities();
    boolean secret();            // always false for third-party plugins
}

Account and dialog snapshots follow the same defensive-copy rule. Media, reply, user, chat and notification snapshots are targets. A plugin cannot mutate Telegram state through a snapshot.

Snapshots do not contain phone numbers, access hashes, auth keys, raw file paths or secret chat data unless the relevant permission explicitly allows the field.

6. Permissions#

Permissions are declared in the manifest and granted by the user at install or update. They gate host API calls. They are not a sandbox for DEX code; see security.md.

java
public interface PluginPermissions {
    boolean isGranted(String permission);
    void require(String permission) throws PermissionDeniedException;
    Set<String> granted();
}

Names are stable strings exposed as constants in Permissions.

6.1 Permission catalogue#

PermissionRiskGrants
ui.settingslowAdd a settings entry/screen and the settings header slot
ui.appearancelowBlur strength, avatar shape, code themes and custom colors through AppearanceHost
ui.chatmediumChat toolbar and message actions; chat slots are reserved
ui.chatlistmediumChat list actions, decorations and the chat list header slot
ui.profilemediumProfile actions; profile slots are reserved
ui.drawerlowReserved; this tree has no classic drawer
ui.composermediumAttachment/composer actions
ui.screenshighReplace CHAT_LIST, CHAT, SETTINGS, PROFILE and MAIN_NAVIGATION with plugin views
ui.custom_screenslowOpen a plugin-owned full-screen view with AndroidHost.openScreen
messages.readhighRead message text, entities and metadata
messages.sendhighSend text messages through the host API
messages.modifyhighEdit, delete and forward messages
messages.backgroundcriticalAct on messages without a foreground user action
chats.readmediumRead dialog and chat metadata
users.readmediumRead user profiles
contacts.readhighRead the contact list
media.readhighRead media metadata and download media
media.writemediumSave or share media
notifications.readhighRead notification content
notifications.managemediumModify or cancel notifications
accounts.listlowList Telegram accounts
accounts.switchmediumSwitch the active account
telegram.actionshighMark read, mute, archive, pin and similar actions
networkmediumUse the host HTTP API; for DEX code this is declarative only
clipboard.readhighRead the clipboard through the host API
clipboard.writelowWrite to the clipboard through the host API
locationhighRequest location through the host API
backgroundmediumRun scheduled work while the app process is alive

Blocked for third-party plugins in v1:

  • secret_chats
  • passcode
  • payments
  • calls

These names are not grantable. A package that requests them is rejected. System plugins may use internal APIs for these areas.

6.2 Grant defaults#

  • Low-risk UI permissions are pre-selected on the install screen and remain visible.
  • Medium, high and critical permissions are off by default. ui.screens is high risk and starts off at install.
  • messages.background requires a separate confirmation and is audited.
  • The kernel-owned Allow screen replacement plugins switch defaults on and can disable all screen overlays without uninstalling plugins.
  • A plugin update that adds permissions requires a new consent. Declining cancels the update.
  • The user can revoke permissions later in the plugin details screen. The plugin remains installed; API calls fail with PermissionDeniedException, and the plugin receives onPermissionRevoked.

6.3 API enforcement#

Each access object checks the permission before returning data or performing an action. The check is implemented in the host, not in the plugin. Annotations are documentation:

java
@RequiresPermission(Permissions.MESSAGES_READ)
MessageSnapshot getMessage(long dialogId, int messageId);

The host logs permission denials with the plugin ID and the API method. Repeated denials are shown in the plugin details.

Current enforcement covers settings/message/toolbar contributions, message event subscription, outgoing interceptor registration, clipboard.write, accounts.list, chats.read, messages.read, appearance calls, screen registration and slot registration. Permissions such as network and clipboard.read are not enforced yet because their host methods do not exist. Do not treat the permission catalogue as a complete sandbox.

7. Accounts#

Status: read-only delivered. switchTo is target-only.

java
public interface Accounts {
    List<AccountSnapshot> list();   // accounts.list
    int current();                  // accounts.list
}
  • Only activated accounts are returned.
  • current() returns the selected activated account, otherwise the first activated account, otherwise -1.
  • Every data call carries an account id.
  • There is no implicit "current account" in the API.
  • Background work must specify its account.
  • Account switching requires a user action and is not exposed yet.

8. Chats and messages#

Status: read-only delivered. DialogSnapshot and MessageSnapshot are used by the read API, message actions and events. Send, edit, delete and Telegram actions are target-only in the core Messages API. ChatScreenContext.sendText is delivered for text messages in a replaced chat screen.

8.1 Read#

java
public interface Chats {
    @RequiresPermission(Permissions.CHATS_READ)
    DialogSnapshot getDialog(int account, long dialogId);

    @RequiresPermission(Permissions.CHATS_READ)
    List<DialogSnapshot> getDialogs(int account, int limit); // max 100 per call
}

public interface Messages {
    @RequiresPermission(Permissions.MESSAGES_READ)
    MessageSnapshot getMessage(int account, long dialogId, int messageId);

    @RequiresPermission(Permissions.MESSAGES_READ)
    List<MessageSnapshot> getMessages(int account, long dialogId, int limit, int offset); // max 100

    @RequiresPermission(Permissions.MESSAGES_READ)
    List<MessageSnapshot> searchMessages(int account, long dialogId, String query, int limit); // max 50
}
  • Reads are in-memory only. They do not trigger a network history load.
  • Search is a bounded, case-insensitive substring search over loaded text and captions, not a server-side search.
  • Limits and offsets are clamped. Zero returns an empty result.
  • Rate limits are not enforced yet.
  • Secret chats are filtered out before the API boundary. A plugin cannot request them by id, search them, or receive their events.

8.2 Send, edit, delete#

java
public interface Messages {
    @RequiresPermission(Permissions.MESSAGES_SEND)
    CompletableFuture<MessageSnapshot> sendText(SendTextRequest request);

    @RequiresPermission(Permissions.MESSAGES_MODIFY)
    CompletableFuture<MessageSnapshot> editText(EditTextRequest request);

    @RequiresPermission(Permissions.MESSAGES_MODIFY)
    CompletableFuture<Void> deleteMessages(long dialogId, int... messageIds);
}

SendTextRequest:

java
SendTextRequest.builder()
    .account(0)
    .dialogId(dialogId)
    .text("Hello")
    .replyToMessageId(messageId)   // optional
    .silent(true)                  // optional
    .build();

Rules:

  • A send initiated by a plugin UI click is user-initiated and runs normally.
  • A send from a background callback requires messages.background and shows a host confirmation unless the user enabled background sends for that plugin.
  • The host enforces rate limits: 20 messages/minute and 500/day per plugin by default.
  • The host records an audit entry for every plugin-initiated send, edit and delete.
  • The host rejects sends to secret chats, channels where the account cannot post, and messages that violate Telegram limits.
  • Media sending is not part of API v1. It is planned with an explicit attachment model.

8.3 Telegram actions#

java
public interface TelegramActions {
    @RequiresPermission(Permissions.TELEGRAM_ACTIONS)
    CompletableFuture<Void> markAsRead(long dialogId);

    @RequiresPermission(Permissions.TELEGRAM_ACTIONS)
    CompletableFuture<Void> muteDialog(long dialogId, long untilDate);

    @RequiresPermission(Permissions.TELEGRAM_ACTIONS)
    CompletableFuture<Void> archiveDialog(long dialogId, boolean archive);
}

The set is intentionally small. Dangerous actions such as leaving a chat, deleting a chat, transferring ownership or changing privacy settings are not exposed in v1.

8.4 Contacts, media and notifications#

java
public interface Contacts {
    @RequiresPermission(Permissions.USERS_READ)
    UserSnapshot getUser(long userId);

    @RequiresPermission(Permissions.CONTACTS_READ)
    List<UserSnapshot> getContacts(int limit); // max 500

    @RequiresPermission(Permissions.USERS_READ)
    List<UserSnapshot> searchUsers(String query, int limit); // max 50
}
  • Media in v1 is metadata on MessageSnapshot.media(). A download/save API is phase 2; media.read is reserved for it.
  • Notifications in v1 are available through the notification interceptor, not a bulk read API. notifications.read gates the notification content passed to the interceptor.
  • Secret chat contacts and media are filtered out like messages.

9. Events#

java
public interface Events {
    <T extends Event> Subscription subscribe(Class<T> type, EventListener<T> listener);
    <T extends Event> Subscription subscribe(
        Class<T> type, EventPriority priority, EventListener<T> listener);
}

public interface EventListener<T> {
    void onEvent(T event);
}

public interface Subscription extends AutoCloseable {
    @Override void close();
}

Events are read-only. They run on the plugin's serial background executor, so a slow listener does not block the UI or another plugin. Use PluginScheduler.runOnMain for UI. Subscriptions are removed automatically on unload. Events that carry message content require the matching read permission; without it, the event is not delivered.

Current emission:

EventStatus
AppLifecycleEventSTART, RESUME, PAUSE, STOP emitted; onStart/onStop are paired
AccountEventemitted on account activation and logout
ChatOpenedEventemitted when a non-secret chat becomes fully visible
ChatClosedEventemitted when a non-secret chat fragment is destroyed
ThemeChangedEventemitted after an appearance apply or reset; duplicates are suppressed
PluginStateEventemitted on enable, disable and uninstall
MessageEventemitted for normal received, sent, edited and deleted messages; secret, scheduled, quick-reply and welcome messages are excluded; received/deleted events are deduplicated
MessageSendFailedEventemitted when a send fails; errorCode may be 0 when upstream has no TL_error

Target events:

EventFields
AppLifecycleEventSTART, RESUME, PAUSE, STOP
AccountEventaccount, STARTED, STOPPED
ChatOpenedEventaccount, dialog snapshot
ChatClosedEventaccount, dialog id
MessageEventaccount, RECEIVED, SENT, EDITED, DELETED, message snapshot
MessageSendFailedEventaccount, dialog id, error code
ThemeChangedEventtheme id, dark/light
PluginStateEventplugin id, enabled/disabled (plugin manager only)

Delivery order is priority (HIGH, NORMAL, LOW), then registration order. An exception in a listener is logged and does not stop other listeners.

Events are not a firehose of every Telegram update. Adding a new event is an API change with a privacy review. Plugins that need raw update streams cannot get them in v1; this is deliberate for account safety and API stability.

10. Interceptors#

Interceptors change an operation. They run synchronously on the operation thread and must return within 50 ms.

Status: the outgoing text interceptor is wired through SendMessagesHelper; only plain text messages are covered. The notification interceptor is wired through NotificationsController for per-chat notifications. Secret chats are excluded from both paths.

java
public interface Interceptors {
    Registration addOutgoingMessageInterceptor(OutgoingMessageInterceptor interceptor);
    Registration addNotificationInterceptor(NotificationInterceptor interceptor);
}

public interface NotificationInterceptor {
    void intercept(NotificationContext context);
}

public interface NotificationContext {
    int account();
    long dialogId();
    String title();
    String text();
    String channelId();
    void setTitle(String title);
    void setText(String text);
    void setChannelId(String channelId);
    void cancel();
    boolean isCancelled();
}

public interface OutgoingMessageInterceptor {
    void intercept(OutgoingMessageContext context);
}

public interface OutgoingMessageContext {
    int account();
    long dialogId();
    String text();
    List<MessageEntity> entities();
    void setText(String text);
    void setEntities(List<MessageEntity> entities);
    void cancel();
    boolean isCancelled();
}

Rules:

  • messages.send is required to modify or cancel an outgoing message; notifications.manage is required to modify or cancel a notification.
  • Interceptors run in priority order; each sees the previous interceptor's changes.
  • The 50 ms per-interceptor and 150 ms total budgets are measured, not preemptive. A slow chain leaves the operation unmodified and records a timeout.
  • Cancelling stops the send and shows the host's normal "message not sent" state.
  • Secret chats never reach an interceptor.
  • A plugin cannot send a new message from an interceptor; it can only modify or cancel the message the user is already sending.
  • Interceptors are audited and can be disabled by the user in the plugin details.

11. Contributions#

Contributions are declarative. The host owns rendering, theming, accessibility and layout.

java
public interface Contributions {
    Registration addSettingsEntry(SettingsEntry entry);
    Registration addMessageAction(MessageAction action);
    Registration addChatToolbarAction(ChatToolbarAction action);

    // phase 2, experimental
    Registration addChatListAction(ChatListAction action);
    Registration addProfileAction(ProfileAction action);
    Registration addDrawerItem(DrawerItem item);
    Registration addComposerAction(ComposerAction action);
    Registration addMessageDecorator(MessageDecorator decorator);
    Registration addDialogDecorator(DialogDecorator decorator);
}

Current contributions are SettingsEntry, MessageAction and ChatToolbarAction. Every item marked phase 2 is absent from the SDK and from the host.

11.1 Common descriptors#

java
LocalizedText.of("Translate")
LocalizedText.key("translate.title", "Translate")
IconRef.host("msg_info")
IconRef.asset("assets/translate.webp")
  • LocalizedText resolves from i18n/<locale>.json, then the fallback, then English. The file is a flat JSON object of string keys to strings, up to 128 KB.
  • IconRef.host uses a host icon name. The set is documented and stable.
  • IconRef.asset must be a PNG or WebP under assets/. Use the plugin's own catalog icon so the same artwork appears in the plugin manager and in the settings entry.
  • Registration.close() removes the contribution immediately.
  • IDs are stable within a plugin. Duplicate IDs are rejected.

11.2 Settings#

java
context.contributions().addSettingsEntry(
    SettingsEntry.builder("general")
        .title(LocalizedText.of("Hello settings"))
        .subtitle(LocalizedText.of("Greeting options"))
        .icon(IconRef.asset("assets/icon.png"))
        .screen(HelloSettings::new)
        .build()
);

The host lists the entry in the NextGram settings screen under the plugin settings section. A tap opens the declarative screen in a host-owned settings activity, so the plugin needs no activity or view of its own.

An entry can run an action instead of opening a declarative screen:

java
SettingsEntry.builder("open-manager")
    .title(LocalizedText.of("Plugins"))
    .action(context -> context.ui().showToast("Plugin manager"))
    .build()

A settings screen is declarative. Extend AbstractSettingsScreen to skip the optional onChanged callback:

java
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", "General")
            .switchRow("enabled", "Enabled", true)
            .textRow("name", "Your name", "World", false)
            .selectorRow("language", "Language", "English", List.of("English", "Русский"))
            .sliderRow("scale", "Scale", 1, 50, 100)
            .buttonRow("preview", "Preview", ctx -> ctx.ui().showToast("Hello"))
            .infoRow("Changes apply immediately.")
            .build();
    }

    @Override
    public void onChanged(String key) {
        // optional side effects
    }
}

Supported rows in v1:

  • section header;
  • switch;
  • text input (opens a host input dialog);
  • number input;
  • single-choice selector (opens a host bottom sheet);
  • integer slider with a minimum, maximum and default value;
  • button;
  • info text;
  • divider;
  • custom row via AndroidHost if the screen is opened as a full plugin screen, not in the declarative list.

The host stores values in the plugin's PluginPreferences, keyed by the row key. A plugin can read the same key through PluginStorage. This keeps the settings API small and gives the host control over validation, theming and localization.

Custom screens use the Android host:

java
public final class AdvancedScreen implements PluginScreen {
    @Override
    public View onCreateView(ScreenContext context) {
        LinearLayout layout = new LinearLayout(context.context());
        return layout;
    }
}

context.require(AndroidHost.class).openScreen(new AdvancedScreen()) opens it and requires ui.custom_screens. The host owns the activity, fragment, toolbar, insets, lifecycle and back handling. The plugin returns only the content view. It must not assume that its view survives a configuration change; state must be saved in plugin storage or the view's saved state. See screens.md for the full contract.

11.3 Appearance#

The appearance permission is declared as ui.appearance. Blur values are integers from 1 to 100, where 50 is the default look, values below 50 weaken the blur and values above 50 strengthen it.

java
int strength = context.storage().global().getInt("blur_strength", 50);
context.require(AppearanceHost.class).setBlurStrength(strength);

AppearanceHost exposes blurStrength(), setBlurStrength(int) and resetBlurStrength(). Existing screens keep the blur they were built with; new screens use the new value, and the main panels refresh after the next app restart. Disabling or uninstalling the plugin restores the default.

Avatar shape is global and uses AVATAR_SHAPE_CIRCLE, AVATAR_SHAPE_SQUIRCLE, AVATAR_SHAPE_ROUNDED and AVATAR_SHAPE_SQUARE:

java
AppearanceHost host = context.require(AppearanceHost.class);
host.setAvatarShape(AppearanceHost.AVATAR_SHAPE_SQUIRCLE);
int current = host.avatarShape();
host.resetAvatarShape();

avatarShape() returns the effective shape, including a shape set by another plugin. Only one plugin owns the shape at a time; the last writer wins and reset affects only that writer.

A code plugin can apply a complete theme, a semantic palette or a mix of both through AppearanceHost:

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

host.applyTheme(
    AppearanceTheme.builder(AppearanceTheme.Base.DARK)
        .color(AppearancePalette.WINDOW_BACKGROUND, 0xFF141218)
        .color(AppearancePalette.TEXT_PRIMARY, 0xFFE6E0E9)
        .color(AppearancePalette.ACCENT, 0xFFD0BCFF)
        .rawColor("windowBackgroundWhite", 0xFF141218)
        .customColor("surfaceRaised", 0xFF1B1E24)
        .build()
);

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

applyTheme requires ui.appearance, is marshalled onto the main thread and returns a CompletableFuture<Void> that completes exceptionally on failure. Semantic tokens are validated by the builder; raw upstream keys are merged after semantic colors and override them; unknown raw keys are dropped with a warning. Custom colors are scoped to the plugin and are never written to upstream theme keys. Limits are 256 entries per map and 128-character keys. See themes.md for the token set, raw-key rules, apply/reset semantics, persistence and safe mode.

The legacy palette API is a compatibility wrapper over the same runtime:

java
host.applyPalette(
    AppearancePalette.builder(AppearancePalette.Base.DARK)
        .color(AppearancePalette.WINDOW_BACKGROUND, 0xFF141218)
        .color(AppearancePalette.TEXT_PRIMARY, 0xFFE6E0E9)
        .color(AppearancePalette.ACCENT, 0xFFD0BCFF)
        .build()
);

host.resetPalette();
boolean active = host.hasPalette();

resetPalette() reverts to the theme that was active before the palette; hasPalette() reports whether this plugin's palette is currently applied. There is no theme plugin kind: a code plugin with ui.appearance is the only theme provider.

11.4 Message actions#

java
context.contributions().addMessageAction(
    MessageAction.builder("translate")
        .title(LocalizedText.of("Translate"))
        .icon(IconRef.host("msg_info"))
        .permission(Permissions.MESSAGES_READ)
        .visible(context -> context.message().text() != null)
        .handler((context, message) -> {
            context.ui().showDialog(
                DialogSpec.builder()
                    .title("Translation")
                    .message("...")
                    .positive("Copy", () -> context.ui().copyToClipboard("..."))
                    .build()
            );
        })
        .build()
);
  • Actions appear in the existing "More" menu, not as new top-level buttons.
  • visible runs when the menu is built. It must be fast and must not throw.
  • The handler runs on the main thread and must return quickly. Use the scheduler for network work.
  • An action that opens a screen uses AndroidHost.openScreen.
  • A plugin cannot reorder or remove core actions.

11.5 Chat toolbar actions#

java
context.contributions().addChatToolbarAction(
    ChatToolbarAction.builder("stats")
        .title(LocalizedText.of("Chat stats"))
        .icon(IconRef.host("stats"))
        .permission(Permissions.CHATS_READ)
        .handler((context, dialog) -> { /* open screen */ })
        .build()
);

They appear in the chat overflow menu in v1. A pinned toolbar slot is a later feature; it needs a conflict policy when several plugins want the same slot.

11.6 Phase 2 contributions#

  • ChatListAction and DialogDecorator add long-press actions and badges/subtitles.
  • ProfileAction adds overflow actions on profiles.
  • DrawerItem adds an entry to the main drawer; this tree has no classic drawer, so the item is reserved until an upstream drawer exists.
  • ComposerAction adds an item to the attachment panel.
  • MessageDecorator adds a badge, footer text or accent; the host draws it, so plugin code never runs during scroll or draw.

These are in the design but not in the first implementation. Their APIs will be finalized against real use cases before shipping.

12. Services#

Status: the registry is implemented and can store and select providers. No host service keys, default providers or UI for provider selection exist yet. TranslationService, TranslationRequest and TranslationResult are types only; the host does not consume them.

java
public interface Services {
    <T> Registration register(ServiceKey<T> key, T provider);
    <T> T get(ServiceKey<T> key); // active provider or default
    <T> List<T> all(ServiceKey<T> key);
    <T> void select(ServiceKey<T> key, String providerId); // user action
}

Planned public service key (no host provider is registered yet):

KeyInterfaceDefault
core.translationTranslationServiceHost's translation pipeline
java
public interface TranslationService {
    CompletableFuture<TranslationResult> translate(TranslationRequest request);
}

Rules:

  • A service key is defined by the SDK, not by a plugin.
  • The host and built-in plugins register defaults.
  • Only one provider is active per key. If several are installed, the user picks one in plugin settings.
  • A failing provider falls back to the default and is marked unhealthy.
  • Plugin-to-plugin interfaces are not public in v1 because separate class loaders would create incompatible types. Plugin communication uses host-defined services only.

13. Storage#

java
public interface PluginStorage {
    PluginPreferences global();
    PluginPreferences account(int account);
    File filesDir();
    File cacheDir();
    File accountFilesDir(int account);
}

public interface PluginPreferences {
    boolean getBoolean(String key, boolean fallback);
    int getInt(String key, int fallback);
    long getLong(String key, long fallback);
    String getString(String key, String fallback);
    Set<String> getStringSet(String key, Set<String> fallback);
    void put(String key, Object value);
    void remove(String key);
    void clear();
    Map<String, ?> getAll();
    void apply();
    void commit();
}
  • Storage is private to the plugin and namespaced by the host.
  • Global and per-account values are separate.
  • commit() is synchronous and must not be called on the main thread for large writes.
  • Files live under the app's no-backup directory. They are not included in Android auto-backup. Data export and import are not implemented yet; uninstall can keep the plugin data on the device.
  • A future SecretStorage will use the Android Keystore. In v1, plugins that store API keys must warn the user that the preference file is private but not encrypted.

14. Scheduling and logging#

java
public interface PluginScheduler {
    void runOnMain(Runnable task);
    void runOnBackground(Runnable task);
    Cancellable schedule(Runnable task, long delayMs);
    Cancellable schedulePeriodic(Runnable task, long initialDelayMs, long periodMs);
    void cancelAll();
}
  • Each plugin has a serial background executor.
  • Periodic tasks have a 15-minute minimum period and run only while the app process is alive in v1.
  • Tasks are cancelled on disable/unload.
  • A task that throws is logged; it does not kill the executor.
  • A task queue is bounded; overflow is logged and rejected.
java
public interface PluginLogger {
    void debug(String message, Object... args);
    void info(String message, Object... args);
    void warn(String message, Object... args);
    void error(String message, Throwable error);
}

Logs use the tag ngp/<plugin-id>. The host keeps a ring buffer per plugin, visible in the plugin details screen. Logs are never uploaded automatically. The user can export them when reporting a bug. Plugins must not log message contents, phone numbers or tokens.

15. Platform-neutral UI#

java
public interface PluginUi {
    void showToast(CharSequence text);
    void showBulletin(CharSequence text);
    void showDialog(DialogSpec spec);
    CompletableFuture<Boolean> showConfirm(DialogSpec spec);
    void copyToClipboard(CharSequence text); // clipboard.write
}

This covers small interactions that do not need a custom view. Anything larger uses AndroidHost.openScreen on Android. UI calls must run on the main thread. The host applies the current theme and accessibility rules.

Status: toast, bulletin, dialog, confirm and clipboard are implemented. Custom screens are available through AndroidHost.openScreen; appearance through AppearanceHost. require(...) supports both hosts.

16. UI host (Android)#

Status: delivered. The full contract is in screens.md; this section is the summary.

java
public interface AndroidHost extends PlatformHost {
    Screens screens();
    Context themedContext();
    void openScreen(PluginScreen screen);
}

public interface Screens {
    Registration replace(ScreenKey key, PluginScreenFactory factory);
    Registration addSlot(SlotKey key, SlotContribution contribution);
    boolean isReplaced(ScreenKey key);
}
  • themedContext() returns a context with the current Telegram theme, density and layout direction. It is valid only while the app is in the foreground; do not cache it across screens.
  • screens().replace requires ui.screens and accepts exactly ScreenKey.CHAT_LIST, CHAT, SETTINGS, PROFILE and MAIN_NAVIGATION.
  • screens().addSlot requires the slot permission: ui.chatlist for SlotKey.CHAT_LIST_HEADER and ui.settings for SlotKey.SETTINGS_HEADER.
  • openScreen requires ui.custom_screens and presents a host-owned full-screen fragment. The plugin does not control the action bar, insets, transitions or back stack. ScreenContext.screenKey() is null for this screen.
  • The host keeps the stock fragment and adds an opaque overlay. The stock screen, lifecycle and navigation stack remain intact; the stock screen keeps running underneath the plugin view.
  • MAIN_NAVIGATION covers only the tab bar. There is no drawer key in this tree.
  • The host owns accessibility. Plugins must set content descriptions on interactive views and use sp for text.
  • The host may recreate views after configuration changes. Plugin state belongs in storage or the view's saved state.
  • Protected surfaces never receive plugin views or screen contexts: login, passcode, payments, secret chats, installer, consent, safe mode, plugin manager and calls. SharedConfig.appLocked and inactive accounts also resolve to stock.
  • The kernel-owned Allow screen replacement plugins switch defaults on and restores stock screens without uninstalling plugins.

PluginScreen and its lifecycle:

java
public interface PluginScreen {
    View onCreateView(ScreenContext context);
    default void onResume() {}
    default void onPause() {}
    default void onDestroyView() {}
    default boolean onBackPressed() { return false; }
    default void onThemeChanged() {}
}

The five screen contexts add host data and actions on top of ScreenContext:

ContextAdds
ChatListScreenContextchats, openChat, openSettings, openProfile, openMainNavigation
ChatScreenContextdialogId, chats, messages, openProfile, sendText, close
SettingsScreenContextopenNextGramSettings
ProfileScreenContextuserId, title, chats, openChat
MainNavigationScreenContextcurrentTab, selectTab, openChatList, openSettings, openProfile

No plugin may call Activity.setContentView, register its own activity, provide a BaseFragment, or add a view to the Telegram window outside the provided host.

17. Script SDK#

Status: implemented. The QuickJS runtime, the JavaScript bridge, the TypeScript SDK (@nextgram/plugin) and the CLI (@nextgram/cli) ship with this tree. On-device runtime checks remain a release gate.

Script plugins use a subset of the same model. The JavaScript types mirror the core snapshots and contributions, but there is no custom view API and no raw Android access.

ts
import { definePlugin } from "@nextgram/plugin";

export default definePlugin({
  onLoad(ctx) {
    ctx.ui.addSettingsScreen({
      id: "general",
      title: "Quick Translate",
      rows: [
        { type: "switch", key: "enabled", title: "Enabled", default: true },
        { type: "text", key: "target", title: "Target language", default: "en" },
      ],
    });

    ctx.messages.addAction({
      id: "translate",
      title: "Translate",
      async onSelect(message) {
        if (!message.text) return;
        const result = await ctx.http.post("https://example.dev/translate", {
          text: message.text,
          target: ctx.settings.get("target", "en"),
        });
        ctx.ui.showDialog({ title: "Translation", message: result.text });
      },
    });
  },
});

Script capabilities:

  • ctx.storage, ctx.scheduler, ctx.logger and ctx.permissions;
  • ctx.ui, ctx.screens, ctx.contributions and ctx.navigation;
  • ctx.appearance, ctx.resources and ctx.events;
  • ctx.interceptors for outgoing messages and notifications;
  • ctx.messages(), ctx.chats(), ctx.chatAdmin() and ctx.automation();
  • ctx.http(), ctx.media() and ctx.notifications();
  • ctx.native.call for a hybrid package's registered Java methods.

Rules:

  • All bridge values are JSON-serializable. No functions, views, files or Android objects cross the bridge.
  • Async host calls return Promises. The host queue is bounded.
  • The script cannot create a thread, timer or network socket directly. Timers are host APIs and are cancelled on unload.
  • The script cannot use eval to escape the sandbox; QuickJS has no host bindings outside the bridge.
  • A script callback that exceeds the time limit is interrupted and the plugin is disabled.
  • onLoad may return a Promise; the host waits up to 1 s before treating the plugin as failed.
  • TypeScript-only plugins enable and disable live. Hybrid and Java packages need a restart when their DEX changes.

The TypeScript package ships the exact v1 types. The CLI compiles with esbuild to a single IIFE, checks the manifest, and signs the package. See typescript.md.

18. Threading rules#

SurfaceThread
Lifecycle callbacksmain
UI contribution visibility and click handlersmain
Settings build/onChangedmain
PluginScreenFactory and PluginScreen lifecyclemain
Eventsplugin serial background executor
Interceptorsoperation thread (often main)
Storage APIany thread; commit() not on main for large writes
PluginScheduler.runOnMainmain
PluginScheduler.runOnBackgroundplugin serial background executor

The host throws WrongThreadException when a UI method is called off the main thread. It does not silently marshal, because silent marshalling hides performance problems.

19. Versioning and compatibility#

  • The API major version is part of the package: dev.nextgram.plugin.v1.
  • v1 is frozen after the first public release. Breaking changes require v2.
  • The appearance and screen API is a pre-release hard break. formatVersion and api stay 1, but PluginKind.THEME and kind: "theme" are removed. A plugin that references either must be rebuilt against the current SDK. Existing code plugins that call AppearanceHost.applyPalette, resetPalette, hasPalette, setBlurStrength or setAvatarShape remain compatible; dev.nextgram.betterblur 1.0.1 loads without a rebuild.
  • nextgram-plugin-sdk-android is additive. A plugin that does not import dev.nextgram.plugin.v1.android sees no change.
  • Additive changes are allowed:
    • new interfaces;
    • new event types;
    • new permissions (older hosts reject them, so minHost is required);
    • new optional fields in specs;
    • new default methods only when they cannot conflict with existing implementations.
  • Removing or changing a method, field or constant is a breaking change.
  • Deprecated API stays for at least two host minor releases.
  • The SDK uses @Stable, @Experimental and @Internal annotations. @Experimental may change in a minor release; @Internal is not for plugins.
  • Before the first public SDK release, CI should run binary compatibility checks and build the sample plugins against the oldest supported SDK.

Manifest compatibility:

  • api must equal a supported major.
  • minHost and maxHost must include the current host version.
  • A plugin built for API 1 runs on every host that supports API 1, regardless of the Telegram upstream version, as long as minHost matches.

License#

The app and the SDK are GPL-3.0. The SDK is published with a plugin-linking exception so that a plugin which only links against the public SDK can choose another license, including a closed-source license. The exact exception wording must be reviewed by counsel before the first public SDK release. Plugins that copy or modify GPL-covered app code remain subject to the GPL.

20. SDK test kit#

Status: planned. Only the host verifier/installer JVM tests exist today.

dev.nextgram:plugin-sdk-v1-test provides:

  • FakePluginContext with in-memory storage, a manual scheduler, fake accounts, fake chats/messages and a recording UI;
  • FakeAndroidHost that records openScreen calls and screen/slot registrations;
  • JUnit 5 extensions for lifecycle and permission tests;
  • manifest fixtures for verifier tests;
  • a PluginContractTest that checks the entry point, no-arg constructor and lifecycle.

Plugin authors should test:

  • load/unload with no accounts;
  • permission denied paths;
  • empty and large data;
  • main-thread budget;
  • configuration change and screen recreation;
  • update with new permissions.

21. Minimal plugin example#

java
package dev.example.hello;

import dev.nextgram.plugin.v1.AbstractNextGramPlugin;
import dev.nextgram.plugin.v1.PluginContext;
import dev.nextgram.plugin.v1.Permissions;
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("hello")
                .title(LocalizedText.of("Hello NextGram"))
                .subtitle(LocalizedText.of("A minimal plugin"))
                .icon(IconRef.host("settings"))
                .screen(HelloSettings::new)
                .build()
        );

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

The corresponding package contains plugin.json, android/dex/classes.dex, assets/icon.png and the signature files. The full example manifest is in examples/hello-plugin/plugin.json.

That manifest declares ui.settings, ui.chat and messages.read. Add ui.appearance to apply a theme through AppearanceHost, or ui.screens to replace a screen through Screens. Appearance has no package payload and no theme manifest field; see themes.md and screens.md.