refactor: split remaining monitor runtime helpers
parent
4e94f3aa02
commit
b86bc9de95
@ -0,0 +1,471 @@
|
||||
import type { ClawdbotConfig } from "../runtime-api.js";
|
||||
import { normalizeFeishuExternalKey } from "./external-keys.js";
|
||||
import { downloadMessageResourceFeishu } from "./media.js";
|
||||
import { parsePostContent } from "./post.js";
|
||||
import { getFeishuRuntime } from "./runtime.js";
|
||||
import type { FeishuMediaInfo } from "./types.js";
|
||||
|
||||
export type FeishuMention = {
|
||||
key: string;
|
||||
id: {
|
||||
open_id?: string;
|
||||
user_id?: string;
|
||||
union_id?: string;
|
||||
};
|
||||
name: string;
|
||||
tenant_key?: string;
|
||||
};
|
||||
|
||||
type FeishuMessageLike = {
|
||||
message: {
|
||||
content: string;
|
||||
message_type: string;
|
||||
mentions?: FeishuMention[];
|
||||
chat_id: string;
|
||||
root_id?: string;
|
||||
parent_id?: string;
|
||||
thread_id?: string;
|
||||
message_id: string;
|
||||
};
|
||||
sender: {
|
||||
sender_id: {
|
||||
open_id?: string;
|
||||
user_id?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
export type GroupSessionScope = "group" | "group_sender" | "group_topic" | "group_topic_sender";
|
||||
|
||||
export type ResolvedFeishuGroupSession = {
|
||||
peerId: string;
|
||||
parentPeer: { kind: "group"; id: string } | null;
|
||||
groupSessionScope: GroupSessionScope;
|
||||
replyInThread: boolean;
|
||||
threadReply: boolean;
|
||||
};
|
||||
|
||||
function buildFeishuConversationId(params: {
|
||||
chatId: string;
|
||||
scope: GroupSessionScope | "group_sender";
|
||||
topicId?: string;
|
||||
senderOpenId?: string;
|
||||
}): string {
|
||||
switch (params.scope) {
|
||||
case "group_sender":
|
||||
return `${params.chatId}:sender:${params.senderOpenId}`;
|
||||
case "group_topic":
|
||||
return `${params.chatId}:topic:${params.topicId}`;
|
||||
case "group_topic_sender":
|
||||
return `${params.chatId}:topic:${params.topicId}:sender:${params.senderOpenId}`;
|
||||
default:
|
||||
return params.chatId;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveFeishuGroupSession(params: {
|
||||
chatId: string;
|
||||
senderOpenId: string;
|
||||
messageId: string;
|
||||
rootId?: string;
|
||||
threadId?: string;
|
||||
groupConfig?: {
|
||||
groupSessionScope?: GroupSessionScope;
|
||||
topicSessionMode?: "enabled" | "disabled";
|
||||
replyInThread?: "enabled" | "disabled";
|
||||
};
|
||||
feishuCfg?: {
|
||||
groupSessionScope?: GroupSessionScope;
|
||||
topicSessionMode?: "enabled" | "disabled";
|
||||
replyInThread?: "enabled" | "disabled";
|
||||
};
|
||||
}): ResolvedFeishuGroupSession {
|
||||
const { chatId, senderOpenId, messageId, rootId, threadId, groupConfig, feishuCfg } = params;
|
||||
const normalizedThreadId = threadId?.trim();
|
||||
const normalizedRootId = rootId?.trim();
|
||||
const threadReply = Boolean(normalizedThreadId || normalizedRootId);
|
||||
const replyInThread =
|
||||
(groupConfig?.replyInThread ?? feishuCfg?.replyInThread ?? "disabled") === "enabled" ||
|
||||
threadReply;
|
||||
const legacyTopicSessionMode =
|
||||
groupConfig?.topicSessionMode ?? feishuCfg?.topicSessionMode ?? "disabled";
|
||||
const groupSessionScope: GroupSessionScope =
|
||||
groupConfig?.groupSessionScope ??
|
||||
feishuCfg?.groupSessionScope ??
|
||||
(legacyTopicSessionMode === "enabled" ? "group_topic" : "group");
|
||||
const topicScope =
|
||||
groupSessionScope === "group_topic" || groupSessionScope === "group_topic_sender"
|
||||
? (normalizedRootId ?? normalizedThreadId ?? (replyInThread ? messageId : null))
|
||||
: null;
|
||||
|
||||
let peerId = chatId;
|
||||
switch (groupSessionScope) {
|
||||
case "group_sender":
|
||||
peerId = buildFeishuConversationId({ chatId, scope: "group_sender", senderOpenId });
|
||||
break;
|
||||
case "group_topic":
|
||||
peerId = topicScope
|
||||
? buildFeishuConversationId({ chatId, scope: "group_topic", topicId: topicScope })
|
||||
: chatId;
|
||||
break;
|
||||
case "group_topic_sender":
|
||||
peerId = topicScope
|
||||
? buildFeishuConversationId({
|
||||
chatId,
|
||||
scope: "group_topic_sender",
|
||||
topicId: topicScope,
|
||||
senderOpenId,
|
||||
})
|
||||
: buildFeishuConversationId({ chatId, scope: "group_sender", senderOpenId });
|
||||
break;
|
||||
case "group":
|
||||
default:
|
||||
peerId = chatId;
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
peerId,
|
||||
parentPeer:
|
||||
topicScope &&
|
||||
(groupSessionScope === "group_topic" || groupSessionScope === "group_topic_sender")
|
||||
? { kind: "group", id: chatId }
|
||||
: null,
|
||||
groupSessionScope,
|
||||
replyInThread,
|
||||
threadReply,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseMessageContent(content: string, messageType: string): string {
|
||||
if (messageType === "post") {
|
||||
return parsePostContent(content).textContent;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
if (messageType === "text") {
|
||||
return parsed.text || "";
|
||||
}
|
||||
if (messageType === "share_chat") {
|
||||
if (parsed && typeof parsed === "object") {
|
||||
const share = parsed as { body?: unknown; summary?: unknown; share_chat_id?: unknown };
|
||||
if (typeof share.body === "string" && share.body.trim()) {
|
||||
return share.body.trim();
|
||||
}
|
||||
if (typeof share.summary === "string" && share.summary.trim()) {
|
||||
return share.summary.trim();
|
||||
}
|
||||
if (typeof share.share_chat_id === "string" && share.share_chat_id.trim()) {
|
||||
return `[Forwarded message: ${share.share_chat_id.trim()}]`;
|
||||
}
|
||||
}
|
||||
return "[Forwarded message]";
|
||||
}
|
||||
if (messageType === "merge_forward") {
|
||||
return "[Merged and Forwarded Message - loading...]";
|
||||
}
|
||||
return content;
|
||||
} catch {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
function formatSubMessageContent(content: string, contentType: string): string {
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
switch (contentType) {
|
||||
case "text":
|
||||
return parsed.text || content;
|
||||
case "post":
|
||||
return parsePostContent(content).textContent;
|
||||
case "image":
|
||||
return "[Image]";
|
||||
case "file":
|
||||
return `[File: ${parsed.file_name || "unknown"}]`;
|
||||
case "audio":
|
||||
return "[Audio]";
|
||||
case "video":
|
||||
return "[Video]";
|
||||
case "sticker":
|
||||
return "[Sticker]";
|
||||
case "merge_forward":
|
||||
return "[Nested Merged Forward]";
|
||||
default:
|
||||
return `[${contentType}]`;
|
||||
}
|
||||
} catch {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseMergeForwardContent(params: {
|
||||
content: string;
|
||||
log?: (...args: any[]) => void;
|
||||
}): string {
|
||||
const { content, log } = params;
|
||||
const maxMessages = 50;
|
||||
log?.("feishu: parsing merge_forward sub-messages from API response");
|
||||
|
||||
let items: Array<{
|
||||
message_id?: string;
|
||||
msg_type?: string;
|
||||
body?: { content?: string };
|
||||
sender?: { id?: string };
|
||||
upper_message_id?: string;
|
||||
create_time?: string;
|
||||
}>;
|
||||
try {
|
||||
items = JSON.parse(content);
|
||||
} catch {
|
||||
log?.("feishu: merge_forward items parse failed");
|
||||
return "[Merged and Forwarded Message - parse error]";
|
||||
}
|
||||
if (!Array.isArray(items) || items.length === 0) {
|
||||
return "[Merged and Forwarded Message - no sub-messages]";
|
||||
}
|
||||
const subMessages = items.filter((item) => item.upper_message_id);
|
||||
if (subMessages.length === 0) {
|
||||
return "[Merged and Forwarded Message - no sub-messages found]";
|
||||
}
|
||||
|
||||
log?.(`feishu: merge_forward contains ${subMessages.length} sub-messages`);
|
||||
subMessages.sort(
|
||||
(a, b) => parseInt(a.create_time || "0", 10) - parseInt(b.create_time || "0", 10),
|
||||
);
|
||||
|
||||
const lines = ["[Merged and Forwarded Messages]"];
|
||||
for (const item of subMessages.slice(0, maxMessages)) {
|
||||
lines.push(`- ${formatSubMessageContent(item.body?.content || "", item.msg_type || "text")}`);
|
||||
}
|
||||
if (subMessages.length > maxMessages) {
|
||||
lines.push(`... and ${subMessages.length - maxMessages} more messages`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function checkBotMentioned(event: FeishuMessageLike, botOpenId?: string): boolean {
|
||||
if (!botOpenId) {
|
||||
return false;
|
||||
}
|
||||
if ((event.message.content ?? "").includes("@_all")) {
|
||||
return true;
|
||||
}
|
||||
const mentions = event.message.mentions ?? [];
|
||||
if (mentions.length > 0) {
|
||||
return mentions.some((mention) => mention.id.open_id === botOpenId);
|
||||
}
|
||||
if (event.message.message_type === "post") {
|
||||
return parsePostContent(event.message.content).mentionedOpenIds.some((id) => id === botOpenId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function normalizeMentions(
|
||||
text: string,
|
||||
mentions?: FeishuMention[],
|
||||
botStripId?: string,
|
||||
): string {
|
||||
if (!mentions || mentions.length === 0) {
|
||||
return text;
|
||||
}
|
||||
const escaped = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const escapeName = (value: string) => value.replace(/</g, "<").replace(/>/g, ">");
|
||||
let result = text;
|
||||
for (const mention of mentions) {
|
||||
const mentionId = mention.id.open_id;
|
||||
const replacement =
|
||||
botStripId && mentionId === botStripId
|
||||
? ""
|
||||
: mentionId
|
||||
? `<at user_id="${mentionId}">${escapeName(mention.name)}</at>`
|
||||
: `@${mention.name}`;
|
||||
result = result.replace(new RegExp(escaped(mention.key), "g"), () => replacement).trim();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function normalizeFeishuCommandProbeBody(text: string): string {
|
||||
if (!text) {
|
||||
return "";
|
||||
}
|
||||
return text
|
||||
.replace(/<at\b[^>]*>[^<]*<\/at>/giu, " ")
|
||||
.replace(/(^|\s)@[^/\s]+(?=\s|$|\/)/gu, "$1")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function parseMediaKeys(
|
||||
content: string,
|
||||
messageType: string,
|
||||
): { imageKey?: string; fileKey?: string; fileName?: string } {
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
const imageKey = normalizeFeishuExternalKey(parsed.image_key);
|
||||
const fileKey = normalizeFeishuExternalKey(parsed.file_key);
|
||||
switch (messageType) {
|
||||
case "image":
|
||||
return { imageKey, fileName: parsed.file_name };
|
||||
case "file":
|
||||
case "audio":
|
||||
case "sticker":
|
||||
return { fileKey, fileName: parsed.file_name };
|
||||
case "video":
|
||||
case "media":
|
||||
return { fileKey, imageKey, fileName: parsed.file_name };
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function toMessageResourceType(messageType: string): "image" | "file" {
|
||||
return messageType === "image" ? "image" : "file";
|
||||
}
|
||||
|
||||
function inferPlaceholder(messageType: string): string {
|
||||
switch (messageType) {
|
||||
case "image":
|
||||
return "<media:image>";
|
||||
case "file":
|
||||
return "<media:document>";
|
||||
case "audio":
|
||||
return "<media:audio>";
|
||||
case "video":
|
||||
case "media":
|
||||
return "<media:video>";
|
||||
case "sticker":
|
||||
return "<media:sticker>";
|
||||
default:
|
||||
return "<media:document>";
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveFeishuMediaList(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
messageId: string;
|
||||
messageType: string;
|
||||
content: string;
|
||||
maxBytes: number;
|
||||
log?: (msg: string) => void;
|
||||
accountId?: string;
|
||||
}): Promise<FeishuMediaInfo[]> {
|
||||
const { cfg, messageId, messageType, content, maxBytes, log, accountId } = params;
|
||||
const mediaTypes = ["image", "file", "audio", "video", "media", "sticker", "post"];
|
||||
if (!mediaTypes.includes(messageType)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const out: FeishuMediaInfo[] = [];
|
||||
const core = getFeishuRuntime();
|
||||
|
||||
if (messageType === "post") {
|
||||
const { imageKeys, mediaKeys } = parsePostContent(content);
|
||||
if (imageKeys.length === 0 && mediaKeys.length === 0) {
|
||||
return [];
|
||||
}
|
||||
if (imageKeys.length > 0) {
|
||||
log?.(`feishu: post message contains ${imageKeys.length} embedded image(s)`);
|
||||
}
|
||||
if (mediaKeys.length > 0) {
|
||||
log?.(`feishu: post message contains ${mediaKeys.length} embedded media file(s)`);
|
||||
}
|
||||
|
||||
for (const imageKey of imageKeys) {
|
||||
try {
|
||||
const result = await downloadMessageResourceFeishu({
|
||||
cfg,
|
||||
messageId,
|
||||
fileKey: imageKey,
|
||||
type: "image",
|
||||
accountId,
|
||||
});
|
||||
const contentType =
|
||||
result.contentType ?? (await core.media.detectMime({ buffer: result.buffer }));
|
||||
const saved = await core.channel.media.saveMediaBuffer(
|
||||
result.buffer,
|
||||
contentType,
|
||||
"inbound",
|
||||
maxBytes,
|
||||
);
|
||||
out.push({
|
||||
path: saved.path,
|
||||
contentType: saved.contentType,
|
||||
placeholder: "<media:image>",
|
||||
});
|
||||
log?.(`feishu: downloaded embedded image ${imageKey}, saved to ${saved.path}`);
|
||||
} catch (err) {
|
||||
log?.(`feishu: failed to download embedded image ${imageKey}: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const media of mediaKeys) {
|
||||
try {
|
||||
const result = await downloadMessageResourceFeishu({
|
||||
cfg,
|
||||
messageId,
|
||||
fileKey: media.fileKey,
|
||||
type: "file",
|
||||
accountId,
|
||||
});
|
||||
const contentType =
|
||||
result.contentType ?? (await core.media.detectMime({ buffer: result.buffer }));
|
||||
const saved = await core.channel.media.saveMediaBuffer(
|
||||
result.buffer,
|
||||
contentType,
|
||||
"inbound",
|
||||
maxBytes,
|
||||
);
|
||||
out.push({
|
||||
path: saved.path,
|
||||
contentType: saved.contentType,
|
||||
placeholder: "<media:video>",
|
||||
});
|
||||
log?.(`feishu: downloaded embedded media ${media.fileKey}, saved to ${saved.path}`);
|
||||
} catch (err) {
|
||||
log?.(`feishu: failed to download embedded media ${media.fileKey}: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const mediaKeys = parseMediaKeys(content, messageType);
|
||||
if (!mediaKeys.imageKey && !mediaKeys.fileKey) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const fileKey = mediaKeys.fileKey || mediaKeys.imageKey;
|
||||
if (!fileKey) {
|
||||
return [];
|
||||
}
|
||||
const result = await downloadMessageResourceFeishu({
|
||||
cfg,
|
||||
messageId,
|
||||
fileKey,
|
||||
type: toMessageResourceType(messageType),
|
||||
accountId,
|
||||
});
|
||||
const contentType =
|
||||
result.contentType ?? (await core.media.detectMime({ buffer: result.buffer }));
|
||||
const saved = await core.channel.media.saveMediaBuffer(
|
||||
result.buffer,
|
||||
contentType,
|
||||
"inbound",
|
||||
maxBytes,
|
||||
result.fileName || mediaKeys.fileName,
|
||||
);
|
||||
out.push({
|
||||
path: saved.path,
|
||||
contentType: saved.contentType,
|
||||
placeholder: inferPlaceholder(messageType),
|
||||
});
|
||||
log?.(`feishu: downloaded ${messageType} media, saved to ${saved.path}`);
|
||||
} catch (err) {
|
||||
log?.(`feishu: failed to download ${messageType} media: ${String(err)}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@ -0,0 +1,183 @@
|
||||
import {
|
||||
fetchMattermostChannel,
|
||||
fetchMattermostUser,
|
||||
sendMattermostTyping,
|
||||
updateMattermostPost,
|
||||
type MattermostChannel,
|
||||
type MattermostClient,
|
||||
type MattermostUser,
|
||||
} from "./client.js";
|
||||
import { buildButtonProps, type MattermostInteractionResponse } from "./interactions.js";
|
||||
|
||||
export type MattermostMediaKind = "image" | "audio" | "video" | "document" | "unknown";
|
||||
|
||||
export type MattermostMediaInfo = {
|
||||
path: string;
|
||||
contentType?: string;
|
||||
kind: MattermostMediaKind;
|
||||
};
|
||||
|
||||
const CHANNEL_CACHE_TTL_MS = 5 * 60_000;
|
||||
const USER_CACHE_TTL_MS = 10 * 60_000;
|
||||
|
||||
type FetchRemoteMedia = (params: {
|
||||
url: string;
|
||||
requestInit?: RequestInit;
|
||||
filePathHint?: string;
|
||||
maxBytes: number;
|
||||
ssrfPolicy?: { allowedHostnames?: string[] };
|
||||
}) => Promise<{ buffer: Uint8Array; contentType?: string | null }>;
|
||||
|
||||
type SaveMediaBuffer = (
|
||||
buffer: Uint8Array,
|
||||
contentType: string | undefined,
|
||||
direction: "inbound" | "outbound",
|
||||
maxBytes: number,
|
||||
) => Promise<{ path: string; contentType?: string | null }>;
|
||||
|
||||
export function createMattermostMonitorResources(params: {
|
||||
accountId: string;
|
||||
callbackUrl: string;
|
||||
client: MattermostClient;
|
||||
logger: { debug?: (...args: unknown[]) => void };
|
||||
mediaMaxBytes: number;
|
||||
fetchRemoteMedia: FetchRemoteMedia;
|
||||
saveMediaBuffer: SaveMediaBuffer;
|
||||
mediaKindFromMime: (contentType?: string) => MattermostMediaKind | null | undefined;
|
||||
}) {
|
||||
const {
|
||||
accountId,
|
||||
callbackUrl,
|
||||
client,
|
||||
logger,
|
||||
mediaMaxBytes,
|
||||
fetchRemoteMedia,
|
||||
saveMediaBuffer,
|
||||
mediaKindFromMime,
|
||||
} = params;
|
||||
const channelCache = new Map<string, { value: MattermostChannel | null; expiresAt: number }>();
|
||||
const userCache = new Map<string, { value: MattermostUser | null; expiresAt: number }>();
|
||||
|
||||
const resolveMattermostMedia = async (
|
||||
fileIds?: string[] | null,
|
||||
): Promise<MattermostMediaInfo[]> => {
|
||||
const ids = (fileIds ?? []).map((id) => id?.trim()).filter(Boolean);
|
||||
if (ids.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const out: MattermostMediaInfo[] = [];
|
||||
for (const fileId of ids) {
|
||||
try {
|
||||
const fetched = await fetchRemoteMedia({
|
||||
url: `${client.apiBaseUrl}/files/${fileId}`,
|
||||
requestInit: {
|
||||
headers: {
|
||||
Authorization: `Bearer ${client.token}`,
|
||||
},
|
||||
},
|
||||
filePathHint: fileId,
|
||||
maxBytes: mediaMaxBytes,
|
||||
ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] },
|
||||
});
|
||||
const saved = await saveMediaBuffer(
|
||||
Buffer.from(fetched.buffer),
|
||||
fetched.contentType ?? undefined,
|
||||
"inbound",
|
||||
mediaMaxBytes,
|
||||
);
|
||||
const contentType = saved.contentType ?? fetched.contentType ?? undefined;
|
||||
out.push({
|
||||
path: saved.path,
|
||||
contentType,
|
||||
kind: mediaKindFromMime(contentType) ?? "unknown",
|
||||
});
|
||||
} catch (err) {
|
||||
logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const sendTypingIndicator = async (channelId: string, parentId?: string) => {
|
||||
await sendMattermostTyping(client, { channelId, parentId });
|
||||
};
|
||||
|
||||
const resolveChannelInfo = async (channelId: string): Promise<MattermostChannel | null> => {
|
||||
const cached = channelCache.get(channelId);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return cached.value;
|
||||
}
|
||||
try {
|
||||
const info = await fetchMattermostChannel(client, channelId);
|
||||
channelCache.set(channelId, {
|
||||
value: info,
|
||||
expiresAt: Date.now() + CHANNEL_CACHE_TTL_MS,
|
||||
});
|
||||
return info;
|
||||
} catch (err) {
|
||||
logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
|
||||
channelCache.set(channelId, {
|
||||
value: null,
|
||||
expiresAt: Date.now() + CHANNEL_CACHE_TTL_MS,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const resolveUserInfo = async (userId: string): Promise<MattermostUser | null> => {
|
||||
const cached = userCache.get(userId);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return cached.value;
|
||||
}
|
||||
try {
|
||||
const info = await fetchMattermostUser(client, userId);
|
||||
userCache.set(userId, {
|
||||
value: info,
|
||||
expiresAt: Date.now() + USER_CACHE_TTL_MS,
|
||||
});
|
||||
return info;
|
||||
} catch (err) {
|
||||
logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
|
||||
userCache.set(userId, {
|
||||
value: null,
|
||||
expiresAt: Date.now() + USER_CACHE_TTL_MS,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const buildModelPickerProps = (
|
||||
channelId: string,
|
||||
buttons: Array<unknown>,
|
||||
): Record<string, unknown> | undefined =>
|
||||
buildButtonProps({
|
||||
callbackUrl,
|
||||
accountId,
|
||||
channelId,
|
||||
buttons,
|
||||
});
|
||||
|
||||
const updateModelPickerPost = async (params: {
|
||||
channelId: string;
|
||||
postId: string;
|
||||
message: string;
|
||||
buttons?: Array<unknown>;
|
||||
}): Promise<MattermostInteractionResponse> => {
|
||||
const props = buildModelPickerProps(params.channelId, params.buttons ?? []) ?? {
|
||||
attachments: [],
|
||||
};
|
||||
await updateMattermostPost(client, params.postId, {
|
||||
message: params.message,
|
||||
props,
|
||||
});
|
||||
return {};
|
||||
};
|
||||
|
||||
return {
|
||||
resolveMattermostMedia,
|
||||
sendTypingIndicator,
|
||||
resolveChannelInfo,
|
||||
resolveUserInfo,
|
||||
updateModelPickerPost,
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,373 @@
|
||||
import type { Message } from "@grammyjs/types";
|
||||
import { shouldDebounceTextInbound } from "openclaw/plugin-sdk/channel-runtime";
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-runtime";
|
||||
import {
|
||||
createInboundDebouncer,
|
||||
resolveInboundDebounceMs,
|
||||
} from "openclaw/plugin-sdk/reply-runtime";
|
||||
import { danger, logVerbose, warn } from "openclaw/plugin-sdk/runtime-env";
|
||||
import {
|
||||
hasInboundMedia,
|
||||
isRecoverableMediaGroupError,
|
||||
resolveInboundMediaFileId,
|
||||
} from "./bot-handlers.media.js";
|
||||
import type { TelegramMediaRef } from "./bot-message-context.js";
|
||||
import { MEDIA_GROUP_TIMEOUT_MS, type MediaGroupEntry } from "./bot-updates.js";
|
||||
import { resolveMedia } from "./bot/delivery.js";
|
||||
import type { TelegramContext } from "./bot/types.js";
|
||||
import type { TelegramTransport } from "./fetch.js";
|
||||
|
||||
export type TelegramDebounceLane = "default" | "forward";
|
||||
|
||||
export type TelegramDebounceEntry = {
|
||||
ctx: TelegramContext;
|
||||
msg: Message;
|
||||
allMedia: TelegramMediaRef[];
|
||||
storeAllowFrom: string[];
|
||||
debounceKey: string | null;
|
||||
debounceLane: TelegramDebounceLane;
|
||||
botUsername?: string;
|
||||
};
|
||||
|
||||
export type TextFragmentEntry = {
|
||||
key: string;
|
||||
messages: Array<{ msg: Message; ctx: TelegramContext; receivedAtMs: number }>;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
const DEFAULT_TEXT_FRAGMENT_MAX_GAP_MS = 1500;
|
||||
|
||||
type TelegramBotApi = {
|
||||
sendMessage: (
|
||||
chatId: number | string,
|
||||
text: string,
|
||||
params?: { message_thread_id?: number },
|
||||
) => Promise<unknown>;
|
||||
getFile: (fileId: string) => Promise<{ file_path?: string }>;
|
||||
};
|
||||
|
||||
export function createTelegramInboundBufferRuntime(params: {
|
||||
accountId?: string | null;
|
||||
bot: { api: TelegramBotApi };
|
||||
cfg: OpenClawConfig;
|
||||
logger: { warn: (...args: unknown[]) => void };
|
||||
mediaMaxBytes: number;
|
||||
opts: {
|
||||
token: string;
|
||||
testTimings?: {
|
||||
textFragmentGapMs?: number;
|
||||
mediaGroupFlushMs?: number;
|
||||
};
|
||||
};
|
||||
processMessage: (
|
||||
ctx: TelegramContext,
|
||||
media: TelegramMediaRef[],
|
||||
storeAllowFrom: string[],
|
||||
metadata?: { messageIdOverride?: string },
|
||||
replyMedia?: TelegramMediaRef[],
|
||||
) => Promise<void>;
|
||||
loadStoreAllowFrom: () => Promise<string[]>;
|
||||
runtime: {
|
||||
error?: (message: string) => void;
|
||||
};
|
||||
telegramTransport?: TelegramTransport;
|
||||
}) {
|
||||
const {
|
||||
accountId,
|
||||
bot,
|
||||
cfg,
|
||||
logger,
|
||||
mediaMaxBytes,
|
||||
opts,
|
||||
processMessage,
|
||||
loadStoreAllowFrom,
|
||||
runtime,
|
||||
telegramTransport,
|
||||
} = params;
|
||||
const TELEGRAM_TEXT_FRAGMENT_START_THRESHOLD_CHARS = 4000;
|
||||
const TELEGRAM_TEXT_FRAGMENT_MAX_GAP_MS =
|
||||
typeof opts.testTimings?.textFragmentGapMs === "number" &&
|
||||
Number.isFinite(opts.testTimings.textFragmentGapMs)
|
||||
? Math.max(10, Math.floor(opts.testTimings.textFragmentGapMs))
|
||||
: DEFAULT_TEXT_FRAGMENT_MAX_GAP_MS;
|
||||
const TELEGRAM_TEXT_FRAGMENT_MAX_ID_GAP = 1;
|
||||
const TELEGRAM_TEXT_FRAGMENT_MAX_PARTS = 12;
|
||||
const TELEGRAM_TEXT_FRAGMENT_MAX_TOTAL_CHARS = 50_000;
|
||||
const mediaGroupTimeoutMs =
|
||||
typeof opts.testTimings?.mediaGroupFlushMs === "number" &&
|
||||
Number.isFinite(opts.testTimings.mediaGroupFlushMs)
|
||||
? Math.max(10, Math.floor(opts.testTimings.mediaGroupFlushMs))
|
||||
: MEDIA_GROUP_TIMEOUT_MS;
|
||||
const debounceMs = resolveInboundDebounceMs({ cfg, channel: "telegram" });
|
||||
const FORWARD_BURST_DEBOUNCE_MS = 80;
|
||||
|
||||
const mediaGroupBuffer = new Map<string, MediaGroupEntry>();
|
||||
let mediaGroupProcessing: Promise<void> = Promise.resolve();
|
||||
const textFragmentBuffer = new Map<string, TextFragmentEntry>();
|
||||
let textFragmentProcessing: Promise<void> = Promise.resolve();
|
||||
|
||||
const resolveTelegramDebounceLane = (msg: Message): TelegramDebounceLane => {
|
||||
const forwardMeta = msg as {
|
||||
forward_origin?: unknown;
|
||||
forward_from?: unknown;
|
||||
forward_from_chat?: unknown;
|
||||
forward_sender_name?: unknown;
|
||||
forward_date?: unknown;
|
||||
};
|
||||
return (forwardMeta.forward_origin ??
|
||||
forwardMeta.forward_from ??
|
||||
forwardMeta.forward_from_chat ??
|
||||
forwardMeta.forward_sender_name ??
|
||||
forwardMeta.forward_date)
|
||||
? "forward"
|
||||
: "default";
|
||||
};
|
||||
|
||||
const buildSyntheticTextMessage = (params: {
|
||||
base: Message;
|
||||
text: string;
|
||||
date?: number;
|
||||
from?: Message["from"];
|
||||
}): Message => ({
|
||||
...params.base,
|
||||
...(params.from ? { from: params.from } : {}),
|
||||
text: params.text,
|
||||
caption: undefined,
|
||||
caption_entities: undefined,
|
||||
entities: undefined,
|
||||
...(params.date != null ? { date: params.date } : {}),
|
||||
});
|
||||
|
||||
const buildSyntheticContext = (
|
||||
ctx: Pick<TelegramContext, "me"> & { getFile?: unknown },
|
||||
message: Message,
|
||||
): TelegramContext => {
|
||||
const getFile =
|
||||
typeof ctx.getFile === "function"
|
||||
? (ctx.getFile as TelegramContext["getFile"]).bind(ctx as object)
|
||||
: async () => ({});
|
||||
return { message, me: ctx.me, getFile };
|
||||
};
|
||||
|
||||
const resolveReplyMediaForMessage = async (
|
||||
ctx: TelegramContext,
|
||||
msg: Message,
|
||||
): Promise<TelegramMediaRef[]> => {
|
||||
const replyMessage = msg.reply_to_message;
|
||||
if (!replyMessage || !hasInboundMedia(replyMessage)) {
|
||||
return [];
|
||||
}
|
||||
const replyFileId = resolveInboundMediaFileId(replyMessage);
|
||||
if (!replyFileId) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
const media = await resolveMedia(
|
||||
{
|
||||
message: replyMessage,
|
||||
me: ctx.me,
|
||||
getFile: async () => await bot.api.getFile(replyFileId),
|
||||
},
|
||||
mediaMaxBytes,
|
||||
opts.token,
|
||||
telegramTransport,
|
||||
);
|
||||
if (!media) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
path: media.path,
|
||||
contentType: media.contentType,
|
||||
stickerMetadata: media.stickerMetadata,
|
||||
},
|
||||
];
|
||||
} catch (err) {
|
||||
logger.warn({ chatId: msg.chat.id, error: String(err) }, "reply media fetch failed");
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const processMediaGroup = async (entry: MediaGroupEntry) => {
|
||||
try {
|
||||
entry.messages.sort(
|
||||
(a: { msg: Message; ctx: TelegramContext }, b: { msg: Message; ctx: TelegramContext }) =>
|
||||
a.msg.message_id - b.msg.message_id,
|
||||
);
|
||||
const captionMsg = entry.messages.find((item) => item.msg.caption || item.msg.text);
|
||||
const primaryEntry = captionMsg ?? entry.messages[0];
|
||||
|
||||
const allMedia: TelegramMediaRef[] = [];
|
||||
for (const { ctx } of entry.messages) {
|
||||
let media;
|
||||
try {
|
||||
media = await resolveMedia(ctx, mediaMaxBytes, opts.token, telegramTransport);
|
||||
} catch (mediaErr) {
|
||||
if (!isRecoverableMediaGroupError(mediaErr)) {
|
||||
throw mediaErr;
|
||||
}
|
||||
runtime.error?.(
|
||||
warn(`media group: skipping photo that failed to fetch: ${String(mediaErr)}`),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (media) {
|
||||
allMedia.push({
|
||||
path: media.path,
|
||||
contentType: media.contentType,
|
||||
stickerMetadata: media.stickerMetadata,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const storeAllowFrom = await loadStoreAllowFrom();
|
||||
const replyMedia = await resolveReplyMediaForMessage(primaryEntry.ctx, primaryEntry.msg);
|
||||
await processMessage(primaryEntry.ctx, allMedia, storeAllowFrom, undefined, replyMedia);
|
||||
} catch (err) {
|
||||
runtime.error?.(danger(`media group handler failed: ${String(err)}`));
|
||||
}
|
||||
};
|
||||
|
||||
const flushTextFragments = async (entry: TextFragmentEntry) => {
|
||||
try {
|
||||
entry.messages.sort((a, b) => a.msg.message_id - b.msg.message_id);
|
||||
const first = entry.messages[0];
|
||||
const last = entry.messages.at(-1);
|
||||
if (!first || !last) {
|
||||
return;
|
||||
}
|
||||
const combinedText = entry.messages.map((item) => item.msg.text ?? "").join("");
|
||||
if (!combinedText.trim()) {
|
||||
return;
|
||||
}
|
||||
const syntheticMessage = buildSyntheticTextMessage({
|
||||
base: first.msg,
|
||||
text: combinedText,
|
||||
date: last.msg.date ?? first.msg.date,
|
||||
});
|
||||
const storeAllowFrom = await loadStoreAllowFrom();
|
||||
await processMessage(buildSyntheticContext(first.ctx, syntheticMessage), [], storeAllowFrom, {
|
||||
messageIdOverride: String(last.msg.message_id),
|
||||
});
|
||||
} catch (err) {
|
||||
runtime.error?.(danger(`text fragment handler failed: ${String(err)}`));
|
||||
}
|
||||
};
|
||||
|
||||
const queueTextFragmentFlush = async (entry: TextFragmentEntry) => {
|
||||
textFragmentProcessing = textFragmentProcessing
|
||||
.then(async () => {
|
||||
await flushTextFragments(entry);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
await textFragmentProcessing;
|
||||
};
|
||||
|
||||
const runTextFragmentFlush = async (entry: TextFragmentEntry) => {
|
||||
textFragmentBuffer.delete(entry.key);
|
||||
await queueTextFragmentFlush(entry);
|
||||
};
|
||||
|
||||
const scheduleTextFragmentFlush = (entry: TextFragmentEntry) => {
|
||||
clearTimeout(entry.timer);
|
||||
entry.timer = setTimeout(async () => {
|
||||
await runTextFragmentFlush(entry);
|
||||
}, TELEGRAM_TEXT_FRAGMENT_MAX_GAP_MS);
|
||||
};
|
||||
|
||||
const inboundDebouncer = createInboundDebouncer<TelegramDebounceEntry>({
|
||||
debounceMs,
|
||||
resolveDebounceMs: (entry) =>
|
||||
entry.debounceLane === "forward" ? FORWARD_BURST_DEBOUNCE_MS : debounceMs,
|
||||
buildKey: (entry) => entry.debounceKey,
|
||||
shouldDebounce: (entry) => {
|
||||
const text = entry.msg.text ?? entry.msg.caption ?? "";
|
||||
const hasDebounceableText = shouldDebounceTextInbound({
|
||||
text,
|
||||
cfg,
|
||||
commandOptions: { botUsername: entry.botUsername },
|
||||
});
|
||||
if (entry.debounceLane === "forward") {
|
||||
return hasDebounceableText || entry.allMedia.length > 0;
|
||||
}
|
||||
return hasDebounceableText && entry.allMedia.length === 0;
|
||||
},
|
||||
onFlush: async (entries) => {
|
||||
const last = entries.at(-1);
|
||||
if (!last) {
|
||||
return;
|
||||
}
|
||||
if (entries.length === 1) {
|
||||
const replyMedia = await resolveReplyMediaForMessage(last.ctx, last.msg);
|
||||
await processMessage(last.ctx, last.allMedia, last.storeAllowFrom, undefined, replyMedia);
|
||||
return;
|
||||
}
|
||||
const combinedText = entries
|
||||
.map((entry) => entry.msg.text ?? entry.msg.caption ?? "")
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
const combinedMedia = entries.flatMap((entry) => entry.allMedia);
|
||||
if (!combinedText.trim() && combinedMedia.length === 0) {
|
||||
return;
|
||||
}
|
||||
const first = entries[0];
|
||||
const syntheticMessage = buildSyntheticTextMessage({
|
||||
base: first.msg,
|
||||
text: combinedText,
|
||||
date: last.msg.date ?? first.msg.date,
|
||||
});
|
||||
const messageIdOverride = last.msg.message_id ? String(last.msg.message_id) : undefined;
|
||||
const replyMedia = await resolveReplyMediaForMessage(first.ctx, syntheticMessage);
|
||||
await processMessage(
|
||||
buildSyntheticContext(first.ctx, syntheticMessage),
|
||||
combinedMedia,
|
||||
first.storeAllowFrom,
|
||||
messageIdOverride ? { messageIdOverride } : undefined,
|
||||
replyMedia,
|
||||
);
|
||||
},
|
||||
onError: (err, items) => {
|
||||
runtime.error?.(danger(`telegram debounce flush failed: ${String(err)}`));
|
||||
const chatId = items[0]?.msg.chat.id;
|
||||
if (chatId != null) {
|
||||
const threadId = items[0]?.msg.message_thread_id;
|
||||
void bot.api
|
||||
.sendMessage(
|
||||
chatId,
|
||||
"Something went wrong while processing your message. Please try again.",
|
||||
threadId != null ? { message_thread_id: threadId } : undefined,
|
||||
)
|
||||
.catch((sendErr) => {
|
||||
logVerbose(`telegram: error fallback send failed: ${String(sendErr)}`);
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
buildSyntheticContext,
|
||||
buildSyntheticTextMessage,
|
||||
inboundDebouncer,
|
||||
mediaGroupBuffer,
|
||||
mediaGroupProcessing: () => mediaGroupProcessing,
|
||||
setMediaGroupProcessing: (next: Promise<void>) => {
|
||||
mediaGroupProcessing = next;
|
||||
},
|
||||
mediaGroupTimeoutMs,
|
||||
processMediaGroup,
|
||||
textFragmentBuffer,
|
||||
textFragmentProcessing: () => textFragmentProcessing,
|
||||
setTextFragmentProcessing: (next: Promise<void>) => {
|
||||
textFragmentProcessing = next;
|
||||
},
|
||||
scheduleTextFragmentFlush,
|
||||
flushTextFragments,
|
||||
resolveReplyMediaForMessage,
|
||||
resolveTelegramDebounceLane,
|
||||
TELEGRAM_TEXT_FRAGMENT_MAX_GAP_MS,
|
||||
TELEGRAM_TEXT_FRAGMENT_MAX_ID_GAP,
|
||||
TELEGRAM_TEXT_FRAGMENT_MAX_PARTS,
|
||||
TELEGRAM_TEXT_FRAGMENT_MAX_TOTAL_CHARS,
|
||||
TELEGRAM_TEXT_FRAGMENT_START_THRESHOLD_CHARS,
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,362 @@
|
||||
import type { RuntimeEnv } from "../../api.js";
|
||||
import type { PendingApproval, TlonSettingsStore } from "../settings.js";
|
||||
import { normalizeShip } from "../targets.js";
|
||||
import { sendDm } from "../urbit/send.js";
|
||||
import type { UrbitSSEClient } from "../urbit/sse-client.js";
|
||||
import {
|
||||
findPendingApproval,
|
||||
formatApprovalConfirmation,
|
||||
formatApprovalRequest,
|
||||
formatBlockedList,
|
||||
formatPendingList,
|
||||
parseAdminCommand,
|
||||
parseApprovalResponse,
|
||||
removePendingApproval,
|
||||
} from "./approval.js";
|
||||
|
||||
type TlonApprovalApi = Pick<UrbitSSEClient, "poke" | "scry">;
|
||||
|
||||
type ApprovedMessageProcessor = (approval: PendingApproval) => Promise<void>;
|
||||
|
||||
export function createTlonApprovalRuntime(params: {
|
||||
api: TlonApprovalApi;
|
||||
runtime: RuntimeEnv;
|
||||
botShipName: string;
|
||||
getPendingApprovals: () => PendingApproval[];
|
||||
setPendingApprovals: (approvals: PendingApproval[]) => void;
|
||||
getCurrentSettings: () => TlonSettingsStore;
|
||||
setCurrentSettings: (settings: TlonSettingsStore) => void;
|
||||
getEffectiveDmAllowlist: () => string[];
|
||||
setEffectiveDmAllowlist: (ships: string[]) => void;
|
||||
getEffectiveOwnerShip: () => string | null;
|
||||
processApprovedMessage: ApprovedMessageProcessor;
|
||||
refreshWatchedChannels: () => Promise<number>;
|
||||
}) {
|
||||
const {
|
||||
api,
|
||||
runtime,
|
||||
botShipName,
|
||||
getPendingApprovals,
|
||||
setPendingApprovals,
|
||||
getCurrentSettings,
|
||||
setCurrentSettings,
|
||||
getEffectiveDmAllowlist,
|
||||
setEffectiveDmAllowlist,
|
||||
getEffectiveOwnerShip,
|
||||
processApprovedMessage,
|
||||
refreshWatchedChannels,
|
||||
} = params;
|
||||
|
||||
const savePendingApprovals = async (): Promise<void> => {
|
||||
try {
|
||||
await api.poke({
|
||||
app: "settings",
|
||||
mark: "settings-event",
|
||||
json: {
|
||||
"put-entry": {
|
||||
desk: "moltbot",
|
||||
"bucket-key": "tlon",
|
||||
"entry-key": "pendingApprovals",
|
||||
value: JSON.stringify(getPendingApprovals()),
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
runtime.error?.(`[tlon] Failed to save pending approvals: ${String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const addToDmAllowlist = async (ship: string): Promise<void> => {
|
||||
const normalizedShip = normalizeShip(ship);
|
||||
const nextAllowlist = getEffectiveDmAllowlist().includes(normalizedShip)
|
||||
? getEffectiveDmAllowlist()
|
||||
: [...getEffectiveDmAllowlist(), normalizedShip];
|
||||
setEffectiveDmAllowlist(nextAllowlist);
|
||||
try {
|
||||
await api.poke({
|
||||
app: "settings",
|
||||
mark: "settings-event",
|
||||
json: {
|
||||
"put-entry": {
|
||||
desk: "moltbot",
|
||||
"bucket-key": "tlon",
|
||||
"entry-key": "dmAllowlist",
|
||||
value: nextAllowlist,
|
||||
},
|
||||
},
|
||||
});
|
||||
runtime.log?.(`[tlon] Added ${normalizedShip} to dmAllowlist`);
|
||||
} catch (err) {
|
||||
runtime.error?.(`[tlon] Failed to update dmAllowlist: ${String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const addToChannelAllowlist = async (ship: string, channelNest: string): Promise<void> => {
|
||||
const normalizedShip = normalizeShip(ship);
|
||||
const currentSettings = getCurrentSettings();
|
||||
const channelRules = currentSettings.channelRules ?? {};
|
||||
const rule = channelRules[channelNest] ?? { mode: "restricted", allowedShips: [] };
|
||||
const allowedShips = [...(rule.allowedShips ?? [])];
|
||||
|
||||
if (!allowedShips.includes(normalizedShip)) {
|
||||
allowedShips.push(normalizedShip);
|
||||
}
|
||||
|
||||
const updatedRules = {
|
||||
...channelRules,
|
||||
[channelNest]: { ...rule, allowedShips },
|
||||
};
|
||||
setCurrentSettings({ ...currentSettings, channelRules: updatedRules });
|
||||
|
||||
try {
|
||||
await api.poke({
|
||||
app: "settings",
|
||||
mark: "settings-event",
|
||||
json: {
|
||||
"put-entry": {
|
||||
desk: "moltbot",
|
||||
"bucket-key": "tlon",
|
||||
"entry-key": "channelRules",
|
||||
value: JSON.stringify(updatedRules),
|
||||
},
|
||||
},
|
||||
});
|
||||
runtime.log?.(`[tlon] Added ${normalizedShip} to ${channelNest} allowlist`);
|
||||
} catch (err) {
|
||||
runtime.error?.(`[tlon] Failed to update channelRules: ${String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const blockShip = async (ship: string): Promise<void> => {
|
||||
const normalizedShip = normalizeShip(ship);
|
||||
try {
|
||||
await api.poke({
|
||||
app: "chat",
|
||||
mark: "chat-block-ship",
|
||||
json: { ship: normalizedShip },
|
||||
});
|
||||
runtime.log?.(`[tlon] Blocked ship ${normalizedShip}`);
|
||||
} catch (err) {
|
||||
runtime.error?.(`[tlon] Failed to block ship ${normalizedShip}: ${String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const isShipBlocked = async (ship: string): Promise<boolean> => {
|
||||
const normalizedShip = normalizeShip(ship);
|
||||
try {
|
||||
const blocked = (await api.scry("/chat/blocked.json")) as string[] | undefined;
|
||||
return (
|
||||
Array.isArray(blocked) && blocked.some((item) => normalizeShip(item) === normalizedShip)
|
||||
);
|
||||
} catch (err) {
|
||||
runtime.log?.(`[tlon] Failed to check blocked list: ${String(err)}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const getBlockedShips = async (): Promise<string[]> => {
|
||||
try {
|
||||
const blocked = (await api.scry("/chat/blocked.json")) as string[] | undefined;
|
||||
return Array.isArray(blocked) ? blocked : [];
|
||||
} catch (err) {
|
||||
runtime.log?.(`[tlon] Failed to get blocked list: ${String(err)}`);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const unblockShip = async (ship: string): Promise<boolean> => {
|
||||
const normalizedShip = normalizeShip(ship);
|
||||
try {
|
||||
await api.poke({
|
||||
app: "chat",
|
||||
mark: "chat-unblock-ship",
|
||||
json: { ship: normalizedShip },
|
||||
});
|
||||
runtime.log?.(`[tlon] Unblocked ship ${normalizedShip}`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
runtime.error?.(`[tlon] Failed to unblock ship ${normalizedShip}: ${String(err)}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const sendOwnerNotification = async (message: string): Promise<void> => {
|
||||
const ownerShip = getEffectiveOwnerShip();
|
||||
if (!ownerShip) {
|
||||
runtime.log?.("[tlon] No ownerShip configured, cannot send notification");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await sendDm({
|
||||
api,
|
||||
fromShip: botShipName,
|
||||
toShip: ownerShip,
|
||||
text: message,
|
||||
});
|
||||
runtime.log?.(`[tlon] Sent notification to owner ${ownerShip}`);
|
||||
} catch (err) {
|
||||
runtime.error?.(`[tlon] Failed to send notification to owner: ${String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const queueApprovalRequest = async (approval: PendingApproval): Promise<void> => {
|
||||
if (await isShipBlocked(approval.requestingShip)) {
|
||||
runtime.log?.(`[tlon] Ignoring request from blocked ship ${approval.requestingShip}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const approvals = getPendingApprovals();
|
||||
const existingIndex = approvals.findIndex(
|
||||
(item) =>
|
||||
item.type === approval.type &&
|
||||
item.requestingShip === approval.requestingShip &&
|
||||
(approval.type !== "channel" || item.channelNest === approval.channelNest) &&
|
||||
(approval.type !== "group" || item.groupFlag === approval.groupFlag),
|
||||
);
|
||||
|
||||
if (existingIndex !== -1) {
|
||||
const existing = approvals[existingIndex];
|
||||
if (approval.originalMessage) {
|
||||
existing.originalMessage = approval.originalMessage;
|
||||
existing.messagePreview = approval.messagePreview;
|
||||
}
|
||||
runtime.log?.(
|
||||
`[tlon] Updated existing approval for ${approval.requestingShip} (${approval.type}) - re-sending notification`,
|
||||
);
|
||||
await savePendingApprovals();
|
||||
await sendOwnerNotification(formatApprovalRequest(existing));
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingApprovals([...approvals, approval]);
|
||||
await savePendingApprovals();
|
||||
await sendOwnerNotification(formatApprovalRequest(approval));
|
||||
runtime.log?.(
|
||||
`[tlon] Queued approval request: ${approval.id} (${approval.type} from ${approval.requestingShip})`,
|
||||
);
|
||||
};
|
||||
|
||||
const handleApprovalResponse = async (text: string): Promise<boolean> => {
|
||||
const parsed = parseApprovalResponse(text);
|
||||
if (!parsed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const approval = findPendingApproval(getPendingApprovals(), parsed.id);
|
||||
if (!approval) {
|
||||
await sendOwnerNotification(
|
||||
`No pending approval found${parsed.id ? ` for ID: ${parsed.id}` : ""}`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (parsed.action === "approve") {
|
||||
switch (approval.type) {
|
||||
case "dm":
|
||||
await addToDmAllowlist(approval.requestingShip);
|
||||
if (approval.originalMessage) {
|
||||
runtime.log?.(
|
||||
`[tlon] Processing original message from ${approval.requestingShip} after approval`,
|
||||
);
|
||||
await processApprovedMessage(approval);
|
||||
}
|
||||
break;
|
||||
case "channel":
|
||||
if (approval.channelNest) {
|
||||
await addToChannelAllowlist(approval.requestingShip, approval.channelNest);
|
||||
if (approval.originalMessage) {
|
||||
runtime.log?.(
|
||||
`[tlon] Processing original message from ${approval.requestingShip} in ${approval.channelNest} after approval`,
|
||||
);
|
||||
await processApprovedMessage(approval);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "group":
|
||||
if (approval.groupFlag) {
|
||||
try {
|
||||
await api.poke({
|
||||
app: "groups",
|
||||
mark: "group-join",
|
||||
json: {
|
||||
flag: approval.groupFlag,
|
||||
"join-all": true,
|
||||
},
|
||||
});
|
||||
runtime.log?.(`[tlon] Joined group ${approval.groupFlag} after approval`);
|
||||
setTimeout(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const newCount = await refreshWatchedChannels();
|
||||
if (newCount > 0) {
|
||||
runtime.log?.(
|
||||
`[tlon] Discovered ${newCount} new channel(s) after joining group`,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
runtime.log?.(
|
||||
`[tlon] Channel discovery after group join failed: ${String(err)}`,
|
||||
);
|
||||
}
|
||||
})();
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
await sendOwnerNotification(formatApprovalConfirmation(approval, "approve"));
|
||||
} else if (parsed.action === "block") {
|
||||
await blockShip(approval.requestingShip);
|
||||
await sendOwnerNotification(formatApprovalConfirmation(approval, "block"));
|
||||
} else {
|
||||
await sendOwnerNotification(formatApprovalConfirmation(approval, "deny"));
|
||||
}
|
||||
|
||||
setPendingApprovals(removePendingApproval(getPendingApprovals(), approval.id));
|
||||
await savePendingApprovals();
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleAdminCommand = async (text: string): Promise<boolean> => {
|
||||
const command = parseAdminCommand(text);
|
||||
if (!command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (command.type) {
|
||||
case "blocked": {
|
||||
const blockedShips = await getBlockedShips();
|
||||
await sendOwnerNotification(formatBlockedList(blockedShips));
|
||||
runtime.log?.(`[tlon] Owner requested blocked ships list (${blockedShips.length} ships)`);
|
||||
return true;
|
||||
}
|
||||
case "pending":
|
||||
await sendOwnerNotification(formatPendingList(getPendingApprovals()));
|
||||
runtime.log?.(
|
||||
`[tlon] Owner requested pending approvals list (${getPendingApprovals().length} pending)`,
|
||||
);
|
||||
return true;
|
||||
case "unblock": {
|
||||
const shipToUnblock = command.ship;
|
||||
if (!(await isShipBlocked(shipToUnblock))) {
|
||||
await sendOwnerNotification(`${shipToUnblock} is not blocked.`);
|
||||
return true;
|
||||
}
|
||||
const success = await unblockShip(shipToUnblock);
|
||||
await sendOwnerNotification(
|
||||
success ? `Unblocked ${shipToUnblock}.` : `Failed to unblock ${shipToUnblock}.`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
queueApprovalRequest,
|
||||
handleApprovalResponse,
|
||||
handleAdminCommand,
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
import type { RuntimeEnv } from "../../api.js";
|
||||
import { extractCites, extractMessageText, type ParsedCite } from "./utils.js";
|
||||
|
||||
type TlonScryApi = {
|
||||
scry: (path: string) => Promise<unknown>;
|
||||
};
|
||||
|
||||
export function createTlonCitationResolver(params: { api: TlonScryApi; runtime: RuntimeEnv }) {
|
||||
const { api, runtime } = params;
|
||||
|
||||
const resolveCiteContent = async (cite: ParsedCite): Promise<string | null> => {
|
||||
if (cite.type !== "chan" || !cite.nest || !cite.postId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const scryPath = `/channels/v4/${cite.nest}/posts/post/${cite.postId}.json`;
|
||||
runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
|
||||
|
||||
const data: any = await api.scry(scryPath);
|
||||
if (data?.essay?.content) {
|
||||
return extractMessageText(data.essay.content) || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (err) {
|
||||
runtime.log?.(`[tlon] Failed to fetch cited post: ${String(err)}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const resolveAllCites = async (content: unknown): Promise<string> => {
|
||||
const cites = extractCites(content);
|
||||
if (cites.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const resolved: string[] = [];
|
||||
for (const cite of cites) {
|
||||
const text = await resolveCiteContent(cite);
|
||||
if (text) {
|
||||
resolved.push(`> ${cite.author || "unknown"} wrote: ${text}`);
|
||||
}
|
||||
}
|
||||
|
||||
return resolved.length > 0 ? `${resolved.join("\n")}\n\n` : "";
|
||||
};
|
||||
|
||||
return {
|
||||
resolveCiteContent,
|
||||
resolveAllCites,
|
||||
};
|
||||
}
|
||||
Loading…
Reference in New Issue