| 1 | import { |
| 2 | activeTurnBlock, |
| 3 | cleanEnvValue, |
| 4 | commandAction as coreCommandAction, |
| 5 | compactRuntimeError, |
| 6 | envFirst, |
| 7 | isPlaceholderValue, |
| 8 | latestRunningTurn, |
| 9 | parseApprovalDecisionArgs, |
| 10 | parseBool, |
| 11 | parseCommand, |
| 12 | parseEnvText, |
| 13 | parseList, |
| 14 | parseTextContent as coreParseTextContent, |
| 15 | preservedChatStateFields as corePreservedChatStateFields, |
| 16 | splitMessage, |
| 17 | stripGroupPrefix as coreStripGroupPrefix, |
| 18 | turnOutcomeText |
| 19 | } from "../../bridge-core/src/lib.mjs"; |
| 20 | |
| 21 | export { |
| 22 | activeTurnBlock, |
| 23 | cleanEnvValue, |
| 24 | compactRuntimeError, |
| 25 | envFirst, |
| 26 | isPlaceholderValue, |
| 27 | latestRunningTurn, |
| 28 | parseApprovalDecisionArgs, |
| 29 | parseBool, |
| 30 | parseCommand, |
| 31 | parseEnvText, |
| 32 | parseList, |
| 33 | splitMessage, |
| 34 | turnOutcomeText |
| 35 | }; |
| 36 | |
| 37 | export async function patchTurnCursor(threadStore, chatId, threadId, turnId, patch) { |
| 38 | const current = await threadStore.getChat(chatId); |
| 39 | if (!current || current.threadId !== threadId || current.activeTurnId !== turnId) { |
| 40 | return false; |
| 41 | } |
| 42 | await threadStore.patchChat(chatId, { |
| 43 | ...patch, |
| 44 | updatedAt: new Date().toISOString() |
| 45 | }); |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | export function parseTextContent(content) { |
| 50 | return coreParseTextContent(content, ["text", "content"]); |
| 51 | } |
| 52 | |
| 53 | export function incomingIdentity(event) { |
| 54 | const sender = event?.sender?.sender_id || {}; |
| 55 | const message = event?.message || {}; |
| 56 | return { |
| 57 | chatId: message.chat_id || "", |
| 58 | messageId: message.message_id || "", |
| 59 | chatType: message.chat_type || "", |
| 60 | messageType: message.message_type || "", |
| 61 | openId: sender.open_id || "", |
| 62 | unionId: sender.union_id || "", |
| 63 | userId: sender.user_id || "", |
| 64 | // Thread/topic group context: these fields let the bridge reply |
| 65 | // inside the same topic instead of spawning a new standalone topic. |
| 66 | // / 话题群上下文:用于在同一话题内回复,而非新建独立话题。 |
| 67 | parentId: message.parent_id || "", |
| 68 | rootId: message.root_id || "", |
| 69 | threadId: message.thread_id || "" |
| 70 | }; |
| 71 | } |
| 72 | |
| 73 | export function isAllowed(identity, allowlist, allowUnlisted = false) { |
| 74 | if (allowUnlisted) return true; |
| 75 | const allowed = new Set(allowlist); |
| 76 | return [identity.chatId, identity.openId, identity.unionId, identity.userId] |
| 77 | .filter(Boolean) |
| 78 | .some((id) => allowed.has(id)); |
| 79 | } |
| 80 | |
| 81 | export function pairingRefusalText(identity) { |
| 82 | return [ |
| 83 | "This chat is not in CODEWHALE_CHAT_ALLOWLIST.", |
| 84 | `chat_id=${identity.chatId}`, |
| 85 | identity.openId ? `open_id=${identity.openId}` : "", |
| 86 | identity.unionId ? `union_id=${identity.unionId}` : "", |
| 87 | identity.userId ? `user_id=${identity.userId}` : "" |
| 88 | ] |
| 89 | .filter(Boolean) |
| 90 | .join("\n"); |
| 91 | } |
| 92 | |
| 93 | export function stripGroupPrefix(text, { chatType, requirePrefix, prefix }) { |
| 94 | return coreStripGroupPrefix(text, { |
| 95 | chatType, |
| 96 | requirePrefix, |
| 97 | prefix: prefix || "/ds", |
| 98 | directChatTypes: ["p2p"] |
| 99 | }); |
| 100 | } |
| 101 | |
| 102 | export function commandAction(command) { |
| 103 | return coreCommandAction(command); |
| 104 | } |
| 105 | |
| 106 | export function preservedChatStateFields(state = {}) { |
| 107 | return corePreservedChatStateFields(state, ["model", "replyToMessageId", "authorizedIdentity"]); |
| 108 | } |
| 109 | |
| 110 | export function validateBridgeConfig(env, options = {}) { |
| 111 | const runtimeEnv = options.runtimeEnv || null; |
| 112 | const workspaceRoot = options.workspaceRoot || ""; |
| 113 | const errors = []; |
| 114 | const warnings = []; |
| 115 | const info = []; |
| 116 | const add = (list, code, message) => list.push({ code, message }); |
| 117 | |
| 118 | for (const [label, ...keys] of [ |
| 119 | ["FEISHU_APP_ID", "FEISHU_APP_ID"], |
| 120 | ["FEISHU_APP_SECRET", "FEISHU_APP_SECRET"], |
| 121 | ["CODEWHALE_RUNTIME_URL", "CODEWHALE_RUNTIME_URL", "DEEPSEEK_RUNTIME_URL"], |
| 122 | ["CODEWHALE_RUNTIME_TOKEN", "CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN"], |
| 123 | ["CODEWHALE_WORKSPACE", "CODEWHALE_WORKSPACE", "DEEPSEEK_WORKSPACE"], |
| 124 | ["FEISHU_THREAD_MAP_PATH", "FEISHU_THREAD_MAP_PATH"] |
| 125 | ]) { |
| 126 | const value = envFirst(env, ...keys); |
| 127 | if (!value) { |
| 128 | add(errors, "missing_required", `${label} is required`); |
| 129 | } else if (isPlaceholderValue(value)) { |
| 130 | add(errors, "placeholder_value", `${label} still contains a placeholder value`); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | const domain = cleanEnvValue(env.FEISHU_DOMAIN || "feishu").toLowerCase(); |
| 135 | if (!["feishu", "lark"].includes(domain) && !/^https:\/\/open\./.test(domain)) { |
| 136 | add(errors, "invalid_domain", "FEISHU_DOMAIN must be feishu, lark, or an https://open.* URL"); |
| 137 | } |
| 138 | |
| 139 | const runtimeUrl = envFirst(env, "CODEWHALE_RUNTIME_URL", "DEEPSEEK_RUNTIME_URL") || "http://127.0.0.1:7878"; |
| 140 | try { |
| 141 | const parsed = new URL(runtimeUrl); |
| 142 | const localHosts = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]); |
| 143 | if (!["http:", "https:"].includes(parsed.protocol)) { |
| 144 | add(errors, "invalid_runtime_url", "CODEWHALE_RUNTIME_URL must use http or https"); |
| 145 | } |
| 146 | if (!localHosts.has(parsed.hostname)) { |
| 147 | add(errors, "remote_runtime_url", "CODEWHALE_RUNTIME_URL must point at localhost on Lighthouse"); |
| 148 | } |
| 149 | } catch { |
| 150 | add(errors, "invalid_runtime_url", "CODEWHALE_RUNTIME_URL is not a valid URL"); |
| 151 | } |
| 152 | |
| 153 | const workspace = envFirst(env, "CODEWHALE_WORKSPACE", "DEEPSEEK_WORKSPACE"); |
| 154 | if (workspace && !workspace.startsWith("/")) { |
| 155 | add(errors, "relative_workspace", "CODEWHALE_WORKSPACE must be an absolute path"); |
| 156 | } |
| 157 | if ( |
| 158 | workspace && |
| 159 | workspaceRoot && |
| 160 | workspace !== workspaceRoot && |
| 161 | !workspace.startsWith(`${workspaceRoot}/`) |
| 162 | ) { |
| 163 | add(warnings, "workspace_root", `CODEWHALE_WORKSPACE is outside ${workspaceRoot}`); |
| 164 | } |
| 165 | |
| 166 | const threadMapPath = cleanEnvValue(env.FEISHU_THREAD_MAP_PATH); |
| 167 | if (threadMapPath && !threadMapPath.startsWith("/")) { |
| 168 | add(errors, "relative_thread_map", "FEISHU_THREAD_MAP_PATH must be an absolute path"); |
| 169 | } |
| 170 | |
| 171 | const allowGroups = parseBool(env.FEISHU_ALLOW_GROUPS, false); |
| 172 | const requirePrefix = parseBool(env.FEISHU_REQUIRE_PREFIX_IN_GROUP, true); |
| 173 | const allowUnlisted = parseBool( |
| 174 | envFirst(env, "CODEWHALE_ALLOW_UNLISTED", "DEEPSEEK_ALLOW_UNLISTED"), |
| 175 | false |
| 176 | ); |
| 177 | const allowlist = parseList( |
| 178 | envFirst(env, "CODEWHALE_CHAT_ALLOWLIST", "DEEPSEEK_CHAT_ALLOWLIST") |
| 179 | ); |
| 180 | |
| 181 | if (!allowlist.length && allowUnlisted) { |
| 182 | add(warnings, "pairing_mode_open", "CODEWHALE_ALLOW_UNLISTED=true leaves first-pairing mode open"); |
| 183 | } else if (!allowlist.length) { |
| 184 | add(warnings, "not_paired", "CODEWHALE_CHAT_ALLOWLIST is empty; all chats will be refused"); |
| 185 | } |
| 186 | if (allowGroups && allowUnlisted) { |
| 187 | add(errors, "open_group_control", "Group control cannot be enabled while unlisted chats are allowed"); |
| 188 | } |
| 189 | if (allowGroups && !requirePrefix) { |
| 190 | add(warnings, "group_without_prefix", "Group control is enabled without requiring FEISHU_GROUP_PREFIX"); |
| 191 | } |
| 192 | if (!allowGroups) { |
| 193 | add(info, "dm_only", "Direct-message control is enabled; group chats are disabled"); |
| 194 | } |
| 195 | |
| 196 | const maxReplyChars = Number(env.FEISHU_MAX_REPLY_CHARS || 3500); |
| 197 | if (!Number.isFinite(maxReplyChars) || maxReplyChars < 100 || maxReplyChars > FEISHU_MAX_TEXT_CHARS) { |
| 198 | add(errors, "invalid_max_reply_chars", `FEISHU_MAX_REPLY_CHARS must be between 100 and ${FEISHU_MAX_TEXT_CHARS}`); |
| 199 | } |
| 200 | const turnTimeoutMs = Number(envFirst(env, "CODEWHALE_TURN_TIMEOUT_MS", "DEEPSEEK_TURN_TIMEOUT_MS") || 900000); |
| 201 | if (!Number.isFinite(turnTimeoutMs) || turnTimeoutMs < 1000) { |
| 202 | add(errors, "invalid_turn_timeout", "CODEWHALE_TURN_TIMEOUT_MS must be at least 1000"); |
| 203 | } |
| 204 | |
| 205 | if (runtimeEnv) { |
| 206 | const runtimeToken = envFirst(runtimeEnv, "CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN"); |
| 207 | const bridgeToken = envFirst(env, "CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN"); |
| 208 | if (!runtimeToken) { |
| 209 | add(errors, "missing_runtime_token", "runtime.env is missing CODEWHALE_RUNTIME_TOKEN"); |
| 210 | } else if (isPlaceholderValue(runtimeToken)) { |
| 211 | add(errors, "placeholder_runtime_token", "runtime.env CODEWHALE_RUNTIME_TOKEN is still a placeholder"); |
| 212 | } else if (bridgeToken && bridgeToken !== runtimeToken) { |
| 213 | add(errors, "token_mismatch", "Runtime and bridge CODEWHALE_RUNTIME_TOKEN values do not match"); |
| 214 | } |
| 215 | |
| 216 | const apiKey = cleanEnvValue(runtimeEnv.DEEPSEEK_API_KEY); |
| 217 | if (!apiKey) { |
| 218 | add(warnings, "missing_api_key", "runtime.env is missing DEEPSEEK_API_KEY"); |
| 219 | } else if (isPlaceholderValue(apiKey)) { |
| 220 | add(warnings, "placeholder_api_key", "runtime.env DEEPSEEK_API_KEY is still a placeholder"); |
| 221 | } |
| 222 | |
| 223 | const runtimePort = Number(envFirst(runtimeEnv, "CODEWHALE_RUNTIME_PORT", "DEEPSEEK_RUNTIME_PORT") || 7878); |
| 224 | if (!Number.isInteger(runtimePort) || runtimePort <= 0 || runtimePort > 65535) { |
| 225 | add(errors, "invalid_runtime_port", "CODEWHALE_RUNTIME_PORT must be a valid TCP port"); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | return { |
| 230 | ok: errors.length === 0, |
| 231 | errors, |
| 232 | warnings, |
| 233 | info |
| 234 | }; |
| 235 | } |
| 236 | |
| 237 | export function formatValidationReport(result) { |
| 238 | const lines = ["Feishu bridge config validation"]; |
| 239 | for (const item of result.errors) lines.push(`[fail] ${item.message}`); |
| 240 | for (const item of result.warnings) lines.push(`[warn] ${item.message}`); |
| 241 | for (const item of result.info) lines.push(`[info] ${item.message}`); |
| 242 | if (result.ok) lines.push("[ok] No blocking config errors found"); |
| 243 | return lines.join("\n"); |
| 244 | } |
| 245 | |
| 246 | export const FEISHU_MAX_TEXT_CHARS = 30000; |
| 247 | |
| 248 | export function helpText() { |
| 249 | return [ |
| 250 | "Codewhale phone bridge commands:", |
| 251 | "/help - show this help", |
| 252 | "/status - runtime and workspace status", |
| 253 | "/threads - recent runtime threads", |
| 254 | "/new - create a new thread for this chat", |
| 255 | "/resume <thread_id> - bind this chat to an existing thread", |
| 256 | "/model <name|default> - set or reset this chat's model", |
| 257 | "/interrupt - interrupt the active turn", |
| 258 | "/compact - compact the current thread", |
| 259 | "/allow <approval_id> [remember] - approve a pending tool call", |
| 260 | "/deny <approval_id> - deny a pending tool call", |
| 261 | "", |
| 262 | "Anything else is sent as a Codewhale prompt." |
| 263 | ].join("\n"); |
| 264 | } |
| 265 |