@grinev/opencode-telegram-bot 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,70 @@
1
1
  import { en } from "./en.js";
2
+ import { de } from "./de.js";
3
+ import { es } from "./es.js";
2
4
  import { ru } from "./ru.js";
3
- export const SUPPORTED_LOCALES = ["en", "ru"];
4
- const dictionaries = {
5
- en,
6
- ru,
7
- };
5
+ import { zh } from "./zh.js";
6
+ const LOCALE_DEFINITIONS = [
7
+ {
8
+ code: "en",
9
+ label: "English",
10
+ dateLocale: "en-US",
11
+ dictionary: en,
12
+ },
13
+ {
14
+ code: "de",
15
+ label: "Deutsch",
16
+ dateLocale: "de-DE",
17
+ dictionary: de,
18
+ },
19
+ {
20
+ code: "es",
21
+ label: "Español",
22
+ dateLocale: "es-ES",
23
+ dictionary: es,
24
+ },
25
+ {
26
+ code: "ru",
27
+ label: "Русский",
28
+ dateLocale: "ru-RU",
29
+ dictionary: ru,
30
+ },
31
+ {
32
+ code: "zh",
33
+ label: "简体中文",
34
+ dateLocale: "zh-CN",
35
+ dictionary: zh,
36
+ },
37
+ ];
38
+ const DEFAULT_LOCALE = "en";
39
+ export const SUPPORTED_LOCALES = LOCALE_DEFINITIONS.map((definition) => definition.code);
40
+ const localeDefinitionByCode = Object.fromEntries(LOCALE_DEFINITIONS.map((definition) => [definition.code, definition]));
8
41
  let runtimeLocaleOverride = null;
