[Feature]: Add a minimal local extension loader for native Telegram commands
Problem
There is currently no update-safe way to add a small bot-native Telegram command that executes local code without sending a prompt to OpenCode.
My concrete use case is a /quota command that:
- calls a local quota API or executable;
- displays provider limits directly in Telegram;
- optionally provides a Refresh button;
- does not create an OpenCode session message;
- does not invoke an LLM or consume model tokens.
Editing the installed npm package works only temporarily because the changes are replaced when the bot is updated. Maintaining a permanent fork also seems excessive for a small local integration.
The existing /commands feature does not cover this case because it executes OpenCode custom commands through session.command. This proposal is specifically about native Telegram handlers implemented locally by the bot.
This is also different from forwarding arbitrary unknown slash commands, which was discussed in #56.
Current architecture
From reviewing the current main branch:
- bot commands are defined centrally in
src/bot/commands/definitions.ts; - handlers are registered in
src/bot/routers/command-router.ts; - callbacks are registered separately through the callback router;
BOT_COMMANDSis used for TelegramsetMyCommands;- authentication and the interaction guard run before the command routers;
- the bot already has a persistent application directory through
getRuntimePaths()andOPENCODE_TELEGRAM_HOME.
Because the application directory survives npm updates, it could also contain trusted local extensions.
Proposal
Add a minimal, opt-in loader for trusted local .mjs extensions.
For example:
<appHome>/extensions/*.mjs
Typical Linux location:
~/.config/opencode-telegram-bot/extensions/
An extension could export a small manifest and a setup function:
export default {
apiVersion: 1,
id: "omniroute-quota",
commands: [
{
command: "quota",
description: "Show provider quota limits",
allowWhenBusy: true,
},
],
setup({ composer, logger }) {
composer.command("quota", async (ctx) => {
const text = await loadQuotaStatus();
await ctx.reply(text);
});
composer.callbackQuery(
"ext:omniroute-quota:refresh",
async (ctx) => {
const text = await loadQuotaStatus();
await ctx.editMessageText(text);
await ctx.answerCallbackQuery();
},
);
},
};
The exact API is open for discussion. The important requirements are:
- extension files live outside the installed npm package;
- extensions can register native Telegram commands;
- extensions can register namespaced callback handlers;
- extension commands are included in
setMyCommands; - handlers remain behind the existing authorization middleware;
- one broken extension does not prevent the bot from starting;
- built-in commands cannot be overridden;
- the API is versioned from the beginning.
Suggested MVP boundaries
To keep the first implementation small, the MVP does not need:
- hot reload;
- an extension marketplace;
- automatic extension downloads;
- dependency installation;
- sandboxing;
- project-local extensions;
- a complex lifecycle API;
- compatibility with arbitrary npm plugin packages.
Restarting the bot after adding or changing an extension is sufficient.
Extensions should be documented as fully trusted local code running with the same OS permissions as the bot.
Interaction guard
Some local read-only commands, such as /quota, should be usable while an OpenCode task is running.
An extension command could explicitly request this:
{
command: "quota",
description: "Show provider quota limits",
allowWhenBusy: true,
}
The default should remain false.
Possible integration points
A minimal implementation would likely involve:
- adding
extensionsDirPathtosrc/runtime/paths.ts; - loading extension manifests before
createBot(); - merging extension command definitions with the built-in command list;
- mounting extension composers after authentication and the interaction guard;
- mounting them before unknown-command and unknown-callback fallbacks;
- allowing explicitly marked commands through the busy-state guard;
- adding loader, collision and failure-isolation tests.
Backward compatibility
When the extensions directory does not exist or is empty, the bot should behave exactly as it does today.
Done criteria
- [ ] The bot loads local
.mjsextensions from its persistent application directory. - [ ] npm updates do not delete installed extensions.
- [ ] An extension can register a native Telegram slash command.
- [ ] The command appears in Telegram
setMyCommands. - [ ] The command runs without invoking OpenCode or an LLM.
- [ ] An extension can register a namespaced callback handler.
- [ ] Extension handlers run behind the existing authorization middleware.
- [ ] Built-in commands cannot be overridden.
- [ ] A broken extension does not stop the bot.
- [ ] Unsupported
apiVersionvalues are rejected with a clear log message. - [ ] The behavior is covered by tests and documented.
I would be willing to work on a PR after confirming that this direction fits the project.
@NANAMINER thanks for the detailed write-up — the integration points you listed are accurate.
I want to go a narrower route first. Your actual need is "run something local, show its output, don't touch OpenCode, don't burn tokens" — that doesn't require executing arbitrary JS inside the bot process. A declarative local command covers it:
<appHome>/local-commands/quota.json
{
"description": "Show provider quota limits",
"exec": "node /home/you/bin/quota.js",
"allowWhenBusy": true
}
One file per command, filename becomes the command name. It lives in the persistent app directory, so npm updates don't touch it — your main requirement. It appears in setMyCommands, runs behind the existing auth middleware, can't override built-ins, and a broken file only disables itself. No directory, no behaviour change.
This avoids versioning a public JS API and leaking grammy's Composer into a contract I'd have to keep stable across upgrades.
On the Refresh button — that one is a hard no, and not for effort reasons. The bot allows exactly one active interaction at a time: InteractionManager holds a single state slot, and starting a new interaction evicts the previous one. Question prompts, permission requests, rename and inline menus all rely on that, and the guard middleware is built around it. A persistent button under a command's output doesn't fit: it would either evict an active question/permission prompt, or get rejected by the guard when the slot is taken. A button that works only depending on unrelated bot state is worse than no button. Calling the command again costs one extra message and always works.
If demand appears for things that genuinely need code, the .mjs loader can land in the same directory later, with the file extension separating the two levels. Not closing that door — just not opening a versioned public API for a single use case.
If that works for you, a PR along these lines would be welcome — happy to align on the schema first.
@grinev Thanks for the detailed response and for outlining the reasoning behind the narrower approach. This direction makes sense to me.
A declarative "local-commands/*.json" mechanism covers the intended use case well without introducing a public JS API prematurely. Dropping the persistent Refresh callback is also reasonable given the current interaction model — re-running the command is perfectly sufficient for this use case.
The proposed baseline looks good:
{ "description": "Show provider quota limits", "exec": "node /home/you/bin/quota.js", "allowWhenBusy": true }
From my side, the main requirements are:
- persistent across package updates;
- registered via "setMyCommands";
- executed without involving OpenCode or an LLM;
- protected by the existing authorization middleware;
- unable to override built-in commands;
- isolated so an invalid command definition does not affect bot startup;
- optionally allowed while the bot is busy via "allowWhenBusy".
Thanks also for being open to keeping the ".mjs" route as a possible future extension if more advanced use cases eventually justify it.
I'm happy to align on the schema first. If we can settle the execution/output semantics and validation rules, I'd be happy to work on a PR along these lines.
Here is the spec:
Discovery
- Directory:
<appHome>/local-commands/, where<appHome>comes fromgetRuntimePaths(). The PR should addlocalCommandsDirPaththere. - Top level only, no recursion. Only
*.jsonfiles are read; anything else is ignored. - The filename without the extension is the command name — there is no
commandfield in the file.quota.jsongives/quota. - Missing or empty directory means the bot behaves exactly as it does today.
- Loaded once at startup, before
createBot(). No hot reload — a restart is required after changes.
Validation
- Command name must match
^[a-z0-9_]{1,32}$(Telegram's own constraint forsetMyCommands). - A name colliding with a built-in command (including
start) is skipped with a warning. Built-ins always win. - Duplicates are impossible — the filesystem enforces uniqueness.
- Combined built-in + local list must stay within Telegram's 100-command limit; anything beyond it is skipped with a warning.
Schema
{
"description": "Show provider quota limits",
"exec": "node /home/you/bin/quota.js",
"allowWhenBusy": true
}
description— required, non-empty, single line, max 256 chars (Telegram's limit). Not localized; the string is used as written.exec— required, non-empty string.allowWhenBusy— optional boolean, defaults tofalse.- Unknown fields are ignored rather than rejected, so the schema can grow additively. No
apiVersionfield — this is data, not an API.
Execution semantics
execruns through the platform shell (/bin/sh -con POSIX,cmd.exe /con Windows). It is a single string, not an argv array — pipes and quoting work as the user expects. The value comes from a local file owned by the user, at the same trust level as.env.- No argument passing. Text following the command in Telegram is ignored and never reaches the shell. This keeps the first version free of injection concerns.
- Working directory:
<appHome>. Environment: inherited from the bot process. - Timeout: 30 seconds, hard-coded for now. On expiry the process is killed and the user gets a timeout message. If a real need for per-command timeouts shows up,
timeoutMscan be added later without breaking anything.
Output semantics
- Exit code
0→ reply withstdout. - Non-zero exit → reply with an error message containing the exit code and the tail of
stderr. No stack traces. - Empty
stdouton success → a short "no output" message rather than an empty reply. - Output is sent as plain text, with no
parse_mode. Script output is arbitrary and would routinely break Markdown parsing. Aformatfield for a monospace block can come later if it's actually wanted. - Output longer than Telegram's message limit is truncated with a visible marker — not split across multiple messages.
Guard behaviour
This is the part worth getting right, since it is easy to over-deliver here:
- Handlers register as ordinary
bot.command(...), after the auth middleware and the interaction guard — same as every built-in. allowWhenBusy: trueonly affects the busy gate, the one that today lets/abort,/detach,/statusand/helpthrough while OpenCode is working.- It does not grant access during an active interaction. When the bot is waiting for an answer to a question, a permission decision, or a rename input, local commands are blocked exactly like any other non-allowed command. They must not be added to
allowedCommands.
Failure isolation
- Unreadable file, invalid JSON, failed validation → warning in the log with the file path and the reason, that one command is skipped, everything else still loads.
- Startup logs a summary: how many local commands were loaded and how many were skipped.
- A command failing at runtime affects only that reply.
Touch points
Roughly: runtime/paths.ts, a new loader + executor module, the command registry (bot/commands/definitions.ts and bot/routers/command-utils.ts currently build their lists at import time and need to become a registry), bot/routers/command-router.ts, and the busy gate in bot/middleware/interaction-guard-decision.ts. The callback router is deliberately untouched.
Out of scope
Hot reload, arguments, per-command timeouts, output formatting options, inline keyboards, project-local commands, and anything resembling a JS API.
Expected with the PR
Tests covering the loader (valid, malformed, name collision, invalid name), the executor (success, non-zero exit, timeout, truncation), the busy gate in both states, and setMyCommands including local commands. Plus a README section describing the directory, the schema, and the trust model — these commands run with the same OS permissions as the bot.
If any of this looks wrong from where you sit, say so before writing code — easier to change here than in review.
@NANAMINER I've implemented this https://github.com/grinev/opencode-telegram-bot/commit/df6453b350223271b13f92748c401402f1655e9b see in upcoming release