Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b1c26f900 | ||
|
|
f12c1b391f | ||
|
|
dfb6630de1 | ||
|
|
eb7656d68c | ||
|
|
0e1dcf9cb4 | ||
|
|
d05c3d0659 | ||
|
|
01c43b0b0c | ||
|
|
fc4aa9a683 | ||
|
|
c043e9767f | ||
|
|
8b48299d8f | ||
|
|
0f27cff247 | ||
|
|
2d1ae0916f | ||
|
|
d0455f2683 | ||
|
|
f25fe032c4 | ||
|
|
0a5b1fbcd1 |
No files matched your search
@@ -1,5 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
## 2026.1.15 (unreleased)
|
||||
|
||||
- Fix: guard model fallback against undefined provider/model values. (#954) — thanks @roshanasingh4.
|
||||
- Telegram: add bidirectional reaction support with configurable notifications and agent guidance. (#964) — thanks @bohdanpodvirnyi.
|
||||
|
||||
## 2026.1.14-1
|
||||
|
||||
### Highlights
|
||||
@@ -22,6 +27,7 @@
|
||||
- Browser: add `snapshot refs=aria` (Playwright aria-ref ids) for self-resolving refs across `snapshot` → `act`.
|
||||
- Browser: `profile="chrome"` now defaults to host control and returns clearer “attach a tab” errors.
|
||||
- Browser: extension mode recovers when only one tab is attached (stale targetId fallback).
|
||||
- Browser: fix `tab not found` for extension relay snapshots/actions when Playwright blocks `newCDPSession` (use the single available Page).
|
||||
- Control UI: show raw any-map entries in config views; move Docs link into the left nav.
|
||||
|
||||
#### Plugins
|
||||
|
||||
@@ -297,6 +297,49 @@ Outbound Telegram API calls retry on transient network/429 errors with exponenti
|
||||
- Reaction removal semantics: see [/tools/reactions](/tools/reactions).
|
||||
- Tool gating: `channels.telegram.actions.reactions`, `channels.telegram.actions.sendMessage`, `channels.telegram.actions.deleteMessage` (default: enabled).
|
||||
|
||||
## Reaction notifications
|
||||
|
||||
**How reactions work:**
|
||||
Telegram reactions arrive as **separate `message_reaction` events**, not as properties in message payloads. When a user adds a reaction, Clawdbot:
|
||||
|
||||
1. Receives the `message_reaction` update from Telegram API
|
||||
2. Converts it to a **system event** with format: `"Telegram reaction added: {emoji} by {user} on msg {id}"`
|
||||
3. Enqueues the system event using the **same session key** as regular messages
|
||||
4. When the next message arrives in that conversation, system events are drained and prepended to the agent's context
|
||||
|
||||
The agent sees reactions as **system notifications** in the conversation history, not as message metadata.
|
||||
|
||||
**Configuration:**
|
||||
- `channels.telegram.reactionNotifications`: Controls which reactions trigger notifications
|
||||
- `"off"` — ignore all reactions (default when not set)
|
||||
- `"own"` — notify when users react to bot messages (best-effort; in-memory)
|
||||
- `"all"` — notify for all reactions
|
||||
|
||||
- `channels.telegram.reactionLevel`: Controls agent's reaction capability
|
||||
- `"off"` — agent cannot react to messages
|
||||
- `"ack"` — bot sends acknowledgment reactions (👀 while processing) (default)
|
||||
- `"minimal"` — agent can react sparingly (guideline: 1 per 5-10 exchanges)
|
||||
- `"extensive"` — agent can react liberally when appropriate
|
||||
|
||||
**Forum groups:** Reactions in forum groups include `message_thread_id` and use session keys like `agent:main:telegram:group:{chatId}:topic:{threadId}`. This ensures reactions and messages in the same topic stay together.
|
||||
|
||||
**Example config:**
|
||||
```json5
|
||||
{
|
||||
channels: {
|
||||
telegram: {
|
||||
reactionNotifications: "all", // See all reactions
|
||||
reactionLevel: "minimal" // Agent can react sparingly
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Requirements:**
|
||||
- Telegram bots must explicitly request `message_reaction` in `allowed_updates` (configured automatically by Clawdbot)
|
||||
- For webhook mode, reactions are included in the webhook `allowed_updates`
|
||||
- For polling mode, reactions are included in the `getUpdates` `allowed_updates`
|
||||
|
||||
## Delivery targets (CLI/cron)
|
||||
- Use a chat id (`123456789`) or a username (`@name`) as the target.
|
||||
- Example: `clawdbot message send --channel telegram --to 123456789 --message "hi"`.
|
||||
@@ -360,6 +403,8 @@ Provider options:
|
||||
- `channels.telegram.actions.reactions`: gate Telegram tool reactions.
|
||||
- `channels.telegram.actions.sendMessage`: gate Telegram tool message sends.
|
||||
- `channels.telegram.actions.deleteMessage`: gate Telegram tool message deletes.
|
||||
- `channels.telegram.reactionNotifications`: `off | own | all` — control which reactions trigger system events (default: `off` when not set).
|
||||
- `channels.telegram.reactionLevel`: `off | ack | minimal | extensive` — control agent's reaction capability (default: `ack` when not set).
|
||||
|
||||
Related global options:
|
||||
- `agents.list[].groupChat.mentionPatterns` (mention gating patterns).
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ Fetch a URL and extract readable content.
|
||||
maxChars: 50000,
|
||||
timeoutSeconds: 30,
|
||||
cacheTtlMinutes: 15,
|
||||
userAgent: "clawdbot/2026.1.14-1"
|
||||
userAgent: "clawdbot/2026.1.15"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@clawdbot/matrix",
|
||||
"version": "2026.1.14-1",
|
||||
"version": "2026.1.15",
|
||||
"type": "module",
|
||||
"description": "Clawdbot Matrix channel plugin",
|
||||
"clawdbot": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@clawdbot/voice-call",
|
||||
"version": "2026.1.14-1",
|
||||
"version": "2026.1.15",
|
||||
"type": "module",
|
||||
"description": "Clawdbot voice-call plugin",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@clawdbot/zalo",
|
||||
"version": "2026.1.14-1",
|
||||
"version": "2026.1.15",
|
||||
"type": "module",
|
||||
"description": "Clawdbot Zalo channel plugin",
|
||||
"clawdbot": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clawdbot",
|
||||
"version": "2026.1.14-1",
|
||||
"version": "2026.1.15",
|
||||
"description": "WhatsApp gateway CLI (Baileys web) with Pi RPC agent",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -45,5 +45,9 @@ echo "💿 DMG: $DMG"
|
||||
"$ROOT_DIR/scripts/create-dmg.sh" "$APP" "$DMG"
|
||||
|
||||
if [[ "$NOTARIZE" == "1" ]]; then
|
||||
if [[ -n "${SIGN_IDENTITY:-}" ]]; then
|
||||
echo "🔏 Signing DMG: $DMG"
|
||||
/usr/bin/codesign --force --sign "$SIGN_IDENTITY" --timestamp "$DMG"
|
||||
fi
|
||||
"$ROOT_DIR/scripts/notarize-mac-artifact.sh" "$DMG"
|
||||
fi
|
||||
@@ -213,6 +213,34 @@ describe("runWithModelFallback", () => {
|
||||
expect(calls).toEqual([{ provider: "anthropic", model: "claude-opus-4-5" }]);
|
||||
});
|
||||
|
||||
it("defaults provider/model when missing (regression #946)", async () => {
|
||||
const cfg = makeCfg({
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
primary: "openai/gpt-4.1-mini",
|
||||
fallbacks: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const calls: Array<{ provider: string; model: string }> = [];
|
||||
|
||||
const result = await runWithModelFallback({
|
||||
cfg,
|
||||
provider: undefined as unknown as string,
|
||||
model: undefined as unknown as string,
|
||||
run: async (provider, model) => {
|
||||
calls.push({ provider, model });
|
||||
return "ok";
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.result).toBe("ok");
|
||||
expect(calls).toEqual([{ provider: "openai", model: "gpt-4.1-mini" }]);
|
||||
});
|
||||
|
||||
it("falls back on missing API key errors", async () => {
|
||||
const cfg = makeCfg();
|
||||
const run = vi
|
||||
|
||||
@@ -119,8 +119,6 @@ function resolveFallbackCandidates(params: {
|
||||
/** Optional explicit fallbacks list; when provided (even empty), replaces agents.defaults.model.fallbacks. */
|
||||
fallbacksOverride?: string[];
|
||||
}): ModelCandidate[] {
|
||||
const provider = params.provider.trim() || DEFAULT_PROVIDER;
|
||||
const model = params.model.trim() || DEFAULT_MODEL;
|
||||
const primary = params.cfg
|
||||
? resolveConfiguredModelRef({
|
||||
cfg: params.cfg,
|
||||
@@ -128,11 +126,15 @@ function resolveFallbackCandidates(params: {
|
||||
defaultModel: DEFAULT_MODEL,
|
||||
})
|
||||
: null;
|
||||
const defaultProvider = primary?.provider ?? DEFAULT_PROVIDER;
|
||||
const defaultModel = primary?.model ?? DEFAULT_MODEL;
|
||||
const provider = String(params.provider ?? "").trim() || defaultProvider;
|
||||
const model = String(params.model ?? "").trim() || defaultModel;
|
||||
const aliasIndex = buildModelAliasIndex({
|
||||
cfg: params.cfg ?? {},
|
||||
defaultProvider: DEFAULT_PROVIDER,
|
||||
defaultProvider,
|
||||
});
|
||||
const allowlist = buildAllowedModelKeys(params.cfg, DEFAULT_PROVIDER);
|
||||
const allowlist = buildAllowedModelKeys(params.cfg, defaultProvider);
|
||||
const seen = new Set<string>();
|
||||
const candidates: ModelCandidate[] = [];
|
||||
|
||||
@@ -160,7 +162,7 @@ function resolveFallbackCandidates(params: {
|
||||
for (const raw of modelFallbacks) {
|
||||
const resolved = resolveModelRefFromString({
|
||||
raw: String(raw ?? ""),
|
||||
defaultProvider: DEFAULT_PROVIDER,
|
||||
defaultProvider,
|
||||
aliasIndex,
|
||||
});
|
||||
if (!resolved) continue;
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createAgentSession, SessionManager, SettingsManager } from "@mariozechn
|
||||
import { resolveHeartbeatPrompt } from "../../../auto-reply/heartbeat.js";
|
||||
import { resolveChannelCapabilities } from "../../../config/channel-capabilities.js";
|
||||
import { getMachineDisplayName } from "../../../infra/machine-name.js";
|
||||
import { resolveTelegramReactionLevel } from "../../../telegram/reaction-level.js";
|
||||
import { normalizeMessageChannel } from "../../../utils/message-channel.js";
|
||||
import { isReasoningTagProvider } from "../../../utils/provider-utils.js";
|
||||
import { resolveUserPath } from "../../../utils.js";
|
||||
@@ -161,6 +162,17 @@ export async function runEmbeddedAttempt(
|
||||
accountId: params.agentAccountId,
|
||||
}) ?? [])
|
||||
: undefined;
|
||||
const reactionGuidance =
|
||||
runtimeChannel === "telegram" && params.config
|
||||
? (() => {
|
||||
const resolved = resolveTelegramReactionLevel({
|
||||
cfg: params.config,
|
||||
accountId: params.agentAccountId ?? undefined,
|
||||
});
|
||||
const level = resolved.agentReactionGuidance;
|
||||
return level ? { level, channel: "Telegram" } : undefined;
|
||||
})()
|
||||
: undefined;
|
||||
const runtimeInfo = {
|
||||
host: machineName,
|
||||
os: `${os.type()} ${os.release()}`,
|
||||
@@ -192,6 +204,7 @@ export async function runEmbeddedAttempt(
|
||||
? resolveHeartbeatPrompt(params.config?.agents?.defaults?.heartbeat?.prompt)
|
||||
: undefined,
|
||||
skillsPrompt,
|
||||
reactionGuidance,
|
||||
runtimeInfo,
|
||||
sandboxInfo,
|
||||
tools,
|
||||
|
||||
@@ -14,6 +14,10 @@ export function buildEmbeddedSystemPrompt(params: {
|
||||
reasoningTagHint: boolean;
|
||||
heartbeatPrompt?: string;
|
||||
skillsPrompt?: string;
|
||||
reactionGuidance?: {
|
||||
level: "minimal" | "extensive";
|
||||
channel: string;
|
||||
};
|
||||
runtimeInfo: {
|
||||
host: string;
|
||||
os: string;
|
||||
@@ -40,6 +44,7 @@ export function buildEmbeddedSystemPrompt(params: {
|
||||
reasoningTagHint: params.reasoningTagHint,
|
||||
heartbeatPrompt: params.heartbeatPrompt,
|
||||
skillsPrompt: params.skillsPrompt,
|
||||
reactionGuidance: params.reactionGuidance,
|
||||
runtimeInfo: params.runtimeInfo,
|
||||
sandboxInfo: params.sandboxInfo,
|
||||
toolNames: params.tools.map((tool) => tool.name),
|
||||
|
||||
@@ -34,6 +34,16 @@ describe("buildAgentSystemPrompt", () => {
|
||||
expect(prompt).toContain("<final>...</final>");
|
||||
});
|
||||
|
||||
it("includes a CLI quick reference section", () => {
|
||||
const prompt = buildAgentSystemPrompt({
|
||||
workspaceDir: "/tmp/clawd",
|
||||
});
|
||||
|
||||
expect(prompt).toContain("## Clawdbot CLI Quick Reference");
|
||||
expect(prompt).toContain("clawdbot daemon restart");
|
||||
expect(prompt).toContain("Do not invent commands");
|
||||
});
|
||||
|
||||
it("lists available tools when provided", () => {
|
||||
const prompt = buildAgentSystemPrompt({
|
||||
workspaceDir: "/tmp/clawd",
|
||||
@@ -198,4 +208,17 @@ describe("buildAgentSystemPrompt", () => {
|
||||
expect(prompt).toContain("User can toggle with /elevated on|off.");
|
||||
expect(prompt).toContain("Current elevated level: on");
|
||||
});
|
||||
|
||||
it("includes reaction guidance when provided", () => {
|
||||
const prompt = buildAgentSystemPrompt({
|
||||
workspaceDir: "/tmp/clawd",
|
||||
reactionGuidance: {
|
||||
level: "minimal",
|
||||
channel: "Telegram",
|
||||
},
|
||||
});
|
||||
|
||||
expect(prompt).toContain("## Reactions");
|
||||
expect(prompt).toContain("Reactions are enabled for Telegram in MINIMAL mode.");
|
||||
});
|
||||
});
|
||||
@@ -43,6 +43,11 @@ export function buildAgentSystemPrompt(params: {
|
||||
defaultLevel: "on" | "off";
|
||||
};
|
||||
};
|
||||
/** Reaction guidance for the agent (for Telegram minimal/extensive modes). */
|
||||
reactionGuidance?: {
|
||||
level: "minimal" | "extensive";
|
||||
channel: string;
|
||||
};
|
||||
}) {
|
||||
const coreToolSummaries: Record<string, string> = {
|
||||
read: "Read file contents",
|
||||
@@ -217,6 +222,15 @@ export function buildAgentSystemPrompt(params: {
|
||||
"TOOLS.md does not control tool availability; it is user guidance for how to use external tools.",
|
||||
"If a task is more complex or takes longer, spawn a sub-agent. It will do the work for you and ping you when it's done. You can always check up on it.",
|
||||
"",
|
||||
"## Clawdbot CLI Quick Reference",
|
||||
"Clawdbot is controlled via subcommands. Do not invent commands.",
|
||||
"To manage the Gateway daemon service (start/stop/restart):",
|
||||
"- clawdbot daemon status",
|
||||
"- clawdbot daemon start",
|
||||
"- clawdbot daemon stop",
|
||||
"- clawdbot daemon restart",
|
||||
"If unsure, ask the user to run `clawdbot help` (or `clawdbot daemon --help`) and paste the output.",
|
||||
"",
|
||||
...skillsSection,
|
||||
...memorySection,
|
||||
hasGateway ? "## Clawdbot Self-Update" : "",
|
||||
@@ -342,6 +356,29 @@ export function buildAgentSystemPrompt(params: {
|
||||
if (extraSystemPrompt) {
|
||||
lines.push("## Group Chat Context", extraSystemPrompt, "");
|
||||
}
|
||||
if (params.reactionGuidance) {
|
||||
const { level, channel } = params.reactionGuidance;
|
||||
const guidanceText =
|
||||
level === "minimal"
|
||||
? [
|
||||
`Reactions are enabled for ${channel} in MINIMAL mode.`,
|
||||
"React ONLY when truly relevant:",
|
||||
"- Acknowledge important user requests or confirmations",
|
||||
"- Express genuine sentiment (humor, appreciation) sparingly",
|
||||
"- Avoid reacting to routine messages or your own replies",
|
||||
"Guideline: at most 1 reaction per 5-10 exchanges.",
|
||||
].join("\n")
|
||||
: [
|
||||
`Reactions are enabled for ${channel} in EXTENSIVE mode.`,
|
||||
"Feel free to react liberally:",
|
||||
"- Acknowledge messages with appropriate emojis",
|
||||
"- Express sentiment and personality through reactions",
|
||||
"- React to interesting content, humor, or notable events",
|
||||
"- Use reactions to confirm understanding or agreement",
|
||||
"Guideline: react whenever it feels natural.",
|
||||
].join("\n");
|
||||
lines.push("## Reactions", guidanceText, "");
|
||||
}
|
||||
if (reasoningHint) {
|
||||
lines.push("## Reasoning Format", reasoningHint, "");
|
||||
}
|
||||
|
||||
@@ -33,9 +33,30 @@ describe("handleTelegramAction", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("adds reactions", async () => {
|
||||
it("adds reactions when reactionLevel is minimal", async () => {
|
||||
const cfg = {
|
||||
channels: { telegram: { botToken: "tok" } },
|
||||
channels: { telegram: { botToken: "tok", reactionLevel: "minimal" } },
|
||||
} as ClawdbotConfig;
|
||||
await handleTelegramAction(
|
||||
{
|
||||
action: "react",
|
||||
chatId: "123",
|
||||
messageId: "456",
|
||||
emoji: "✅",
|
||||
},
|
||||
cfg,
|
||||
);
|
||||
expect(reactMessageTelegram).toHaveBeenCalledWith(
|
||||
"123",
|
||||
456,
|
||||
"✅",
|
||||
expect.objectContaining({ token: "tok", remove: false }),
|
||||
);
|
||||
});
|
||||
|
||||
it("adds reactions when reactionLevel is extensive", async () => {
|
||||
const cfg = {
|
||||
channels: { telegram: { botToken: "tok", reactionLevel: "extensive" } },
|
||||
} as ClawdbotConfig;
|
||||
await handleTelegramAction(
|
||||
{
|
||||
@@ -56,7 +77,7 @@ describe("handleTelegramAction", () => {
|
||||
|
||||
it("removes reactions on empty emoji", async () => {
|
||||
const cfg = {
|
||||
channels: { telegram: { botToken: "tok" } },
|
||||
channels: { telegram: { botToken: "tok", reactionLevel: "minimal" } },
|
||||
} as ClawdbotConfig;
|
||||
await handleTelegramAction(
|
||||
{
|
||||
@@ -77,7 +98,7 @@ describe("handleTelegramAction", () => {
|
||||
|
||||
it("removes reactions when remove flag set", async () => {
|
||||
const cfg = {
|
||||
channels: { telegram: { botToken: "tok" } },
|
||||
channels: { telegram: { botToken: "tok", reactionLevel: "extensive" } },
|
||||
} as ClawdbotConfig;
|
||||
await handleTelegramAction(
|
||||
{
|
||||
@@ -97,10 +118,48 @@ describe("handleTelegramAction", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("respects reaction gating", async () => {
|
||||
it("blocks reactions when reactionLevel is off", async () => {
|
||||
const cfg = {
|
||||
channels: { telegram: { botToken: "tok", reactionLevel: "off" } },
|
||||
} as ClawdbotConfig;
|
||||
await expect(
|
||||
handleTelegramAction(
|
||||
{
|
||||
action: "react",
|
||||
chatId: "123",
|
||||
messageId: "456",
|
||||
emoji: "✅",
|
||||
},
|
||||
cfg,
|
||||
),
|
||||
).rejects.toThrow(/Telegram agent reactions disabled.*reactionLevel="off"/);
|
||||
});
|
||||
|
||||
it("blocks reactions when reactionLevel is ack (default)", async () => {
|
||||
const cfg = {
|
||||
channels: { telegram: { botToken: "tok", reactionLevel: "ack" } },
|
||||
} as ClawdbotConfig;
|
||||
await expect(
|
||||
handleTelegramAction(
|
||||
{
|
||||
action: "react",
|
||||
chatId: "123",
|
||||
messageId: "456",
|
||||
emoji: "✅",
|
||||
},
|
||||
cfg,
|
||||
),
|
||||
).rejects.toThrow(/Telegram agent reactions disabled.*reactionLevel="ack"/);
|
||||
});
|
||||
|
||||
it("also respects legacy actions.reactions gating", async () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
telegram: { botToken: "tok", actions: { reactions: false } },
|
||||
telegram: {
|
||||
botToken: "tok",
|
||||
reactionLevel: "minimal",
|
||||
actions: { reactions: false },
|
||||
},
|
||||
},
|
||||
} as ClawdbotConfig;
|
||||
await expect(
|
||||
@@ -113,7 +172,7 @@ describe("handleTelegramAction", () => {
|
||||
},
|
||||
cfg,
|
||||
),
|
||||
).rejects.toThrow(/Telegram reactions are disabled/);
|
||||
).rejects.toThrow(/Telegram reactions are disabled via actions.reactions/);
|
||||
});
|
||||
|
||||
it("sends a text message", async () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentToolResult } from "@mariozechner/pi-agent-core";
|
||||
import { resolveChannelCapabilities } from "../../config/channel-capabilities.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { resolveTelegramReactionLevel } from "../../telegram/reaction-level.js";
|
||||
import {
|
||||
deleteMessageTelegram,
|
||||
reactMessageTelegram,
|
||||
@@ -82,8 +83,20 @@ export async function handleTelegramAction(
|
||||
const isActionEnabled = createActionGate(cfg.channels?.telegram?.actions);
|
||||
|
||||
if (action === "react") {
|
||||
// Check reaction level first
|
||||
const reactionLevelInfo = resolveTelegramReactionLevel({
|
||||
cfg,
|
||||
accountId: accountId ?? undefined,
|
||||
});
|
||||
if (!reactionLevelInfo.agentReactionsEnabled) {
|
||||
throw new Error(
|
||||
`Telegram agent reactions disabled (reactionLevel="${reactionLevelInfo.level}"). ` +
|
||||
`Set channels.telegram.reactionLevel to "minimal" or "extensive" to enable.`,
|
||||
);
|
||||
}
|
||||
// Also check the existing action gate for backward compatibility
|
||||
if (!isActionEnabled("reactions")) {
|
||||
throw new Error("Telegram reactions are disabled.");
|
||||
throw new Error("Telegram reactions are disabled via actions.reactions.");
|
||||
}
|
||||
const chatId = readStringOrNumberParam(params, "chatId", {
|
||||
required: true,
|
||||
|
||||
@@ -4,7 +4,19 @@ export type CommandArgsFormatter = (values: CommandArgValues) => string | undefi
|
||||
|
||||
function normalizeArgValue(value: unknown): string | undefined {
|
||||
if (value == null) return undefined;
|
||||
const text = typeof value === "string" ? value.trim() : String(value).trim();
|
||||
let text: string;
|
||||
if (typeof value === "string") {
|
||||
text = value.trim();
|
||||
} else if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
||||
text = String(value).trim();
|
||||
} else if (typeof value === "symbol") {
|
||||
text = value.toString().trim();
|
||||
} else if (typeof value === "function") {
|
||||
text = value.toString().trim();
|
||||
} else {
|
||||
// Objects and arrays
|
||||
text = JSON.stringify(value);
|
||||
}
|
||||
return text ? text : undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -137,7 +137,23 @@ function formatPositionalArgs(
|
||||
for (const definition of definitions) {
|
||||
const value = values[definition.name];
|
||||
if (value == null) continue;
|
||||
const rendered = typeof value === "string" ? value.trim() : String(value);
|
||||
let rendered: string;
|
||||
if (typeof value === "string") {
|
||||
rendered = value.trim();
|
||||
} else if (
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean" ||
|
||||
typeof value === "bigint"
|
||||
) {
|
||||
rendered = String(value);
|
||||
} else if (typeof value === "symbol") {
|
||||
rendered = value.toString();
|
||||
} else if (typeof value === "function") {
|
||||
rendered = value.toString();
|
||||
} else {
|
||||
// Objects and arrays
|
||||
rendered = JSON.stringify(value);
|
||||
}
|
||||
if (!rendered) continue;
|
||||
parts.push(rendered);
|
||||
if (definition.captureRemaining) break;
|
||||
|
||||
@@ -78,11 +78,38 @@ export type TemplateContext = MsgContext & {
|
||||
IsNewSession?: string;
|
||||
};
|
||||
|
||||
function formatTemplateValue(value: unknown): string {
|
||||
if (value == null) return "";
|
||||
if (typeof value === "string") return value;
|
||||
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
||||
return String(value);
|
||||
}
|
||||
if (typeof value === "symbol" || typeof value === "function") {
|
||||
return value.toString();
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.flatMap((entry) => {
|
||||
if (entry == null) return [];
|
||||
if (typeof entry === "string") return [entry];
|
||||
if (typeof entry === "number" || typeof entry === "boolean" || typeof entry === "bigint") {
|
||||
return [String(entry)];
|
||||
}
|
||||
return [];
|
||||
})
|
||||
.join(",");
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// Simple {{Placeholder}} interpolation using inbound message context.
|
||||
export function applyTemplate(str: string | undefined, ctx: TemplateContext) {
|
||||
if (!str) return "";
|
||||
return str.replace(/{{\s*(\w+)\s*}}/g, (_, key) => {
|
||||
const value = ctx[key as keyof TemplateContext];
|
||||
return value == null ? "" : String(value);
|
||||
return formatTemplateValue(value);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
describe("pw-session getPageForTargetId", () => {
|
||||
it("falls back to the only page when CDP session attachment is blocked (extension relays)", async () => {
|
||||
vi.resetModules();
|
||||
|
||||
const pageOn = vi.fn();
|
||||
const contextOn = vi.fn();
|
||||
const browserOn = vi.fn();
|
||||
const browserClose = vi.fn(async () => {});
|
||||
|
||||
const context = {
|
||||
pages: () => [],
|
||||
on: contextOn,
|
||||
newCDPSession: vi.fn(async () => {
|
||||
throw new Error("Not allowed");
|
||||
}),
|
||||
} as unknown as import("playwright-core").BrowserContext;
|
||||
|
||||
const page = {
|
||||
on: pageOn,
|
||||
context: () => context,
|
||||
} as unknown as import("playwright-core").Page;
|
||||
|
||||
// Fill pages() after page exists.
|
||||
(context as unknown as { pages: () => unknown[] }).pages = () => [page];
|
||||
|
||||
const browser = {
|
||||
contexts: () => [context],
|
||||
on: browserOn,
|
||||
close: browserClose,
|
||||
} as unknown as import("playwright-core").Browser;
|
||||
|
||||
vi.doMock("playwright-core", () => ({
|
||||
chromium: {
|
||||
connectOverCDP: vi.fn(async () => browser),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.doMock("./chrome.js", () => ({
|
||||
getChromeWebSocketUrl: vi.fn(async () => null),
|
||||
}));
|
||||
|
||||
const mod = await import("./pw-session.js");
|
||||
const resolved = await mod.getPageForTargetId({
|
||||
cdpUrl: "http://127.0.0.1:18792",
|
||||
targetId: "NOT_A_TAB",
|
||||
});
|
||||
expect(resolved).toBe(page);
|
||||
|
||||
await mod.closePlaywrightBrowserConnection();
|
||||
expect(browserClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -332,7 +332,13 @@ export async function getPageForTargetId(opts: {
|
||||
const first = pages[0];
|
||||
if (!opts.targetId) return first;
|
||||
const found = await findPageByTargetId(browser, opts.targetId);
|
||||
if (!found) throw new Error("tab not found");
|
||||
if (!found) {
|
||||
// Extension relays can block CDP attachment APIs (e.g. Target.attachToBrowserTarget),
|
||||
// which prevents us from resolving a page's targetId via newCDPSession(). If Playwright
|
||||
// only exposes a single Page, use it as a best-effort fallback.
|
||||
if (pages.length === 1) return first;
|
||||
throw new Error("tab not found");
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,21 @@ export type TelegramAccountConfig = {
|
||||
webhookPath?: string;
|
||||
/** Per-action tool gating (default: true for all). */
|
||||
actions?: TelegramActionConfig;
|
||||
/**
|
||||
* Controls which user reactions trigger notifications:
|
||||
* - "off" (default): ignore all reactions
|
||||
* - "own": notify when users react to bot messages
|
||||
* - "all": notify agent of all reactions
|
||||
*/
|
||||
reactionNotifications?: "off" | "own" | "all";
|
||||
/**
|
||||
* Controls agent's reaction capability:
|
||||
* - "off": agent cannot react
|
||||
* - "ack" (default): bot sends acknowledgment reactions (👀 while processing)
|
||||
* - "minimal": agent can react sparingly (guideline: 1 per 5-10 exchanges)
|
||||
* - "extensive": agent can react liberally when appropriate
|
||||
*/
|
||||
reactionLevel?: "off" | "ack" | "minimal" | "extensive";
|
||||
};
|
||||
|
||||
export type TelegramTopicConfig = {
|
||||
|
||||
@@ -63,8 +63,12 @@ export const TelegramAccountSchemaBase = z.object({
|
||||
actions: z
|
||||
.object({
|
||||
reactions: z.boolean().optional(),
|
||||
sendMessage: z.boolean().optional(),
|
||||
deleteMessage: z.boolean().optional(),
|
||||
})
|
||||
.optional(),
|
||||
reactionNotifications: z.enum(["off", "own", "all"]).optional(),
|
||||
reactionLevel: z.enum(["off", "ack", "minimal", "extensive"]).optional(),
|
||||
});
|
||||
|
||||
export const TelegramAccountSchema = TelegramAccountSchemaBase.superRefine((value, ctx) => {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { API_CONSTANTS } from "grammy";
|
||||
|
||||
type TelegramUpdateType = (typeof API_CONSTANTS.ALL_UPDATE_TYPES)[number];
|
||||
|
||||
export function resolveTelegramAllowedUpdates(): ReadonlyArray<TelegramUpdateType> {
|
||||
const updates = [...API_CONSTANTS.DEFAULT_UPDATE_TYPES] as TelegramUpdateType[];
|
||||
if (!updates.includes("message_reaction")) {
|
||||
updates.push("message_reaction");
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+93
-2
@@ -18,11 +18,17 @@ import {
|
||||
resolveChannelGroupRequireMention,
|
||||
} from "../config/group-policy.js";
|
||||
import { loadSessionStore, resolveStorePath } from "../config/sessions.js";
|
||||
import { logVerbose, shouldLogVerbose } from "../globals.js";
|
||||
import { danger, logVerbose, shouldLogVerbose } from "../globals.js";
|
||||
import { enqueueSystemEvent } from "../infra/system-events.js";
|
||||
import { getChildLogger } from "../logging.js";
|
||||
import { resolveAgentRoute } from "../routing/resolve-route.js";
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { resolveTelegramAccount } from "./accounts.js";
|
||||
import { resolveTelegramForumThreadId, resolveTelegramStreamMode } from "./bot/helpers.js";
|
||||
import {
|
||||
buildTelegramGroupPeerId,
|
||||
resolveTelegramForumThreadId,
|
||||
resolveTelegramStreamMode,
|
||||
} from "./bot/helpers.js";
|
||||
import type { TelegramContext, TelegramMessage } from "./bot/types.js";
|
||||
import { registerTelegramHandlers } from "./bot-handlers.js";
|
||||
import { createTelegramMessageProcessor } from "./bot-message.js";
|
||||
@@ -34,6 +40,7 @@ import {
|
||||
type TelegramUpdateKeyContext,
|
||||
} from "./bot-updates.js";
|
||||
import { resolveTelegramFetch } from "./fetch.js";
|
||||
import { wasSentByBot } from "./sent-message-cache.js";
|
||||
|
||||
export type TelegramBotOptions = {
|
||||
token: string;
|
||||
@@ -59,8 +66,14 @@ export function getTelegramSequentialKey(ctx: {
|
||||
message?: TelegramMessage;
|
||||
edited_message?: TelegramMessage;
|
||||
callback_query?: { message?: TelegramMessage };
|
||||
message_reaction?: { chat?: { id?: number } };
|
||||
};
|
||||
}): string {
|
||||
// Handle reaction updates
|
||||
const reaction = ctx.update?.message_reaction;
|
||||
if (reaction?.chat?.id) {
|
||||
return `telegram:${reaction.chat.id}`;
|
||||
}
|
||||
const msg =
|
||||
ctx.message ??
|
||||
ctx.update?.message ??
|
||||
@@ -291,6 +304,84 @@ export function createTelegramBot(opts: TelegramBotOptions) {
|
||||
opts,
|
||||
});
|
||||
|
||||
// Handle emoji reactions to messages
|
||||
bot.on("message_reaction", async (ctx) => {
|
||||
try {
|
||||
const reaction = ctx.messageReaction;
|
||||
if (!reaction) return;
|
||||
if (shouldSkipUpdate(ctx)) return;
|
||||
|
||||
const chatId = reaction.chat.id;
|
||||
const messageId = reaction.message_id;
|
||||
const user = reaction.user;
|
||||
|
||||
// Resolve reaction notification mode (default: "off")
|
||||
const reactionMode = telegramCfg.reactionNotifications ?? "off";
|
||||
if (reactionMode === "off") return;
|
||||
if (user?.is_bot) return;
|
||||
if (reactionMode === "own" && !wasSentByBot(chatId, messageId)) return;
|
||||
|
||||
// Detect added reactions
|
||||
const oldEmojis = new Set(
|
||||
reaction.old_reaction
|
||||
.filter((r): r is { type: "emoji"; emoji: string } => r.type === "emoji")
|
||||
.map((r) => r.emoji),
|
||||
);
|
||||
const addedReactions = reaction.new_reaction
|
||||
.filter((r): r is { type: "emoji"; emoji: string } => r.type === "emoji")
|
||||
.filter((r) => !oldEmojis.has(r.emoji));
|
||||
|
||||
if (addedReactions.length === 0) return;
|
||||
|
||||
// Build sender label
|
||||
const senderName = user
|
||||
? [user.first_name, user.last_name].filter(Boolean).join(" ").trim() || user.username
|
||||
: undefined;
|
||||
const senderUsername = user?.username ? `@${user.username}` : undefined;
|
||||
let senderLabel = senderName;
|
||||
if (senderName && senderUsername) {
|
||||
senderLabel = `${senderName} (${senderUsername})`;
|
||||
} else if (!senderName && senderUsername) {
|
||||
senderLabel = senderUsername;
|
||||
}
|
||||
if (!senderLabel && user?.id) {
|
||||
senderLabel = `id:${user.id}`;
|
||||
}
|
||||
senderLabel = senderLabel || "unknown";
|
||||
|
||||
// Extract forum thread info (similar to message processing)
|
||||
const messageThreadId = (reaction as any).message_thread_id;
|
||||
const isForum = (reaction.chat as any).is_forum === true;
|
||||
const resolvedThreadId = resolveTelegramForumThreadId({
|
||||
isForum,
|
||||
messageThreadId,
|
||||
});
|
||||
|
||||
// Resolve agent route for session
|
||||
const isGroup = reaction.chat.type === "group" || reaction.chat.type === "supergroup";
|
||||
const peerId = isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : String(chatId);
|
||||
const route = resolveAgentRoute({
|
||||
cfg,
|
||||
channel: "telegram",
|
||||
accountId: account.accountId,
|
||||
peer: { kind: isGroup ? "group" : "dm", id: peerId },
|
||||
});
|
||||
|
||||
// Enqueue system event for each added reaction
|
||||
for (const r of addedReactions) {
|
||||
const emoji = r.emoji;
|
||||
const text = `Telegram reaction added: ${emoji} by ${senderLabel} on msg ${messageId}`;
|
||||
enqueueSystemEvent(text, {
|
||||
sessionKey: route.sessionKey,
|
||||
contextKey: `telegram:reaction:add:${chatId}:${messageId}:${user?.id ?? "anon"}:${emoji}`,
|
||||
});
|
||||
logVerbose(`telegram: reaction event enqueued: ${text}`);
|
||||
}
|
||||
} catch (err) {
|
||||
runtime.error?.(danger(`telegram reaction handler failed: ${String(err)}`));
|
||||
}
|
||||
});
|
||||
|
||||
registerTelegramHandlers({
|
||||
cfg,
|
||||
accountId: account.accountId,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { computeBackoff, sleepWithAbort } from "../infra/backoff.js";
|
||||
import { formatDurationMs } from "../infra/format-duration.js";
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { resolveTelegramAccount } from "./accounts.js";
|
||||
import { resolveTelegramAllowedUpdates } from "./allowed-updates.js";
|
||||
import { createTelegramBot } from "./bot.js";
|
||||
import { makeProxyFetch } from "./proxy.js";
|
||||
import { readTelegramUpdateOffset, writeTelegramUpdateOffset } from "./update-offset-store.js";
|
||||
@@ -33,6 +34,8 @@ export function createTelegramRunnerOptions(cfg: ClawdbotConfig): RunOptions<unk
|
||||
fetch: {
|
||||
// Match grammY defaults
|
||||
timeout: 30,
|
||||
// Request reactions without dropping default update types.
|
||||
allowed_updates: resolveTelegramAllowedUpdates(),
|
||||
},
|
||||
// Suppress grammY getUpdates stack traces; we log concise errors ourselves.
|
||||
silent: true,
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { resolveTelegramReactionLevel } from "./reaction-level.js";
|
||||
|
||||
describe("resolveTelegramReactionLevel", () => {
|
||||
const prevTelegramToken = process.env.TELEGRAM_BOT_TOKEN;
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.TELEGRAM_BOT_TOKEN = "test-token";
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (prevTelegramToken === undefined) {
|
||||
delete process.env.TELEGRAM_BOT_TOKEN;
|
||||
} else {
|
||||
process.env.TELEGRAM_BOT_TOKEN = prevTelegramToken;
|
||||
}
|
||||
});
|
||||
|
||||
it("defaults to ack level when reactionLevel is not set", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
channels: { telegram: {} },
|
||||
};
|
||||
|
||||
const result = resolveTelegramReactionLevel({ cfg });
|
||||
expect(result.level).toBe("ack");
|
||||
expect(result.ackEnabled).toBe(true);
|
||||
expect(result.agentReactionsEnabled).toBe(false);
|
||||
expect(result.agentReactionGuidance).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns off level with no reactions enabled", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
channels: { telegram: { reactionLevel: "off" } },
|
||||
};
|
||||
|
||||
const result = resolveTelegramReactionLevel({ cfg });
|
||||
expect(result.level).toBe("off");
|
||||
expect(result.ackEnabled).toBe(false);
|
||||
expect(result.agentReactionsEnabled).toBe(false);
|
||||
expect(result.agentReactionGuidance).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns ack level with only ackEnabled", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
channels: { telegram: { reactionLevel: "ack" } },
|
||||
};
|
||||
|
||||
const result = resolveTelegramReactionLevel({ cfg });
|
||||
expect(result.level).toBe("ack");
|
||||
expect(result.ackEnabled).toBe(true);
|
||||
expect(result.agentReactionsEnabled).toBe(false);
|
||||
expect(result.agentReactionGuidance).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns minimal level with agent reactions enabled and minimal guidance", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
channels: { telegram: { reactionLevel: "minimal" } },
|
||||
};
|
||||
|
||||
const result = resolveTelegramReactionLevel({ cfg });
|
||||
expect(result.level).toBe("minimal");
|
||||
expect(result.ackEnabled).toBe(false);
|
||||
expect(result.agentReactionsEnabled).toBe(true);
|
||||
expect(result.agentReactionGuidance).toBe("minimal");
|
||||
});
|
||||
|
||||
it("returns extensive level with agent reactions enabled and extensive guidance", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
channels: { telegram: { reactionLevel: "extensive" } },
|
||||
};
|
||||
|
||||
const result = resolveTelegramReactionLevel({ cfg });
|
||||
expect(result.level).toBe("extensive");
|
||||
expect(result.ackEnabled).toBe(false);
|
||||
expect(result.agentReactionsEnabled).toBe(true);
|
||||
expect(result.agentReactionGuidance).toBe("extensive");
|
||||
});
|
||||
|
||||
it("resolves reaction level from a specific account", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
channels: {
|
||||
telegram: {
|
||||
reactionLevel: "ack",
|
||||
accounts: {
|
||||
work: { botToken: "tok-work", reactionLevel: "extensive" },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = resolveTelegramReactionLevel({ cfg, accountId: "work" });
|
||||
expect(result.level).toBe("extensive");
|
||||
expect(result.ackEnabled).toBe(false);
|
||||
expect(result.agentReactionsEnabled).toBe(true);
|
||||
expect(result.agentReactionGuidance).toBe("extensive");
|
||||
});
|
||||
|
||||
it("falls back to global level when account has no reactionLevel", () => {
|
||||
const cfg: ClawdbotConfig = {
|
||||
channels: {
|
||||
telegram: {
|
||||
reactionLevel: "minimal",
|
||||
accounts: {
|
||||
work: { botToken: "tok-work" },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = resolveTelegramReactionLevel({ cfg, accountId: "work" });
|
||||
expect(result.level).toBe("minimal");
|
||||
expect(result.agentReactionsEnabled).toBe(true);
|
||||
expect(result.agentReactionGuidance).toBe("minimal");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { resolveTelegramAccount } from "./accounts.js";
|
||||
|
||||
export type TelegramReactionLevel = "off" | "ack" | "minimal" | "extensive";
|
||||
|
||||
export type ResolvedReactionLevel = {
|
||||
level: TelegramReactionLevel;
|
||||
/** Whether ACK reactions (e.g., 👀 when processing) are enabled. */
|
||||
ackEnabled: boolean;
|
||||
/** Whether agent-controlled reactions are enabled. */
|
||||
agentReactionsEnabled: boolean;
|
||||
/** Guidance level for agent reactions (minimal = sparse, extensive = liberal). */
|
||||
agentReactionGuidance?: "minimal" | "extensive";
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve the effective reaction level and its implications.
|
||||
*/
|
||||
export function resolveTelegramReactionLevel(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
accountId?: string;
|
||||
}): ResolvedReactionLevel {
|
||||
const account = resolveTelegramAccount({
|
||||
cfg: params.cfg,
|
||||
accountId: params.accountId,
|
||||
});
|
||||
const level = (account.config.reactionLevel ?? "ack") as TelegramReactionLevel;
|
||||
|
||||
switch (level) {
|
||||
case "off":
|
||||
return {
|
||||
level,
|
||||
ackEnabled: false,
|
||||
agentReactionsEnabled: false,
|
||||
};
|
||||
case "ack":
|
||||
return {
|
||||
level,
|
||||
ackEnabled: true,
|
||||
agentReactionsEnabled: false,
|
||||
};
|
||||
case "minimal":
|
||||
return {
|
||||
level,
|
||||
ackEnabled: false,
|
||||
agentReactionsEnabled: true,
|
||||
agentReactionGuidance: "minimal",
|
||||
};
|
||||
case "extensive":
|
||||
return {
|
||||
level,
|
||||
ackEnabled: false,
|
||||
agentReactionsEnabled: true,
|
||||
agentReactionGuidance: "extensive",
|
||||
};
|
||||
default:
|
||||
// Fallback to ack behavior
|
||||
return {
|
||||
level: "ack",
|
||||
ackEnabled: true,
|
||||
agentReactionsEnabled: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { loadWebMedia } from "../web/media.js";
|
||||
import { resolveTelegramAccount } from "./accounts.js";
|
||||
import { resolveTelegramFetch } from "./fetch.js";
|
||||
import { markdownToTelegramHtml } from "./format.js";
|
||||
import { recordSentMessage } from "./sent-message-cache.js";
|
||||
import { parseTelegramTarget, stripTelegramInternalPrefixes } from "./targets.js";
|
||||
import { resolveTelegramVoiceSend } from "./voice.js";
|
||||
|
||||
@@ -272,6 +273,9 @@ export async function sendMessageTelegram(
|
||||
}
|
||||
const mediaMessageId = String(result?.message_id ?? "unknown");
|
||||
const resolvedChatId = String(result?.chat?.id ?? chatId);
|
||||
if (result?.message_id) {
|
||||
recordSentMessage(chatId, result.message_id);
|
||||
}
|
||||
recordChannelActivity({
|
||||
channel: "telegram",
|
||||
accountId: account.accountId,
|
||||
@@ -353,6 +357,9 @@ export async function sendMessageTelegram(
|
||||
},
|
||||
);
|
||||
const messageId = String(res?.message_id ?? "unknown");
|
||||
if (res?.message_id) {
|
||||
recordSentMessage(chatId, res.message_id);
|
||||
}
|
||||
recordChannelActivity({
|
||||
channel: "telegram",
|
||||
accountId: account.accountId,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { clearSentMessageCache, recordSentMessage, wasSentByBot } from "./sent-message-cache.js";
|
||||
|
||||
describe("sent-message-cache", () => {
|
||||
afterEach(() => {
|
||||
clearSentMessageCache();
|
||||
});
|
||||
|
||||
it("records and retrieves sent messages", () => {
|
||||
recordSentMessage(123, 1);
|
||||
recordSentMessage(123, 2);
|
||||
recordSentMessage(456, 10);
|
||||
|
||||
expect(wasSentByBot(123, 1)).toBe(true);
|
||||
expect(wasSentByBot(123, 2)).toBe(true);
|
||||
expect(wasSentByBot(456, 10)).toBe(true);
|
||||
expect(wasSentByBot(123, 3)).toBe(false);
|
||||
expect(wasSentByBot(789, 1)).toBe(false);
|
||||
});
|
||||
|
||||
it("handles string chat IDs", () => {
|
||||
recordSentMessage("123", 1);
|
||||
expect(wasSentByBot("123", 1)).toBe(true);
|
||||
expect(wasSentByBot(123, 1)).toBe(true);
|
||||
});
|
||||
|
||||
it("clears cache", () => {
|
||||
recordSentMessage(123, 1);
|
||||
expect(wasSentByBot(123, 1)).toBe(true);
|
||||
|
||||
clearSentMessageCache();
|
||||
expect(wasSentByBot(123, 1)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* In-memory cache of sent message IDs per chat.
|
||||
* Used to identify bot's own messages for reaction filtering ("own" mode).
|
||||
*/
|
||||
|
||||
const TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
type CacheEntry = {
|
||||
messageIds: Set<number>;
|
||||
timestamps: Map<number, number>;
|
||||
};
|
||||
|
||||
const sentMessages = new Map<string, CacheEntry>();
|
||||
|
||||
function getChatKey(chatId: number | string): string {
|
||||
return String(chatId);
|
||||
}
|
||||
|
||||
function cleanupExpired(entry: CacheEntry): void {
|
||||
const now = Date.now();
|
||||
for (const [msgId, timestamp] of entry.timestamps) {
|
||||
if (now - timestamp > TTL_MS) {
|
||||
entry.messageIds.delete(msgId);
|
||||
entry.timestamps.delete(msgId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a message ID as sent by the bot.
|
||||
*/
|
||||
export function recordSentMessage(chatId: number | string, messageId: number): void {
|
||||
const key = getChatKey(chatId);
|
||||
let entry = sentMessages.get(key);
|
||||
if (!entry) {
|
||||
entry = { messageIds: new Set(), timestamps: new Map() };
|
||||
sentMessages.set(key, entry);
|
||||
}
|
||||
entry.messageIds.add(messageId);
|
||||
entry.timestamps.set(messageId, Date.now());
|
||||
// Periodic cleanup
|
||||
if (entry.messageIds.size > 100) {
|
||||
cleanupExpired(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a message was sent by the bot.
|
||||
*/
|
||||
export function wasSentByBot(chatId: number | string, messageId: number): boolean {
|
||||
const key = getChatKey(chatId);
|
||||
const entry = sentMessages.get(key);
|
||||
if (!entry) return false;
|
||||
// Clean up expired entries on read
|
||||
cleanupExpired(entry);
|
||||
return entry.messageIds.has(messageId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all cached entries (for testing).
|
||||
*/
|
||||
export function clearSentMessageCache(): void {
|
||||
sentMessages.clear();
|
||||
}
|
||||
@@ -16,9 +16,10 @@ const createTelegramBotSpy = vi.fn(() => ({
|
||||
stop: stopSpy,
|
||||
}));
|
||||
|
||||
vi.mock("grammy", () => ({
|
||||
webhookCallback: () => handlerSpy,
|
||||
}));
|
||||
vi.mock("grammy", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("grammy")>();
|
||||
return { ...actual, webhookCallback: () => handlerSpy };
|
||||
});
|
||||
|
||||
vi.mock("./bot.js", () => ({
|
||||
createTelegramBot: (...args: unknown[]) => createTelegramBotSpy(...args),
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ClawdbotConfig } from "../config/config.js";
|
||||
import { formatErrorMessage } from "../infra/errors.js";
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
import { resolveTelegramAllowedUpdates } from "./allowed-updates.js";
|
||||
import { createTelegramBot } from "./bot.js";
|
||||
|
||||
export async function startTelegramWebhook(opts: {
|
||||
@@ -63,6 +64,7 @@ export async function startTelegramWebhook(opts: {
|
||||
|
||||
await bot.api.setWebhook(publicUrl, {
|
||||
secret_token: opts.secret,
|
||||
allowed_updates: resolveTelegramAllowedUpdates(),
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(port, host, resolve));
|
||||
|
||||
Reference in new issue
Block a user