Skip to content

Commit c7e49ad

Browse files
feat(onboard): support Telegram mention-only mode (#2417)
## Summary Parity with Discord's existing `requireMention` toggle, scoped to Telegram. Teams running the bot in busy Telegram groups can now restrict it to reply only when @mentioned instead of to every group message. ## Problem Telegram's group behavior in NemoClaw is hardcoded to `groupPolicy: open` — the bot answers every message the moment it joins a group. Users have no CLI flag, env var, or onboard prompt to narrow this; the only workaround is hand-patching `openclaw.json` after build. Discord already has the equivalent via `requireMention`. ## Changes - **[`src/lib/sandbox-channels.ts`](src/lib/sandbox-channels.ts)** — add `requireMentionEnvKey: \"TELEGRAM_REQUIRE_MENTION\"` + help string to the Telegram `ChannelDef`. - **[`src/lib/onboard.ts`](src/lib/onboard.ts)** — loosen the interactive mention-prompt gate: the prompt used to require both `requireMentionEnvKey` AND a populated `serverIdEnvKey` (Discord-specific). Now any channel with `requireMentionEnvKey` fires the prompt, with the Discord-specific server-ID check preserved. Also build a `telegramConfig` from `TELEGRAM_REQUIRE_MENTION` and pass it through `patchStagedDockerfile`. - **[`Dockerfile`](Dockerfile)** — add `ARG NEMOCLAW_TELEGRAM_CONFIG_B64=e30=`, promote to ENV, and wire into the Python openclaw.json generator: \`\`groupPolicy\`\` becomes \`\`mentions\`\` when \`\`requireMention\`\` is truthy, otherwise \`\`open\`\` (existing default preserved). ## Usage **Interactive:** ``` [5/8] Messaging channels ... ✓ telegram token saved Reply only when @mentioned? [Y/n] ``` **Non-interactive:** ```bash TELEGRAM_REQUIRE_MENTION=1 nemoclaw onboard --non-interactive ``` Unset env + non-interactive = same as before (open groups). No behavior change for existing scripted onboards. ## Test plan - [x] `npx vitest run test/onboard.test.ts src/lib/sandbox-channels.test.ts test/onboard-selection.test.ts` — 179 tests pass including 3 new ones: - \`#1737: patches the staged Dockerfile with Telegram mention-only config\` — round-trips \`{\"requireMention\": true}\`. - \`#1737: patches the staged Dockerfile with Telegram open-group config when requireMention=false\` — explicit \`false\` round-trips. - \`#1737: preserves default Telegram group-open behavior when telegramConfig is empty\` — backward compat: ARG default \`e30=\` is not rewritten when the caller passes \`{}\`. - [x] Typecheck clean. - [x] Existing Discord guild + messaging-channels tests unchanged and green. ## Prior art Closed PR [#1784](#1784) by @kagura-agent proposed the same approach and was thanked by @wscurran with CodeRabbit review addressed before the author voluntarily closed \"to reduce PR volume.\" This PR takes the same shape with a refreshed test layout and an explicit backward-compat regression test. Fixes #1737. Signed-off-by: latenighthackathon <[email protected]> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Configurable Telegram "mention-only" mode added as a build/runtime input and passed into the running environment. * Container now accepts an encoded Telegram config and uses it to set the channel policy instead of a fixed default. * Onboarding records Telegram mention preference, triggers sandbox recreation when it changes, and channel setup prompts respect mention-only controls. * **Tests** * Added unit tests for config injection, session persistence, validation, and compatibility. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: latenighthackathon <[email protected]> Co-authored-by: latenighthackathon <[email protected]> Co-authored-by: cjagwani <[email protected]>
1 parent 2ebc0d9 commit c7e49ad

7 files changed

Lines changed: 321 additions & 5 deletions

File tree

‎Dockerfile‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,10 @@ ARG NEMOCLAW_MESSAGING_ALLOWED_IDS_B64=e30=
266266
# (e.g. {"1234567890":{"requireMention":true,"users":["555"]}}).
267267
# Used to enable guild-channel responses for native Discord. Default: empty map.
268268
ARG NEMOCLAW_DISCORD_GUILDS_B64=e30=
269+
# Base64-encoded JSON Telegram config (e.g. {"requireMention":true}).
270+
# When requireMention is true, Telegram groups get groupPolicy: mentions;
271+
# otherwise groupPolicy: open (existing default). See #1737. Default: empty map.
272+
ARG NEMOCLAW_TELEGRAM_CONFIG_B64=e30=
269273
# Set to "1" to force-disable device-pairing auth. Also auto-disabled when
270274
# CHAT_UI_URL is a non-loopback address (Brev Launchable, remote deployments)
271275
# since terminal-based pairing is impossible in those contexts.
@@ -305,6 +309,7 @@ ENV NEMOCLAW_MODEL=${NEMOCLAW_MODEL} \
305309
NEMOCLAW_MESSAGING_CHANNELS_B64=${NEMOCLAW_MESSAGING_CHANNELS_B64} \
306310
NEMOCLAW_MESSAGING_ALLOWED_IDS_B64=${NEMOCLAW_MESSAGING_ALLOWED_IDS_B64} \
307311
NEMOCLAW_DISCORD_GUILDS_B64=${NEMOCLAW_DISCORD_GUILDS_B64} \
312+
NEMOCLAW_TELEGRAM_CONFIG_B64=${NEMOCLAW_TELEGRAM_CONFIG_B64} \
308313
NEMOCLAW_DISABLE_DEVICE_AUTH=${NEMOCLAW_DISABLE_DEVICE_AUTH} \
309314
NEMOCLAW_PROXY_HOST=${NEMOCLAW_PROXY_HOST} \
310315
NEMOCLAW_PROXY_PORT=${NEMOCLAW_PROXY_PORT} \

‎scripts/generate-openclaw-config.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
NEMOCLAW_MESSAGING_CHANNELS_B64 Base64-encoded channel list
2727
NEMOCLAW_MESSAGING_ALLOWED_IDS_B64 Base64-encoded allowed IDs map
2828
NEMOCLAW_DISCORD_GUILDS_B64 Base64-encoded Discord guild config
29+
NEMOCLAW_TELEGRAM_CONFIG_B64 Base64-encoded Telegram config (e.g. {"requireMention": true})
2930
NEMOCLAW_DISABLE_DEVICE_AUTH Set to "1" to force-disable device auth
3031
NEMOCLAW_PROXY_HOST Egress proxy host (default: 10.200.0.1)
3132
NEMOCLAW_PROXY_PORT Egress proxy port (default: 3128)
@@ -110,6 +111,11 @@ def build_config(env: dict | None = None) -> dict:
110111
env.get("NEMOCLAW_DISCORD_GUILDS_B64", "e30=") or "e30="
111112
).decode("utf-8")
112113
)
114+
_telegram_config = json.loads(
115+
base64.b64decode(
116+
env.get("NEMOCLAW_TELEGRAM_CONFIG_B64", "e30=") or "e30="
117+
).decode("utf-8")
118+
)
113119