9
- function normalizeLocale(locale) {
10
- const normalized = locale.trim().toLowerCase();
42
+ export function resolveSupportedLocale(locale) {
43
+ const normalized = locale?.trim().toLowerCase();
44
+ if (!normalized) {
45
+ return null;
46
+ }
47
+ if (Object.hasOwn(localeDefinitionByCode, normalized)) {
48
+ return normalized;
49
+ }
11
50
  const baseLocale = normalized.split("-")[0];
12
- if (baseLocale === "ru") {
13
- return "ru";
51
+ if (Object.hasOwn(localeDefinitionByCode, baseLocale)) {
52
+ return baseLocale;
14
53
  }
15
- return "en";
54
+ return null;
55
+ }
56
+ export function normalizeLocale(locale, fallback = DEFAULT_LOCALE) {
57
+ return resolveSupportedLocale(locale) ?? fallback;
58
+ }
59
+ export function isSupportedLocale(locale) {
60
+ return resolveSupportedLocale(locale) !== null;
61
+ }
62
+ export function getLocaleOptions() {
63
+ return LOCALE_DEFINITIONS.map(({ code, label }) => ({ code, label }));
64
+ }
65
+ export function getDateLocale(locale) {
66
+ const activeLocale = locale ?? getLocale();
67
+ return localeDefinitionByCode[activeLocale].dateLocale;
16
68
  }
17
69
  function interpolate(template, params) {
18
70
  if (!params) {
@@ -31,7 +83,7 @@ export function getLocale() {
31
83
  return runtimeLocaleOverride;
32
84
  }
33
85
  const localeFromEnv = process.env.BOT_LOCALE;
34
- return normalizeLocale(localeFromEnv ?? "en");
86
+ return normalizeLocale(localeFromEnv, DEFAULT_LOCALE);
35
87
  }
36
88
  export function setRuntimeLocale(locale) {
37
89
  runtimeLocaleOverride = locale;
@@ -41,7 +93,7 @@ export function resetRuntimeLocale() {
41
93
  }
42
94
  export function t(key, params, locale) {
43
95
  const activeLocale = locale ?? getLocale();
44
- const dictionary = dictionaries[activeLocale];
96
+ const dictionary = localeDefinitionByCode[activeLocale].dictionary;
45
97
  const template = dictionary[key] ?? en[key];
46
98
  if (!template) {
47
99
  return key;
package/dist/i18n/ru.js CHANGED
@@ -43,6 +43,11 @@ export const ru = {
43
43
  "bot.prompt_send_error": "Не удалось отправить запрос в OpenCode.",
44
44
  "bot.session_error": "🔴 OpenCode вернул ошибку: {message}",
45
45
  "bot.unknown_command": "⚠️ Неизвестная команда: {command}. Используйте /help для списка команд.",
46
+ "bot.photo_downloading": "⏳ Скачиваю фото...",
47
+ "bot.photo_too_large": "⚠️ Фото слишком большое (макс. {maxSizeMb}МБ)",
48
+ "bot.photo_model_no_image": "⚠️ Текущая модель не поддерживает изображения. Отправляю только текст.",
49
+ "bot.photo_download_error": "🔴 Не удалось скачать фото",
50
+ "bot.photo_no_caption": "💡 Совет: Добавьте подпись, чтобы описать, что делать с этим фото.",
46
51
  "status.header_running": "🟢 **OpenCode Server запущен**",
47
52
  "status.health.healthy": "Healthy",
48
53
  "status.health.unhealthy": "Unhealthy",
@@ -115,6 +120,7 @@ export const ru = {
115
120
  "model.change_error_callback": "Ошибка при смене модели",
116
121
  "model.menu.empty": "⚠️ Нет доступных моделей",
117
122
  "model.menu.current": "Текущая модель: {name}\n\nВыберите модель:",
123
+ "model.menu.favorites_hint": "ℹ️ Список моделей формируется из favorites в OpenCode CLI.",
118
124
  "model.menu.error": "🔴 Не удалось получить список моделей",
119
125
  "variant.model_not_selected_callback": "Ошибка: модель не выбрана",
120
126
  "variant.changed_callback": "Variant изменен: {name}",
@@ -192,13 +198,16 @@ export const ru = {
192
198
  "tool.file_header.write": "Write File/Path: {path}\n============================================================\n\n",
193
199
  "tool.file_header.edit": "Edit File/Path: {path}\n============================================================\n\n",
194
200
  "runtime.wizard.ask_token": "Введите токен Telegram-бота (получить у @BotFather).\n> ",
201
+ "runtime.wizard.ask_language": "Выберите язык интерфейса.\nВведите номер языка из списка или код локали.\nНажмите Enter, чтобы оставить язык по умолчанию: {defaultLocale}\n{options}\n> ",
202
+ "runtime.wizard.language_invalid": "Введите номер языка из списка или поддерживаемый код локали.\n",
203
+ "runtime.wizard.language_selected": "Выбран язык: {language}\n",
195
204
  "runtime.wizard.token_required": "Токен обязателен. Попробуйте еще раз.\n",
196
205
  "runtime.wizard.token_invalid": "Похоже на невалидный токен (ожидается формат <id>:<secret>). Попробуйте еще раз.\n",
197
206
  "runtime.wizard.ask_user_id": "Введите ваш Telegram User ID (можно узнать у @userinfobot).\n> ",
198
207
  "runtime.wizard.user_id_invalid": "Введите положительное целое число (> 0).\n",
199
208
  "runtime.wizard.ask_api_url": "Введите URL OpenCode API (опционально).\nНажмите Enter для значения по умолчанию: {defaultUrl}\n> ",
200
209
  "runtime.wizard.api_url_invalid": "Введите корректный URL (http/https) или нажмите Enter для значения по умолчанию.\n",
201
- "runtime.wizard.start": "Запуск first-run wizard для настройки OpenCode Telegram Bot.\n",
210
+ "runtime.wizard.start": "Настройка OpenCode Telegram Bot.\n",
202
211
  "runtime.wizard.saved": "Конфигурация сохранена:\n- {envPath}\n- {settingsPath}\n",
203
212
  "runtime.wizard.not_configured_starting": "Приложение еще не сконфигурировано. Запускаю wizard...\n",
204
213
  "runtime.wizard.tty_required": "Интерактивный wizard требует TTY-терминал. Запустите `opencode-telegram config` в интерактивной оболочке.",
@@ -0,0 +1,247 @@
1
+ export const zh = {
2
+ "cmd.description.status": "服务器和会话状态",
3
+ "cmd.description.new": "创建新会话",
4
+ "cmd.description.stop": "停止当前操作",
5
+ "cmd.description.sessions": "列出会话",
6
+ "cmd.description.projects": "列出项目",
7
+ "cmd.description.model": "选择模型",
8
+ "cmd.description.agent": "选择模式",
9
+ "cmd.description.opencode_start": "启动 OpenCode 服务器",
10
+ "cmd.description.opencode_stop": "停止 OpenCode 服务器",
11
+ "cmd.description.help": "帮助",
12
+ "callback.unknown_command": "未知命令",
13
+ "callback.processing_error": "处理错误",
14
+ "error.load_agents": "❌ 加载代理列表失败",
15
+ "error.load_models": "❌ 加载模型列表失败",
16
+ "error.load_variants": "❌ 加载变体列表失败",
17
+ "error.context_button": "❌ 处理上下文按钮失败",
18
+ "error.generic": "🔴 出现了一些问题。",
19
+ "interaction.blocked.expired": "⚠️ 此交互已过期。请重新开始。",
20
+ "interaction.blocked.expected_callback": "⚠️ 此步骤请使用内联按钮,或点击取消。",
21
+ "interaction.blocked.expected_text": "⚠️ 此步骤请发送一条文本消息。",
22
+ "interaction.blocked.expected_command": "⚠️ 此步骤请发送一条命令。",
23
+ "interaction.blocked.command_not_allowed": "⚠️ 当前步骤不可用此命令。",
24
+ "interaction.blocked.finish_current": "⚠️ 请先完成当前交互(回答或取消),然后再打开其他菜单。",
25
+ "inline.blocked.expected_choice": "⚠️ 请使用内联按钮选择一个选项,或点击取消。",
26
+ "inline.blocked.command_not_allowed": "⚠️ 内联菜单激活期间不可用此命令。",
27
+ "question.blocked.expected_answer": "⚠️ 请使用按钮、自定义回答或取消来回答当前问题。",
28
+ "question.blocked.command_not_allowed": "⚠️ 在当前问答流程完成之前不可用此命令。",
29
+ "inline.button.cancel": "❌ 取消",
30
+ "inline.inactive_callback": "此菜单已失效",
31
+ "inline.cancelled_callback": "已取消",
32
+ "common.unknown": "未知",
33
+ "common.unknown_error": "未知错误",
34
+ "start.welcome": "👋 欢迎使用 OpenCode Telegram Bot!\n\n可用命令:\n/projects — 选择项目\n/sessions — 会话列表\n/new — 新建会话\n/agent — 切换模式\n/model — 选择模型\n/status — 状态\n/help — 帮助",
35
+ "help.text": "📖 **帮助**\n\n/status - 查看服务器状态\n/sessions - 会话列表\n/new - 创建新会话\n/help - 帮助",
36
+ "bot.thinking": "💭 思考中...",
37
+ "bot.project_not_selected": "🏗 未选择项目。\n\n请先使用 /projects 选择一个项目。",
38
+ "bot.creating_session": "🔄 正在创建新会话...",
39
+ "bot.create_session_error": "🔴 创建会话失败。请重试 /new,或使用 /status 检查服务器状态。",
40
+ "bot.session_created": "✅ 会话已创建:{title}",
41
+ "bot.session_busy": "⏳ 代理正在执行任务。请等待完成,或使用 /stop 中断当前运行。",
42
+ "bot.session_reset_project_mismatch": "⚠️ 活动会话与所选项目不匹配,因此已重置。使用 /sessions 选择一个会话,或 /new 创建新会话。",
43
+ "bot.prompt_send_error": "向 OpenCode 发送请求失败。",
44
+ "bot.session_error": "🔴 OpenCode 返回错误:{message}",
45
+ "bot.unknown_command": "⚠️ 未知命令:{command}。使用 /help 查看可用命令。",
46
+ "bot.photo_downloading": "⏳ 正在下载照片...",
47
+ "bot.photo_too_large": "⚠️ 照片过大(最大 {maxSizeMb}MB)",
48
+ "bot.photo_model_no_image": "⚠️ 当前模型不支持图像输入。将仅发送文本。",
49
+ "bot.photo_download_error": "🔴 下载照片失败",
50
+ "bot.photo_no_caption": "💡 提示:添加说明文字以描述你希望对这张照片做什么。",
51
+ "status.header_running": "🟢 **OpenCode 服务器正在运行**",
52
+ "status.health.healthy": "健康",
53
+ "status.health.unhealthy": "不健康",
54
+ "status.line.health": "状态:{health}",
55
+ "status.line.version": "版本:{version}",
56
+ "status.line.managed_yes": "由机器人管理:是",
57
+ "status.line.managed_no": "由机器人管理:否",
58
+ "status.line.pid": "PID:{pid}",
59
+ "status.line.uptime_sec": "运行时间:{seconds} 秒",
60
+ "status.line.mode": "模式:{mode}",
61
+ "status.line.model": "模型:{model}",
62
+ "status.agent_not_set": "未设置",
63
+ "status.project_selected": "🏗 项目:{project}",
64
+ "status.project_not_selected": "🏗 项目:未选择",
65
+ "status.project_hint": "使用 /projects 选择项目",
66
+ "status.session_selected": "📋 当前会话:{title}",
67
+ "status.session_not_selected": "📋 当前会话:未选择",
68
+ "status.session_hint": "使用 /sessions 选择一个会话,或 /new 创建",
69
+ "status.server_unavailable": "🔴 OpenCode 服务器不可用\n\n使用 /opencode_start 启动服务器。",
70
+ "projects.empty": "📭 未找到项目。\n\n在 OpenCode 中打开一个目录并至少创建一个会话,然后它会出现在这里。",
71
+ "projects.select": "请选择一个项目:",
72
+ "projects.select_with_current": "请选择一个项目:\n\n当前:🏗 {project}",
73
+ "projects.fetch_error": "🔴 OpenCode 服务器不可用,或加载项目时发生错误。",
74
+ "projects.selected": "✅ 已选择项目:{project}\n\n📋 会话已重置。请在此项目中使用 /sessions 或 /new。",
75
+ "projects.select_error": "🔴 选择项目失败。",
76
+ "sessions.project_not_selected": "🏗 未选择项目。\n\n请先使用 /projects 选择一个项目。",
77
+ "sessions.empty": "📭 未找到会话。\n\n使用 /new 创建新会话。",
78
+ "sessions.select": "请选择一个会话:",
79
+ "sessions.fetch_error": "🔴 OpenCode 服务器不可用,或加载会话时发生错误。",
80
+ "sessions.select_project_first": "🔴 未选择项目。使用 /projects。",
81
+ "sessions.loading_context": "⏳ 正在加载上下文和最新消息...",
82
+ "sessions.selected": "✅ 已选择会话:{title}",
83
+ "sessions.select_error": "🔴 选择会话失败。",
84
+ "sessions.preview.empty": "没有最近消息。",
85
+ "sessions.preview.title": "最近消息:",
86
+ "sessions.preview.you": "你:",
87
+ "sessions.preview.agent": "代理:",
88
+ "new.project_not_selected": "🏗 未选择项目。\n\n请先使用 /projects 选择一个项目。",
89
+ "new.created": "✅ 新会话已创建:{title}",
90
+ "new.create_error": "🔴 OpenCode 服务器不可用,或创建会话时发生错误。",
91
+ "stop.no_active_session": "🛑 代理尚未启动\n\n使用 /new 创建会话,或通过 /sessions 选择一个。",
92
+ "stop.in_progress": "🛑 已停止事件流,正在发送中止信号...\n\n等待代理停止。",
93
+ "stop.warn_unconfirmed": "⚠️ 事件流已停止,但服务器未确认中止。\n\n检查 /status,并在几秒后重试 /stop。",
94
+ "stop.warn_maybe_finished": "⚠️ 事件流已停止,但代理可能已完成。",
95
+ "stop.success": "✅ 代理操作已中断。本次运行的后续消息将不再发送。",
96
+ "stop.warn_still_busy": "⚠️ 信号已发送,但代理仍在忙。\n\n事件流已禁用,因此不会发送中间消息。",
97
+ "stop.warn_timeout": "⚠️ 中止请求超时。\n\n事件流已禁用,请在几秒后重试 /stop。",
98
+ "stop.warn_local_only": "⚠️ 已在本地停止事件流,但服务器端中止失败。",
99
+ "stop.error": "🔴 停止操作失败。\n\n事件流已停止,请再次尝试 /stop。",
100
+ "opencode_start.already_running_managed": "⚠️ OpenCode 服务器已在运行\n\nPID:{pid}\n运行时间:{seconds} 秒",
101
+ "opencode_start.already_running_external": "✅ OpenCode 服务器正作为外部进程运行\n\n版本:{version}\n\n该服务器不是由机器人启动,因此 /opencode-stop 无法停止它。",
102
+ "opencode_start.starting": "🔄 正在启动 OpenCode 服务器...",
103
+ "opencode_start.start_error": "🔴 启动 OpenCode 服务器失败\n\n错误:{error}\n\n请检查 OpenCode CLI 已安装且在 PATH 中可用:\n`opencode --version`\n`npm install -g @opencode-ai/cli`",
104
+ "opencode_start.started_not_ready": "⚠️ OpenCode 服务器已启动,但未响应\n\nPID:{pid}\n\n服务器可能仍在启动中。几秒后试试 /status。",
105
+ "opencode_start.success": "✅ OpenCode 服务器启动成功\n\nPID:{pid}\n版本:{version}",
106
+ "opencode_start.error": "🔴 启动服务器时发生错误。\n\n请查看应用日志了解详情。",
107
+ "opencode_stop.external_running": "⚠️ OpenCode 服务器正作为外部进程运行\n\n该服务器不是通过 /opencode-start 启动的。\n请手动停止它,或使用 /status 检查状态。",
108
+ "opencode_stop.not_running": "⚠️ OpenCode 服务器未运行",
109
+ "opencode_stop.stopping": "🛑 正在停止 OpenCode 服务器...\n\nPID:{pid}",
110
+ "opencode_stop.stop_error": "🔴 停止 OpenCode 服务器失败\n\n错误:{error}",
111
+ "opencode_stop.success": "✅ OpenCode 服务器已成功停止",
112
+ "opencode_stop.error": "🔴 停止服务器时发生错误。\n\n请查看应用日志了解详情。",
113
+ "agent.changed_callback": "模式已更改:{name}",
114
+ "agent.changed_message": "✅ 模式已切换为:{name}",
115
+ "agent.change_error_callback": "切换模式失败",
116
+ "agent.menu.current": "当前模式:{name}\n\n请选择模式:",
117
+ "agent.menu.select": "请选择工作模式:",
118
+ "model.changed_callback": "模型已更改:{name}",
119
+ "model.changed_message": "✅ 模型已切换为:{name}",
120
+ "model.change_error_callback": "切换模型失败",
121
+ "model.menu.empty": "⚠️ 没有可用模型",
122
+ "model.menu.current": "当前模型:{name}\n\n请选择模型:",
123
+ "model.menu.favorites_hint": "ℹ️ 模型列表来自 OpenCode CLI 的收藏(favorites)。",
124
+ "model.menu.error": "🔴 获取模型列表失败",
125
+ "variant.model_not_selected_callback": "错误:未选择模型",
126
+ "variant.changed_callback": "变体已更改:{name}",
127
+ "variant.changed_message": "✅ 变体已切换为:{name}",
128
+ "variant.change_error_callback": "切换变体失败",
129
+ "variant.select_model_first": "⚠️ 请先选择一个模型",
130
+ "variant.menu.empty": "⚠️ 没有可用变体",
131
+ "variant.menu.current": "当前变体:{name}\n\n请选择变体:",
132
+ "variant.menu.error": "🔴 获取变体列表失败",
133
+ "context.button.confirm": "✅ 是的,压缩上下文",
134
+ "context.no_active_session": "⚠️ 没有活动会话。使用 /new 创建会话",
135
+ "context.confirm_text": '📊 会话 "{title}" 的上下文压缩\n\n这会通过移除历史中的旧消息来减少上下文占用。当前任务不会被中断。\n\n继续?',
136
+ "context.callback_session_not_found": "未找到会话",
137
+ "context.callback_compacting": "正在压缩上下文...",
138
+ "context.progress": "⏳ 正在压缩上下文...",
139
+ "context.error": "❌ 上下文压缩失败",
140
+ "context.success": "✅ 上下文压缩成功",
141
+ "permission.inactive_callback": "权限请求已失效",
142
+ "permission.processing_error_callback": "处理错误",
143
+ "permission.no_active_request_callback": "错误:没有活动请求",
144
+ "permission.reply.once": "仅允许一次",
145
+ "permission.reply.always": "始终允许",
146
+ "permission.reply.reject": "已拒绝",
147
+ "permission.send_reply_error": "❌ 发送权限回复失败",
148
+ "permission.blocked.expected_reply": "⚠️ 请先使用上方按钮回答权限请求。",
149
+ "permission.blocked.command_not_allowed": "⚠️ 在你回答权限请求之前不可用此命令。",
150
+ "permission.header": "{emoji} **权限请求:{name}**\n\n",
151
+ "permission.button.allow": "✅ 允许一次",
152
+ "permission.button.always": "🔓 始终允许",
153
+ "permission.button.reject": "❌ 拒绝",
154
+ "permission.name.bash": "Bash",
155
+ "permission.name.edit": "编辑",
156
+ "permission.name.write": "写入",
157
+ "permission.name.read": "读取",
158
+ "permission.name.webfetch": "Web 获取",
159
+ "permission.name.websearch": "Web 搜索",
160
+ "permission.name.glob": "文件搜索",
161
+ "permission.name.grep": "内容搜索",
162
+ "permission.name.list": "列出目录",
163
+ "permission.name.task": "任务",
164
+ "permission.name.lsp": "LSP",
165
+ "question.inactive_callback": "投票已失效",
166
+ "question.processing_error_callback": "处理错误",
167
+ "question.select_one_required_callback": "请至少选择一个选项",
168
+ "question.enter_custom_callback": "请发送你的自定义回答",
169
+ "question.cancelled": "❌ 投票已取消",
170
+ "question.answer_already_received": "已收到答案,请稍候...",
171
+ "question.completed_no_answers": "✅ 投票完成(无答案)",
172
+ "question.no_active_project": "❌ 没有活动项目",
173
+ "question.no_active_request": "❌ 没有活动请求",
174
+ "question.send_answers_error": "❌ 向代理发送答案失败",
175
+ "question.multi_hint": "\n*你可以选择多个选项*",
176
+ "question.button.submit": "✅ 完成",
177
+ "question.button.custom": "🔤 自定义回答",
178
+ "question.button.cancel": "❌ 取消",
179
+ "question.use_custom_button_first": '⚠️ 要发送文本,请先点击当前问题的 "自定义回答" 按钮。',
180
+ "question.summary.title": "✅ 投票已完成!\n\n",
181
+ "question.summary.question": "问题 {index}:\n{question}\n\n",
182
+ "question.summary.answer": "回答:\n{answer}\n\n",
183
+ "keyboard.agent_mode": "{emoji} {name} 模式",
184
+ "keyboard.context": "📊 {used} / {limit} ({percent}%)",
185
+ "keyboard.context_empty": "📊 0",
186
+ "keyboard.variant": "💭 {name}",
187
+ "keyboard.variant_default": "💡 默认",
188
+ "keyboard.updated": "⌨️ 键盘已更新",
189
+ "pinned.default_session_title": "新会话",
190
+ "pinned.unknown": "未知",
191
+ "pinned.line.project": "项目: {project}",
192
+ "pinned.line.model": "模型: {model}",
193
+ "pinned.line.context": "上下文: {used} / {limit} ({percent}%)",
194
+ "pinned.files.title": "文件({count}):",
195
+ "pinned.files.item": " {path}{diff}",
196
+ "pinned.files.more": " ... 还有 {count} 个",
197
+ "tool.todo.overflow": "*(还有 {count} 个任务)*",
198
+ "tool.file_header.write": "写入文件/路径: {path}\n============================================================\n\n",
199
+ "tool.file_header.edit": "编辑文件/路径: {path}\n============================================================\n\n",
200
+ "runtime.wizard.ask_token": "请输入 Telegram 机器人 token(从 @BotFather 获取)。\n> ",
201
+ "runtime.wizard.ask_language": "请选择界面语言。\n输入列表中的语言编号或 locale code。\n按 Enter 保持默认语言:{defaultLocale}\n{options}\n> ",
202
+ "runtime.wizard.language_invalid": "请输入列表中的语言编号或受支持的 locale code。\n",
203
+ "runtime.wizard.language_selected": "已选择语言:{language}\n",
204
+ "runtime.wizard.token_required": "必须提供 token。请重试。\n",
205
+ "runtime.wizard.token_invalid": "token 看起来无效(期望格式 <id>:<secret>)。请重试。\n",
206
+ "runtime.wizard.ask_user_id": "请输入你的 Telegram User ID(可从 @userinfobot 获取)。\n> ",
207
+ "runtime.wizard.user_id_invalid": "请输入一个正整数(> 0)。\n",
208
+ "runtime.wizard.ask_api_url": "请输入 OpenCode API URL(可选)。\n按 Enter 使用默认值:{defaultUrl}\n> ",
209
+ "runtime.wizard.api_url_invalid": "请输入有效 URL(http/https),或按 Enter 使用默认值。\n",
210
+ "runtime.wizard.start": "OpenCode Telegram Bot 设置。\n",
211
+ "runtime.wizard.saved": "配置已保存:\n- {envPath}\n- {settingsPath}\n",
212
+ "runtime.wizard.not_configured_starting": "应用尚未配置。正在启动向导...\n",
213
+ "runtime.wizard.tty_required": "交互式向导需要 TTY 终端。请在交互式 shell 中运行 `opencode-telegram config`。",
214
+ "rename.no_session": "⚠️ 没有活动会话。请先创建或选择一个会话。",
215
+ "rename.prompt": "📝 请输入会话的新标题:\n\n当前:{title}",
216
+ "rename.empty_title": "⚠️ 标题不能为空。",
217
+ "rename.success": "✅ 会话已重命名为:{title}",
218
+ "rename.error": "🔴 重命名会话失败。",
219
+ "rename.cancelled": "❌ 重命名已取消。",
220
+ "rename.inactive_callback": "重命名请求已失效",
221
+ "rename.inactive": "⚠️ 重命名请求未激活。请再次运行 /rename。",
222
+ "rename.blocked.expected_name": "⚠️ 请以文本输入新会话名称,或在重命名消息中点击取消。",
223
+ "rename.blocked.command_not_allowed": "⚠️ 重命名等待新名称期间不可用此命令。",
224
+ "rename.button.cancel": "❌ 取消",
225
+ "cmd.description.rename": "重命名当前会话",
226
+ "cli.usage": "用法:\n opencode-telegram [start] [--mode sources|installed]\n opencode-telegram status\n opencode-telegram stop\n opencode-telegram config\n\n说明:\n - 不带命令时默认执行 `start`\n - `--mode` 目前仅支持 `start` 命令",
227
+ "cli.placeholder.status": "命令 `status` 目前是占位符。真实状态检查将会在 service 层(阶段 5)添加。",
228
+ "cli.placeholder.stop": "命令 `stop` 目前是占位符。真实的后台进程停止将会在 service 层(阶段 5)添加。",
229
+ "cli.placeholder.unavailable": "命令不可用。",
230
+ "cli.error.prefix": "CLI 错误:{message}",
231
+ "cli.args.unknown_command": "未知命令:{value}",
232
+ "cli.args.mode_requires_value": "选项 --mode 需要一个值:sources|installed",
233
+ "cli.args.invalid_mode": "无效的 --mode 值:{value}。期望 sources|installed",
234
+ "cli.args.unknown_option": "未知选项:{value}",
235
+ "cli.args.mode_only_start": "选项 --mode 仅支持 start 命令",
236
+ "legacy.models.fetch_error": "🔴 获取模型列表失败。请使用 /status 检查服务器状态。",
237
+ "legacy.models.empty": "📋 没有可用模型。请在 OpenCode 中配置 providers。",
238
+ "legacy.models.header": "📋 **可用模型:**\n\n",
239
+ "legacy.models.no_provider_models": " ⚠️ 没有可用模型\n",
240
+ "legacy.models.env_hint": "💡 在 .env 中使用该模型:\n",
241
+ "legacy.models.error": "🔴 加载模型列表时发生错误。",
242
+ "stt.recognizing": "🎤 正在识别音频...",
243
+ "stt.recognized": "🎤 识别结果:\n{text}",
244
+ "stt.not_configured": "🎤 语音识别尚未配置。\n\n在 .env 中设置 STT_API_URL 和 STT_API_KEY 以启用。",
245
+ "stt.error": "🔴 识别音频失败:{error}",
246
+ "stt.empty_result": "🎤 音频消息中未检测到语音。",
247
+ };
@@ -23,6 +23,10 @@ function classifyIncomingInput(ctx) {
23
23
  }
24
24
  return { inputType: "text" };
25
25
  }
26
+ // Photo, voice, audio, and other non-text messages are classified as "other"
27
+ if (ctx.message?.photo) {
28
+ return { inputType: "other" };
29
+ }
26
30
  return { inputType: "other" };
27
31
  }
28
32
  function getExpectedInputBlockReason(expectedInput) {
@@ -0,0 +1,62 @@
1
+ import { opencodeClient } from "../opencode/client.js";
2
+ import { logger } from "../utils/logger.js";
3
+ const capabilitiesCache = {};
4
+ /**
5
+ * Get model capabilities from OpenCode API
6
+ * Results are cached in memory per model
7
+ */
8
+ export async function getModelCapabilities(providerID, modelID) {
9
+ const cacheKey = `${providerID}/${modelID}`;
10
+ if (capabilitiesCache[cacheKey] !== undefined) {
11
+ logger.debug(`[ModelCapabilities] Cache hit for ${cacheKey}`);
12
+ return capabilitiesCache[cacheKey];
13
+ }
14
+ try {
15
+ logger.debug(`[ModelCapabilities] Fetching capabilities for ${cacheKey}`);
16
+ const response = await opencodeClient.config.providers();
17
+ if (response.error || !response.data) {
18
+ logger.error("[ModelCapabilities] API returned error:", response.error);
19
+ capabilitiesCache[cacheKey] = null;
20
+ return null;
21
+ }
22
+ const providers = response.data.providers;
23
+ const provider = providers.find((p) => p.id === providerID);
24
+ if (!provider) {
25
+ logger.warn(`[ModelCapabilities] Provider ${providerID} not found`);
26
+ capabilitiesCache[cacheKey] = null;
27
+ return null;
28
+ }
29
+ const model = provider.models[modelID];
30
+ if (!model) {
31
+ logger.warn(`[ModelCapabilities] Model ${cacheKey} not found in provider`);
32
+ capabilitiesCache[cacheKey] = null;
33
+ return null;
34
+ }
35
+ logger.debug(`[ModelCapabilities] Found capabilities for ${cacheKey}`);
36
+ capabilitiesCache[cacheKey] = model.capabilities;
37
+ return model.capabilities;
38
+ }
39
+ catch (error) {
40
+ logger.error("[ModelCapabilities] Failed to fetch providers:", error);
41
+ capabilitiesCache[cacheKey] = null;
42
+ return null;
43
+ }
44
+ }
45
+ /**
46
+ * Check if model supports a specific input type
47
+ */
48
+ export function supportsInput(capabilities, inputType) {
49
+ if (!capabilities) {
50
+ return false;
51
+ }
52
+ return capabilities.input[inputType] === true;
53
+ }
54
+ /**
55
+ * Check if model supports attachments in general
56
+ */
57
+ export function supportsAttachment(capabilities) {
58
+ if (!capabilities) {
59
+ return false;
60
+ }
61
+ return capabilities.attachment === true;
62
+ }
@@ -5,7 +5,7 @@ import { createInterface } from "node:readline/promises";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import dotenv from "dotenv";
7
7
  import { getRuntimePaths } from "./paths.js";
8
- import { t } from "../i18n/index.js";
8
+ import { getLocale, getLocaleOptions, resolveSupportedLocale, setRuntimeLocale, t, } from "../i18n/index.js";
9
9
  const DEFAULT_API_URL = "http://localhost:4096";
10
10
  const FALLBACK_MODEL_PROVIDER = "opencode";
11
11
  const FALLBACK_MODEL_ID = "big-pickle";
@@ -60,6 +60,7 @@ function finalizeEnvContent(lines) {
60
60
  export function buildEnvFileContent(existingContent, values) {
61
61
  let lines = normalizeEnvLineEndings(existingContent);
62
62
  const orderedUpdates = [
63
+ ["BOT_LOCALE", values.BOT_LOCALE],
63
64
  ["TELEGRAM_BOT_TOKEN", values.TELEGRAM_BOT_TOKEN],
64
65
  ["TELEGRAM_ALLOWED_USER_ID", values.TELEGRAM_ALLOWED_USER_ID],
65
66
  ["OPENCODE_API_URL", values.OPENCODE_API_URL],
@@ -188,6 +189,35 @@ async function askToken() {
188
189
  return token;
189
190
  }
190
191
  }
192
+ async function askLocale() {
193
+ const localeOptions = getLocaleOptions();
194
+ const defaultLocale = getLocale();
195
+ const defaultLocaleOption = localeOptions.find((localeOption) => localeOption.code === defaultLocale) ?? localeOptions[0];
196
+ const optionsText = localeOptions
197
+ .map((localeOption, index) => `${index + 1} - ${localeOption.label} (${localeOption.code})`)
198
+ .join("\n");
199
+ const prompt = t("runtime.wizard.ask_language", {
200
+ options: optionsText,
201
+ defaultLocale: `${defaultLocaleOption.label} (${defaultLocaleOption.code})`,
202
+ });
203
+ for (;;) {
204
+ const answer = await askVisible(prompt);
205
+ if (!answer) {
206
+ return defaultLocaleOption.code;
207
+ }
208
+ if (/^\d+$/.test(answer)) {
209
+ const index = Number.parseInt(answer, 10) - 1;
210
+ if (index >= 0 && index < localeOptions.length) {
211
+ return localeOptions[index].code;
212
+ }
213
+ }
214
+ const localeByCode = resolveSupportedLocale(answer);
215
+ if (localeByCode) {
216
+ return localeByCode;
217
+ }
218
+ process.stdout.write(t("runtime.wizard.language_invalid"));
219
+ }
220
+ }
191
221
  async function askAllowedUserId() {
192
222
  for (;;) {
193
223
  const allowedUserId = await askVisible(t("runtime.wizard.ask_user_id"));
@@ -213,6 +243,16 @@ async function askApiUrl() {
213
243
  }
214
244
  }
215
245
  async function collectWizardValues() {
246
+ const locale = await askLocale();
247
+ setRuntimeLocale(locale);
248
+ const selectedLocaleOption = getLocaleOptions().find((localeOption) => localeOption.code === locale) ?? null;
249
+ process.stdout.write("\n");
250
+ process.stdout.write(t("runtime.wizard.language_selected", {
251
+ language: selectedLocaleOption !== null
252
+ ? `${selectedLocaleOption.label} (${selectedLocaleOption.code})`
253
+ : locale,
254
+ }));
255
+ process.stdout.write("\n");
216
256
  process.stdout.write(t("runtime.wizard.start"));
217
257
  process.stdout.write("\n");
218
258
  const token = await askToken();
@@ -220,6 +260,7 @@ async function collectWizardValues() {
220
260
  const apiUrl = await askApiUrl();
221
261
  process.stdout.write("\n");
222
262
  return {
263
+ locale,
223
264
  token,
224
265
  allowedUserId,
225
266
  apiUrl,
@@ -249,6 +290,7 @@ async function runWizardAndPersist(runtimePaths) {
249
290
  const provider = existingParsed.OPENCODE_MODEL_PROVIDER || modelDefaults.provider;
250
291
  const modelId = existingParsed.OPENCODE_MODEL_ID || modelDefaults.modelId;
251
292
  const envValues = {
293
+ BOT_LOCALE: wizardValues.locale,
252
294
  TELEGRAM_BOT_TOKEN: wizardValues.token,
253
295
  TELEGRAM_ALLOWED_USER_ID: wizardValues.allowedUserId,
254
296
  OPENCODE_API_URL: wizardValues.apiUrl,
@@ -12,6 +12,12 @@ const SYNC_SAFETY_WINDOW_MS = 60_000;
12
12
  const SYNC_COOLDOWN_MS = 60_000;
13
13
  const STORAGE_FALLBACK_SCAN_LIMIT = 200;
14
14
  const SQLITE_FALLBACK_QUERY_LIMIT = 200;
15
+ const SERVER_UNAVAILABLE_ERROR_MARKERS = [
16
+ "fetch failed",
17
+ "econnrefused",
18
+ "connection refused",
19
+ "connect refused",
20
+ ];
15
21
  const EMPTY_CACHE = {
16
22
  version: CACHE_VERSION,
17
23
  lastSyncedUpdatedAt: 0,
@@ -144,6 +150,50 @@ function createVirtualProjectId(worktree) {
144
150
  const hash = createHash("sha1").update(worktree).digest("hex").slice(0, 16);
145
151
  return `dir_${hash}`;
146
152
  }
153
+ function hasServerUnavailableMarker(value) {
154
+ const lower = value.toLowerCase();
155
+ return SERVER_UNAVAILABLE_ERROR_MARKERS.some((marker) => lower.includes(marker));
156
+ }
157
+ function isServerUnavailableError(error) {
158
+ const queue = [error];
159
+ const seen = new Set();
160
+ while (queue.length > 0) {
161
+ const current = queue.pop();
162
+ if (!current || seen.has(current)) {
163
+ continue;
164
+ }
165
+ seen.add(current);
166
+ if (typeof current === "string") {
167
+ if (hasServerUnavailableMarker(current)) {
168
+ return true;
169
+ }
170
+ continue;
171
+ }
172
+ if (current instanceof Error) {
173
+ if (hasServerUnavailableMarker(`${current.name}: ${current.message}`)) {
174
+ return true;
175
+ }
176
+ const errorWithCause = current;
177
+ if (errorWithCause.cause) {
178
+ queue.push(errorWithCause.cause);
179
+ }
180
+ continue;
181
+ }
182
+ if (typeof current === "object") {
183
+ const value = current;
184
+ if (typeof value.code === "string" && hasServerUnavailableMarker(value.code)) {
185
+ return true;
186
+ }
187
+ if (typeof value.message === "string" && hasServerUnavailableMarker(value.message)) {
188
+ return true;
189
+ }
190
+ if (value.cause) {
191
+ queue.push(value.cause);
192
+ }
193
+ }
194
+ }
195
+ return false;
196
+ }
147
197
  async function runSync() {
148
198
  await ensureCacheLoaded();
149
199
  const params = buildListParams();
@@ -352,7 +402,12 @@ export async function syncSessionDirectoryCache(options) {
352
402
  lastSyncAttemptAt = Date.now();
353
403
  })
354
404
  .catch((error) => {
355
- logger.warn("[SessionCache] Failed to sync sessions cache", error);
405
+ if (isServerUnavailableError(error)) {
406
+ logger.warn("[SessionCache] OpenCode server is not running. Start it with: opencode serve");
407
+ }
408
+ else {
409
+ logger.warn("[SessionCache] Failed to sync sessions cache", error);
410
+ }
356
411
  lastSyncAttemptAt = 0;
357
412
  })
358
413
  .finally(() => {