返回 CodeWhale
lib.mjs
1 import {
2 activeTurnBlock,
3 cleanEnvValue,
4 commandAction as coreCommandAction,
5 compactRuntimeError,
6 envFirst,
7 isPlaceholderValue,
8 latestRunningTurn,
9 parseApprovalDecisionArgs,
10 parseBool,
11 parseCommand as coreParseCommand,
12 parseEnvText,
13 parseList,
14 preservedChatStateFields,
15 splitMessage,
16 stripGroupPrefix as coreStripGroupPrefix
17 } from "../../bridge-core/src/lib.mjs";
18
19 export {
20 activeTurnBlock,
21 cleanEnvValue,
22 compactRuntimeError,
23 envFirst,
24 isPlaceholderValue,
25 latestRunningTurn,
26 parseApprovalDecisionArgs,
27 parseBool,
28 parseEnvText,
29 parseList,
30 preservedChatStateFields,
31 splitMessage
32 };
33
34 export function telegramIdentity(update) {
35 const message = update?.message || update?.edited_message || {};
36 const chat = message.chat || {};
37 const from = message.from || {};
38 const username = from.username ? `@${from.username}` : "";
39 return {
40 updateId: update?.update_id ?? null,
41 chatId: chat.id != null ? String(chat.id) : "",
42 messageId: message.message_id != null ? String(message.message_id) : "",
43 chatType: chat.type || "",
44 userId: from.id != null ? String(from.id) : "",
45 username,
46 firstName: from.first_name || "",
47 text: typeof message.text === "string" ? message.text : "",
48 isBot: Boolean(from.is_bot)
49 };
50 }
51
52 export function isGroupChat(chatType) {
53 return chatType === "group" || chatType === "supergroup";
54 }
55
56 export function isAllowed(identity, allowlist, allowUnlisted = false) {
57 if (allowUnlisted) return true;
58 const allowed = new Set(allowlist);
59 return [identity.chatId, identity.userId, identity.username]
60 .filter(Boolean)
61 .some((id) => allowed.has(id));
62 }
63
64 export function pairingRefusalText(identity) {
65 return [
66 "This Telegram chat is not in TELEGRAM_CHAT_ALLOWLIST.",
67 `chat_id=${identity.chatId}`,
68 identity.userId ? `user_id=${identity.userId}` : "",
69 identity.username ? `username=${identity.username}` : "",
70 "",
71 "For first pairing, add one of those IDs to TELEGRAM_CHAT_ALLOWLIST, or temporarily set TELEGRAM_ALLOW_UNLISTED=true."
72 ]
73 .filter(Boolean)
74 .join("\n");
75 }
76
77 export function stripGroupPrefix(text, { chatType, requirePrefix, prefix }) {
78 return coreStripGroupPrefix(text, {
79 chatType,
80 requirePrefix,
81 prefix: prefix || "/cw",
82 directChatTypes: ["private", "channel"]
83 });
84 }
85
86 export function parseCommand(text) {
87 const answer = String(text || "").trim().match(/^\/answer(?:@\w+)?(?:\s+([\s\S]*))?$/i);
88 if (answer) return { name: "answer", args: (answer[1] || "").trim() };
89 return coreParseCommand(text, { stripBotMention: true });
90 }
91
92 export function commandAction(command) {
93 if (command.name === "answer") return { kind: "answer", text: command.args };
94 return coreCommandAction(command, { allowMenu: true, allowStart: true });
95 }
96
97 export function controlKeyboard() {
98 return {
99 inline_keyboard: [
100 [
101 { text: "Status", callback_data: "cw:status" },
102 { text: "New thread", callback_data: "cw:new" }
103 ],
104 [
105 { text: "Threads", callback_data: "cw:threads" },
106 { text: "Interrupt", callback_data: "cw:interrupt" }
107 ],
108 [
109 { text: "Compact", callback_data: "cw:compact" },
110 { text: "Reset model", callback_data: "cw:model:default" }
111 ],
112 [{ text: "Help", callback_data: "cw:help" }]
113 ]
114 };
115 }
116
117 export function activeTurnKeyboard() {
118 return {
119 inline_keyboard: [
120 [
121 { text: "Status", callback_data: "cw:status" },
122 { text: "Interrupt", callback_data: "cw:interrupt" }
123 ],
124 [{ text: "Threads", callback_data: "cw:threads" }]
125 ]
126 };
127 }
128
129 export function approvalKeyboard(actionToken) {
130 return {
131 inline_keyboard: [
132 [
133 { text: "Allow once", callback_data: `cw:act:${actionToken}` },
134 { text: "Allow + remember", callback_data: `cw:act:${actionToken}:remember` }
135 ],
136 [{ text: "Deny", callback_data: `cw:act:${actionToken}:deny` }]
137 ]
138 };
139 }
140
141 export function threadListKeyboard(threadActions) {
142 const rows = [];
143 for (const action of threadActions.slice(0, 8)) {
144 rows.push([{ text: action.label, callback_data: `cw:act:${action.token}` }]);
145 }
146 rows.push([{ text: "New thread", callback_data: "cw:new" }]);
147 return { inline_keyboard: rows };
148 }
149
150 export function callbackAction(data) {
151 const value = String(data || "");
152 switch (value) {
153 case "cw:status":
154 return { kind: "status" };
155 case "cw:new":
156 return { kind: "new_thread" };
157 case "cw:threads":
158 return { kind: "threads" };
159 case "cw:interrupt":
160 return { kind: "interrupt" };
161 case "cw:compact":
162 return { kind: "compact" };
163 case "cw:help":
164 return { kind: "help" };
165 case "cw:model:default":
166 return { kind: "set_model", modelName: "default" };
167 default:
168 break;
169 }
170 if (value.startsWith("cw:act:")) {
171 const [, , token, suffix] = value.split(":", 4);
172 return { kind: "stored_action", token: token || "", suffix: suffix || "" };
173 }
174 return null;
175 }
176
177 const MARKDOWN_V2_SPECIALS = /([_*\[\]()~`>#+\-=|{}.!\\])/g;
178 const FENCED_CODE_BLOCK = /^ {0,3}```([^\r\n`]*)\r?\n([\s\S]*?)^ {0,3}```[ \t]*$/gm;
179 const BLOCK_PLACEHOLDER_PREFIX = "\u0000mdv2:block:";
180 const INLINE_PLACEHOLDER_PREFIX = "\u0000mdv2:inline:";
181 const PLACEHOLDER_SUFFIX = "\u0000";
182
183 export function telegramMessageBody(text, options = {}) {
184 const maxChars = Math.floor(Number(options.maxChars) || 0);
185 if (options.markdown === false) {
186 return { text: boundedPlainTelegramText(text, maxChars) };
187 }
188 const markdownText = telegramMarkdownV2(text);
189 if (maxChars > 0 && markdownText.length > maxChars) {
190 return { text: boundedPlainTelegramText(text, maxChars) };
191 }
192 return {
193 text: markdownText,
194 parse_mode: "MarkdownV2"
195 };
196 }
197
198 export function telegramMarkdownV2(text) {
199 const placeholders = [];
200 const source = String(text || "");
201 const fenced = source.replace(FENCED_CODE_BLOCK, (_match, language, body) =>
202 markdownPlaceholder(
203 placeholders,
204 `\`\`\`${safeFenceLanguage(language)}\n${escapeMarkdownV2Code(removeClosingFenceNewline(body))}\n\`\`\``,
205 BLOCK_PLACEHOLDER_PREFIX
206 )
207 );
208 return restoreMarkdownPlaceholders(renderMarkdownLines(fenced), placeholders, BLOCK_PLACEHOLDER_PREFIX);
209 }
210
211 export function plainTelegramText(text) {
212 const placeholders = [];
213 const fenced = String(text || "").replace(FENCED_CODE_BLOCK, (_match, _language, code) =>
214 markdownPlaceholder(placeholders, code, BLOCK_PLACEHOLDER_PREFIX)
215 );
216 return restoreMarkdownPlaceholders(renderPlainLines(fenced), placeholders, BLOCK_PLACEHOLDER_PREFIX);
217 }
218
219 function stripPlainInlineMarkers(text) {
220 return String(text || "")
221 .replace(/\*\*([^*\n]+)\*\*/g, "$1")
222 .replace(/__([^_\n]+)__/g, "$1")
223 .replace(/[*_~]/g, "");
224 }
225
226 function renderPlainInline(text) {
227 const placeholders = [];
228 let plain = String(text || "").replace(/`([^`\n]+)`/g, (_match, code) =>
229 markdownPlaceholder(placeholders, code, INLINE_PLACEHOLDER_PREFIX)
230 );
231 plain = replaceBalancedMarkdownLinks(plain, (label, url) => {
232 const cleanLabel = restoreMarkdownPlaceholders(
233 stripPlainInlineMarkers(label),
234 placeholders,
235 INLINE_PLACEHOLDER_PREFIX
236 );
237 const cleanUrl = restoreMarkdownPlaceholders(url, placeholders, INLINE_PLACEHOLDER_PREFIX);
238 return markdownPlaceholder(placeholders, `${cleanLabel} (${cleanUrl})`, INLINE_PLACEHOLDER_PREFIX);
239 });
240 plain = stripPlainInlineMarkers(plain);
241 return restoreMarkdownPlaceholders(plain, placeholders, INLINE_PLACEHOLDER_PREFIX);
242 }
243
244 function boundedPlainTelegramText(text, maxChars) {
245 const plain = plainTelegramText(text);
246 if (maxChars > 0 && plain.length > maxChars) {
247 return String(text || "");
248 }
249 return plain;
250 }
251
252 export function isTelegramMarkdownParseError(error) {
253 if (Number(error?.errorCode) !== 400) return false;
254 const text = String(error?.description || error?.message || "").toLowerCase();
255 return (
256 text.includes("parse") ||
257 text.includes("can't parse entities") ||
258 text.includes("entity") ||
259 text.includes("markdown")
260 );
261 }
262
263 function renderMarkdownLines(text) {
264 const lines = String(text || "").split("\n");
265 const output = [];
266 for (let index = 0; index < lines.length; index += 1) {
267 if (isMarkdownTable(lines, index)) {
268 const { rendered, nextIndex } = renderMarkdownTable(lines, index);
269 output.push(rendered);
270 index = nextIndex - 1;
271 } else {
272 output.push(renderMarkdownInline(lines[index]));
273 }
274 }
275 return output.join("\n");
276 }
277
278 function renderPlainLines(text) {
279 const lines = String(text || "").split("\n");
280 const output = [];
281 for (let index = 0; index < lines.length; index += 1) {
282 if (isMarkdownTable(lines, index)) {
283 const { rendered, nextIndex } = renderPlainTable(lines, index);
284 output.push(rendered);
285 index = nextIndex - 1;
286 } else {
287 output.push(renderPlainInline(lines[index]));
288 }
289 }
290 return output.join("\n");
291 }
292
293 function renderMarkdownInline(text) {
294 const placeholders = [];
295 let value = replaceMarkdownLinks(String(text || ""), placeholders);
296 value = value.replace(/`([^`\n]+)`/g, (_match, code) =>
297 markdownPlaceholder(placeholders, `\`${escapeMarkdownV2Code(code)}\``, INLINE_PLACEHOLDER_PREFIX)
298 );
299 value = value.replace(/\*\*([^*\n]+)\*\*/g, (_match, body) =>
300 markdownPlaceholder(placeholders, `*${escapeMarkdownV2Text(body)}*`, INLINE_PLACEHOLDER_PREFIX)
301 );
302 value = escapeMarkdownV2Text(value);
303 return restoreMarkdownPlaceholders(value, placeholders, INLINE_PLACEHOLDER_PREFIX);
304 }
305
306 function replaceMarkdownLinks(text, placeholders) {
307 return replaceBalancedMarkdownLinks(text, (rawLabel, rawUrl) => {
308 const label = escapeMarkdownV2Text(rawLabel);
309 const url = escapeMarkdownV2Url(rawUrl);
310 return markdownPlaceholder(placeholders, `[${label}](${url})`, INLINE_PLACEHOLDER_PREFIX);
311 });
312 }
313
314 function replaceBalancedMarkdownLinks(text, renderLink) {
315 if (!text.includes("](")) return text;
316
317 const openings = [];
318 const closings = new Map();
319 for (let index = 0; index < text.length; index += 1) {
320 const char = text[index];
321 if (char === "\\" && /[\\()]/.test(text[index + 1] ?? "")) {
322 index += 1;
323 } else if (char === "(") {
324 openings.push(index);
325 } else if (char === ")" && openings.length) {
326 closings.set(openings.pop(), index);
327 } else if (/\s/.test(char)) {
328 openings.length = 0;
329 }
330 }
331
332 let offset = 0;
333 let result = "";
334 const codeOrLink = /`[^`\n]+`|\[([^\]\n]+)\]\(/g;
335 for (let match = codeOrLink.exec(text); match; match = codeOrLink.exec(text)) {
336 if (match[1] === undefined) continue;
337 const start = match.index + match[0].length;
338 const end = closings.get(start - 1);
339 if (end === undefined || end === start) continue;
340 const url = text.slice(start, end).replace(/\\([\\()])/g, "$1");
341 result += text.slice(offset, match.index);
342 result += renderLink(match[1], url);
343 offset = end + 1;
344 codeOrLink.lastIndex = offset;
345 }
346 return result + text.slice(offset);
347 }
348
349 function renderMarkdownTable(lines, startIndex) {
350 const headers = tableCells(lines[startIndex]);
351 const rows = [];
352 let index = startIndex + 2;
353 while (index < lines.length && looksLikeTableRow(lines[index])) {
354 rows.push(tableCells(lines[index]));
355 index += 1;
356 }
357 const headerText = headers.map(escapeMarkdownV2Text).join(" / ");
358 const rendered = [`*${headerText}*`];
359 for (const row of rows) {
360 const fields = headers.map((header, cellIndex) => {
361 const value = row[cellIndex] || "";
362 return `${escapeMarkdownV2Text(header)}: ${escapeMarkdownV2Text(value)}`;
363 });
364 rendered.push(`• ${fields.join("; ")}`);
365 }
366 return { rendered: rendered.join("\n"), nextIndex: index };
367 }
368
369 function renderPlainTable(lines, startIndex) {
370 const headers = tableCells(lines[startIndex]).map(renderPlainInline);
371 const rows = [];
372 let index = startIndex + 2;
373 while (index < lines.length && looksLikeTableRow(lines[index])) {
374 rows.push(tableCells(lines[index]).map(renderPlainInline));
375 index += 1;
376 }
377 const rendered = [headers.join(" / ")];
378 for (const row of rows) {
379 const fields = headers.map((header, cellIndex) => `${header}: ${row[cellIndex] || ""}`);
380 rendered.push(`- ${fields.join("; ")}`);
381 }
382 return { rendered: rendered.join("\n"), nextIndex: index };
383 }
384
385 function isMarkdownTable(lines, index) {
386 return (
387 looksLikeTableRow(lines[index]) &&
388 index + 1 < lines.length &&
389 looksLikeTableSeparator(lines[index + 1])
390 );
391 }
392
393 function looksLikeTableRow(line) {
394 return tableCells(line).length >= 2;
395 }
396
397 function looksLikeTableSeparator(line) {
398 const cells = tableCells(line);
399 return cells.length >= 2 && cells.every((cell) => /^:?-{3,}:?$/.test(cell));
400 }
401
402 function tableCells(line) {
403 const trimmed = String(line || "").trim();
404 if (!trimmed.includes("|")) return [];
405 const cells = [""];
406 // Read escape pairs together so an escaped backslash cannot escape the next pipe.
407 for (const [token] of trimmed.matchAll(/\\[\\|]|[^\\|]+|[\\|]/g)) {
408 if (token === "|") {
409 cells.push("");
410 } else {
411 cells[cells.length - 1] += token === "\\|" ? "|" : token;
412 }
413 }
414 if (trimmed.startsWith("|")) cells.shift();
415 if (cells.at(-1) === "") cells.pop();
416 return cells.map((cell) => cell.trim());
417 }
418
419 function escapeMarkdownV2Text(text) {
420 return String(text || "").replace(MARKDOWN_V2_SPECIALS, "\\$1");
421 }
422
423 function escapeMarkdownV2Code(text) {
424 return String(text || "").replace(/([`\\])/g, "\\$1");
425 }
426
427 function escapeMarkdownV2Url(text) {
428 return String(text || "").replace(/([)\\])/g, "\\$1");
429 }
430
431 function safeFenceLanguage(language) {
432 return String(language || "").trim().replace(/[^\w+-]/g, "");
433 }
434
435 function removeClosingFenceNewline(text) {
436 return String(text || "").replace(/\n$/, "");
437 }
438
439 function markdownPlaceholder(placeholders, rendered, prefix) {
440 const index = placeholders.push(rendered) - 1;
441 return `${prefix}${index}${PLACEHOLDER_SUFFIX}`;
442 }
443
444 function restoreMarkdownPlaceholders(text, placeholders, prefix) {
445 return String(text || "").replace(
446 new RegExp(`${prefix}(\\d+)${PLACEHOLDER_SUFFIX}`, "g"),
447 (_match, index) => placeholders[Number(index)] || ""
448 );
449 }
450
451 export function telegramRetryDelayMs(error, fallbackMs = 3000) {
452 const retryAfter = Number(error?.parameters?.retry_after || 0);
453 if (Number.isFinite(retryAfter) && retryAfter > 0) {
454 return Math.min(retryAfter * 1000, 60000);
455 }
456 return fallbackMs;
457 }
458
459 const POLLING_CONFLICT_DELAYS_MS = [15000, 25000, 35000, 45000, 55000];
460
461 export function telegramPollingConflictDelayMs(attempt = 0) {
462 const index = Math.max(0, Math.floor(Number(attempt) || 0));
463 return POLLING_CONFLICT_DELAYS_MS[index] ?? null;
464 }
465
466 export function telegramSendRetryDelayMs(error, attempt = 0) {
467 const retryAfter = Number(error?.parameters?.retry_after || 0);
468 if (error?.errorCode === 429 && attempt < 3) {
469 if (Number.isFinite(retryAfter) && retryAfter > 0) {
470 return Math.min(retryAfter * 1000, 60000);
471 }
472 return 3000;
473 }
474 return null;
475 }
476
477 export function isPermanentTelegramError(error) {
478 const code = Number(error?.errorCode);
479 return code >= 400 && code < 500 && code !== 429;
480 }
481
482 export function looksLikePollingConflict(error) {
483 const text = String(error?.description || error?.message || "").toLowerCase();
484 return error?.errorCode === 409 || text.includes("terminated by other getupdates request");
485 }
486
487 export function validateBridgeConfig(env, options = {}) {
488 const runtimeEnv = options.runtimeEnv || null;
489 const workspaceRoot = options.workspaceRoot || "";
490 const errors = [];
491 const warnings = [];
492 const info = [];
493 const add = (list, code, message) => list.push({ code, message });
494
495 const botToken = envFirst(env, "TELEGRAM_BOT_TOKEN");
496 if (!botToken) {
497 add(errors, "missing_required", "TELEGRAM_BOT_TOKEN is required");
498 } else if (isPlaceholderValue(botToken)) {
499 add(errors, "placeholder_value", "TELEGRAM_BOT_TOKEN still contains a placeholder value");
500 }
501
502 const runtimeUrl = envFirst(env, "CODEWHALE_RUNTIME_URL", "DEEPSEEK_RUNTIME_URL") || "http://127.0.0.1:7878";
503 try {
504 const parsed = new URL(runtimeUrl);
505 const localHosts = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
506 if (!["http:", "https:"].includes(parsed.protocol)) {
507 add(errors, "invalid_runtime_url", "CODEWHALE_RUNTIME_URL must use http or https");
508 }
509 if (!localHosts.has(parsed.hostname) && options.requireLocalRuntime !== false) {
510 add(errors, "remote_runtime_url", "CODEWHALE_RUNTIME_URL should point at localhost on a VM deployment");
511 }
512 } catch {
513 add(errors, "invalid_runtime_url", "CODEWHALE_RUNTIME_URL is not a valid URL");
514 }
515
516 const runtimeToken = envFirst(env, "CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN");
517 if (!runtimeToken) {
518 add(errors, "missing_required", "CODEWHALE_RUNTIME_TOKEN is required");
519 } else if (isPlaceholderValue(runtimeToken)) {
520 add(errors, "placeholder_value", "CODEWHALE_RUNTIME_TOKEN still contains a placeholder value");
521 }
522
523 const workspace = envFirst(env, "CODEWHALE_WORKSPACE", "DEEPSEEK_WORKSPACE");
524 if (workspace && !workspace.startsWith("/")) {
525 add(errors, "relative_workspace", "CODEWHALE_WORKSPACE must be an absolute path");
526 }
527 if (
528 workspace &&
529 workspaceRoot &&
530 workspace !== workspaceRoot &&
531 !workspace.startsWith(`${workspaceRoot}/`)
532 ) {
533 add(warnings, "workspace_root", `CODEWHALE_WORKSPACE is outside ${workspaceRoot}`);
534 }
535
536 const threadMapPath = envFirst(env, "TELEGRAM_THREAD_MAP_PATH");
537 if (threadMapPath && !threadMapPath.startsWith("/")) {
538 add(errors, "relative_thread_map", "TELEGRAM_THREAD_MAP_PATH must be an absolute path");
539 }
540
541 const allowGroups = parseBool(env.TELEGRAM_ALLOW_GROUPS, false);
542 const requirePrefix = parseBool(env.TELEGRAM_REQUIRE_PREFIX_IN_GROUP, true);
543 const allowUnlisted = parseBool(
544 envFirst(env, "TELEGRAM_ALLOW_UNLISTED", "CODEWHALE_ALLOW_UNLISTED", "DEEPSEEK_ALLOW_UNLISTED"),
545 false
546 );
547 const allowlist = parseList(
548 envFirst(env, "TELEGRAM_CHAT_ALLOWLIST", "CODEWHALE_CHAT_ALLOWLIST", "DEEPSEEK_CHAT_ALLOWLIST")
549 );
550
551 if (!allowlist.length && allowUnlisted) {
552 add(warnings, "pairing_mode_open", "TELEGRAM_ALLOW_UNLISTED=true leaves first-pairing mode open");
553 } else if (!allowlist.length) {
554 add(warnings, "not_paired", "TELEGRAM_CHAT_ALLOWLIST is empty; all chats will be refused");
555 }
556 if (allowGroups && allowUnlisted) {
557 add(errors, "open_group_control", "Group control cannot be enabled while unlisted chats are allowed");
558 }
559 if (allowGroups && !requirePrefix) {
560 add(warnings, "group_without_prefix", "Group control is enabled without requiring TELEGRAM_GROUP_PREFIX");
561 }
562 if (!allowGroups) {
563 add(info, "dm_only", "Direct-message control is enabled; group chats are disabled");
564 }
565
566 const maxReplyChars = Number(env.TELEGRAM_MAX_REPLY_CHARS || 3500);
567 if (!Number.isFinite(maxReplyChars) || maxReplyChars < 100 || maxReplyChars > 4096) {
568 add(errors, "invalid_max_reply_chars", "TELEGRAM_MAX_REPLY_CHARS must be between 100 and 4096");
569 }
570 const pollTimeout = Number(env.TELEGRAM_POLL_TIMEOUT_SECONDS || 50);
571 if (!Number.isFinite(pollTimeout) || pollTimeout < 1 || pollTimeout > 60) {
572 add(errors, "invalid_poll_timeout", "TELEGRAM_POLL_TIMEOUT_SECONDS must be between 1 and 60");
573 }
574 const turnTimeoutMs = Number(envFirst(env, "CODEWHALE_TURN_TIMEOUT_MS", "DEEPSEEK_TURN_TIMEOUT_MS") || 900000);
575 if (!Number.isFinite(turnTimeoutMs) || turnTimeoutMs < 1000) {
576 add(errors, "invalid_turn_timeout", "CODEWHALE_TURN_TIMEOUT_MS must be at least 1000");
577 }
578
579 if (runtimeEnv) {
580 const runtimeFileToken = envFirst(runtimeEnv, "CODEWHALE_RUNTIME_TOKEN", "DEEPSEEK_RUNTIME_TOKEN");
581 if (!runtimeFileToken) {
582 add(errors, "missing_runtime_token", "runtime.env is missing CODEWHALE_RUNTIME_TOKEN");
583 } else if (isPlaceholderValue(runtimeFileToken)) {
584 add(errors, "placeholder_runtime_token", "runtime.env CODEWHALE_RUNTIME_TOKEN is still a placeholder");
585 } else if (runtimeToken && runtimeToken !== runtimeFileToken) {
586 add(errors, "token_mismatch", "Runtime and bridge token values do not match");
587 }
588
589 const provider = envFirst(runtimeEnv, "CODEWHALE_PROVIDER", "DEEPSEEK_PROVIDER");
590 if (!provider) {
591 add(warnings, "missing_provider", "runtime.env does not set CODEWHALE_PROVIDER");
592 }
593
594 const runtimePort = Number(envFirst(runtimeEnv, "CODEWHALE_RUNTIME_PORT", "DEEPSEEK_RUNTIME_PORT") || 7878);
595 if (!Number.isInteger(runtimePort) || runtimePort <= 0 || runtimePort > 65535) {
596 add(errors, "invalid_runtime_port", "runtime port must be a valid TCP port");
597 }
598 }
599
600 return {
601 ok: errors.length === 0,
602 errors,
603 warnings,
604 info
605 };
606 }
607
608 export function formatValidationReport(result) {
609 const lines = ["Telegram bridge config validation"];
610 for (const item of result.errors) lines.push(`[fail] ${item.message}`);
611 for (const item of result.warnings) lines.push(`[warn] ${item.message}`);
612 for (const item of result.info) lines.push(`[info] ${item.message}`);
613 if (result.ok) lines.push("[ok] No blocking config errors found");
614 return lines.join("\n");
615 }
616
617 export function helpText() {
618 return [
619 "CodeWhale Telegram bridge commands:",
620 "/menu - open tappable controls",
621 "/help - show this help",
622 "/status - runtime and workspace status",
623 "/threads - recent runtime threads",
624 "/new - create a new thread for this chat",
625 "/resume <thread_id> - bind this chat to an existing thread",
626 "/model <name|default> - set or reset this chat's model",
627 "/interrupt - interrupt the active turn",
628 "/compact - compact the current thread",
629 "/allow <approval_id> [remember] - approve a pending tool call",
630 "/deny <approval_id> - deny a pending tool call",
631 "/answer <response> - answer the current agent question",
632 "",
633 "Anything else is sent as a CodeWhale prompt."
634 ].join("\n");
635 }
636
636 lines Plain Text