114120
_token_keys = {"discord": "token", "telegram": "botToken", "slack": "botToken"}
115121
_env_keys = {
@@ -145,7 +151,9 @@ def _placeholder(channel: str, env_key: str) -> str:
145151
if ch in ("telegram", "discord"):
146152
account["proxy"] = proxy_url
147153
if ch == "telegram":
148-
account["groupPolicy"] = "open"
154+
account["groupPolicy"] = (
155+
"mentions" if _telegram_config.get("requireMention") else "open"
156+
)
149157
if ch in _allowed_ids and _allowed_ids[ch]:
150158
account["dmPolicy"] = "allowlist"
151159
account["allowFrom"] = _allowed_ids[ch]

‎src/lib/onboard-session.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,44 @@ describe("onboard session", () => {
182182
expect(fresh.messagingChannels).toBeNull();
183183
});
184184

185+
it("#1737: persists telegramConfig across save/load roundtrips (requireMention=true)", () => {
186+
const created = session.createSession();
187+
created.telegramConfig = { requireMention: true };
188+
session.saveSession(created);
189+
190+
const loaded = session.loadSession()!;
191+
expect(loaded.telegramConfig).toEqual({ requireMention: true });
192+
});
193+
194+
it("#1737: persists telegramConfig across save/load roundtrips (requireMention=false)", () => {
195+
const created = session.createSession();
196+
created.telegramConfig = { requireMention: false };
197+
session.saveSession(created);
198+
199+
const loaded = session.loadSession()!;
200+
expect(loaded.telegramConfig).toEqual({ requireMention: false });
201+
});
202+
203+
it("#1737: rejects malformed telegramConfig on load", () => {
204+
// Simulate a hand-edited session file with garbage in telegramConfig.
205+
// Going through saveSession() would re-normalize the value before it
206+
// hits disk, so write raw JSON directly to exercise the load-time
207+
// parseTelegramConfig() path.
208+
const seed = session.createSession();
209+
session.saveSession(seed);
210+
const onDisk = JSON.parse(fs.readFileSync(session.SESSION_FILE, "utf-8"));
211+
onDisk.telegramConfig = { requireMention: "yes" };
212+
fs.writeFileSync(session.SESSION_FILE, JSON.stringify(onDisk));
213+
214+
const loaded = session.loadSession()!;
215+
expect(loaded.telegramConfig).toBeNull();
216+
});
217+
218+
it("#1737: defaults telegramConfig to null for fresh sessions", () => {
219+
const fresh = session.createSession();
220+
expect(fresh.telegramConfig).toBeNull();
221+
});
222+
185223
it("persists and clears web search config through safe session updates", () => {
186224
session.saveSession(session.createSession());
187225
session.markStepComplete("provider_selection", {
@@ -409,6 +447,32 @@ describe("onboard session", () => {
409447
expect(loaded.messagingChannels).toEqual(["slack", "discord"]);
410448
});
411449

450+
it("#1737: filterSafeUpdates routes telegramConfig through markStepComplete", () => {
451+
session.saveSession(session.createSession());
452+
session.markStepComplete("provider_selection", {
453+
telegramConfig: { requireMention: true },
454+
});
455+
456+
const loaded = session.loadSession()!;
457+
expect(loaded.telegramConfig).toEqual({ requireMention: true });
458+
459+
// Explicit null (clearing the field) should also round-trip.
460+
session.markStepComplete("provider_selection", { telegramConfig: null });
461+
const cleared = session.loadSession()!;
462+
expect(cleared.telegramConfig).toBeNull();
463+
});
464+
465+
it("#1737: filterSafeUpdates drops malformed telegramConfig values", () => {
466+
session.saveSession(session.createSession());
467+
// Non-boolean requireMention — must not leak through.
468+
session.markStepComplete("provider_selection", {
469+
telegramConfig: { requireMention: "yes" } as unknown as { requireMention: boolean },
470+
});
471+
472+
const loaded = session.loadSession()!;
473+
expect(loaded.telegramConfig).toBeNull();
474+
});
475+
412476
it("createSession with messagingChannels override", () => {
413477
const created = session.createSession({ messagingChannels: ["telegram", "slack"] });
414478
expect(created.messagingChannels).toEqual(["telegram", "slack"]);

‎src/lib/onboard-session.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,15 @@ export interface Session {
8989
// migrated set is NOT seeded from the persisted record, so the cleanup
9090
// gate keeps the file until the *current* value is actually re-migrated.
9191
migratedLegacyValueHashes: Record<string, string> | null;
92+
telegramConfig: TelegramConfig | null;
9293
metadata: SessionMetadata;
9394
steps: Record<string, StepState>;
9495
}
9596

97+
export interface TelegramConfig {
98+
requireMention: boolean;
99+
}
100+
96101
export interface LockInfo {
97102
pid: number;
98103
startedAt: string | null;
@@ -120,6 +125,7 @@ export interface SessionUpdates {
120125
policyPresets?: string[];
121126
messagingChannels?: string[];
122127
migratedLegacyValueHashes?: Record<string, string>;
128+
telegramConfig?: TelegramConfig | null;
123129
metadata?: { gatewayName?: string; fromDockerfile?: string | null };
124130
}
125131

@@ -209,6 +215,13 @@ function parseWebSearchConfig(value: SessionJsonValue | undefined): WebSearchCon
209215
return isObject(value) && value.fetchEnabled === true ? { fetchEnabled: true } : null;
210216
}
211217

218+
function parseTelegramConfig(value: unknown): TelegramConfig | null {
219+
if (!isObject(value)) return null;
220+
if (value.requireMention === true) return { requireMention: true };
221+
if (value.requireMention === false) return { requireMention: false };
222+
return null;
223+
}
224+
212225
function parseSessionMetadata(value: SessionJsonValue | undefined): SessionMetadata | undefined {
213226
if (!isObject(value)) return undefined;
214227
return {
@@ -288,6 +301,7 @@ export function createSession(overrides: Partial<Session> = {}): Session {
288301
migratedLegacyValueHashes: overrides.migratedLegacyValueHashes
289302
? readStringRecord(overrides.migratedLegacyValueHashes)
290303
: null,
304+
telegramConfig: parseTelegramConfig(overrides.telegramConfig),
291305
metadata: {
292306
gatewayName: overrides.metadata?.gatewayName ?? "nemoclaw",
293307
fromDockerfile: overrides.metadata?.fromDockerfile ?? null,
@@ -320,6 +334,7 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined):
320334
policyPresets: readStringArray(data.policyPresets),
321335
messagingChannels: readStringArray(data.messagingChannels),
322336
migratedLegacyValueHashes: readStringRecord(data.migratedLegacyValueHashes),
337+
telegramConfig: parseTelegramConfig(data.telegramConfig),
323338
lastStepStarted: readString(data.lastStepStarted),
324339
lastCompletedStep: readString(data.lastCompletedStep),
325340
failure: sanitizeFailure(isObject(data.failure) ? data.failure : null),
@@ -633,6 +648,11 @@ export function filterSafeUpdates(updates: SessionUpdates): Partial<Session> {
633648
}
634649
safe.migratedLegacyValueHashes = cleaned;
635650
}
651+
if (isObject(updates.telegramConfig) && typeof updates.telegramConfig.requireMention === "boolean") {
652+
safe.telegramConfig = { requireMention: updates.telegramConfig.requireMention };
653+
} else if (updates.telegramConfig === null) {
654+
safe.telegramConfig = null;
655+
}
636656
if (isObject(updates.metadata) && typeof updates.metadata.gatewayName === "string") {
637657
safe.metadata = {
638658
gatewayName: updates.metadata.gatewayName,

‎src/lib/onboard.ts‎

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,18 @@ let RECREATE_SANDBOX = false;
414414
// null means "use auto-allocation" (skip dashboard port check in preflight).
415415
let _preflightDashboardPort: number | null = null;
416416

417+
// Read TELEGRAM_REQUIRE_MENTION (set either by the interactive mention prompt
418+
// or by the user's shell) and map it to a boolean, or null when the env var
419+
// is unset / invalid. Used at build time to bake groupPolicy into
420+
// openclaw.json and at resume time to detect drift against the recorded
421+
// session state. See #1737 and the CodeRabbit follow-up on #2417.
422+
function computeTelegramRequireMention(): boolean | null {
423+
const raw = process.env.TELEGRAM_REQUIRE_MENTION;
424+
if (raw === "1") return true;
425+
if (raw === "0") return false;
426+
return null;
427+
}
428+
417429
function isNonInteractive(): boolean {
418430
return NON_INTERACTIVE || process.env.NEMOCLAW_NON_INTERACTIVE === "1";
419431
}
@@ -1955,6 +1967,7 @@ function patchStagedDockerfile(
19551967
messagingAllowedIds: LooseObject = {},
19561968
discordGuilds: LooseObject = {},
19571969
baseImageRef: string | null = null,
1970+
telegramConfig: LooseObject = {},
19581971
) {
19591972
const { providerKey, primaryModelRef, inferenceBaseUrl, inferenceApi, inferenceCompat } =
19601973
getSandboxInferenceConfig(model, provider, preferredInferenceApi);
@@ -2096,6 +2109,12 @@ function patchStagedDockerfile(
20962109
`ARG NEMOCLAW_DISCORD_GUILDS_B64=${encodeDockerJsonArg(discordGuilds)}`,
20972110
);
20982111
}
2112+
if (telegramConfig && Object.keys(telegramConfig).length > 0) {
2113+
dockerfile = dockerfile.replace(
2114+
/^ARG NEMOCLAW_TELEGRAM_CONFIG_B64=.*$/m,
2115+
`ARG NEMOCLAW_TELEGRAM_CONFIG_B64=${encodeDockerJsonArg(telegramConfig)}`,
2116+
);
2117+
}
20992118
fs.writeFileSync(dockerfilePath, dockerfile);
21002119
}
21012120

@@ -4462,6 +4481,31 @@ async function createSandbox(
44624481
};
44634482
}
44644483
}
4484+
// Telegram mention-only mode — parity with Discord's requireMention.
4485+
// Off by default so existing sandboxes behave the same; opt-in via
4486+
// TELEGRAM_REQUIRE_MENTION=1 or the interactive prompt. See #1737.
4487+
const telegramConfig: { requireMention?: boolean } = {};
4488+
if (enabledTokenEnvKeys.has("TELEGRAM_BOT_TOKEN")) {
4489+
const telegramRequireMention = computeTelegramRequireMention();
4490+
if (telegramRequireMention !== null) {
4491+
telegramConfig.requireMention = telegramRequireMention;
4492+
}
4493+
}
4494+
// Persist the effective Telegram config into the session so a later resume
4495+
// can detect drift (TELEGRAM_REQUIRE_MENTION changed since last build) and
4496+
// force a sandbox recreate — otherwise the old groupPolicy would stay baked
4497+
// in. Mirrors the pattern used for webSearchConfig. See CodeRabbit on #2417.
4498+
if (typeof telegramConfig.requireMention === "boolean") {
4499+
onboardSession.updateSession((current) => {
4500+
current.telegramConfig = { requireMention: telegramConfig.requireMention as boolean };
4501+
return current;
4502+
});
4503+
} else {
4504+
onboardSession.updateSession((current) => {
4505+
current.telegramConfig = null;
4506+
return current;
4507+
});
4508+
}
44654509
// Pull the base image and resolve its digest so the Dockerfile is pinned to
44664510
// exactly what we just fetched. This prevents stale :latest tags from
44674511
// silently reusing a cached old image after NemoClaw upgrades (#1904).
@@ -4500,6 +4544,7 @@ async function createSandbox(
45004544
messagingAllowedIds,
45014545
discordGuilds,
45024546
resolved ? resolved.ref : null,
4547+
telegramConfig,
45034548
);
45044549
// Only pass non-sensitive env vars to the sandbox. Credentials flow through
45054550
// OpenShell providers — the gateway injects them as placeholders and the L7
@@ -6342,17 +6387,23 @@ async function setupMessagingChannels(): Promise<string[]> {
63426387
}
63436388
}
63446389
}
6345-
if (ch.requireMentionEnvKey && ch.serverIdEnvKey && process.env[ch.serverIdEnvKey]) {
6346-
const existingRequireMention = process.env[ch.requireMentionEnvKey];
6390+
// Mention-control prompt: fires for any channel that exposes a
6391+
// requireMention env key. Discord gates the prompt behind a configured
6392+
// server ID (mention control only makes sense in a guild). Telegram
6393+
// has no serverIdEnvKey because mention control applies to every group
6394+
// the bot is added to, so the prompt always fires there. See #1737.
6395+
const requireMentionKey = ch.requireMentionEnvKey;
6396+
if (requireMentionKey && (!ch.serverIdEnvKey || Boolean(process.env[ch.serverIdEnvKey]))) {
6397+
const existingRequireMention = process.env[requireMentionKey];
63476398
if (existingRequireMention === "0" || existingRequireMention === "1") {
63486399
const mode = existingRequireMention === "0" ? "all messages" : "@mentions only";
63496400
console.log(` ✓ ${ch.name} — reply mode already set: ${mode}`);
63506401
} else {
63516402
console.log(` ${ch.requireMentionHelp}`);
63526403
const answer = (await prompt(" Reply only when @mentioned? [Y/n]: ")).trim().toLowerCase();
6353-
process.env[ch.requireMentionEnvKey] = answer === "n" || answer === "no" ? "0" : "1";
6404+
process.env[requireMentionKey] = answer === "n" || answer === "no" ? "0" : "1";
63546405
const mode =
6355-
process.env[ch.requireMentionEnvKey] === "0" ? "all messages" : "@mentions only";
6406+
process.env[requireMentionKey] === "0" ? "all messages" : "@mentions only";
63566407
console.log(` ✓ ${ch.name} reply mode saved: ${mode}`);
63576408
}
63586409
}
@@ -8433,9 +8484,27 @@ async function onboard(opts: OnboardOptions = {}): Promise<void> {
84338484

84348485
const sandboxReuseState = getSandboxReuseState(sandboxName);
84358486
const webSearchConfigChanged = Boolean(session?.webSearchConfig) !== Boolean(webSearchConfig);
8487+
// Telegram mention-mode is baked into openclaw.json at sandbox build time, so
8488+
// changes to TELEGRAM_REQUIRE_MENTION only take effect after a rebuild. Treat
8489+
// a mismatch between the recorded config and the current env value as drift
8490+
// so the reuse path forces a recreate (mirrors webSearchConfigChanged). See
8491+
// #1737 and the CodeRabbit review on #2417.
8492+
//
8493+
// Compare *effective* modes — null and false both produce groupPolicy: open
8494+
// at config-generation time (default behavior), so they collapse to the same
8495+
// bucket here. Without this, a sandbox built before TELEGRAM_REQUIRE_MENTION
8496+
// existed (recordedTelegramRequireMention === null) would be reused with the
8497+
// old groupPolicy: open even after the user sets TELEGRAM_REQUIRE_MENTION=1,
8498+
// and vice versa.
8499+
const currentTelegramRequireMention = computeTelegramRequireMention();
8500+
const recordedTelegramRequireMention = session?.telegramConfig?.requireMention ?? null;
8501+
const effectiveCurrent = currentTelegramRequireMention ?? false;
8502+
const effectiveRecorded = recordedTelegramRequireMention ?? false;
8503+
const telegramConfigChanged = effectiveCurrent !== effectiveRecorded;
84368504
const resumeSandbox =
84378505
resume &&
84388506
!webSearchConfigChanged &&
8507+
!telegramConfigChanged &&
84398508
session?.steps?.sandbox?.status === "complete" &&
84408509
sandboxReuseState === "ready";
84418510
if (resumeSandbox) {
@@ -8451,6 +8520,11 @@ async function onboard(opts: OnboardOptions = {}): Promise<void> {
84518520
if (sandboxName) {
84528521
registry.removeSandbox(sandboxName);
84538522
}
8523+
} else if (telegramConfigChanged) {
8524+
note(" [resume] TELEGRAM_REQUIRE_MENTION changed; recreating sandbox.");
8525+
if (sandboxName) {
8526+
registry.removeSandbox(sandboxName);
8527+
}
84548528
} else if (sandboxReuseState === "not_ready") {
84558529
note(
84568530
` [resume] Recorded sandbox '${sandboxName}' exists but is not ready; recreating it.`,

‎src/lib/sandbox-channels.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ export const KNOWN_CHANNELS: Record<string, ChannelDef> = {
3636
userIdHelp: "Send /start to @userinfobot on Telegram to get your numeric user ID.",
3737
userIdLabel: "Telegram User ID (for DM access)",
3838
allowIdsMode: "dm",
39+
requireMentionEnvKey: "TELEGRAM_REQUIRE_MENTION",
40+
requireMentionHelp:
41+
"Controls Telegram group-chat behavior only — reply only when @mentioned vs. to all group messages. Direct messages are unaffected by this setting and remain subject to pairing and TELEGRAM_ALLOWED_IDS.",
3942
},
4043
discord: {
4144
envKey: "DISCORD_BOT_TOKEN",

0 commit comments

Comments
 (0)